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

110 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-04-30 13:13:49 +02:00
import { db, getWorkerUtils } from "bridge-common";
interface ReceiveWhatsappMessageTaskOptions {
message: any;
}
const receiveWhatsappMessageTask = async ({
message,
}: ReceiveWhatsappMessageTaskOptions): Promise<void> => {};
export default receiveWhatsappMessageTask;
2023-02-13 12:41:30 +00:00
/* eslint-disable camelcase */
2024-04-30 13:13:49 +02:00
/*
2024-04-21 16:59:50 +02:00
import { withDb, AppDatabase } from "../../lib/db";
import workerUtils from "../../lib/utils";
2023-02-13 12:41:30 +00:00
interface WebhookPayload {
to: string;
from: string;
message_id: string;
sent_at: string;
message: string;
attachment: string;
filename: string;
mime_type: string;
}
interface WhatsappMessageTaskOptions {
waMessageId: string;
waMessage: string;
waTimestamp: string;
attachment: string;
filename: string;
mimetype: string;
botPhoneNumber: string;
whatsappBotId: string;
}
const formatPayload = (
2024-04-21 16:59:50 +02:00
messageInfo: WhatsappMessageTaskOptions,
2023-02-13 12:41:30 +00:00
): WebhookPayload => {
const {
waMessageId,
waMessage,
waTimestamp,
attachment,
filename,
mimetype,
botPhoneNumber,
} = messageInfo;
const parsedMessage = JSON.parse(waMessage);
2024-04-21 16:59:50 +02:00
const message =
parsedMessage.message?.conversation ??
parsedMessage.message?.extendedTextMessage?.text ??
2023-02-13 12:41:30 +00:00
parsedMessage.message?.imageMessage?.caption ??
parsedMessage.message?.videoMessage?.caption;
return {
to: botPhoneNumber,
from: parsedMessage.key.remoteJid,
message_id: waMessageId,
sent_at: waTimestamp,
message,
attachment,
filename,
mime_type: mimetype,
};
};
const notifyWebhooks = async (
db: AppDatabase,
2024-04-21 16:59:50 +02:00
messageInfo: WhatsappMessageTaskOptions,
2023-02-13 12:41:30 +00:00
) => {
const { waMessageId, whatsappBotId } = messageInfo;
const webhooks = await db.webhooks.findAllByBackendId(
"whatsapp",
2024-04-21 16:59:50 +02:00
whatsappBotId,
2023-02-13 12:41:30 +00:00
);
if (webhooks && webhooks.length === 0) return;
webhooks.forEach(({ id }) => {
const payload = formatPayload(messageInfo);
console.log({ payload });
workerUtils.addJob(
"notify-webhook",
{
payload,
webhookId: id,
},
{
// this de-deduplicates the job
jobKey: `webhook-${id}-message-${waMessageId}`,
2024-04-21 16:59:50 +02:00
},
2023-02-13 12:41:30 +00:00
);
});
};
const whatsappMessageTask = async (
2024-04-21 16:59:50 +02:00
options: WhatsappMessageTaskOptions,
2023-02-13 12:41:30 +00:00
): Promise<void> => {
console.log(options);
withDb(async (db: AppDatabase) => {
await notifyWebhooks(db, options);
});
};
export default whatsappMessageTask;
2024-04-30 13:13:49 +02:00
*/