Edits history of script submission #22812 for ' Upload Media (whatsapp_business)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import * as wmill from "windmill-client"
    import { S3Object } from "windmill-client"
    
    /**
     * Upload Media
     * 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.
     */
    export async function main(
      auth: RT.WhatsappBusiness,
      file: S3Object,
      mime_type: string,
      file_name: string | undefined
    ) {
      const bytes = await wmill.loadS3File(file)
      if (!bytes) {
        throw new Error("Could not load the file from object storage")
      }
    
      const name =
        file_name !== undefined && file_name !== ""
          ? file_name
          : (file.s3.split("/").pop() ?? "file")
    
      const form = new FormData()
      form.append("messaging_product", "whatsapp")
      form.append("type", mime_type)
      form.append("file", new Blob([bytes], { type: mime_type }), name)
    
      const apiVersion = auth.api_version || "v25.0"
      const response = await fetch(
        `https://graph.facebook.com/${apiVersion}/${auth.phone_number_id}/media`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
          body: form,
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 5 hours ago