diff --git a/backend/.wwebjs_auth/sessions/1657314170.txt b/backend/.wwebjs_auth/sessions/1657314170.txt new file mode 100644 index 0000000..22950ec --- /dev/null +++ b/backend/.wwebjs_auth/sessions/1657314170.txt @@ -0,0 +1 @@ +Whatsapp id: 33 | Fri Jul 08 2022 15:02:50 GMT-0300 (Brasilia Standard Time) \ No newline at end of file diff --git a/backend/src/controllers/WhatsAppSessionController.ts b/backend/src/controllers/WhatsAppSessionController.ts index aa9d9b7..62c645f 100644 --- a/backend/src/controllers/WhatsAppSessionController.ts +++ b/backend/src/controllers/WhatsAppSessionController.ts @@ -44,7 +44,7 @@ const restart = async (req: Request, res: Response): Promise => { const whatsapp = await ShowWhatsAppService(whatsappId); - await restartWhatsSession(whatsapp) + restartWhatsSession(whatsapp, true) return res.status(200).json({ message: "Starting session." }); }; diff --git a/backend/src/helpers/RestartWhatsSession.ts b/backend/src/helpers/RestartWhatsSession.ts index bc6fb36..1864152 100644 --- a/backend/src/helpers/RestartWhatsSession.ts +++ b/backend/src/helpers/RestartWhatsSession.ts @@ -10,7 +10,7 @@ const fsPromises = require("fs/promises"); const fs = require('fs') // Restart session -export const restartWhatsSession = async (whatsapp: Whatsapp) => { +export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boolean = false) => { console.log('RESTARTING THE whatsapp.id: ', whatsapp.id) @@ -34,6 +34,6 @@ export const restartWhatsSession = async (whatsapp: Whatsapp) => { console.log('RESTARTING SESSION...') - await StartWhatsAppSession(whatsapp); + await StartWhatsAppSession(whatsapp, backupSession); } \ No newline at end of file diff --git a/backend/src/helpers/SetTicketMessagesAsRead.ts b/backend/src/helpers/SetTicketMessagesAsRead.ts index 5350c81..27fbf6c 100644 --- a/backend/src/helpers/SetTicketMessagesAsRead.ts +++ b/backend/src/helpers/SetTicketMessagesAsRead.ts @@ -19,9 +19,9 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise => { try { const wbot = await GetTicketWbot(ticket); - await wbot.sendSeen( - `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us` - ); + + await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`); + } catch (err) { logger.warn( `Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}` diff --git a/backend/src/libs/wbot.ts b/backend/src/libs/wbot.ts index ffe26fc..a3cdfdb 100644 --- a/backend/src/libs/wbot.ts +++ b/backend/src/libs/wbot.ts @@ -10,6 +10,7 @@ const fs = require('fs') import { copyFolder } from "../helpers/CopyFolder"; import path from "path"; import { number } from "yup"; +import { removeDir } from "../helpers/DeleteDirectory"; interface Session extends Client { id?: number; @@ -43,7 +44,7 @@ const syncUnreadMessages = async (wbot: Session) => { } }; -export const initWbot = async (whatsapp: Whatsapp): Promise => { +export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean = false): Promise => { return new Promise((resolve, reject) => { try { @@ -63,29 +64,12 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined }, }); - //OPÇÃO DEFAULT NAO MD - // const wbot: Session = new Client({session: sessionCfg, - // puppeteer: {executablePath: process.env.CHROME_BIN || undefined - // } - // }); - - //OPÇÃO MD ANTIGO COM ERRO - // const io = getIO(); - // const sessionName = whatsapp.name; - // const SESSION_FILE_PATH = './session.json' - // let sessionCfg - // if(fs.existsSync(SESSION_FILE_PATH)){ - // sessionCfg = require(SESSION_FILE_PATH) - // } - // const wbot: Session = new Client({ puppeteer: { headless: true }, clientId: 'bd_'+whatsapp.id}) - - wbot.initialize(); wbot.on("qr", async qr => { - + if (!backupSession.includes(whatsapp.id)) { backupSession.push(whatsapp.id) } @@ -163,19 +147,22 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { await syncUnreadMessages(wbot); resolve(wbot); - + console.log(`>>>>>>>>>>>>>>>>>>>>>>>>>.. BACKUP SESSION whatsapp.id ${whatsapp.id} | backupSession: ${backupSession}`) - const whatsIndex = backupSession.findIndex((id:number) => id === +whatsapp.id); + const whatsIndex = backupSession.findIndex((id: number) => id === +whatsapp.id); console.log(' whatsIndex: ', whatsIndex) - - if (whatsIndex !== -1) { - backupSession.splice(whatsIndex, 1); + if (whatsIndex !== -1 || backupSessionRestore) { + + if (whatsIndex !== -1) { + backupSession.splice(whatsIndex, 1); + } + setTimeout(async () => { @@ -183,6 +170,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { const destPath = path.join(__dirname, `../../.wwebjs_auth/sessions`, `session-bd_${whatsapp.id}`) if (fs.existsSync(path.join(__dirname, `../../.wwebjs_auth/sessions`))) { + + await removeDir(destPath) + // copy the good session for backup dir copyFolder(sourcePath, destPath) } @@ -193,9 +183,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise => { console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`) - }, 30000); + }, 55000); - console.log(' PASSOU NO TIMEOUT!') + console.log(' PASSOU NO TIMEOUT whatsapp.id: ',whatsapp.id) } diff --git a/backend/src/services/WbotServices/StartWhatsAppSession.ts b/backend/src/services/WbotServices/StartWhatsAppSession.ts index af0c6ae..3b02cd2 100644 --- a/backend/src/services/WbotServices/StartWhatsAppSession.ts +++ b/backend/src/services/WbotServices/StartWhatsAppSession.ts @@ -5,7 +5,7 @@ import { getIO } from "../../libs/socket"; import wbotMonitor from "./wbotMonitor"; import { logger } from "../../utils/logger"; -export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise => { +export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise => { await whatsapp.update({ status: "OPENING" }); const io = getIO(); @@ -15,7 +15,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise => }); try { - const wbot = await initWbot(whatsapp); + const wbot = await initWbot(whatsapp, backupSession); wbotMessageListener(wbot); wbotMonitor(wbot, whatsapp); } catch (err) { diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 730af1e..3b9b488 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -5,7 +5,7 @@ import * as Sentry from "@sentry/node"; import { copyFolder } from "../../helpers/CopyFolder"; import { removeDir } from "../../helpers/DeleteDirectory"; -import path from 'path'; +import path from 'path'; import { Contact as WbotContact, @@ -26,27 +26,28 @@ import FindOrCreateTicketService from "../TicketServices/FindOrCreateTicketServi import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import { debounce } from "../../helpers/Debounce"; import UpdateTicketService from "../TicketServices/UpdateTicketService"; -import { date } from "faker"; +import { date } from "faker"; import ShowQueueService from "../QueueService/ShowQueueService"; -import ShowTicketMessage from "../TicketServices/ShowTicketMessage" +import ShowTicketMessage from "../TicketServices/ShowTicketMessage" import BotIsOnQueue from "../../helpers/BotIsOnQueue" import Queue from "../../models/Queue"; -import fs from 'fs'; +import fs from 'fs'; import { StartWhatsAppSession } from "../../services/WbotServices/StartWhatsAppSession"; -import { removeWbot } from '../../libs/wbot' +import { removeWbot } from '../../libs/wbot' import { restartWhatsSession } from "../../helpers/RestartWhatsSession"; // test del import data_ura from './ura' import msg_client_transfer from './ura_msg_transfer' -import final_message from "./ura_final_message"; +import final_message from "./ura_final_message"; import SendWhatsAppMessage from "./SendWhatsAppMessage"; +import Whatsapp from "../../models/Whatsapp"; // - + interface Session extends Client { id?: number; @@ -124,7 +125,7 @@ const verifyMediaMessage = async ( mediaUrl: media.filename, mediaType: media.mimetype.split("/")[0], quotedMsgId: quotedMsg?.id - }; + }; await ticket.update({ lastMessage: msg.body || media.filename }); const newMessage = await CreateMessageService({ messageData }); @@ -138,7 +139,7 @@ const verifyMessage = async ( contact: Contact ) => { - + const quotedMsg = await verifyQuotedMessage(msg); const messageData = { id: msg.id.id, @@ -150,13 +151,13 @@ const verifyMessage = async ( read: msg.fromMe, quotedMsgId: quotedMsg?.id }; - + await ticket.update({ lastMessage: msg.body }); await CreateMessageService({ messageData }); }; - + const verifyQueue = async ( @@ -166,56 +167,56 @@ const verifyQueue = async ( contact: Contact ) => { - const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!); - + const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!); + /*if (queues.length === 1) { await UpdateTicketService({ ticketData: { queueId: queues[0].id }, ticketId: ticket.id }); return; - }*/ + }*/ - - - let selectedOption = null; - let choosenQueue = null - - const botInfo = await BotIsOnQueue('botqueue') - - if(botInfo.isOnQueue){ + let selectedOption = null; + let choosenQueue = null - choosenQueue = await ShowQueueService(botInfo.botQueueId); - - } + + const botInfo = await BotIsOnQueue('botqueue') + + + if (botInfo.isOnQueue) { + + choosenQueue = await ShowQueueService(botInfo.botQueueId); + + } else if (queues.length === 1) { - selectedOption = 1; - choosenQueue = queues[+selectedOption - 1]; + selectedOption = 1; + choosenQueue = queues[+selectedOption - 1]; } - else{ + else { + + selectedOption = msg.body; - selectedOption = msg.body; - //////////////// EXTRAIR APENAS O NÚMERO /////////////////// - selectedOption = selectedOption.replace(/[^1-9]/g, '') + selectedOption = selectedOption.replace(/[^1-9]/g, '') /////////////////////////////////// - choosenQueue = queues[+selectedOption - 1]; + choosenQueue = queues[+selectedOption - 1]; } - - + + if (choosenQueue) { - // Atualizando o status do ticket para mostrar notificação para o atendente da fila escolhida pelo usuário. De queueChoice para pending - if(queues.length > 1 && !botInfo.isOnQueue){ - - await ticket.update({status: "pending" }); + // Atualizando o status do ticket para mostrar notificação para o atendente da fila escolhida pelo usuário. De queueChoice para pending + if (queues.length > 1 && !botInfo.isOnQueue) { - } + await ticket.update({ status: "pending" }); + + } // await UpdateTicketService({ @@ -223,53 +224,53 @@ const verifyQueue = async ( ticketId: ticket.id }); - + let botOptions = '' // O bot abre a mensagem na fila para atender o usuario - if(botInfo.isOnQueue){ - - await UpdateTicketService({ - ticketData:{ status: 'open', userId: botInfo.userIdBot }, - ticketId: ticket.id - }); + if (botInfo.isOnQueue) { - data_ura.forEach((s, index) => { botOptions += `*${index + 1}* - ${s.option}\n` }); - } + await UpdateTicketService({ + ticketData: { status: 'open', userId: botInfo.userIdBot }, + ticketId: ticket.id + }); + + data_ura.forEach((s, index) => { botOptions += `*${index + 1}* - ${s.option}\n` }); + } // let body = '' - if(botOptions.length > 0){ - body = `\u200e${choosenQueue.greetingMessage}\n\n${botOptions}\n${final_message.msg}`; + if (botOptions.length > 0) { + body = `\u200e${choosenQueue.greetingMessage}\n\n${botOptions}\n${final_message.msg}`; } - else{ + else { body = `\u200e${choosenQueue.greetingMessage}`; } - + const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); await verifyMessage(sentMessage, ticket, contact); } else { - //test del transfere o atendimento se entrar na ura infinita - let ticket_message = await ShowTicketMessage(ticket.id, false); - if(ticket_message.length > 10){ - - await UpdateTicketService({ ticketData: {status: 'pending', queueId: queues[0].id }, ticketId: ticket.id }); - - } - else{ + //test del transfere o atendimento se entrar na ura infinita + let ticket_message = await ShowTicketMessage(ticket.id, false); + if (ticket_message.length > 10) { + + await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues[0].id }, ticketId: ticket.id }); + + } + else { let options = ""; queues.forEach((queue, index) => { options += `*${index + 1}* - ${queue.name}\n`; }); - + const body = `\u200e${greetingMessage}\n${options}`; - + const debouncedSentMessage = debounce( async () => { const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); @@ -278,13 +279,13 @@ const verifyQueue = async ( 3000, ticket.id ); - + debouncedSentMessage(); - } - - //console.log('TICKET MESSAGE ON QUEUE CHOICE: ', ticket_message) - // + } + + //console.log('TICKET MESSAGE ON QUEUE CHOICE: ', ticket_message) + // } }; @@ -306,30 +307,30 @@ const isValidMsg = (msg: WbotMessage): boolean => { }; -const queuesOutBot =async (wbot:Session, botId: string | number) => { +const queuesOutBot = async (wbot: Session, botId: string | number) => { - const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!); + const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!); - const indexQueue = queues.findIndex((q) => q.id == botId) + const indexQueue = queues.findIndex((q) => q.id == botId) - if(indexQueue != -1){ - queues.splice(indexQueue, 1) - } + if (indexQueue != -1) { + queues.splice(indexQueue, 1) + } + + return { queues, greetingMessage } - return {queues, greetingMessage} - } -const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: Session) =>{ +const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: Session) => { - await ticket.update({ userId: null }); + await ticket.update({ userId: null }); - await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues.id }, ticketId: ticket.id}); + await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues.id }, ticketId: ticket.id }); } -const botSendMessage = (ticket:Ticket, contact:Contact, wbot: Session, msg: string) => { +const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: string) => { const debouncedSentMessage = debounce( @@ -349,10 +350,12 @@ const handleMessage = async ( msg: WbotMessage, wbot: Session ): Promise => { - if (!isValidMsg(msg)) { + if (!isValidMsg(msg)) { return; } + + try { let msgContact: WbotContact; let groupContact: Contact | undefined; @@ -366,15 +369,15 @@ const handleMessage = async ( // in this case, return and let this message be handled by "media_uploaded" event, when it will have "hasMedia = true" if (!msg.hasMedia && msg.type !== "chat" && msg.type !== "vcard") return; - msgContact = await wbot.getContactById(msg.to); + msgContact = await wbot.getContactById(msg.to); } else { msgContact = await msg.getContact(); - + //console.log('-----msgContact TESTE MSG: ', msgContact, ' | msg.body: ', msg.body) - console.log('-----msgContact TESTE MSG2: ', msgContact, ' | msg: ', msg) - + console.log('-----msgContact TESTE MSG2: ', msgContact, ' | msg: ', msg) + } const chat = await msg.getChat(); @@ -395,378 +398,413 @@ const handleMessage = async ( const unreadMessages = msg.fromMe ? 0 : chat.unreadCount; - const contact = await verifyContact(msgContact); - + const contact = await verifyContact(msgContact); - if ( unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return; - const ticket = await FindOrCreateTicketService( - contact, - wbot.id!, - unreadMessages, - groupContact - ); + if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return; + + const ticket = await FindOrCreateTicketService( + contact, + wbot.id!, + unreadMessages, + groupContact + ); + + // test del + // console.log('>>>>>>>>>>>>>> wbot MOBILE NUMBER: ', wbot.info["wid"]["user"]) + // console.log('>>>>>>>>>>>>>> wbot.id: ', wbot.id) + // console.log('>>>>>>>>>>>>>> ticket.id: ', ticket.id) + // console.log('>>>>>>>>>>>>>> ticket.whatsappId: ', ticket.whatsappId) + + // Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen + if (wbot.id != ticket.whatsappId) { + await ticket.update({ whatsappId: wbot.id }); + } + // + + + if (msg.hasMedia) { + await verifyMediaMessage(msg, ticket, contact); + } else { + await verifyMessage(msg, ticket, contact); + } + + //setTimeout(()=>verifyQueue(wbot, msg, ticket, contact), 3000); + + if ( + !ticket.queue && + !chat.isGroup && + !msg.fromMe && + !ticket.userId && + whatsapp.queues.length >= 1 + ) { + await verifyQueue(wbot, msg, ticket, contact); + } + + + + // O bot interage com o cliente e encaminha o atendimento para fila de atendende quando o usuário escolhe a opção falar com atendente + + const botInfo = await BotIsOnQueue('botqueue') + + if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) { + + + if (msg.body === '0') { + + const queue = await ShowQueueService(ticket.queue.id); + + const greetingMessage = `\u200e${queue.greetingMessage}`; + + let options = ""; + + data_ura.forEach((s, index) => { options += `*${index + 1}* - ${s.option}\n` }); + + botSendMessage(ticket, contact, wbot, `${greetingMessage}\n\n${options}\n${final_message.msg}`) - // test del - // console.log('>>>>>>>>>>>>>> wbot MOBILE NUMBER: ', wbot.info["wid"]["user"]) - // console.log('>>>>>>>>>>>>>> wbot.id: ', wbot.id) - // console.log('>>>>>>>>>>>>>> ticket.id: ', ticket.id) - // console.log('>>>>>>>>>>>>>> ticket.whatsappId: ', ticket.whatsappId) - - // Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen - if(wbot.id != ticket.whatsappId){ - await ticket.update({ whatsappId: wbot.id }); } - // + else { - - if (msg.hasMedia) { - await verifyMediaMessage(msg, ticket, contact); - } else { - await verifyMessage(msg, ticket, contact); - } - //setTimeout(()=>verifyQueue(wbot, msg, ticket, contact), 3000); - - if ( - !ticket.queue && - !chat.isGroup && - !msg.fromMe && - !ticket.userId && - whatsapp.queues.length >= 1 - ) { - await verifyQueue(wbot, msg, ticket, contact); - } + // Pega as ultimas 9 opções numericas digitadas pelo cliente em orde DESC + // Consulta apenas mensagens do usuári - - - // O bot interage com o cliente e encaminha o atendimento para fila de atendende quando o usuário escolhe a opção falar com atendente - - const botInfo = await BotIsOnQueue('botqueue') - if( botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot){ + let lastOption = '' - - if(msg.body === '0'){ + let ura_length = data_ura.length - const queue = await ShowQueueService(ticket.queue.id); + let indexAttendant = data_ura.findIndex((u) => u.atendente) - const greetingMessage = `\u200e${queue.greetingMessage}`; + let opt_user_attendant = '-1' - let options = ""; - - data_ura.forEach((s, index) => { options += `*${index + 1}* - ${s.option}\n` }); - - botSendMessage(ticket, contact, wbot, `${greetingMessage}\n\n${options}\n${final_message.msg}`) - + if (indexAttendant != -1) { + opt_user_attendant = data_ura[indexAttendant].id } - else{ + // console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ indexAttendant: ',indexAttendant, ' | opt_user_attendant: ', opt_user_attendant) - // Pega as ultimas 9 opções numericas digitadas pelo cliente em orde DESC - // Consulta apenas mensagens do usuári + let ticket_message = await ShowTicketMessage(ticket.id, true, ura_length, `^[0-${ura_length}}]$`); - - let lastOption = '' + if (ticket_message.length > 1) { - let ura_length = data_ura.length + lastOption = ticket_message[1].body - let indexAttendant = data_ura.findIndex((u) => u.atendente ) + const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) - let opt_user_attendant = '-1' + const queues = queuesWhatsGreetingMessage.queues - if(indexAttendant != -1){ - opt_user_attendant = data_ura[indexAttendant].id + if (queues.length > 1) { + + const index_opt_user_attendant = ticket_message.findIndex((q) => q.body == opt_user_attendant) + const index0 = ticket_message.findIndex((q) => q.body == '0') + + if (index_opt_user_attendant != -1) { + + if (index0 > -1 && index0 < index_opt_user_attendant) { + lastOption = '' + } + else { + lastOption = opt_user_attendant + } } - // console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ indexAttendant: ',indexAttendant, ' | opt_user_attendant: ', opt_user_attendant) + } - let ticket_message = await ShowTicketMessage(ticket.id, true, ura_length, `^[0-${ura_length}}]$`); + } - if(ticket_message.length > 1){ - lastOption = ticket_message[1].body - + + + // console.log('----------------- ticket_message: ', ticket_message) + + //console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ MSG.BODY: ', msg.body , ' | opt_user_attendant: ',opt_user_attendant, ' | lastOption: ', lastOption) + + // È numero + if (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= data_ura.length)) { + + const indexUra = data_ura.findIndex((ura) => ura.id == msg.body.trim()) + + + + if (indexUra != -1) { + + if (data_ura[indexUra].id != opt_user_attendant && lastOption != opt_user_attendant) { + + + + console.log('TICKET MESSAGE: ', ticket_message) + + // test del + let next = true + + let indexAux = ticket_message.findIndex((e) => e.body == '0') + + let listMessage = null + + if (indexAux != -1) { + + listMessage = ticket_message.slice(0, indexAux) + } + else { + + listMessage = ticket_message + + } + + let id = '' + let subUra = null + + if (listMessage.length > 1) { + + id = listMessage[listMessage.length - 1].body + subUra = data_ura.filter((e) => e.id == id)[0] + + if (subUra && (!subUra.subOptions || subUra.subOptions.length == 0)) { + + listMessage.pop() + + } + + } + + + if (listMessage.length > 1) { + + id = listMessage[listMessage.length - 1].body + subUra = data_ura.filter((e) => e.id == id)[0] + + if (subUra.subOptions && subUra.subOptions.length > 0) { + + if (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= subUra.subOptions?.length) && subUra.subOptions) { + + + if (subUra.subOptions[+msg.body - 1].responseToClient) { + + botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].responseToClient}`) + + } + else { + botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].subOpt}`) + } + + const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) + + const queues = queuesWhatsGreetingMessage.queues + + if (queues.length > 0) { + await botTransferTicket(queues[0], ticket, contact, wbot) + } + else { + console.log('NO QUEUE!') + } + + } + else { + + let options = ""; + let subOptions: any[] = subUra.subOptions + + subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` }); + + botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\nDigite um número válido disponível no menu de opções de atendimento abaixo: \n${options}\n\n*0* - Voltar ao menu principal`) + + } + + next = false + + } + + } + + + // + if (next) { + if (data_ura[indexUra].subOptions && data_ura[indexUra].subOptions.length > 0) { + + let options = ""; + let option = data_ura[indexUra].option + let subOptions: any[] = data_ura[indexUra].subOptions + let description = data_ura[indexUra].description + + subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` }); + + const body = `\u200e${description}:\n${options}` + + botSendMessage(ticket, contact, wbot, `*${option}*\n\n${body}\n\n *0* - Voltar ao menu principal`) + + } + else { + + //test del deletar isso (Usar somente na hit) + if (data_ura[indexUra].closeChat) { + + + const { ticket: res } = await UpdateTicketService({ + ticketData: { 'status': 'closed', 'userId': botInfo.userIdBot }, ticketId: ticket.id + }); + + /////////////////////////////// + const whatsapp = await ShowWhatsAppService(ticket.whatsappId); + + const { farewellMessage } = whatsapp; + + if (farewellMessage) { + await SendWhatsAppMessage({ body: farewellMessage, ticket: res }); + } + /////////////////////////////// + + } + else { + botSendMessage(ticket, contact, wbot, `${data_ura[indexUra].description}\n\n *0* - Voltar ao menu principal`) + } + // + + + // botSendMessage(ticket, contact, wbot, `${data_ura[indexUra].description}\n\n *0* - Voltar ao menu principal`) + + } + } + + } + else if (data_ura[indexUra].id == opt_user_attendant) { + const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) - const queues = queuesWhatsGreetingMessage.queues - - if(queues.length > 1){ + const queues = queuesWhatsGreetingMessage.queues - const index_opt_user_attendant = ticket_message.findIndex((q) => q.body == opt_user_attendant) - const index0 = ticket_message.findIndex((q) => q.body == '0') - - if(index_opt_user_attendant != -1){ - - if(index0 > -1 && index0 < index_opt_user_attendant){ - lastOption = '' - } - else{ - lastOption = opt_user_attendant - } - } - - } - - } + // Se fila for maior que 1 exibi as opções fila para atendimento humano + if (queues.length > 1) { - + let options = ""; - - // console.log('----------------- ticket_message: ', ticket_message) - - //console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ MSG.BODY: ', msg.body , ' | opt_user_attendant: ',opt_user_attendant, ' | lastOption: ', lastOption) - - // È numero - if( !Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= data_ura.length) ) { + queues.forEach((queue, index) => { - const indexUra = data_ura.findIndex((ura) => ura.id == msg.body.trim()) + options += `*${index + 1}* - ${queue.name}\n`; - + }); - if(indexUra != -1){ - - if(data_ura[indexUra].id != opt_user_attendant && lastOption != opt_user_attendant){ + const body = `\u200eSelecione uma das opções de atendimento abaixo:\n${options}`; - + botSendMessage(ticket, contact, wbot, body) - console.log('TICKET MESSAGE: ', ticket_message) + } // Para situações onde há apenas uma fila com exclusão da fila do bot, já direciona o cliente para essa fila de atendimento humano + else if (queues.length == 1) { - // test del - let next = true + await botTransferTicket(queues[0], ticket, contact, wbot) - let indexAux = ticket_message.findIndex((e)=>e.body=='0') - - let listMessage = null - - if(indexAux!=-1){ - - listMessage = ticket_message.slice(0, indexAux) - } - else{ - - listMessage = ticket_message - - } - - let id = '' - let subUra = null - - if(listMessage.length > 1){ - - id = listMessage[listMessage.length-1].body - subUra = data_ura.filter((e)=>e.id == id )[0] - - if(subUra && (!subUra.subOptions || subUra.subOptions.length == 0)){ - - listMessage.pop() - - } - - } - - - if(listMessage.length > 1){ - - id = listMessage[listMessage.length-1].body - subUra = data_ura.filter((e)=>e.id == id )[0] - - if(subUra.subOptions && subUra.subOptions.length > 0){ - - if( !Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= subUra.subOptions?.length) && subUra.subOptions ) { - - - if(subUra.subOptions[+msg.body - 1].responseToClient){ - - botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].responseToClient}`) - - } - else{ - botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].subOpt}`) - } - - const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) - - const queues = queuesWhatsGreetingMessage.queues - - if(queues.length>0){ - await botTransferTicket(queues[0], ticket, contact, wbot) - } - else{ - console.log('NO QUEUE!') - } - - } - else{ - - let options = ""; - let subOptions:any[] = subUra.subOptions - - subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` }); - - botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\nDigite um número válido disponível no menu de opções de atendimento abaixo: \n${options}\n\n*0* - Voltar ao menu principal`) - - } - - next = false - - } - - } - - - // - if(next){ - if(data_ura[indexUra].subOptions && data_ura[indexUra].subOptions.length > 0){ - - let options = ""; - let option = data_ura[indexUra].option - let subOptions:any[] = data_ura[indexUra].subOptions - let description = data_ura[indexUra].description - - subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` }); - - const body = `\u200e${description}:\n${options}` - - botSendMessage(ticket, contact, wbot, `*${option}*\n\n${body}\n\n *0* - Voltar ao menu principal`) - - } - else{ - - //test del deletar isso (Usar somente na hit) - if(data_ura[indexUra].closeChat){ - - - const {ticket :res} = await UpdateTicketService({ - ticketData:{'status': 'closed', 'userId': botInfo.userIdBot}, ticketId: ticket.id - }); - - /////////////////////////////// - const whatsapp = await ShowWhatsAppService(ticket.whatsappId); - - const { farewellMessage } = whatsapp; - - if (farewellMessage) { - await SendWhatsAppMessage({ body: farewellMessage, ticket: res }); - } - /////////////////////////////// - - } - else{ - botSendMessage(ticket, contact, wbot, `${data_ura[indexUra].description}\n\n *0* - Voltar ao menu principal`) - } - // - - - // botSendMessage(ticket, contact, wbot, `${data_ura[indexUra].description}\n\n *0* - Voltar ao menu principal`) - - } - } + botSendMessage(ticket, contact, wbot, `${msg_client_transfer.msg}`) } - else if(data_ura[indexUra].id == opt_user_attendant){ + } + else if (lastOption == opt_user_attendant) { - const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) + const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) - const queues = queuesWhatsGreetingMessage.queues + const queues = queuesWhatsGreetingMessage.queues - // Se fila for maior que 1 exibi as opções fila para atendimento humano - if(queues.length > 1){ + // É numero + if (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= queues.length)) { - let options = ""; + await botTransferTicket(queues[+msg.body - 1], ticket, contact, wbot) - queues.forEach((queue, index) => { - - options += `*${index + 1}* - ${queue.name}\n`; - - }); - - const body = `\u200eSelecione uma das opções de atendimento abaixo:\n${options}`; - - botSendMessage(ticket, contact, wbot, body) - - } // Para situações onde há apenas uma fila com exclusão da fila do bot, já direciona o cliente para essa fila de atendimento humano - else if(queues.length == 1){ - - await botTransferTicket(queues[0], ticket, contact, wbot) - - botSendMessage(ticket, contact, wbot, `${msg_client_transfer.msg}`) - - } + botSendMessage(ticket, contact, wbot, `${msg_client_transfer.msg}`) } - else if (lastOption == opt_user_attendant){ + else { - const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) - - const queues = queuesWhatsGreetingMessage.queues - - // É numero - if( !Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= queues.length) ) { - - await botTransferTicket(queues[+msg.body - 1], ticket, contact, wbot) - - botSendMessage(ticket, contact, wbot, `${msg_client_transfer.msg}`) - } - else{ - - botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções de atendimento\n\n*0* - Voltar ao menu principal`) - - } - } - + botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções de atendimento\n\n*0* - Voltar ao menu principal`) + } } - } - else{ - - // É numero - if(!Number.isNaN(Number(msg.body.trim()))){ - - botSendMessage(ticket, contact, wbot, `Opção numérica inválida!\nDigite um dos números mostrados no menu de opções\n\n*0* - Voltar ao menu principal`) - - } - else{ - - botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções\n\n*0* - Voltar ao menu principal`) - - } } } - + else { - } - // + // É numero + if (!Number.isNaN(Number(msg.body.trim()))) { - - - // test del - // console.log('WBOT.id: ',wbot.id) + botSendMessage(ticket, contact, wbot, `Opção numérica inválida!\nDigite um dos números mostrados no menu de opções\n\n*0* - Voltar ao menu principal`) - // const sourcePath = path.join(__dirname,`../../../.wwebjs_auth/sessions/`, `session-bd_${wbot.id}`) - // const destPath = path.join(__dirname,`../../../.wwebjs_auth/`, `session-bd_${wbot.id}`) + } + else { - // console.log('================sourcePath: ', sourcePath) - // console.log('================sourcePath: ', destPath) + botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções\n\n*0* - Voltar ao menu principal`) - // removeWbot(33) + } - // await removeDir(destPath) - - // copyFolder(sourcePath, destPath) + } - // await StartWhatsAppSession(whatsapp); + } + + + } + // + + + // test del + + // if (msg.body.trim() == 'broken') { + // throw new Error('Throw makes it go boom!') + // } + + + // console.log('>>>>>>>>>>>> whatsapp.status: ', whatsapp.status) + // + + + + // test del + // console.log('WBOT.id: ',wbot.id) + + // const sourcePath = path.join(__dirname,`../../../.wwebjs_auth/sessions/`, `session-bd_${wbot.id}`) + // const destPath = path.join(__dirname,`../../../.wwebjs_auth/`, `session-bd_${wbot.id}`) + + // console.log('================sourcePath: ', sourcePath) + // console.log('================sourcePath: ', destPath) + + // removeWbot(33) + + // await removeDir(destPath) + + // copyFolder(sourcePath, destPath) + + // await StartWhatsAppSession(whatsapp); + + // console.log('RESTARTING SESSION...') + // - // console.log('RESTARTING SESSION...') - // - } catch (err) { Sentry.captureException(err); logger.error(`Error handling whatsapp message: Err: ${err}`); + + //Solução para contornar erro de sessão + if ((`${err}`).includes(" Evaluation failed: r ")) { + + const sourcePath = path.join(__dirname,`../../../.wwebjs_auth/sessions`) + + let log = new Date(new Date() + 'UTC'); + + const whatsapp = await ShowWhatsAppService(wbot.id!); + + if (whatsapp.status == 'CONNECTED') { + + console.log('ENTROU NO RESTORE...') + + let timestamp = Math.floor(Date.now() / 1000) + fs.writeFile(`${sourcePath}/${timestamp}.txt`, `Whatsapp id: ${whatsapp.id} | ${log}`, (error)=>{}); + + await restartWhatsSession(whatsapp) + + console.log('...PASSOU O RESTORE') + } + + } + } };