Edits history of script submission #22807 for ' Send Media Message (whatsapp_business)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Send Media Message
     * Send an image, video, audio, document or sticker message to a WhatsApp user, referenced by an uploaded media ID or a public URL.
     */
    export async function main(
      auth: RT.WhatsappBusiness,
      to: string,
      media_type: "image" | "video" | "audio" | "document" | "sticker",
      media_id: string | undefined,
      media_link: string | undefined,
      caption: string | undefined,
      filename: string | undefined
    ) {
      const apiVersion = auth.api_version || "v25.0"
      const url = new URL(
        `https://graph.facebook.com/${apiVersion}/${auth.phone_number_id}/messages`
      )
    
      const media: { [key: string]: any } = {}
      if (media_id !== undefined && media_id !== "") {
        media.id = media_id
      } else if (media_link !== undefined && media_link !== "") {
        media.link = media_link
      } else {
        throw new Error("Either media_id or media_link must be provided")
      }
      // caption is only honored on image, video and document; filename only on document
      if (
        caption !== undefined &&
        caption !== "" &&
        (media_type === "image" ||
          media_type === "video" ||
          media_type === "document")
      ) {
        media.caption = caption
      }
      if (filename !== undefined && filename !== "" && media_type === "document") {
        media.filename = filename
      }
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          messaging_product: "whatsapp",
          recipient_type: "individual",
          to,
          type: media_type,
          [media_type]: media,
        }),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 5 hours ago