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"; // import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache"; import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp"; import autoRestore from "../../helpers/AutoRestore"; import { _restore } from "../../helpers/RestoreControll"; interface Request { body: string; ticket: Ticket; quotedMsg?: Message; } const SendWhatsAppMessage = async ({ body, ticket, quotedMsg }: Request): Promise => { let timestamp = Math.floor(Date.now() / 1000) var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`; console.time(timetaken) let quotedMsgSerializedId: string | undefined; if (quotedMsg) { await GetWbotMessage(ticket, quotedMsg.id); quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg); } const whatsapp = await Whatsapp.findByPk(ticket.whatsappId); if (whatsapp && whatsapp.status != 'CONNECTED') { let 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 { 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() }) console.timeEnd(timetaken) return sentMessage; } catch (err) { const whatsapp = await ShowWhatsAppService(ticket.whatsappId); throw new AppError("ERR_SENDING_WAPP_MSG"); } }; export default SendWhatsAppMessage;