projeto-hit/backend/src/services/WbotServices/SendWhatsAppMessage.ts

211 lines
5.4 KiB
TypeScript
Raw Normal View History

import { Message as WbotMessage } from "whatsapp-web.js";
import AppError from "../../errors/AppError";
import GetTicketWbot from "../../helpers/GetTicketWbot";
import GetWbotMessage from "../../helpers/GetWbotMessage";
import SerializeWbotMsgId from "../../helpers/SerializeWbotMsgId";
import Message from "../../models/Message";
import Ticket from "../../models/Ticket";
import Whatsapp from "../../models/Whatsapp";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import wbotByUserQueue from '../../helpers/GetWbotByUserQueue'
import { WhatsIndex } from "../../helpers/LoadBalanceWhatsSameQueue";
import { deleteTicketsByContactsCache, updateTicketCacheByTicketId } from '../../helpers/TicketCache'
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
import { getWbot } from "../../libs/wbot";
import { json } from "sequelize/types";
import sendMessageMultiSession from "../../helpers/TrySendMessageMultiSession";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
2022-11-17 14:40:37 +00:00
import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
2022-12-14 12:29:42 +00:00
import autoRestore from "../../helpers/AutoRestore";
interface Request {
body: string;
ticket: Ticket;
quotedMsg?: Message;
}
const SendWhatsAppMessage = async ({
body,
ticket,
quotedMsg
}: Request): Promise<WbotMessage> => {
let timestamp = Math.floor(Date.now() / 1000)
var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`;
2022-11-17 14:40:37 +00:00
console.time(timetaken)
2022-11-17 14:40:37 +00:00
let quotedMsgSerializedId: string | undefined;
if (quotedMsg) {
await GetWbotMessage(ticket, quotedMsg.id);
quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg);
}
let whatsapps: any
2022-12-14 12:29:42 +00:00
//TEST DEL
// const defaultWhatsapp = await GetDefaultWhatsApp();
// console.log('DEFAULT WHATSAPP: ', JSON.parse(JSON.stringify(defaultWhatsapp)))
let listWhatsapp = null
2022-12-14 12:29:42 +00:00
listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
2022-12-14 12:29:42 +00:00
if (!listWhatsapp) {
listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
}
// console.log('---')
// console.log('listWhatsapp search: ', listWhatsapp)
// console.log('---')
if (listWhatsapp.length > 1) {
console.log('entrou --------------------->')
2022-12-14 12:29:42 +00:00
const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
await ticket.update({ whatsappId: +_whatsapp.id });
2022-12-14 12:29:42 +00:00
}
2022-12-14 12:29:42 +00:00
console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
2022-12-14 12:29:42 +00:00
if (listWhatsapp.length == 0) {
whatsapps = await wbotByUserQueue(ticket.userId)
if (whatsapps.length > 0) {
if (whatsapps.length > 1) {
await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id });
}
else {
await ticket.update({ whatsappId: whatsapps[0].id });
}
}
}
2022-12-14 12:29:42 +00:00
//
// const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
// if (listWhatsapp.length > 1) {
// const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
// await ticket.update({ whatsappId: _whatsapp.id });
// }
// else {
// whatsapps = await Whatsapp.findOne({
// where: { id: ticket.whatsappId },
// attributes: ['status']
// })
// }
// console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
// if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) {
// whatsapps = await wbotByUserQueue(ticket.userId)
// if (whatsapps.length > 0) {
// if (whatsapps.length > 1) {
// await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id });
// }
// else {
// await ticket.update({ whatsappId: whatsapps[0].id });
// }
// }
// }
const wbot = await GetTicketWbot(ticket);
console.log('2 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId)
try {
2022-11-17 14:40:37 +00:00
console.time
const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false });
await ticket.update({ lastMessage: body });
await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
2022-11-17 14:40:37 +00:00
console.timeEnd(timetaken)
return sentMessage;
} catch (err) {
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
if (whatsapp.status != 'RESTORING') {
console.log('THE WHATSAAP ID: ', whatsapp.id, ' WILL BE RESTORED SOON!')
await whatsapp.update({
status: "RESTORING",
});
2022-11-17 14:40:37 +00:00
await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
status: "RESTORING",
})
2022-12-14 12:29:42 +00:00
// setTimeout(() => restartWhatsSession(whatsapp, true), 90000);
setTimeout(async () => await autoRestore(whatsapp.id, 'auto_send_message'), 95000);
}
const sentMessage = await sendMessageMultiSession(ticket, body, quotedMsgSerializedId)
if (sentMessage.length > 0) {
await ticket.update({ lastMessage: body });
await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
return sentMessage;
}
throw new AppError("ERR_SENDING_WAPP_MSG");
}
};
export default SendWhatsAppMessage;