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

@ -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";
//
@ -185,7 +186,7 @@ const verifyQueue = async (
const botInfo = await BotIsOnQueue('botqueue')
if(botInfo.isOnQueue){
if (botInfo.isOnQueue) {
choosenQueue = await ShowQueueService(botInfo.botQueueId);
@ -195,7 +196,7 @@ const verifyQueue = async (
selectedOption = 1;
choosenQueue = queues[+selectedOption - 1];
}
else{
else {
selectedOption = msg.body;
@ -211,9 +212,9 @@ const verifyQueue = async (
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){
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}`;
}
@ -255,12 +256,12 @@ const verifyQueue = async (
//test del transfere o atendimento se entrar na ura infinita
let ticket_message = await ShowTicketMessage(ticket.id, false);
if(ticket_message.length > 10){
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 = "";
@ -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;
@ -398,7 +401,7 @@ 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,
@ -414,7 +417,7 @@ const handleMessage = async (
// console.log('>>>>>>>>>>>>>> ticket.whatsappId: ', ticket.whatsappId)
// Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen
if(wbot.id != ticket.whatsappId){
if (wbot.id != ticket.whatsappId) {
await ticket.update({ whatsappId: wbot.id });
}
//
@ -444,10 +447,10 @@ const handleMessage = async (
const botInfo = await BotIsOnQueue('botqueue')
if( botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot){
if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) {
if(msg.body === '0'){
if (msg.body === '0') {
const queue = await ShowQueueService(ticket.queue.id);
@ -460,7 +463,7 @@ const handleMessage = async (
botSendMessage(ticket, contact, wbot, `${greetingMessage}\n\n${options}\n${final_message.msg}`)
}
else{
else {
// Pega as ultimas 9 opções numericas digitadas pelo cliente em orde DESC
@ -471,11 +474,11 @@ const handleMessage = async (
let ura_length = data_ura.length
let indexAttendant = data_ura.findIndex((u) => u.atendente )
let indexAttendant = data_ura.findIndex((u) => u.atendente)
let opt_user_attendant = '-1'
if(indexAttendant != -1){
if (indexAttendant != -1) {
opt_user_attendant = data_ura[indexAttendant].id
}
@ -483,7 +486,7 @@ const handleMessage = async (
let ticket_message = await ShowTicketMessage(ticket.id, true, ura_length, `^[0-${ura_length}}]$`);
if(ticket_message.length > 1){
if (ticket_message.length > 1) {
lastOption = ticket_message[1].body
@ -491,17 +494,17 @@ const handleMessage = async (
const queues = queuesWhatsGreetingMessage.queues
if(queues.length > 1){
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 (index_opt_user_attendant != -1) {
if(index0 > -1 && index0 < index_opt_user_attendant){
if (index0 > -1 && index0 < index_opt_user_attendant) {
lastOption = ''
}
else{
else {
lastOption = opt_user_attendant
}
}
@ -518,15 +521,15 @@ const handleMessage = async (
//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) ) {
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 (indexUra != -1) {
if(data_ura[indexUra].id != opt_user_attendant && lastOption != opt_user_attendant){
if (data_ura[indexUra].id != opt_user_attendant && lastOption != opt_user_attendant) {
@ -535,15 +538,15 @@ const handleMessage = async (
// test del
let next = true
let indexAux = ticket_message.findIndex((e)=>e.body=='0')
let indexAux = ticket_message.findIndex((e) => e.body == '0')
let listMessage = null
if(indexAux!=-1){
if (indexAux != -1) {
listMessage = ticket_message.slice(0, indexAux)
}
else{
else {
listMessage = ticket_message
@ -552,12 +555,12 @@ const handleMessage = async (
let id = ''
let subUra = null
if(listMessage.length > 1){
if (listMessage.length > 1) {
id = listMessage[listMessage.length-1].body
subUra = data_ura.filter((e)=>e.id == id )[0]
id = listMessage[listMessage.length - 1].body
subUra = data_ura.filter((e) => e.id == id)[0]
if(subUra && (!subUra.subOptions || subUra.subOptions.length == 0)){
if (subUra && (!subUra.subOptions || subUra.subOptions.length == 0)) {
listMessage.pop()
@ -566,22 +569,22 @@ const handleMessage = async (
}
if(listMessage.length > 1){
if (listMessage.length > 1) {
id = listMessage[listMessage.length-1].body
subUra = data_ura.filter((e)=>e.id == id )[0]
id = listMessage[listMessage.length - 1].body
subUra = data_ura.filter((e) => e.id == id)[0]
if(subUra.subOptions && subUra.subOptions.length > 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 (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= subUra.subOptions?.length) && subUra.subOptions) {
if(subUra.subOptions[+msg.body - 1].responseToClient){
if (subUra.subOptions[+msg.body - 1].responseToClient) {
botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].responseToClient}`)
}
else{
else {
botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].subOpt}`)
}
@ -589,18 +592,18 @@ const handleMessage = async (
const queues = queuesWhatsGreetingMessage.queues
if(queues.length>0){
if (queues.length > 0) {
await botTransferTicket(queues[0], ticket, contact, wbot)
}
else{
else {
console.log('NO QUEUE!')
}
}
else{
else {
let options = "";
let subOptions:any[] = subUra.subOptions
let subOptions: any[] = subUra.subOptions
subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` });
@ -616,12 +619,12 @@ const handleMessage = async (
//
if(next){
if(data_ura[indexUra].subOptions && data_ura[indexUra].subOptions.length > 0){
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 subOptions: any[] = data_ura[indexUra].subOptions
let description = data_ura[indexUra].description
subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` });
@ -631,14 +634,14 @@ const handleMessage = async (
botSendMessage(ticket, contact, wbot, `*${option}*\n\n${body}\n\n *0* - Voltar ao menu principal`)
}
else{
else {
//test del deletar isso (Usar somente na hit)
if(data_ura[indexUra].closeChat){
if (data_ura[indexUra].closeChat) {
const {ticket :res} = await UpdateTicketService({
ticketData:{'status': 'closed', 'userId': botInfo.userIdBot}, ticketId: ticket.id
const { ticket: res } = await UpdateTicketService({
ticketData: { 'status': 'closed', 'userId': botInfo.userIdBot }, ticketId: ticket.id
});
///////////////////////////////
@ -652,7 +655,7 @@ const handleMessage = async (
///////////////////////////////
}
else{
else {
botSendMessage(ticket, contact, wbot, `${data_ura[indexUra].description}\n\n *0* - Voltar ao menu principal`)
}
//
@ -664,14 +667,14 @@ const handleMessage = async (
}
}
else if(data_ura[indexUra].id == opt_user_attendant){
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){
if (queues.length > 1) {
let options = "";
@ -686,7 +689,7 @@ const handleMessage = async (
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){
else if (queues.length == 1) {
await botTransferTicket(queues[0], ticket, contact, wbot)
@ -694,20 +697,20 @@ const handleMessage = async (
}
}
else if (lastOption == opt_user_attendant){
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) ) {
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{
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`)
@ -718,15 +721,15 @@ const handleMessage = async (
}
}
else{
else {
// É numero
if(!Number.isNaN(Number(msg.body.trim()))){
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{
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`)
@ -741,6 +744,17 @@ const handleMessage = async (
//
// 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)
@ -767,6 +781,30 @@ const handleMessage = async (
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')
}
}
}
};