Organize directories
This commit is contained in:
parent
8a91c9b89b
commit
4898382f78
433 changed files with 0 additions and 0 deletions
94
apps/metamigo-worker/tasks/whatsapp-message.ts
Normal file
94
apps/metamigo-worker/tasks/whatsapp-message.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/* eslint-disable camelcase */
|
||||
import { withDb, AppDatabase } from "../db";
|
||||
import workerUtils from "../utils";
|
||||
|
||||
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 = (
|
||||
messageInfo: WhatsappMessageTaskOptions
|
||||
): WebhookPayload => {
|
||||
const {
|
||||
waMessageId,
|
||||
waMessage,
|
||||
waTimestamp,
|
||||
attachment,
|
||||
filename,
|
||||
mimetype,
|
||||
botPhoneNumber,
|
||||
} = messageInfo;
|
||||
const parsedMessage = JSON.parse(waMessage);
|
||||
const message = parsedMessage.message?.conversation ??
|
||||
parsedMessage.message?.extendedTextMessage?.text ??
|
||||
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,
|
||||
messageInfo: WhatsappMessageTaskOptions
|
||||
) => {
|
||||
const { waMessageId, whatsappBotId } = messageInfo;
|
||||
const webhooks = await db.webhooks.findAllByBackendId(
|
||||
"whatsapp",
|
||||
whatsappBotId
|
||||
);
|
||||
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}`,
|
||||
}
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const whatsappMessageTask = async (
|
||||
options: WhatsappMessageTaskOptions
|
||||
): Promise<void> => {
|
||||
console.log(options);
|
||||
withDb(async (db: AppDatabase) => {
|
||||
await notifyWebhooks(db, options);
|
||||
});
|
||||
};
|
||||
|
||||
export default whatsappMessageTask;
|
||||
Loading…
Add table
Add a link
Reference in a new issue