Skip to content

Commit 196c10b

Browse files
Merge pull request #108 from raimartinsb/EvolutionAPI-develop
[Improvement] - Send and Update source_id of messages to chatwoot
2 parents ecbf90d + c5d2d77 commit 196c10b

5 files changed

Lines changed: 149 additions & 12 deletions

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
"dependencies": {
4444
"@adiwajshing/keyed-db": "^0.2.4",
4545
"@ffmpeg-installer/ffmpeg": "^1.1.0",
46-
"@figuro/chatwoot-sdk": "^1.1.14",
46+
"@figuro/chatwoot-sdk": "^1.1.16",
4747
"@hapi/boom": "^10.0.1",
4848
"@sentry/node": "^7.59.2",
4949
"@whiskeysockets/baileys": "^6.4.1",

src/config/env.config.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ export type Websocket = {
7070
ENABLED: boolean;
7171
};
7272

73+
export type Chatwoot = {
74+
USE_REPLY_ID: boolean;
75+
};
76+
7377
export type EventsWebhook = {
7478
APPLICATION_STARTUP: boolean;
7579
QRCODE_UPDATED: boolean;
@@ -139,6 +143,7 @@ export interface Env {
139143
QRCODE: QrCode;
140144
AUTHENTICATION: Auth;
141145
PRODUCTION?: Production;
146+
CHATWOOT?: Chatwoot;
142147
}
143148

144149
export type Key = keyof Env;
@@ -297,6 +302,9 @@ export class ConfigService {
297302
SECRET: process.env.AUTHENTICATION_JWT_SECRET || 'L=0YWt]b2w[WF>#>:&E`',
298303
},
299304
},
305+
CHATWOOT: {
306+
USE_REPLY_ID: process.env?.USE_REPLY_ID === 'true',
307+
},
300308
};
301309
}
302310
}

