Edits history of script submission #22799 for ' Download 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"
    
    /**
     * Download Media
     * Download an uploaded or received media item to Windmill object storage and return its S3 reference.
     */
    export async function main(
      auth: RT.WhatsappBusiness,
      media_id: string,
      destination: S3Object
    ) {
      const apiVersion = auth.api_version || "v25.0"
      const metaUrl = new URL(
        `https://graph.facebook.com/${apiVersion}/${media_id}`
      )
      metaUrl.searchParams.append("phone_number_id", auth.phone_number_id)
    
      const metaResponse = await fetch(metaUrl, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
      if (!metaResponse.ok) {
        throw new Error(`${metaResponse.status} ${await metaResponse.text()}`)
      }
      const { url } = (await metaResponse.json()) as { url: string }
    
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
        },
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      await wmill.writeS3File(
        destination,
        response.body as ReadableStream<Uint8Array>
      )
      return destination
    }
    

    Submitted by hugo989 5 hours ago