0

Send Media Message

by
Published today

Send an image, video, audio, document or sticker message to a WhatsApp user, referenced by an uploaded media ID or a public URL.

Script whatsapp_business Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 hours ago
1
//native
2

3
/**
4
 * Send Media Message
5
 * Send an image, video, audio, document or sticker message to a WhatsApp user, referenced by an uploaded media ID or a public URL.
6
 */
7
export async function main(
8
  auth: RT.WhatsappBusiness,
9
  to: string,
10
  media_type: "image" | "video" | "audio" | "document" | "sticker",
11
  media_id: string | undefined,
12
  media_link: string | undefined,
13
  caption: string | undefined,
14
  filename: string | undefined
15
) {
16
  const apiVersion = auth.api_version || "v25.0"
17
  const url = new URL(
18
    `https://graph.facebook.com/${apiVersion}/${auth.phone_number_id}/messages`
19
  )
20

21
  const media: { [key: string]: any } = {}
22
  if (media_id !== undefined && media_id !== "") {
23
    media.id = media_id
24
  } else if (media_link !== undefined && media_link !== "") {
25
    media.link = media_link
26
  } else {
27
    throw new Error("Either media_id or media_link must be provided")
28
  }
29
  // caption is only honored on image, video and document; filename only on document
30
  if (
31
    caption !== undefined &&
32
    caption !== "" &&
33
    (media_type === "image" ||
34
      media_type === "video" ||
35
      media_type === "document")
36
  ) {
37
    media.caption = caption
38
  }
39
  if (filename !== undefined && filename !== "" && media_type === "document") {
40
    media.filename = filename
41
  }
42

43
  const response = await fetch(url, {
44
    method: "POST",
45
    headers: {
46
      Authorization: `Bearer ${auth.token}`,
47
      "Content-Type": "application/json",
48
      Accept: "application/json",
49
    },
50
    body: JSON.stringify({
51
      messaging_product: "whatsapp",
52
      recipient_type: "individual",
53
      to,
54
      type: media_type,
55
      [media_type]: media,
56
    }),
57
  })
58

59
  if (!response.ok) {
60
    throw new Error(`${response.status} ${await response.text()}`)
61
  }
62

63
  return await response.json()
64
}
65