src/dev-env.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,7 @@ AUTHENTICATION:
154154
JWT:
155155
EXPIRIN_IN: 0 # seconds - 3600s === 1h | zero (0) - never expires
156156
SECRET: L=0YWt]b2w[WF>#>:&E`
157+
158+
# Configure to chatwoot
159+
CHATWOOT:
160+
USE_REPLY_ID: false

src/whatsapp/models/message.model.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ export class MessageRaw {
2020
messageTimestamp?: number | Long.Long;
2121
owner: string;
2222
source?: 'android' | 'web' | 'ios';
23+
source_id?: string;
24+
source_reply_id?: string;
2325
}
2426

2527
const messageSchema = new Schema<MessageRaw>({

src/whatsapp/services/chatwoot.service.ts

Lines changed: 134 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { createReadStream, readFileSync, unlinkSync, writeFileSync } from 'fs';
55
import mimeTypes from 'mime-types';
66
import path from 'path';
77

8-
import { ConfigService } from '../../config/env.config';
8+
import { Chatwoot, ConfigService } from '../../config/env.config';
99
import { Logger } from '../../config/logger.config';
1010
import { ROOT_DIR } from '../../config/path.config';
1111
import { ChatwootDto } from '../dto/chatwoot.dto';
@@ -612,6 +612,8 @@ export class ChatwootService {
612612
conversationId: number,
613613
content: string,
614614
messageType: 'incoming' | 'outgoing' | undefined,
615+
source_id?: string,
616+
source_reply_id?: string,
615617
privateMessage?: boolean,
616618
attachments?: {
617619
content: unknown;
@@ -637,6 +639,8 @@ export class ChatwootService {
637639
message_type: messageType,
638640
attachments: attachments,
639641
private: privateMessage || false,
642+
source_id: source_id,
643+
source_reply_id: source_reply_id,
640644
},
641645
});
642646

@@ -732,6 +736,8 @@ export class ChatwootService {
732736
file: string,
733737
messageType: 'incoming' | 'outgoing' | undefined,
734738
content?: string,
739+
source_id?: string,
740+
source_reply_id?: string,
735741
) {
736742
this.logger.verbose('send data to chatwoot');
737743

@@ -748,6 +754,16 @@ export class ChatwootService {
748754
this.logger.verbose('temp file found');
749755
data.append('attachments[]', createReadStream(file));
750756

757+
if (source_id) {
758+
this.logger.verbose('source_id found');
759+
data.append('source_id', source_id);
760+
}
761+
762+
if (source_reply_id) {
763+
this.logger.verbose('source_reply_id found');
764+
data.append('source_reply_id', source_reply_id);
765+
}
766+
751767
this.logger.verbose('get client to instance: ' + this.provider.instanceName);
752768
const config = {
753769
method: 'post',
@@ -913,10 +929,10 @@ export class ChatwootService {
913929
},
914930
};
915931

916-
await waInstance?.audioWhatsapp(data);
932+
const audioWhatsapp = await waInstance?.audioWhatsapp(data);
917933

918934
this.logger.verbose('audio sent');
919-
return;
935+
return audioWhatsapp;
920936
}
921937

922938
this.logger.verbose('send media to instance: ' + waInstance.instanceName);
@@ -938,15 +954,48 @@ export class ChatwootService {
938954
data.mediaMessage.caption = caption;
939955
}
940956

941-
await waInstance?.mediaMessage(data);
957+
const mediaMessage = await waInstance?.mediaMessage(data);
942958

943959
this.logger.verbose('media sent');
944-
return;
960+
return mediaMessage;
945961
} catch (error) {
946962
this.logger.error(error);
947963
}
948964
}
949965

966+
public async updateMessage(
967+
instance: InstanceDto,
968+
accountId: number,
969+
conversationId: number,
970+
messageId: number,
971+
sourceId: string | null,
972+
) {
973+
// const useReplyId = this.configService.get<DelInstance>('DEL_INSTANCE');
974+
const useReplyId = this.configService.get<Chatwoot>('CHATWOOT')?.USE_REPLY_ID;
975+
if (useReplyId === true) {
976+
this.logger.verbose('update message to chatwoot instance: ' + instance.instanceName);
977+
const client = await this.clientCw(instance);
978+
979+
if (!client) {
980+
this.logger.warn('client not found');
981+
return null;
982+
}
983+
this.logger.verbose('check if sourceId to update');
984+
if (sourceId) {
985+
this.logger.verbose('update message to chatwoot');
986+
const dataUpdated = {
987+
source_id: sourceId,
988+
};
989+
await client.messages.update({
990+
accountId,
991+
conversationId,
992+
data: dataUpdated,
993+
messageId,
994+
});
995+
}
996+
}
997+
}
998+
950999
public async receiveWebhook(instance: InstanceDto, body: any) {
9511000
try {
9521001
// espera 500ms para evitar duplicidade de mensagens
@@ -1047,6 +1096,9 @@ export class ChatwootService {
10471096
}
10481097

10491098
for (const message of body.conversation.messages) {
1099+
const messageId = message?.id;
1100+
const conversationId = message?.conversation_id;
1101+
const accountId = message?.account_id;
10501102
this.logger.verbose('check if message is media');
10511103
if (message.attachments && message.attachments.length > 0) {
10521104
this.logger.verbose('message is media');
@@ -1057,7 +1109,8 @@ export class ChatwootService {
10571109
formatText = null;
10581110
}
10591111

1060-
await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
1112+
const mediaMessage = await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
1113+
await this.updateMessage(instance, accountId, conversationId, messageId, mediaMessage?.key?.id);
10611114
}
10621115
} else {
10631116
this.logger.verbose('message is text');
@@ -1074,7 +1127,8 @@ export class ChatwootService {
10741127
},
10751128
};
10761129

1077-
await waInstance?.textMessage(data);
1130+
const message = await waInstance?.textMessage(data);
1131+
await this.updateMessage(instance, accountId, conversationId, messageId, message?.key?.id);
10781132
}
10791133
}
10801134
}
@@ -1149,6 +1203,38 @@ export class ChatwootService {
11491203
return types;
11501204
}
11511205

1206+
private getContextIdTypeMessage(msg: any) {
1207+
this.logger.verbose('get type message');
1208+
1209+
const types = {
1210+
conversation: msg.conversation?.contextInfo?.stanzaId,
1211+
imageMessage: msg.imageMessage?.contextInfo?.stanzaId,
1212+
videoMessage: msg.videoMessage?.contextInfo?.stanzaId,
1213+
extendedTextMessage: msg.extendedTextMessage?.contextInfo?.stanzaId,
1214+
messageContextInfo: msg.messageContextInfo?.stanzaId,
1215+
stickerMessage: undefined,
1216+
documentMessage: msg.documentMessage?.contextInfo?.stanzaId,
1217+
documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.contextInfo?.stanzaId,
1218+
audioMessage: msg.audioMessage?.contextInfo?.stanzaId,
1219+
contactMessage: msg.contactMessage?.contextInfo?.stanzaId,
1220+
contactsArrayMessage: msg.contactsArrayMessage?.contextInfo?.stanzaId,
1221+
locationMessage: msg.locationMessage?.contextInfo?.stanzaId,
1222+
liveLocationMessage: msg.liveLocationMessage?.contextInfo?.stanzaId,
1223+
};
1224+
1225+
this.logger.verbose('type message: ' + types);
1226+
1227+
return types;
1228+
}
1229+
1230+
private getContextMessageContent(types: any) {
1231+
this.logger.verbose('get message context content');
1232+
const typeKey = Object.keys(types).find((key) => types[key] !== undefined && types[key] !== '');
1233+
1234+
const result = typeKey ? types[typeKey] : undefined;
1235+
return result;
1236+
}
1237+
11521238
private getMessageContent(types: any) {
11531239
this.logger.verbose('get message content');
11541240
const typeKey = Object.keys(types).find((key) => types[key] !== undefined);
@@ -1248,6 +1334,18 @@ export class ChatwootService {
12481334
return messageContent;
12491335
}
12501336

1337+
private getContextConversationMessage(msg: any) {
1338+
this.logger.verbose('get context conversation message');
1339+
1340+
const types = this.getContextIdTypeMessage(msg);
1341+
1342+
const messageContext = this.getContextMessageContent(types);
1343+
1344+
this.logger.verbose('context conversation message: ' + messageContext);
1345+
1346+
return messageContext;
1347+
}
1348+
12511349
public async eventWhatsapp(event: string, instance: InstanceDto, body: any) {
12521350
this.logger.verbose('event whatsapp to instance: ' + instance.instanceName);
12531351
try {
@@ -1276,6 +1374,8 @@ export class ChatwootService {
12761374
this.logger.verbose('get conversation message');
12771375
const bodyMessage = await this.getConversationMessage(body.message);
12781376

1377+
const source_reply_id = this.getContextConversationMessage(body.message);
1378+
12791379
const isMedia = this.isMediaMessage(body.message);
12801380

12811381
if (!bodyMessage && !isMedia) {
@@ -1293,6 +1393,8 @@ export class ChatwootService {
12931393

12941394
const messageType = body.key.fromMe ? 'outgoing' : 'incoming';
12951395

1396+
const source_id = body.key?.id;
1397+
12961398
this.logger.verbose('message type: ' + messageType);
12971399

12981400
this.logger.verbose('is media: ' + isMedia);
@@ -1337,7 +1439,7 @@ export class ChatwootService {
13371439
}
13381440

13391441
this.logger.verbose('send data to chatwoot');
1340-
const send = await this.sendData(getConversion, fileName, messageType, content);
1442+
const send = await this.sendData(getConversion, fileName, messageType, content, source_id, source_reply_id);
13411443

13421444
if (!send) {
13431445
this.logger.warn('message not sent');
@@ -1358,7 +1460,14 @@ export class ChatwootService {
13581460
this.logger.verbose('message is not group');
13591461

13601462
this.logger.verbose('send data to chatwoot');
1361-
const send = await this.sendData(getConversion, fileName, messageType, bodyMessage);
1463+
const send = await this.sendData(
1464+
getConversion,
1465+
fileName,
1466+
messageType,
1467+
bodyMessage,
1468+
source_id,
1469+
source_reply_id,
1470+
);
13621471

13631472
if (!send) {
13641473
this.logger.warn('message not sent');
@@ -1394,7 +1503,14 @@ export class ChatwootService {
13941503
}
13951504

13961505
this.logger.verbose('send data to chatwoot');
1397-
const send = await this.createMessage(instance, getConversion, content, messageType);
1506+
const send = await this.createMessage(
1507+
instance,
1508+
getConversion,
1509+
content,
1510+
messageType,
1511+
source_id,
1512+
source_reply_id,
1513+
);
13981514

13991515
if (!send) {
14001516
this.logger.warn('message not sent');
@@ -1415,7 +1531,14 @@ export class ChatwootService {
14151531
this.logger.verbose('message is not group');
14161532

14171533
this.logger.verbose('send data to chatwoot');
1418-
const send = await this.createMessage(instance, getConversion, bodyMessage, messageType);
1534+
const send = await this.createMessage(
1535+
instance,
1536+
getConversion,
1537+
bodyMessage,
1538+
messageType,
1539+
source_id,
1540+
source_reply_id,
1541+
);
14191542

14201543
if (!send) {
14211544
this.logger.warn('message not sent');

0 commit comments

Comments
 (0)