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

@ -9,7 +9,8 @@ import AppError from "../../errors/AppError";
import { userInfo } from "os";
import ShowQueueService from "../QueueService/ShowQueueService";
import UpdateTicketService from "./UpdateTicketService";
import { getSettingValue } from "../../helpers/WhaticketSettings";
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
const FindOrCreateTicketServiceBot = async (
contact: Contact,
@ -17,10 +18,32 @@ const FindOrCreateTicketServiceBot = async (
unreadMessages: number,
groupContact?: Contact
): Promise<any> => {
try {
// let ticket = await Ticket.findOne({
// where: {
// status: {
// [Op.or]: ["open", "pending", "queueChoice"]
// },
// contactId: groupContact ? groupContact.id : contact.id
// }
// });
let ticket = await Ticket.findOne({
let ticket;
if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
let whats = await ListWhatsAppsNumber(whatsappId);
ticket = await Ticket.findOne({
where: {
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"]
@ -28,17 +51,15 @@ const FindOrCreateTicketServiceBot = async (
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 = await BotIsOnQueue("botqueue");
// const botInfo = { isOnQueue: false }
if (ticket) {
await ticket.update({ unreadMessages });
}
@ -51,8 +72,6 @@ const FindOrCreateTicketServiceBot = async (
// order: [["updatedAt", "DESC"]]
// });
// if (ticket) {
// await ticket.update({
@ -64,42 +83,39 @@ const FindOrCreateTicketServiceBot = async (
// }
if (!ticket && !groupContact) {
console.log('BOT CREATING OR REOPENING THE TICKET')
console.log("BOT CREATING OR REOPENING THE TICKET");
ticket = await Ticket.findOne({
where: {
contactId: contact.id,
userId: botInfo.userIdBot
userId: botInfo.userIdBot,
whatsappId: whatsappId
},
order: [["updatedAt", "DESC"]]
});
if (ticket) {
await ticket.update({
status: "open",
userId: botInfo.userIdBot,
unreadMessages
});
console.log('lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
console.log("lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
await dialogFlowStartContext(contact, ticket, botInfo);
}
}
let created = false
let created = false;
if (!ticket) {
created = true;
created = true
let status = "open"
let status = "open";
if (queues.length > 1 && !botInfo.isOnQueue) {
status = "queueChoice"
status = "queueChoice";
}
ticket = await Ticket.create({
@ -112,27 +128,31 @@ const FindOrCreateTicketServiceBot = async (
phoneNumberId
});
console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy')
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)
console.error(
"===> Error on FindOrCreateTicketServiceBot.ts file: \n",
error
);
throw new AppError(error.message);
}
};
export default FindOrCreateTicketServiceBot;
async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo: any) {
let msg: any = { type: 'chat', from: `${contact.number}@c.us`, body: '0' };
async function dialogFlowStartContext(
contact: Contact,
ticket: Ticket,
botInfo: any
) {
let msg: any = { type: "chat", from: `${contact.number}@c.us`, body: "0" };
let queue = await ShowQueueService(botInfo.botQueueId);
@ -144,6 +164,4 @@ async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo:
ticket = await ShowTicketService(ticket.id);
// await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
}

View File

@ -184,7 +184,11 @@ const verifyMediaMessage = async (
phoneNumberId: msg?.phoneNumberId,
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;
}
if (msg?.fromMe) {
@ -204,7 +208,16 @@ const verifyMediaMessage = async (
if (mediaAuthorized) {
try {
await writeFileAsync(
join(__dirname, "..", "..", "..", "..", "..", "public", media.filename),
join(
__dirname,
"..",
"..",
"..",
"..",
"..",
"public",
media.filename
),
media.data,
"base64"
);
@ -226,10 +239,14 @@ const verifyMediaMessage = async (
);
}
messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`;
messageData.mediaUrl = '';
await ticket.update({ lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`});
messageData.mediaUrl = "";
await ticket.update({
lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`
});
const newMessage = await CreateMessageService({ messageData });
console.log(`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`)
console.log(
`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`
);
}
};
@ -318,12 +335,15 @@ const verifyMessage = async (
quotedMsgId: quotedMsg,
phoneNumberId: msg?.phoneNumberId
};
if (msg?.fromMe) {
const botInfo = await BotIsOnQueue("botqueue");
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))) {
messageData = { ...messageData, fromAgent: true };
@ -399,12 +419,17 @@ const verifyQueue = async (
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({
whatsappId: `${ticket.whatsappId}`,
contactId: `${ticket.contactId}`,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id,
history: `|${data[1].id}`
});
@ -435,7 +460,7 @@ const verifyQueue = async (
body = `\u200e${choosenQueue.greetingMessage}`;
}
io.emit('notifyPeding', {data: {ticket, queue: choosenQueue}});
io.emit("notifyPeding", { data: { ticket, queue: choosenQueue } });
sendWhatsAppMessageSocket(ticket, body);
} else {
@ -1004,8 +1029,17 @@ const handleMessage = async (
};
const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
let lastId = await findObject(whatsappId, contactId, "ura");
const data: any = await get({ key: "ura", parse: true });
let whatsapp = await whatsappCache(whatsappId);
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]);
@ -1013,13 +1047,17 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: 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);
let option: any;
@ -1043,7 +1081,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
let uraOptionSelected = await findObject(
whatsappId,
contactId,
"ura"
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
uraOptionSelected = uraOptionSelected[4].split("|");
@ -1052,7 +1090,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id,
history: `|${data[1].id}`
});
@ -1068,7 +1106,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: id,
history
});
@ -1091,7 +1129,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: response.id,
history
});
@ -1101,7 +1139,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: 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) {
let currentMenu = await findObject(whatsappId, contactId, "ura");
let currentMenu = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
const menuValues = data
.filter((m: any) => m.idmaster == currentMenu[3])
@ -1141,7 +1183,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: response.id,
history
});
@ -1328,7 +1370,13 @@ async function vcard(msg: 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);
@ -1349,7 +1397,7 @@ async function backUra(whatsappId: any, contactId: any, data: any) {
await createObject({
whatsappId,
contactId,
identifier: "ura",
identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: id,
history
});
@ -1365,7 +1413,13 @@ async function historyUra(
id: any,
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 = "";
console.log("SELECED OPTION uraOptionSelected: ", uraOptionSelected);
@ -1387,3 +1441,13 @@ async function historyUra(
async function whatsappInfo(whatsappId: string | number) {
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];
}