Skip to content

Commit

Permalink
support image param
Browse files Browse the repository at this point in the history
  • Loading branch information
uriva committed Dec 17, 2024
1 parent 346ac1f commit 41f455d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 17 deletions.
22 changes: 22 additions & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion deps.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * as gamla from "https://deno.land/x/gamla@89.0.0/src/index.ts";
export * as gamla from "https://deno.land/x/gamla@96.0.0/src/index.ts";
export * as grammy from "https://deno.land/x/[email protected]/mod.ts";
37 changes: 21 additions & 16 deletions src/whatsapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,28 +64,25 @@ export const sendWhatsappMessage =
return (await response.json()) as SentMessageResponse;
}).then(({ messages: [{ id }] }) => id));

const textParams = (type: ParamType) =>
pipe(
map(pipe(replace(/\n|\t|(\s\s\s\s)/g, " | "), convertToWhatsAppFormat)),
(texts: string[]) => ({
type,
parameters: texts.map((text) => ({
type: "text",
// Max length is 60, but it also includes the parameter name or something.
text: truncate(57)(text),
})),
}),
);
const templateTextParamConstraints = pipe(
replace(/\n|\t|(\s\s\s\s)/g, " | "),
convertToWhatsAppFormat,
truncate(60),
);

type ParamType = "HEADER" | "BODY" | "FOOTER" | "BUTTONS";
type TemplateTextParam = { type: "text"; text: string };
type TemplateImageParam = { type: "image"; image: { link: string } };
type TemplateParam = TemplateTextParam | TemplateImageParam;
type Component = { type: ParamType; parameters: TemplateParam[] };

export const sendWhatsappTemplate =
(accessToken: string, fromNumberId: string) =>
(
to: string,
name: string,
langCode: string,
params: Partial<Record<ParamType, string[]>>,
components: Component[],
) =>
fetch(`https://graph.facebook.com/v20.0/${fromNumberId}/messages`, {
method: "POST",
Expand All @@ -97,9 +94,17 @@ export const sendWhatsappTemplate =
template: {
name,
language: { code: langCode },
components: Object.entries(params).map((
x,
) => textParams(x[0] as ParamType)(x[1])),
components: components.map((c) => ({
...c,
parameters: c.parameters.map((p) =>
p.type === "text"
? ({
type: "text",
text: templateTextParamConstraints(p.text),
})
: p
),
})),
},
}),
headers: {
Expand Down

0 comments on commit 41f455d

Please sign in to comment.