ajustes para eviatar ura infinita de bots

pull/20/head
adriano 2023-06-29 17:48:24 -03:00
parent 3568bf1461
commit 2f9dbff941
4 changed files with 89 additions and 81 deletions

View File

@ -0,0 +1,58 @@
import { subSeconds } from "date-fns";
import Message from "../models/Message";
import { Op, Sequelize } from "sequelize";
const mostRepeatedPhrase = async (ticketId: number | string, fromMe: boolean = false) => {
let res: any = { body: '', occurrences: 0 }
try {
const mostRepeatedPhrase: any = await Message.findOne({
where: {
ticketId: ticketId,
fromMe: fromMe ? fromMe : 0,
body: {
[Op.notRegexp]: '^[0-9]+$',
},
updatedAt: {
[Op.between]: [+subSeconds(new Date(), 150), +new Date()],
},
},
attributes: [
'body',
[Sequelize.fn('COUNT', Sequelize.col('body')), 'occurrences'],
],
group: ['body'],
order: [[Sequelize.literal('occurrences'), 'DESC']],
limit: 1,
});
if (mostRepeatedPhrase) {
const { body, occurrences } = mostRepeatedPhrase.get();
console.log(`The most repeated phrase is "${body}" with ${occurrences} occurrences.`);
const isNumber = /^\d+$/.test(body.trim());
if (!isNumber) {
return { body, occurrences }
}
} else {
console.log('No phrases found.');
}
} catch (error) {
console.log('error on MostRepeatedPhrase: ', error)
}
return { body: '', occurrences: 0 }
}
export default mostRepeatedPhrase;

View File

@ -48,7 +48,7 @@ const ShowTicketMessage = async (
body: { [Op.regexp]: regexp }, body: { [Op.regexp]: regexp },
} }
} }
else { else if (params.length > 0) {
where_clause = { where_clause = {
ticketId: ticketId, ticketId: ticketId,
fromMe: fromMe ? fromMe : 0, fromMe: fromMe ? fromMe : 0,
@ -58,20 +58,17 @@ const ShowTicketMessage = async (
body: { body: {
[Op.or]: paramsQuery(params) [Op.or]: paramsQuery(params)
} }
// body: {
// [Op.or]: [
// {
// [Op.like]: '%não compreendi%'
// },
// {
// [Op.like]: '%não captei%'
// },
// {
// [Op.like]: '%Não consegui compreender%'
// }
// ]
// },
} }
}
else if (params.length === 0) {
where_clause = {
ticketId: ticketId,
fromMe: fromMe ? fromMe : 0,
}
} }

View File

@ -45,7 +45,8 @@ const SendWhatsAppMessage = async ({
try { try {
let timestamp = Math.floor(Date.now() / 1000) // let timestamp = Math.floor(Date.now() / 1000)
let timestamp = Date.now() +String(Math.floor(Math.random() * 1000))
var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`; var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`;
console.time(timetaken) console.time(timetaken)

View File

@ -36,7 +36,7 @@ import UpdateTicketService from "../TicketServices/UpdateTicketService";
import { date } from "faker"; import { date } from "faker";
import ShowQueueService from "../QueueService/ShowQueueService"; import ShowQueueService from "../QueueService/ShowQueueService";
import ShowTicketMessage from "../TicketServices/ShowTicketMessage" // import ShowTicketMessage from "../TicketServices/ShowTicketMessage"
import BotIsOnQueue from "../../helpers/BotIsOnQueue" import BotIsOnQueue from "../../helpers/BotIsOnQueue"
import Queue from "../../models/Queue"; import Queue from "../../models/Queue";
@ -73,6 +73,7 @@ import SendWhatsAppMedia from "./SendWhatsAppMedia";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import hitPortalMonitoring from "../../helpers/HitPortalMonitoring"; import hitPortalMonitoring from "../../helpers/HitPortalMonitoring";
import { tr } from "date-fns/locale"; import { tr } from "date-fns/locale";
import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase";
@ -501,15 +502,6 @@ const sendDialogflowAwswer = async (
return; return;
} }
// Make disponible later from session out
// wbot.sendPresenceAvailable();
// 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') { 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._`) botSendMessage(ticket, contact, wbot, `Desculpe, nao compreendi!\nEnvie apenas texto quando estiver interagindo com o bot!\n _Digite *0* para voltar ao menu principal._`)
@ -646,19 +638,9 @@ const verifyQueue = async (
} }
else { else {
const repet: any = await mostRepeatedPhrase(ticket.id)
//test del transfere o atendimento se entrar na ura infinita if (repet.occurrences > 4) {
// let ticket_message = await ShowTicketMessage(
// ticket.id,
// false);
let ticket_message = await ShowTicketMessage(ticket.id, false, [],);
console.log('ticket_message.length ', ticket_message.length)
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 });
@ -970,8 +952,6 @@ const handleMessage = async (
// groupContact // groupContact
); );
console.log('okkkkkkkkkkkkkkkkkk 1')
// //
// await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl}) // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -1003,10 +983,6 @@ const handleMessage = async (
} }
console.log('okkkkkkkkkkkkkkkkkk 2')
if ( if (
!ticket.queue && !ticket.queue &&
!chat.isGroup && !chat.isGroup &&
@ -1018,10 +994,6 @@ 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 // 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
//Habilitar esse caso queira usar o bot //Habilitar esse caso queira usar o bot
@ -1029,31 +1001,11 @@ const handleMessage = async (
// const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 } // const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 }
if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) { if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) {
console.log('okkkkkkkkkkkkkkkkkk 4') const repet: any = await mostRepeatedPhrase(ticket.id)
// // TEST DEL console.log('repet.occurrences: ', repet.occurrences)
// let test: any = await ShowTicketMessage(ticket.id, false, true, 5);
// console.log('okkkkkkkkkkkkkkkkkk 5 test: ', test) if (repet.occurrences > 4) {
//test del transfere o atendimento se entrar na ura infinita
let ticket_message = await ShowTicketMessage(
ticket.id, false,
['não compreendi', 'não captei', 'Não consegui compreender'],
true);
let ticket_message2 = await ShowTicketMessage(
ticket.id, false,
['favor informe o',],
true);
// console.log('=========> ticket_message ', ticket_message)
console.log('ticket_message.length ', ticket_message.length)
if (ticket_message.length > 3 || ticket_message2.length > 3) {
// const { queues, } = await ShowWhatsAppService(wbot.id!);
await transferTicket(0, wbot, ticket, contact) await transferTicket(0, wbot, ticket, contact)