2024-06-05 08:52:41 +02:00
|
|
|
import { db } from "@link-stack/bridge-common";
|
2025-11-21 14:55:28 +01:00
|
|
|
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;
|
2025-11-21 14:55:28 +01:00
|
|
|
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,
|
2025-11-21 14:55:28 +01:00
|
|
|
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`;
|
2025-11-21 14:55:28 +01:00
|
|
|
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),
|
|
|
|
|
});
|
2025-11-21 14:55:28 +01:00
|
|
|
|
|
|
|
|
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) {
|
2025-11-21 14:55:28 +01:00
|
|
|
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;
|