feat: ura bot by connected whatsapp number

gertec
adriano 2024-05-31 12:00:06 -03:00
parent 0866cbce79
commit 1d78de9dc9
2 changed files with 243 additions and 161 deletions

View File

@ -6,144 +6,162 @@ import Ticket from "../../models/Ticket";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService"; import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import { userInfo } from "os"; import { userInfo } from "os";
import ShowQueueService from "../QueueService/ShowQueueService"; import ShowQueueService from "../QueueService/ShowQueueService";
import UpdateTicketService from "./UpdateTicketService"; import UpdateTicketService from "./UpdateTicketService";
import { getSettingValue } from "../../helpers/WhaticketSettings";
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
const FindOrCreateTicketServiceBot = async ( const FindOrCreateTicketServiceBot = async (
contact: Contact, contact: Contact,
whatsappId: number, whatsappId: number,
unreadMessages: number, unreadMessages: number,
groupContact?: Contact groupContact?: Contact
): Promise<any> => { ): Promise<any> => {
try {
// let ticket = await Ticket.findOne({
// where: {
// status: {
// [Op.or]: ["open", "pending", "queueChoice"]
// },
// contactId: groupContact ? groupContact.id : contact.id
// }
// });
try { let ticket;
let ticket = await Ticket.findOne({ if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
where: { let whats = await ListWhatsAppsNumber(whatsappId);
status: {
[Op.or]: ["open", "pending", "queueChoice"] ticket = await Ticket.findOne({
}, where: {
contactId: groupContact ? groupContact.id : contact.id status: {
} [Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id,
whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) }
}
});
} else {
ticket = await Ticket.findOne({
where: {
status: {
[Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id
}
});
}
const { queues, greetingMessage, phoneNumberId } =
await ShowWhatsAppService(whatsappId);
//Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue("botqueue");
// const botInfo = { isOnQueue: false }
if (ticket) {
await ticket.update({ unreadMessages });
}
// if (!ticket && groupContact) {
// ticket = await Ticket.findOne({
// where: {
// contactId: groupContact.id
// },
// order: [["updatedAt", "DESC"]]
// });
// if (ticket) {
// await ticket.update({
// status: "pending",
// userId: null,
// unreadMessages
// });
// }
// }
if (!ticket && !groupContact) {
console.log("BOT CREATING OR REOPENING THE TICKET");
ticket = await Ticket.findOne({
where: {
contactId: contact.id,
userId: botInfo.userIdBot,
whatsappId: whatsappId
},
order: [["updatedAt", "DESC"]]
});
if (ticket) {
await ticket.update({
status: "open",
userId: botInfo.userIdBot,
unreadMessages
}); });
const { queues, greetingMessage, phoneNumberId } = console.log("lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
await ShowWhatsAppService(whatsappId);
await dialogFlowStartContext(contact, ticket, botInfo);
//Habilitar esse caso queira usar o bot }
const botInfo = await BotIsOnQueue('botqueue')
// const botInfo = { isOnQueue: false }
if (ticket) {
await ticket.update({ unreadMessages });
}
// if (!ticket && groupContact) {
// ticket = await Ticket.findOne({
// where: {
// contactId: groupContact.id
// },
// order: [["updatedAt", "DESC"]]
// });
// if (ticket) {
// await ticket.update({
// status: "pending",
// userId: null,
// unreadMessages
// });
// }
// }
if (!ticket && !groupContact) {
console.log('BOT CREATING OR REOPENING THE TICKET')
ticket = await Ticket.findOne({
where: {
contactId: contact.id,
userId: botInfo.userIdBot
},
order: [["updatedAt", "DESC"]]
});
if (ticket) {
await ticket.update({
status: "open",
userId: botInfo.userIdBot,
unreadMessages
});
console.log('lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
await dialogFlowStartContext(contact, ticket, botInfo);
}
}
let created = false
if (!ticket) {
created = true
let status = "open"
if (queues.length > 1 && !botInfo.isOnQueue) {
status = "queueChoice"
}
ticket = await Ticket.create({
contactId: groupContact ? groupContact.id : contact.id,
status: status,
userId: botInfo.userIdBot,
isGroup: !!groupContact,
unreadMessages,
whatsappId,
phoneNumberId
});
console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy')
await dialogFlowStartContext(contact, ticket, botInfo);
}
ticket = await ShowTicketService(ticket.id);
return { ticket, created };
} catch (error: any) {
console.error('===> Error on FindOrCreateTicketServiceBot.ts file: \n', error)
throw new AppError(error.message);
} }
let created = false;
if (!ticket) {
created = true;
let status = "open";
if (queues.length > 1 && !botInfo.isOnQueue) {
status = "queueChoice";
}
ticket = await Ticket.create({
contactId: groupContact ? groupContact.id : contact.id,
status: status,
userId: botInfo.userIdBot,
isGroup: !!groupContact,
unreadMessages,
whatsappId,
phoneNumberId
});
console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
await dialogFlowStartContext(contact, ticket, botInfo);
}
ticket = await ShowTicketService(ticket.id);
return { ticket, created };
} catch (error: any) {
console.error(
"===> Error on FindOrCreateTicketServiceBot.ts file: \n",
error
);
throw new AppError(error.message);
}
}; };
export default FindOrCreateTicketServiceBot; export default FindOrCreateTicketServiceBot;
async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo: any) { async function dialogFlowStartContext(
contact: Contact,
ticket: Ticket,
botInfo: any
) {
let msg: any = { type: "chat", from: `${contact.number}@c.us`, body: "0" };
let msg: any = { type: 'chat', from: `${contact.number}@c.us`, body: '0' }; let queue = await ShowQueueService(botInfo.botQueueId);
let queue = await ShowQueueService(botInfo.botQueueId); await UpdateTicketService({
ticketData: { queueId: queue.id },
ticketId: ticket.id
});
await UpdateTicketService({ ticket = await ShowTicketService(ticket.id);
ticketData: { queueId: queue.id },
ticketId: ticket.id
});
ticket = await ShowTicketService(ticket.id); // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
// await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
} }

View File

@ -184,7 +184,11 @@ const verifyMediaMessage = async (
phoneNumberId: msg?.phoneNumberId, phoneNumberId: msg?.phoneNumberId,
fromAgent: false fromAgent: false
}; };
if(messageData.mediaType === 'video' || messageData.mediaType === 'audio' && getSettingValue('blockAudioVideoMedia')?.value === 'enabled'){ if (
messageData.mediaType === "video" ||
(messageData.mediaType === "audio" &&
getSettingValue("blockAudioVideoMedia")?.value === "enabled")
) {
mediaAuthorized = false; mediaAuthorized = false;
} }
if (msg?.fromMe) { if (msg?.fromMe) {
@ -201,35 +205,48 @@ const verifyMediaMessage = async (
body: media.filename body: media.filename
}; };
} }
if(mediaAuthorized){ if (mediaAuthorized) {
try { try {
await writeFileAsync( await writeFileAsync(
join(__dirname, "..", "..", "..", "..", "..", "public", media.filename), join(
__dirname,
"..",
"..",
"..",
"..",
"..",
"public",
media.filename
),
media.data, media.data,
"base64" "base64"
); );
} catch (err) { } catch (err) {
Sentry.captureException(err); Sentry.captureException(err);
logger.error(`There was an error: wbotMessageLitener.ts: ${err}`); logger.error(`There was an error: wbotMessageLitener.ts: ${err}`);
} }
} }
} }
if(mediaAuthorized){ if (mediaAuthorized) {
await ticket.update({ lastMessage: msg.body || media.filename }); await ticket.update({ lastMessage: msg.body || media.filename });
const newMessage = await CreateMessageService({ messageData }); const newMessage = await CreateMessageService({ messageData });
return newMessage; return newMessage;
}else{ } else {
if (ticket.status !== "queueChoice") { if (ticket.status !== "queueChoice") {
botSendMessage( botSendMessage(
ticket, ticket,
`Atenção! Mensagem ignorada, tipo de mídia não suportado.` `Atenção! Mensagem ignorada, tipo de mídia não suportado.`
); );
} }
messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`; messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`;
messageData.mediaUrl = ''; messageData.mediaUrl = "";
await ticket.update({ lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`}); await ticket.update({
const newMessage = await CreateMessageService({ messageData }); lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`
console.log(`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`) });
const newMessage = await CreateMessageService({ messageData });
console.log(
`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`
);
} }
}; };
@ -318,12 +335,15 @@ const verifyMessage = async (
quotedMsgId: quotedMsg, quotedMsgId: quotedMsg,
phoneNumberId: msg?.phoneNumberId phoneNumberId: msg?.phoneNumberId
}; };
if (msg?.fromMe) { if (msg?.fromMe) {
const botInfo = await BotIsOnQueue("botqueue"); const botInfo = await BotIsOnQueue("botqueue");
if (botInfo.isOnQueue) { if (botInfo.isOnQueue) {
const ura: any = await get({ key: "ura" }); let whatsapp = await whatsappCache(ticket.whatsappId);
const ura: any = await get({
key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
});
if (ura && !ura.includes(JSON.stringify(msg?.body))) { if (ura && !ura.includes(JSON.stringify(msg?.body))) {
messageData = { ...messageData, fromAgent: true }; messageData = { ...messageData, fromAgent: true };
@ -341,7 +361,7 @@ const verifyMessage = async (
} else { } else {
messageData = { ...messageData, body: JSON.stringify(msg.vCards) }; messageData = { ...messageData, body: JSON.stringify(msg.vCards) };
} }
} }
await CreateMessageService({ messageData }); await CreateMessageService({ messageData });
}; };
@ -399,12 +419,17 @@ const verifyQueue = async (
ticketId: ticket.id ticketId: ticket.id
}); });
const data = await get({ key: "ura", parse: true }); const whatsapp = await whatsappCache(ticket.whatsappId);
const data = await get({
key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
parse: true
});
await createObject({ await createObject({
whatsappId: `${ticket.whatsappId}`, whatsappId: `${ticket.whatsappId}`,
contactId: `${ticket.contactId}`, contactId: `${ticket.contactId}`,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
@ -435,7 +460,7 @@ const verifyQueue = async (
body = `\u200e${choosenQueue.greetingMessage}`; body = `\u200e${choosenQueue.greetingMessage}`;
} }
io.emit('notifyPeding', {data: {ticket, queue: choosenQueue}}); io.emit("notifyPeding", { data: { ticket, queue: choosenQueue } });
sendWhatsAppMessageSocket(ticket, body); sendWhatsAppMessageSocket(ticket, body);
} else { } else {
@ -779,7 +804,7 @@ const handleMessage = async (
unreadMessages unreadMessages
// groupContact // groupContact
); );
} }
if (getSettingValue("oneContactChatWithManyWhats")?.value == "disabled") { if (getSettingValue("oneContactChatWithManyWhats")?.value == "disabled") {
// Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen // Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen
@ -1004,8 +1029,17 @@ const handleMessage = async (
}; };
const menu = async (userTyped: string, whatsappId: any, contactId: any) => { const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
let lastId = await findObject(whatsappId, contactId, "ura"); let whatsapp = await whatsappCache(whatsappId);
const data: any = await get({ key: "ura", parse: true });
let lastId = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
const data: any = await get({
key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
parse: true
});
console.log("lastId[0]: ", lastId[0]); console.log("lastId[0]: ", lastId[0]);
@ -1013,13 +1047,17 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
} }
lastId = await findObject(whatsappId, contactId, "ura"); lastId = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
console.log("LAST ID: ", lastId); console.log("LAST ID: ", lastId);
let option: any; let option: any;
@ -1043,7 +1081,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
let uraOptionSelected = await findObject( let uraOptionSelected = await findObject(
whatsappId, whatsappId,
contactId, contactId,
"ura" whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
); );
uraOptionSelected = uraOptionSelected[4].split("|"); uraOptionSelected = uraOptionSelected[4].split("|");
@ -1052,7 +1090,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
@ -1068,7 +1106,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: id, value: id,
history history
}); });
@ -1091,7 +1129,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: response.id, value: response.id,
history history
}); });
@ -1101,7 +1139,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
@ -1121,7 +1159,11 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
} }
async function mainOptionsMenu(userTyped: any) { async function mainOptionsMenu(userTyped: any) {
let currentMenu = await findObject(whatsappId, contactId, "ura"); let currentMenu = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
const menuValues = data const menuValues = data
.filter((m: any) => m.idmaster == currentMenu[3]) .filter((m: any) => m.idmaster == currentMenu[3])
@ -1141,7 +1183,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: response.id, value: response.id,
history history
}); });
@ -1328,7 +1370,13 @@ async function vcard(msg: any) {
} }
async function backUra(whatsappId: any, contactId: any, data: any) { async function backUra(whatsappId: any, contactId: any, data: any) {
let uraOptionSelected = await findObject(whatsappId, contactId, "ura"); let whatsapp = await whatsappCache(whatsappId);
let uraOptionSelected = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
uraOptionSelected = uraOptionSelected[4].split("|").filter(Boolean); uraOptionSelected = uraOptionSelected[4].split("|").filter(Boolean);
@ -1349,7 +1397,7 @@ async function backUra(whatsappId: any, contactId: any, data: any) {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: id, value: id,
history history
}); });
@ -1365,7 +1413,13 @@ async function historyUra(
id: any, id: any,
remove?: boolean remove?: boolean
) { ) {
let uraOptionSelected = await findObject(whatsappId, contactId, "ura"); let whatsapp = await whatsappCache(whatsappId);
let uraOptionSelected = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
let history = ""; let history = "";
console.log("SELECED OPTION uraOptionSelected: ", uraOptionSelected); console.log("SELECED OPTION uraOptionSelected: ", uraOptionSelected);
@ -1387,3 +1441,13 @@ async function historyUra(
async function whatsappInfo(whatsappId: string | number) { async function whatsappInfo(whatsappId: string | number) {
return await Whatsapp.findByPk(whatsappId); return await Whatsapp.findByPk(whatsappId);
} }
async function whatsappCache(whatsappId: any) {
let whatsapp = await get({ key: "whatsapp:*", parse: true });
let uraByNumber = await get({ key: "ura_*", parse: true });
// console.log("------------------------> uraByNumber: ", uraByNumber);
whatsapp = whatsapp.filter((w: any) => +w?.id == +whatsappId);
if (whatsapp && whatsapp.length > 0 && uraByNumber) return whatsapp[0];
}