0

Upload Media

by
Published today

Upload a file from Windmill object storage to WhatsApp and return a media ID to use in media messages. Media is kept for 30 days.

Script whatsapp_business Verified

The script

Submitted by hugo989 Bun
Verified 5 hours ago
1
import * as wmill from "windmill-client"
2
import { S3Object } from "windmill-client"
3

4
/**
5
 * Upload Media
6
 * Upload a file from Windmill object storage to WhatsApp and return a media ID to use in media messages. Media is kept for 30 days.
7
 */
8
export async function main(
9
  auth: RT.WhatsappBusiness,
10
  file: S3Object,
11
  mime_type: string,
12
  file_name: string | undefined
13
) {
14
  const bytes = await wmill.loadS3File(file)
15
  if (!bytes) {
16
    throw new Error("Could not load the file from object storage")
17
  }
18

19
  const name =
20
    file_name !== undefined && file_name !== ""
21
      ? file_name
22
      : (file.s3.split("/").pop() ?? "file")
23

24
  const form = new FormData()
25
  form.append("messaging_product", "whatsapp")
26
  form.append("type", mime_type)
27
  form.append("file", new Blob([bytes], { type: mime_type }), name)
28

29
  const apiVersion = auth.api_version || "v25.0"
30
  const response = await fetch(
31
    `https://graph.facebook.com/${apiVersion}/${auth.phone_number_id}/media`,
32
    {
33
      method: "POST",
34
      headers: {
35
        Authorization: `Bearer ${auth.token}`,
36
        Accept: "application/json",
37
      },
38
      body: form,
39
    }
40
  )
41

42
  if (!response.ok) {
43
    throw new Error(`${response.status} ${await response.text()}`)
44
  }
45

46
  return await response.json()
47
}
48