0

Send Text Message

by
Published today

Send a text message to a WhatsApp user. Free-form messages can only be sent within 24 hours of the user's last message; otherwise use a template.

Script whatsapp_business Verified

The script

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

3
/**
4
 * Send Text Message
5
 * Send a text message to a WhatsApp user. Free-form messages can only be sent within 24 hours of the user's last message; otherwise use a template.
6
 */
7
export async function main(
8
  auth: RT.WhatsappBusiness,
9
  to: string,
10
  text: string,
11
  preview_url: boolean | undefined
12
) {
13
  const apiVersion = auth.api_version || "v25.0"
14
  const url = new URL(
15
    `https://graph.facebook.com/${apiVersion}/${auth.phone_number_id}/messages`
16
  )
17

18
  const response = await fetch(url, {
19
    method: "POST",
20
    headers: {
21
      Authorization: `Bearer ${auth.token}`,
22
      "Content-Type": "application/json",
23
      Accept: "application/json",
24
    },
25
    body: JSON.stringify({
26
      messaging_product: "whatsapp",
27
      recipient_type: "individual",
28
      to,
29
      type: "text",
30
      text: {
31
        body: text,
32
        preview_url: preview_url ?? false,
33
      },
34
    }),
35
  })
36

37
  if (!response.ok) {
38
    throw new Error(`${response.status} ${await response.text()}`)
39
  }
40

41
  return await response.json()
42
}
43