mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2026-01-14 15:53:00 -06:00
feat: chatwoot integration completed
This commit is contained in:
@@ -1,11 +1,16 @@
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import path from 'path';
|
||||
import { ChatwootDto } from '../dto/chatwoot.dto';
|
||||
import { WAMonitoringService } from './monitor.service';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import ChatwootClient from '@figuro/chatwoot-sdk';
|
||||
import { createReadStream, unlinkSync } from 'fs';
|
||||
import { createReadStream, unlinkSync, writeFileSync } from 'fs';
|
||||
import axios from 'axios';
|
||||
import FormData from 'form-data';
|
||||
import { SendTextDto } from '../dto/sendMessage.dto';
|
||||
import mimeTypes from 'mime-types';
|
||||
import { SendAudioDto } from '../dto/sendMessage.dto';
|
||||
import { SendMediaDto } from '../dto/sendMessage.dto';
|
||||
|
||||
export class ChatwootService {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
@@ -71,7 +76,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
const contact = await client.contact.getContactable({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
id,
|
||||
});
|
||||
|
||||
@@ -92,7 +97,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
const contact = await client.contacts.create({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
data: {
|
||||
inbox_id: inboxId,
|
||||
name: name || phoneNumber,
|
||||
@@ -115,7 +120,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
const contact = await client.contacts.update({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
id,
|
||||
data,
|
||||
});
|
||||
@@ -131,7 +136,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
const contact = await client.contacts.search({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
q: `+${phoneNumber}`,
|
||||
});
|
||||
|
||||
@@ -145,8 +150,8 @@ export class ChatwootService {
|
||||
throw new Error('client not found');
|
||||
}
|
||||
|
||||
const chatId = body.data.key.remoteJid.split('@')[0];
|
||||
const nameContact = !body.data.key.fromMe ? body.data.pushName : chatId;
|
||||
const chatId = body.key.remoteJid.split('@')[0];
|
||||
const nameContact = !body.key.fromMe ? body.pushName : chatId;
|
||||
|
||||
const filterInbox = await this.getInbox(instance);
|
||||
|
||||
@@ -156,14 +161,14 @@ export class ChatwootService {
|
||||
|
||||
const contactId = contact.id || contact.payload.contact.id;
|
||||
|
||||
if (!body.data.key.fromMe && contact.name === chatId && nameContact !== chatId) {
|
||||
if (!body.key.fromMe && contact.name === chatId && nameContact !== chatId) {
|
||||
await this.updateContact(instance, contactId, {
|
||||
name: nameContact,
|
||||
});
|
||||
}
|
||||
|
||||
const contactConversations = (await client.contacts.listConversations({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
id: contactId,
|
||||
})) as any;
|
||||
|
||||
@@ -178,7 +183,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
const conversation = await client.conversations.create({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
data: {
|
||||
contact_id: `${contactId}`,
|
||||
inbox_id: `${filterInbox.id}`,
|
||||
@@ -196,9 +201,12 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
const inbox = (await client.inboxes.list({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
})) as any;
|
||||
const findByName = inbox.payload.find((inbox) => inbox.name === instance);
|
||||
|
||||
const findByName = inbox.payload.find(
|
||||
(inbox) => inbox.name === instance.instanceName,
|
||||
);
|
||||
return findByName;
|
||||
}
|
||||
|
||||
@@ -216,7 +224,7 @@ export class ChatwootService {
|
||||
const client = await this.clientCw(instance);
|
||||
|
||||
const message = await client.messages.create({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
conversationId: conversationId,
|
||||
data: {
|
||||
content: content,
|
||||
@@ -245,16 +253,17 @@ export class ChatwootService {
|
||||
const filterInbox = await this.getInbox(instance);
|
||||
|
||||
const findConversation = await client.conversations.list({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
inboxId: filterInbox.id,
|
||||
});
|
||||
|
||||
const conversation = findConversation.data.payload.find(
|
||||
(conversation) =>
|
||||
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
|
||||
);
|
||||
|
||||
const message = await client.messages.create({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
conversationId: conversation.id,
|
||||
data: {
|
||||
content: content,
|
||||
@@ -285,7 +294,7 @@ export class ChatwootService {
|
||||
const config = {
|
||||
method: 'post',
|
||||
maxBodyLength: Infinity,
|
||||
url: `${this.provider.url}/api/v1/accounts/${this.provider.accountId}/conversations/${conversationId}/messages`,
|
||||
url: `${this.provider.url}/api/v1/accounts/${this.provider.account_id}/conversations/${conversationId}/messages`,
|
||||
headers: {
|
||||
api_access_token: this.provider.token,
|
||||
...data.getHeaders(),
|
||||
@@ -315,7 +324,7 @@ export class ChatwootService {
|
||||
const filterInbox = await this.getInbox(instance);
|
||||
|
||||
const findConversation = await client.conversations.list({
|
||||
accountId: this.provider.accountId,
|
||||
accountId: this.provider.account_id,
|
||||
inboxId: filterInbox.id,
|
||||
});
|
||||
const conversation = findConversation.data.payload.find(
|
||||
@@ -338,7 +347,7 @@ export class ChatwootService {
|
||||
const config = {
|
||||
method: 'post',
|
||||
maxBodyLength: Infinity,
|
||||
url: `${this.provider.url}/api/v1/accounts/${this.provider.accountId}/conversations/${conversation.id}/messages`,
|
||||
url: `${this.provider.url}/api/v1/accounts/${this.provider.account_id}/conversations/${conversation.id}/messages`,
|
||||
headers: {
|
||||
api_access_token: this.provider.token,
|
||||
...data.getHeaders(),
|
||||
@@ -355,7 +364,360 @@ export class ChatwootService {
|
||||
}
|
||||
}
|
||||
|
||||
public async chatwootWebhook(instance: InstanceDto, body: any) {
|
||||
return true;
|
||||
public async sendAttachment(
|
||||
waInstance: any,
|
||||
number: string,
|
||||
media: any,
|
||||
caption?: string,
|
||||
) {
|
||||
try {
|
||||
const parts = media.split('/');
|
||||
const fileName = decodeURIComponent(parts[parts.length - 1]);
|
||||
|
||||
const mimeType = mimeTypes.lookup(fileName).toString();
|
||||
|
||||
let type = 'document';
|
||||
|
||||
switch (mimeType.split('/')[0]) {
|
||||
case 'image':
|
||||
type = 'image';
|
||||
break;
|
||||
case 'video':
|
||||
type = 'video';
|
||||
break;
|
||||
case 'audio':
|
||||
type = 'audio';
|
||||
break;
|
||||
default:
|
||||
type = 'document';
|
||||
break;
|
||||
}
|
||||
|
||||
if (type === 'audio') {
|
||||
const data: SendAudioDto = {
|
||||
number: number,
|
||||
audioMessage: {
|
||||
audio: media,
|
||||
},
|
||||
options: {
|
||||
delay: 1200,
|
||||
presence: 'recording',
|
||||
},
|
||||
};
|
||||
|
||||
await waInstance?.audioWhatsapp(data);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const data: SendMediaDto = {
|
||||
number: number,
|
||||
mediaMessage: {
|
||||
mediatype: type as any,
|
||||
fileName: fileName,
|
||||
media: media,
|
||||
},
|
||||
options: {
|
||||
delay: 1200,
|
||||
presence: 'composing',
|
||||
},
|
||||
};
|
||||
|
||||
if (caption && type !== 'audio') {
|
||||
data.mediaMessage.caption = caption;
|
||||
}
|
||||
|
||||
await waInstance?.mediaMessage(data);
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async receiveWebhook(instance: InstanceDto, body: any) {
|
||||
try {
|
||||
if (!body?.conversation || body.private) return { message: 'bot' };
|
||||
|
||||
const chatId = body.conversation.meta.sender.phone_number.replace('+', '');
|
||||
const messageReceived = body.content;
|
||||
const senderName = body?.sender?.name;
|
||||
const accountId = body.account.id as number;
|
||||
const waInstance = this.waMonitor.waInstances[instance.instanceName];
|
||||
|
||||
if (chatId === '123456' && body.message_type === 'outgoing') {
|
||||
const command = messageReceived.replace('/', '');
|
||||
|
||||
if (command === 'iniciar') {
|
||||
const state = waInstance?.connectionStatus?.state;
|
||||
|
||||
if (state !== 'open') {
|
||||
await waInstance.connectToWhatsapp();
|
||||
} else {
|
||||
await this.createBotMessage(
|
||||
instance,
|
||||
`🚨 Instância ${body.inbox.name} já está conectada.`,
|
||||
'incoming',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (command === 'status') {
|
||||
const state = waInstance?.connectionStatus?.state;
|
||||
|
||||
if (!state) {
|
||||
await this.createBotMessage(
|
||||
instance,
|
||||
`⚠️ Instância ${body.inbox.name} não existe.`,
|
||||
'incoming',
|
||||
);
|
||||
}
|
||||
|
||||
if (state) {
|
||||
await this.createBotMessage(
|
||||
instance,
|
||||
`⚠️ Status da instância ${body.inbox.name}: *${state}*`,
|
||||
'incoming',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (command === 'desconectar') {
|
||||
const msgLogout = `🚨 Desconectando Whatsapp da caixa de entrada *${body.inbox.name}*: `;
|
||||
|
||||
await this.createBotMessage(instance, msgLogout, 'incoming');
|
||||
await waInstance?.client?.logout('Log out instance: ' + instance.instanceName);
|
||||
await waInstance?.client?.ws?.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
body.message_type === 'outgoing' &&
|
||||
body?.conversation?.messages?.length &&
|
||||
chatId !== '123456'
|
||||
) {
|
||||
// if (IMPORT_MESSAGES_SENT && messages_sent.includes(body.id)) {
|
||||
// console.log(`🚨 Não importar mensagens enviadas, ficaria duplicado.`);
|
||||
|
||||
// const indexMessage = messages_sent.indexOf(body.id);
|
||||
// messages_sent.splice(indexMessage, 1);
|
||||
|
||||
// return { message: 'bot' };
|
||||
// }
|
||||
|
||||
let formatText: string;
|
||||
if (senderName === null || senderName === undefined) {
|
||||
formatText = messageReceived;
|
||||
} else {
|
||||
// formatText = TOSIGN ? `*${senderName}*: ${messageReceived}` : messageReceived;
|
||||
formatText = `*${senderName}*: ${messageReceived}`;
|
||||
}
|
||||
|
||||
for (const message of body.conversation.messages) {
|
||||
if (message.attachments && message.attachments.length > 0) {
|
||||
for (const attachment of message.attachments) {
|
||||
console.log(attachment);
|
||||
if (!messageReceived) {
|
||||
formatText = null;
|
||||
}
|
||||
|
||||
await this.sendAttachment(
|
||||
waInstance,
|
||||
chatId,
|
||||
attachment.data_url,
|
||||
formatText,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const data: SendTextDto = {
|
||||
number: chatId,
|
||||
textMessage: {
|
||||
text: formatText,
|
||||
},
|
||||
options: {
|
||||
delay: 1200,
|
||||
presence: 'composing',
|
||||
},
|
||||
};
|
||||
|
||||
await waInstance?.textMessage(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { message: 'bot' };
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
||||
return { message: 'bot' };
|
||||
}
|
||||
}
|
||||
|
||||
private isMediaMessage(message: any) {
|
||||
const media = [
|
||||
'imageMessage',
|
||||
'documentMessage',
|
||||
'audioMessage',
|
||||
'videoMessage',
|
||||
'stickerMessage',
|
||||
];
|
||||
|
||||
const messageKeys = Object.keys(message);
|
||||
return messageKeys.some((key) => media.includes(key));
|
||||
}
|
||||
|
||||
private getTypeMessage(msg: any) {
|
||||
const types = {
|
||||
conversation: msg.conversation,
|
||||
imageMessage: msg.imageMessage?.caption,
|
||||
videoMessage: msg.videoMessage?.caption,
|
||||
extendedTextMessage: msg.extendedTextMessage?.text,
|
||||
messageContextInfo: msg.messageContextInfo?.stanzaId,
|
||||
stickerMessage: msg.stickerMessage?.fileSha256.toString('base64'),
|
||||
documentMessage: msg.documentMessage?.caption,
|
||||
audioMessage: msg.audioMessage?.caption,
|
||||
};
|
||||
|
||||
return types;
|
||||
}
|
||||
|
||||
private getMessageContent(types: any) {
|
||||
const typeKey = Object.keys(types).find((key) => types[key] !== undefined);
|
||||
return typeKey ? types[typeKey] : undefined;
|
||||
}
|
||||
|
||||
private getConversationMessage(msg: any) {
|
||||
const types = this.getTypeMessage(msg);
|
||||
|
||||
const messageContent = this.getMessageContent(types);
|
||||
|
||||
return messageContent;
|
||||
}
|
||||
|
||||
public async eventWhatsapp(event: string, instance: InstanceDto, body: any) {
|
||||
try {
|
||||
const client = await this.clientCw(instance);
|
||||
|
||||
if (!client) {
|
||||
throw new Error('client not found');
|
||||
}
|
||||
|
||||
const waInstance = this.waMonitor.waInstances[instance.instanceName];
|
||||
|
||||
if (event === 'messages.upsert') {
|
||||
// if (body.key.fromMe && !IMPORT_MESSAGES_SENT) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
if (body.key.remoteJid === 'status@broadcast') {
|
||||
console.log(`🚨 Ignorando status do whatsapp.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const getConversion = await this.createConversation(instance, body);
|
||||
const messageType = body.key.fromMe ? 'outgoing' : 'incoming';
|
||||
|
||||
if (!getConversion) {
|
||||
console.log('🚨 Erro ao criar conversa');
|
||||
return;
|
||||
}
|
||||
|
||||
const isMedia = this.isMediaMessage(body.message);
|
||||
|
||||
const bodyMessage = await this.getConversationMessage(body.message);
|
||||
|
||||
if (isMedia) {
|
||||
const downloadBase64 = await waInstance?.getBase64FromMediaMessage({
|
||||
message: {
|
||||
...body,
|
||||
},
|
||||
});
|
||||
|
||||
const random = Math.random().toString(36).substring(7);
|
||||
const nameFile = `${random}.${mimeTypes.extension(downloadBase64.mimetype)}`;
|
||||
|
||||
const fileData = Buffer.from(downloadBase64.base64, 'base64');
|
||||
|
||||
const fileName = `${path.join(waInstance?.storePath, 'temp', `${nameFile}`)}`;
|
||||
|
||||
writeFileSync(fileName, fileData, 'utf8');
|
||||
|
||||
return await this.sendData(getConversion, fileName, messageType, bodyMessage);
|
||||
}
|
||||
|
||||
const send = await this.createMessage(
|
||||
instance,
|
||||
getConversion,
|
||||
bodyMessage,
|
||||
messageType,
|
||||
);
|
||||
|
||||
return send;
|
||||
}
|
||||
|
||||
if (event === 'status.instance') {
|
||||
const data = body;
|
||||
const inbox = await this.getInbox(instance);
|
||||
const msgStatus = `⚡️ Status da instância ${inbox.name}: ${data.status}`;
|
||||
await this.createBotMessage(instance, msgStatus, 'incoming');
|
||||
}
|
||||
|
||||
if (event === 'connection.update') {
|
||||
if (body.state === 'open') {
|
||||
const msgConnection = `🚀 Conexão realizada com sucesso!`;
|
||||
await this.createBotMessage(instance, msgConnection, 'incoming');
|
||||
}
|
||||
}
|
||||
|
||||
if (event === 'contacts.update') {
|
||||
const data = body;
|
||||
|
||||
if (data.length) {
|
||||
for (const item of data) {
|
||||
const number = item.id.split('@')[0];
|
||||
const photo = item.profilePictureUrl || null;
|
||||
const find = await this.findContact(instance, number);
|
||||
|
||||
if (find) {
|
||||
await this.updateContact(instance, find.id, {
|
||||
avatar_url: photo,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (event === 'qrcode.updated') {
|
||||
if (body.statusCode === 500) {
|
||||
const erroQRcode = `🚨 Limite de geração de QRCode atingido, para gerar um novo QRCode, envie a mensagem /iniciar novamente.`;
|
||||
return await this.createBotMessage(instance, erroQRcode, 'incoming');
|
||||
} else {
|
||||
const fileData = Buffer.from(
|
||||
body?.qrcode.base64.replace('data:image/png;base64,', ''),
|
||||
'base64',
|
||||
);
|
||||
|
||||
const fileName = `${path.join(
|
||||
waInstance?.storePath,
|
||||
'temp',
|
||||
`${`${instance}.png`}`,
|
||||
)}`;
|
||||
|
||||
writeFileSync(fileName, fileData, 'utf8');
|
||||
|
||||
await this.createBotQr(
|
||||
instance,
|
||||
'QRCode gerado com sucesso!',
|
||||
'incoming',
|
||||
fileName,
|
||||
);
|
||||
|
||||
const msgQrCode = `⚡️ QRCode gerado com sucesso!\n\nDigitalize este código QR nos próximos 40 segundos:`;
|
||||
await this.createBotMessage(instance, msgQrCode, 'incoming');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user