link-stack/apps/bridge-worker/tasks/whatsapp/send-whatsapp-message.ts

69 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2024-06-05 08:52:41 +02:00
import { db } from "@link-stack/bridge-common";
import { createLogger } from "@link-stack/logger";
const logger = createLogger("bridge-worker-send-whatsapp-message");
2024-04-30 13:13:49 +02:00
interface SendWhatsappMessageTaskOptions {
2024-05-16 18:22:10 +02:00
token: string;
2024-07-18 11:08:01 +02:00
to: string;
2024-04-30 13:13:49 +02:00
message: any;
attachments?: Array<{
data: string;
filename: string;
mime_type: string;
}>;
2024-04-30 13:13:49 +02:00
}
const sendWhatsappMessageTask = async ({
message,
2024-07-18 11:08:01 +02:00
to,
2024-05-16 18:22:10 +02:00
token,
attachments,
2024-05-16 18:22:10 +02:00
}: SendWhatsappMessageTaskOptions): Promise<void> => {
const bot = await db
.selectFrom("WhatsappBot")
.selectAll()
.where("token", "=", token)
.executeTakeFirstOrThrow();
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${bot.id}/send`;
const params: any = { message, phoneNumber: to };
if (attachments && attachments.length > 0) {
params.attachments = attachments;
logger.debug(
{
attachmentCount: attachments.length,
attachmentNames: attachments.map((att) => att.filename),
},
"Sending WhatsApp message with attachments",
);
}
2024-07-18 11:08:01 +02:00
try {
const result = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
});
if (!result.ok) {
const errorText = await result.text();
logger.error(
{
status: result.status,
errorText,
url,
},
"WhatsApp send failed",
);
throw new Error(`Failed to send message: ${result.status}`);
}
2024-07-18 11:08:01 +02:00
} catch (error) {
logger.error({ error });
2024-07-18 11:08:01 +02:00
throw new Error("Failed to send message");
}
2024-05-16 18:22:10 +02:00
};
2024-04-30 13:13:49 +02:00
export default sendWhatsappMessageTask;