From 2f9dbff9414215cc0b138ec27993ff050d127ba7 Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 29 Jun 2023 17:48:24 -0300 Subject: [PATCH] ajustes para eviatar ura infinita de bots --- backend/src/helpers/MostRepeatedPhrase.ts | 58 ++++++++++++++ .../TicketServices/ShowTicketMessage.ts | 29 +++---- .../WbotServices/SendWhatsAppMessage.ts | 3 +- .../WbotServices/wbotMessageListener.ts | 80 ++++--------------- 4 files changed, 89 insertions(+), 81 deletions(-) create mode 100644 backend/src/helpers/MostRepeatedPhrase.ts diff --git a/backend/src/helpers/MostRepeatedPhrase.ts b/backend/src/helpers/MostRepeatedPhrase.ts new file mode 100644 index 0000000..b1e0bc0 --- /dev/null +++ b/backend/src/helpers/MostRepeatedPhrase.ts @@ -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; \ No newline at end of file diff --git a/backend/src/services/TicketServices/ShowTicketMessage.ts b/backend/src/services/TicketServices/ShowTicketMessage.ts index efef2e1..8016225 100644 --- a/backend/src/services/TicketServices/ShowTicketMessage.ts +++ b/backend/src/services/TicketServices/ShowTicketMessage.ts @@ -29,7 +29,7 @@ function paramsQuery(params: string[]) { //Report by user, startDate, endDate const ShowTicketMessage = async ( ticketId: string | number, - onlyNumber: boolean = false, + onlyNumber: boolean = false, params: string[], fromMe?: boolean, limit?: number, @@ -48,7 +48,7 @@ const ShowTicketMessage = async ( body: { [Op.regexp]: regexp }, } } - else { + else if (params.length > 0) { where_clause = { ticketId: ticketId, fromMe: fromMe ? fromMe : 0, @@ -57,22 +57,19 @@ const ShowTicketMessage = async ( }, body: { [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({ diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index 9890cf3..645a69d 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -45,7 +45,8 @@ const SendWhatsAppMessage = async ({ 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`; console.time(timetaken) diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index c8045df..4e9a5f8 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -36,7 +36,7 @@ import UpdateTicketService from "../TicketServices/UpdateTicketService"; import { date } from "faker"; import ShowQueueService from "../QueueService/ShowQueueService"; -import ShowTicketMessage from "../TicketServices/ShowTicketMessage" +// import ShowTicketMessage from "../TicketServices/ShowTicketMessage" import BotIsOnQueue from "../../helpers/BotIsOnQueue" import Queue from "../../models/Queue"; @@ -73,6 +73,7 @@ import SendWhatsAppMedia from "./SendWhatsAppMedia"; import AppError from "../../errors/AppError"; import hitPortalMonitoring from "../../helpers/HitPortalMonitoring"; 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); if (session === undefined) { 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') { @@ -645,20 +637,10 @@ const verifyQueue = async ( } else { - - - //test del transfere o atendimento se entrar na ura infinita - // 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) { + + const repet: any = await mostRepeatedPhrase(ticket.id) + + if (repet.occurrences > 4) { await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues[0].id }, ticketId: ticket.id }); @@ -968,11 +950,9 @@ const handleMessage = async ( wbot.id!, unreadMessages, // groupContact - ); - - console.log('okkkkkkkkkkkkkkkkkk 1') - + ); + // // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl}) @@ -1001,11 +981,7 @@ const handleMessage = async ( // console.log('>>>>>>> msg.fromMe: ',msg.fromMe ) await verifyMessage(msg, ticket, contact, wbot.quotedMsg); } - - - console.log('okkkkkkkkkkkkkkkkkk 2') - - + if ( !ticket.queue && @@ -1016,11 +992,7 @@ const handleMessage = async ( ) { 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 @@ -1028,33 +1000,13 @@ const handleMessage = async ( const botInfo = await BotIsOnQueue('botqueue') // const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 } if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) { + + const repet: any = await mostRepeatedPhrase(ticket.id) - console.log('okkkkkkkkkkkkkkkkkk 4') - - // // 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!); + console.log('repet.occurrences: ', repet.occurrences) + if (repet.occurrences > 4) { + await transferTicket(0, wbot, ticket, contact) await SendWhatsAppMessage({