Implementação de reestore automatico para quando a sessão estiver conectada e não envia mensagem

pull/21/head
adriano 2022-11-16 10:23:14 -03:00
parent 3aae93141a
commit 74f38a82cf
8 changed files with 152 additions and 48 deletions

View File

@ -123,6 +123,9 @@ export const remove = async (
removeDir(path.join(process.cwd(), '.wwebjs_auth', `session-bd_${whatsappId}`))
removeDir(path.join(process.cwd(), '.wwebjs_auth','sessions', `session-bd_${whatsappId}`))
removeWbot(+whatsappId);
const io = getIO();

View File

@ -1,5 +1,5 @@
import { Request, Response } from "express";
import { getWbot } from "../libs/wbot";
import { getWbot, removeWbot } from "../libs/wbot";
import { removeDir } from "../helpers/DeleteDirectory";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession";
@ -56,10 +56,21 @@ const remove = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
const whatsapp = await ShowWhatsAppService(whatsappId);
const wbot = getWbot(whatsapp.id);
const wbot = getWbot(whatsapp.id);
await wbot.logout();
// TEST DEL
// removeWbot(+whatsapp.id)
// await removeDir(path.join(process.cwd(), '.wwebjs_auth', 'sessions', `session-bd_${whatsappId}`))
// console.log('REMOVEU!!!!!!!!!!!!!!!!!!!!!')
//
return res.status(200).json({ message: "Session disconnected." });
};

View File

@ -17,8 +17,8 @@ export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boo
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/`, `session-bd_${whatsapp.id}`)
const destPath = path.join(__dirname, `../../.wwebjs_auth/`, `session-bd_${whatsapp.id}`)
console.log('================sourcePath: ', sourcePath)
console.log('================destPath: ', destPath)
console.log('================> sourcePath: ', sourcePath)
console.log('================> destPath: ', destPath)
removeWbot(whatsapp.id)
@ -34,6 +34,8 @@ export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boo
console.log('RESTARTING SESSION...')
await StartWhatsAppSession(whatsapp, backupSession);
// await StartWhatsAppSession(whatsapp, backupSession);
setTimeout(() => StartWhatsAppSession(whatsapp, backupSession), 2000);
}

View File

@ -12,6 +12,7 @@ import { splitDateTime } from "./SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await Message.update(
@ -26,39 +27,38 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await ticket.update({ unreadMessages: 0 });
try {
try {
const wbot = await GetTicketWbot(ticket);
const wbot = await GetTicketWbot(ticket);
// test del
// throw new Error('Throw makes it go boom!')
//
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}`
);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {
logger.warn(`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {
const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions`)
const sourcePath = path.join(__dirname,`../../.wwebjs_auth/sessions`)
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
if (whatsapp && whatsapp.status == 'CONNECTED') {
if (whatsapp && whatsapp.status == 'CONNECTED') {
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error)=>{});
fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error) => { });
await restartWhatsSession(whatsapp)
}
}

View File

@ -0,0 +1,49 @@
import Ticket from "../models/Ticket";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
import GetTicketWbot from "./GetTicketWbot";
const sendMessageMultiSession = async (ticket: Ticket, body?: any, quotedMsgSerializedId?: any, sendSeen?: boolean) => {
let sentMessage: any = ''
const listWhatsapp: any = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
if (listWhatsapp.length > 1) {
for (let w = 0; w < listWhatsapp.length; w++) {
if(listWhatsapp[w].id == ticket.whatsappId) continue
try {
console.log('CHANGE THE WHATSAPP SESSION ID: ', listWhatsapp[w].id)
await ticket.update({ whatsappId: listWhatsapp[w].id })
const wbot = await GetTicketWbot(ticket);
if (sendSeen) {
await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);
}
else if (body) {
sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false });
}
break
} catch (error) {
console.log('Cannot send send the message using the whatsapp id: ', listWhatsapp[w].id, ' | error: ', error)
}
}
}
return sentMessage
};
export default sendMessageMultiSession;

View File

@ -160,7 +160,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
console.log(`>>>>>>>>>>>>>>>>>>>>>>>>>.. BACKUP SESSION whatsapp.id ${whatsapp.id} | backupSession: ${backupSession}`)
console.log(`>>>>>>>>>>>>>>>>>>>>>>>>> BACKUP SESSION whatsapp.id ${whatsapp.id} | backupSession: ${backupSession}`)
const whatsIndex = backupSession.findIndex((id: number) => id === +whatsapp.id);
@ -192,7 +192,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`)
}, 55000);
}, 90000);
console.log(' PASSOU NO TIMEOUT whatsapp.id: ',whatsapp.id)
@ -210,6 +210,9 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
export const getWbot = (whatsappId: number): Session => {
const sessionIndex = sessions.findIndex(s => s.id === whatsappId);
console.log('----------> sessionIndex: ', sessionIndex, ' | whatasappId: ', whatsappId)
console.log('----------> sessions: ',sessions.map(s => s.id))
if (sessionIndex === -1) {
throw new AppError("ERR_WAPP_NOT_INITIALIZED");
}

View File

@ -16,6 +16,12 @@ import { deleteTicketsByContactsCache, updateTicketCacheByTicketId } from '../..
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";
interface Request {
body: string;
@ -35,16 +41,17 @@ const SendWhatsAppMessage = async ({
}
//TEST DEL
// const whatsapp = await ShowWhatsAppService(33);
// const wbot2 = getWbot(whatsapp.id);
// await wbot2.logout();
//
let whatsapps:any
let whatsapps: any
const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
@ -64,7 +71,13 @@ const SendWhatsAppMessage = async ({
}
if (listWhatsapp.length == 0 || whatsapps !='CONNECTED') {
console.log('3 --------> ticket.whatsappId: ', ticket.whatsappId)
if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) {
whatsapps = await wbotByUserQueue(ticket.userId)
@ -87,6 +100,9 @@ const SendWhatsAppMessage = async ({
const wbot = await GetTicketWbot(ticket);
console.log('4 --------> ticket.whatsappId: ', ticket.whatsappId)
try {
const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false });
@ -96,6 +112,32 @@ const SendWhatsAppMessage = async ({
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",
});
setTimeout(() => restartWhatsSession(whatsapp, true), 90000);
}
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");
}
};

View File

@ -369,30 +369,24 @@ const handleMessage = async (
wbot: Session
): Promise<void> => {
// TEST DEL MULTI SESSION
// TEST DEL MULTI SESSION
if (!msg.id.fromMe) {
let index = lst.findIndex((x: any) => x.id == msg.id.id)
console.log('INDEX: ', index)
if (index == -1) {
lst.push({ id: msg.id.id })
}
else {
console.log('IGNORED ID: ', msg.id.id)
return
}
// let index = lst.findIndex((x: any) => x.id == msg.id.id)
// console.log('INDEX: ', index)
// if (index == -1) {
// lst.push({id: msg.id.id})
// }
// else{
// console.log('IGNORED ID: ', msg.id.id)
// return
// }
// console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id)
console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id)
// const contact_message = await getLastId(`contact_message:5517988310949`)