Correção do restore

pull/3/head
adriano 2022-07-12 09:37:34 -03:00
parent bb04db9708
commit 5444baafc3
7 changed files with 453 additions and 424 deletions

View File

@ -0,0 +1 @@
Whatsapp id: 33 | Fri Jul 08 2022 15:02:50 GMT-0300 (Brasilia Standard Time)

View File

@ -44,7 +44,7 @@ const restart = async (req: Request, res: Response): Promise<Response> => {
const whatsapp = await ShowWhatsAppService(whatsappId);
await restartWhatsSession(whatsapp)
restartWhatsSession(whatsapp, true)
return res.status(200).json({ message: "Starting session." });
};

View File

@ -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);
}

View File

@ -19,9 +19,9 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
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}`

View File

@ -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<Session> => {
export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean = false): Promise<Session> => {
return new Promise((resolve, reject) => {
try {
@ -63,23 +64,6 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
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();
@ -169,13 +153,16 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
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) {
if (whatsIndex !== -1 || backupSessionRestore) {
if (whatsIndex !== -1) {
backupSession.splice(whatsIndex, 1);
}
backupSession.splice(whatsIndex, 1);
setTimeout(async () => {
@ -183,6 +170,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
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<Session> => {
console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`)
}, 30000);
}, 55000);
console.log(' PASSOU NO TIMEOUT!')
console.log(' PASSOU NO TIMEOUT whatsapp.id: ',whatsapp.id)
}

View File

@ -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<void> => {
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
await whatsapp.update({ status: "OPENING" });
const io = getIO();
@ -15,7 +15,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise<void> =>
});
try {
const wbot = await initWbot(whatsapp);
const wbot = await initWbot(whatsapp, backupSession);
wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp);
} catch (err) {

View File

@ -36,7 +36,7 @@ import Queue from "../../models/Queue";
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
@ -44,6 +44,7 @@ import data_ura from './ura'
import msg_client_transfer from './ura_msg_transfer'
import final_message from "./ura_final_message";
import SendWhatsAppMessage from "./SendWhatsAppMessage";
import Whatsapp from "../../models/Whatsapp";
//
@ -179,13 +180,13 @@ const verifyQueue = async (
let selectedOption = null;
let choosenQueue = null
let choosenQueue = null
const botInfo = await BotIsOnQueue('botqueue')
if(botInfo.isOnQueue){
if (botInfo.isOnQueue) {
choosenQueue = await ShowQueueService(botInfo.botQueueId);
@ -193,27 +194,27 @@ const verifyQueue = async (
else if (queues.length === 1) {
selectedOption = 1;
choosenQueue = queues[+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, '')
///////////////////////////////////
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){
// 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 ticket.update({ status: "pending" });
}
//
@ -227,10 +228,10 @@ const verifyQueue = async (
let botOptions = ''
// O bot abre a mensagem na fila para atender o usuario
if(botInfo.isOnQueue){
if (botInfo.isOnQueue) {
await UpdateTicketService({
ticketData:{ status: 'open', userId: botInfo.userIdBot },
ticketData: { status: 'open', userId: botInfo.userIdBot },
ticketId: ticket.id
});
@ -240,10 +241,10 @@ const verifyQueue = async (
let body = ''
if(botOptions.length > 0){
if (botOptions.length > 0) {
body = `\u200e${choosenQueue.greetingMessage}\n\n${botOptions}\n${final_message.msg}`;
}
else{
else {
body = `\u200e${choosenQueue.greetingMessage}`;
}
@ -253,14 +254,14 @@ const verifyQueue = async (
} else {
//test del transfere o atendimento se entrar na ura infinita
let ticket_message = await ShowTicketMessage(ticket.id, false);
if(ticket_message.length > 10){
//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 });
await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues[0].id }, ticketId: ticket.id });
}
else{
}
else {
let options = "";
@ -281,10 +282,10 @@ const verifyQueue = async (
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 indexQueue = queues.findIndex((q) => q.id == botId)
if(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 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(
@ -353,6 +354,8 @@ const handleMessage = async (
return;
}
try {
let msgContact: WbotContact;
let groupContact: Contact | undefined;
@ -366,7 +369,7 @@ 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();
@ -398,375 +401,410 @@ const handleMessage = async (
const contact = await verifyContact(msgContact);
if ( unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
const ticket = await FindOrCreateTicketService(
contact,
wbot.id!,
unreadMessages,
groupContact
);
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)
// 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}`)
// 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
let lastOption = ''
// 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
let ura_length = data_ura.length
const botInfo = await BotIsOnQueue('botqueue')
let indexAttendant = data_ura.findIndex((u) => u.atendente)
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}`)
let opt_user_attendant = '-1'
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}}]$`);
if (ticket_message.length > 1) {
let lastOption = ''
lastOption = ticket_message[1].body
let ura_length = data_ura.length
const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId)
let indexAttendant = data_ura.findIndex((u) => u.atendente )
const queues = queuesWhatsGreetingMessage.queues
let opt_user_attendant = '-1'
if (queues.length > 1) {
if(indexAttendant != -1){
opt_user_attendant = data_ura[indexAttendant].id
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){
// Se fila for maior que 1 exibi as opções fila para atendimento humano
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')
let options = "";
if(index_opt_user_attendant != -1){
queues.forEach((queue, index) => {
if(index0 > -1 && index0 < index_opt_user_attendant){
lastOption = ''
}
else{
lastOption = opt_user_attendant
}
}
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}`)
}
}
else if (lastOption == opt_user_attendant) {
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`)
}
}
// 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
// Se fila for maior que 1 exibi as opções fila para atendimento humano
if(queues.length > 1){
let options = "";
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}`)
}
}
else if (lastOption == opt_user_attendant){
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`)
}
}
}
}
else{
// É numero
if(!Number.isNaN(Number(msg.body.trim()))){
}
else {
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`)
// É numero
if (!Number.isNaN(Number(msg.body.trim()))) {
}
else{
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`)
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 {
}
botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções\n\n*0* - Voltar ao menu principal`)
}
}
}
//
}
//
// 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)
// 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}`)
// 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)
// console.log('================sourcePath: ', sourcePath)
// console.log('================sourcePath: ', destPath)
// removeWbot(33)
// removeWbot(33)
// await removeDir(destPath)
// await removeDir(destPath)
// copyFolder(sourcePath, destPath)
// copyFolder(sourcePath, destPath)
// await StartWhatsAppSession(whatsapp);
// 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')
}
}
}
};