Skip to content

Commit 99353b2

Browse files
committed
fetch-media-wa
1 parent 32cf7b4 commit 99353b2

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

src/whatsapp.ts

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { encodeBase64 } from "https://deno.land/[email protected]/encoding/base64.ts";
12
import { gamla } from "../deps.ts";
23
import {
34
injectBotPhone,
@@ -289,23 +290,38 @@ export const whatsappWebhookVerificationHandler = (
289290
},
290291
});
291292

292-
const getMediaUrlFromId =
293-
(accessToken: string) => (id: string): Promise<string> =>
294-
fetch(`https://graph.facebook.com/v21.0/${id}`, {
295-
method: "GET",
296-
headers: {
297-
"Authorization": `Bearer ${accessToken}`,
298-
"Content-Type": "application/json",
299-
},
300-
}).then((response) => response.json() as Promise<{ id: string }>).then((
301-
{ id },
302-
) => id);
293+
type MediaGetResponse = {
294+
messaging_product: "whatsapp";
295+
url: string;
296+
mime_type: string;
297+
sha256: string;
298+
file_size: string;
299+
id: string;
300+
};
301+
302+
const getMediaFromId = (accessToken: string) => (id: string): Promise<string> =>
303+
fetch(`https://graph.facebook.com/v21.0/${id}`, {
304+
method: "GET",
305+
headers: {
306+
"Authorization": `Bearer ${accessToken}`,
307+
"Content-Type": "application/json",
308+
},
309+
})
310+
.then((response) => response.json() as Promise<MediaGetResponse>)
311+
.then(({ url }) =>
312+
fetch(url, {
313+
method: "GET",
314+
headers: { Authorization: `Bearer ${accessToken}` },
315+
})
316+
)
317+
.then((response) => (response.arrayBuffer()))
318+
.then(encodeBase64);
303319

304320
const getText = (accessToken: string) => async (msg: WhatsappMessage) => ({
305321
text: isWelcome(msg) ? "/start" : messageText(msg),
306322
...(msg.entry[0].changes[0].value?.messages?.[0].type === "image"
307323
? {
308-
image: await getMediaUrlFromId(accessToken)(
324+
image: await getMediaFromId(accessToken)(
309325
msg.entry[0].changes[0].value.messages[0].image.id,
310326
),
311327
}

0 commit comments

Comments
 (0)