Atualização para funcionamento com varias sessoes

pull/20/head
adriano 2023-04-18 16:30:19 -03:00
parent 48f6943ece
commit 626264d568
5 changed files with 175 additions and 64 deletions

View File

@ -50,7 +50,7 @@ export const hit = async (req: Request, res: Response): Promise<Response> => {
try {
console.log('THE CONTACT: ', contact)
console.log('atdfechou ----------> THE CONTACT: ', contact)
if (contact) {
@ -123,10 +123,53 @@ export const hit = async (req: Request, res: Response): Promise<Response> => {
}
else if (req.body['action'] === 'atdatualizou') {
console.log('status: atdatualizou --------------> contact: ', contact)
if (contact) {
try {
let response = await hitPortalMonitoring(req.body['centro_custo'])
if (!response || response.length == 0) {
console.log('Empty result from hit portal monitoring. Centro_de_custo: ', req.body['centro_custo'])
return res.status(200).json({ "message": "Ok" });
}
const botInfo = await BotIsOnQueue('botqueue')
let ticket = await ShowTicketServiceByContactId(contact['contact.id'])
if (ticket.id && ticket.status == 'pending') {
await sendMessageHitMonitoring(`*Olá. Somos a TI Espaçolaser.*\nAtualização do chamado para sua loja ${contact['contact.name']}. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket);
}
else if (!ticket.id) {
ticket = await CreateTicketService({ contactId: contact['contact.id'], status: 'open', userId: botInfo.userIdBot });
console.log('botInfo.botQueueId: ', botInfo.botQueueId)
await UpdateTicketService({ ticketData: { queueId: botInfo.botQueueId }, ticketId: ticket.id });
await sendMessageHitMonitoring(`*Olá. Somos a TI Espaçolaser.*\nAtualização do chamado para sua loja ${contact['contact.name']}. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket);
}
} catch (error) {
console.log(`Error on try sending the message monitor: `, error)
}
}
}
else {
console.log('--------------> contact: ', contact)
console.log('status: atdatabriu --------------> contact: ', contact)
if (contact) {

View File

@ -2,14 +2,14 @@ import { getIO } from "../libs/socket";
import Ticket from "../models/Ticket";
function sendWhatsAppMessageSocket(ticket: Ticket, body: string, quotedMsgSerializedId?: string | undefined) {
function sendWhatsAppMessageSocket(ticket: Ticket, body: string, quotedMsgSerializedId?: string | undefined, number?: string ) {
const io = getIO();
io.to(`session_${ticket.whatsappId.toString()}`).emit("send_message", {
action: "create",
msg: {
number: `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`,
number: number ? number : `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`,
body: body,
quotedMessageId: quotedMsgSerializedId,
linkPreview: false

View File

@ -11,7 +11,7 @@ import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import sendWhatsAppMediaSocket from "../../helpers/SendWhatsappMessageMediaSocket";
interface Request {
media: Express.Multer.File;
media: Express.Multer.File | any;
ticket: Ticket;
}

View File

@ -33,12 +33,14 @@ interface Request {
body: string;
ticket: Ticket;
quotedMsg?: Message;
number?: string
}
const SendWhatsAppMessage = async ({
body,
ticket,
quotedMsg
quotedMsg,
number
}: Request): Promise<WbotMessage | any> => {
let timestamp = Math.floor(Date.now() / 1000)
@ -163,7 +165,7 @@ const SendWhatsAppMessage = async ({
try {
sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId);
sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId, number);
await ticket.update({ lastMessage: body });

View File

@ -69,6 +69,7 @@ import autoRestore from "../../helpers/AutoRestore";
import { _restore } from "../../helpers/RestoreControll";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl";
import SendWhatsAppMedia from "./SendWhatsAppMedia";
@ -279,27 +280,40 @@ const monitoramento_response2 = async (response: any | null, wbot: any, contact:
if (!response) {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Houve um erro ao tentar consultar o monitoramento da Operadora!${final_message}`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Houve um erro ao tentar consultar o monitoramento da Operadora!${final_message}`);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: `Houve um erro ao tentar consultar o monitoramento da Operadora!${final_message}`, ticket, number: `${contact.number}@c.us` })
}
else if (response.length > 0) {
for (let i = 0; i < response.length; i++) {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body}${final_message}`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body}${final_message}`);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: `*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body}${final_message}`, ticket, number: `${contact.number}@c.us` })
}
}
else if (send_empty_incident) {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Conforme Monitoramento a internet da unidade está operacional${final_message}`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Conforme Monitoramento a internet da unidade está operacional${final_message}`);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: `Conforme Monitoramento a internet da unidade está operacional${final_message}`, ticket, number: `${contact.number}@c.us` })
}
@ -318,9 +332,14 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
if (msgAction.actions[0] == 'request_endpoint') {
const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
await verifyMessage(sentMessage, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
// await verifyMessage(sentMessage, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` })
// const url = 'https://sos.espacolaser.com.br/api/whatsapps/ticket/R32656'
let endPointResponse = await endPointQuery(msgAction.actions[1], 'get')
@ -368,16 +387,28 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
const itsm_response = async (message1: string = '', message2: string = '') => {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*${message1}${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*${message1}${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*${message1}${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`, ticket, number: `${contact.number}@c.us` })
}
const sendMessageBot = async (message1: string = '', message2: string = '') => {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `${message1}${message2}`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `${message1}${message2}`);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: `${message1}${message2}`, ticket, number: `${contact.number}@c.us` })
}
@ -500,9 +531,13 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
console.log('************* contact_custom_field: ', contact_custom_field)
const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` })
await transferTicket(+msgAction.actions[1], wbot, ticket, contact)
}
@ -510,9 +545,13 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
const sourcePath = path.join(__dirname, `../../../public/bot`)
const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
// await verifyMessage(msg, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// // NEW
await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` })
await botSendMedia(ticket, contact, wbot, sourcePath, msgAction.actions[1])
@ -521,9 +560,16 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
}
else {
// const linesOfBody = body.split('\n');
const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body);
await verifyMessage(sentMessage, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
// OLD
// const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body);
// await verifyMessage(sentMessage, ticket, contact);
// await new Promise(f => setTimeout(f, 1000));
// NEW
sendWhatsAppMessageSocket(ticket, body)
// for(let message of linesOfBody) {
// const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, message);
@ -555,12 +601,16 @@ const sendDialogflowAwswer = async (
return;
}
// Make disponible later from session out
// wbot.sendPresenceAvailable();
// console.log('(msg: ', msg )
// console.log('typeof(msg.type): ', typeof (msg.type), ' | msg.type: ', msg.type)
// console.log('KKKKKKKKK msg: ', msg)
// console.log('KKKKKKKKK msg2: ', msg['body'])
if (msg.type != 'chat') {
botSendMessage(ticket, contact, wbot, `Desculpe, nao compreendi!\nEnvie apenas texto quando estiver interagindo com o bot!\n _Digite *0* para voltar ao menu principal._`)
return
@ -582,7 +632,8 @@ const sendDialogflowAwswer = async (
return;
}
chat.sendStateTyping();
// Make disponible later from session out
// chat.sendStateTyping();
await new Promise(f => setTimeout(f, 1000));
@ -820,21 +871,18 @@ const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: Session, med
async () => {
// const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, newMedia, { sendAudioAsVoice: true });
const newMedia = MessageMedia.fromFilePath(`${mediaPath}/${fileNameExtension}`);
const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia, { caption: 'this is my caption' });
const media = { path: `${mediaPath}/${fileNameExtension}` }
// OLD
// const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia, { caption: 'this is my caption' });
// await ticket.update({ lastMessage: fileNameExtension });
// verifyMessage(sentMessage, ticket, contact);
// NEW
await SendWhatsAppMedia({ media: media.path, ticket })
// client.sendMessage("xxxxxxxx@c.us", media, {caption: "some caption"}); })();
// client.sendMessage(msg.from, attachmentData, { caption: 'Here\'s your requested media.' });
await ticket.update({ lastMessage: fileNameExtension });
verifyMessage(sentMessage, ticket, contact);
},
3000,
@ -851,8 +899,12 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st
const debouncedSentMessage = debounce(
async () => {
const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, `${msg}`);
verifyMessage(sentMessage, ticket, contact);
//OLD
// const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, `${msg}`);
// verifyMessage(sentMessage, ticket, contact);
//NEW
await SendWhatsAppMessage({ body: msg, ticket })
},
3000,
ticket.id
@ -1008,6 +1060,9 @@ const handleMessage = async (
// groupContact
);
console.log('okkkkkkkkkkkkkkkkkk 1')
//
// await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -1031,6 +1086,10 @@ const handleMessage = async (
}
console.log('okkkkkkkkkkkkkkkkkk 2')
if (
!ticket.queue &&
!chat.isGroup &&
@ -1043,6 +1102,7 @@ const handleMessage = async (
console.log('okkkkkkkkkkkkkkkkkk 3')
// 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
@ -1052,10 +1112,14 @@ const handleMessage = async (
// const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 }
if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) {
console.log('okkkkkkkkkkkkkkkkkk 4')
// TEST DEL
let test: any = await ShowTicketMessage(ticket.id, false, true, 5);
if (test[0].body.includes('Se deseja solicitar atendimento de urgência, digite *1*') && msg.body == '1') {
console.log('okkkkkkkkkkkkkkkkkk 5 test: ', test)
if (test && test.length > 0 && test[0].body.includes('Se deseja solicitar atendimento de urgência, digite *1*') && msg.body == '1') {
console.log('===================================> ENDPOINT REQUEST')
@ -1084,6 +1148,8 @@ const handleMessage = async (
}
//
console.log('okkkkkkkkkkkkkkkkkk 6')
await sendDialogflowAwswer(wbot, ticket, msg, contact, chat);
}