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

@ -29,7 +29,7 @@ function paramsQuery(params: string[]) {
//Report by user, startDate, endDate //Report by user, startDate, endDate
const ShowTicketMessage = async ( const ShowTicketMessage = async (
ticketId: string | number, ticketId: string | number,
onlyNumber: boolean = false, onlyNumber: boolean = false,
params: string[], params: string[],
fromMe?: boolean, fromMe?: boolean,
limit?: number, limit?: number,
@ -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,
@ -57,22 +57,19 @@ 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,
}
}
const ticket = await Message.findAll({ const ticket = await Message.findAll({

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";
@ -499,16 +500,7 @@ const sendDialogflowAwswer = async (
const session = await createDialogflowSessionWithModel(ticket.queue.dialogflow); const session = await createDialogflowSessionWithModel(ticket.queue.dialogflow);
if (session === undefined) { if (session === undefined) {
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') {
@ -645,20 +637,10 @@ const verifyQueue = async (
} }
else { else {
const repet: any = await mostRepeatedPhrase(ticket.id)
//test del transfere o atendimento se entrar na ura infinita
// let ticket_message = await ShowTicketMessage( if (repet.occurrences > 4) {
// 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 });
@ -968,11 +950,9 @@ const handleMessage = async (
wbot.id!, wbot.id!,
unreadMessages, unreadMessages,
// groupContact // groupContact
); );
console.log('okkkkkkkkkkkkkkkkkk 1')
// //
// await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl}) // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -1001,11 +981,7 @@ const handleMessage = async (
// console.log('>>>>>>> msg.fromMe: ',msg.fromMe ) // console.log('>>>>>>> msg.fromMe: ',msg.fromMe )
await verifyMessage(msg, ticket, contact, wbot.quotedMsg); await verifyMessage(msg, ticket, contact, wbot.quotedMsg);
} }
console.log('okkkkkkkkkkkkkkkkkk 2')
if ( if (
!ticket.queue && !ticket.queue &&
@ -1016,11 +992,7 @@ const handleMessage = async (
) { ) {
await verifyQueue(wbot, msg, ticket, contact); await verifyQueue(wbot, msg, ticket, contact);
} }
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
@ -1028,33 +1000,13 @@ const handleMessage = async (
const botInfo = await BotIsOnQueue('botqueue') const botInfo = await BotIsOnQueue('botqueue')
// 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) {
const repet: any = await mostRepeatedPhrase(ticket.id)
console.log('okkkkkkkkkkkkkkkkkk 4') console.log('repet.occurrences: ', repet.occurrences)
// // TEST DEL
// let test: any = await ShowTicketMessage(ticket.id, false, true, 5);
// console.log('okkkkkkkkkkkkkkkkkk 5 test: ', test)
//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!);
if (repet.occurrences > 4) {
await transferTicket(0, wbot, ticket, contact) await transferTicket(0, wbot, ticket, contact)
await SendWhatsAppMessage({ await SendWhatsAppMessage({