Skip to content

Commit 707aa22

Browse files
committed
Added support for messaging with ads on chatwoot
1 parent 32da15f commit 707aa22

4 files changed

Lines changed: 26 additions & 149 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
* Added Typebot integration
2727
* Added proxy endpoint
2828
* Added send and date_time in webhook data
29+
* Added support for messaging with ads on chatwoot
2930

3031
### Fixed
3132

src/main.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import cors from 'cors';
66
import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
77
import { join } from 'path';
88

9-
import { configService, Cors, HttpServer, Rabbitmq, Webhook } from './config/env.config';
9+
import { Auth, configService, Cors, HttpServer, Rabbitmq, Webhook } from './config/env.config';
1010
import { onUnexpectedError } from './config/error.config';
1111
import { Logger } from './config/logger.config';
1212
import { ROOT_DIR } from './config/path.config';
@@ -61,6 +61,8 @@ function bootstrap() {
6161
const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
6262
const localISOTime = new Date(Date.now() - tzoffset).toISOString();
6363
const now = localISOTime;
64+
const globalApiKey = configService.get<Auth>('AUTHENTICATION').API_KEY.KEY;
65+
const serverUrl = configService.get<HttpServer>('SERVER').URL;
6466

6567
const errorData = {
6668
event: 'error',
@@ -73,6 +75,8 @@ function bootstrap() {
7375
},
7476
},
7577
date_time: now,
78+
api_key: globalApiKey,
79+
server_url: serverUrl,
7680
};
7781

7882
logger.error(errorData);
@@ -83,11 +87,6 @@ function bootstrap() {
8387
httpService.post('', errorData);
8488
}
8589

86-
if (err['message'].includes('No sessions')) {
87-
console.log(err['message']);
88-
process.exit(1);
89-
}
90-
9190
return res.status(err['status'] || 500).json({
9291
status: err['status'] || 500,
9392
error: err['error'] || 'Internal Server Error',

src/whatsapp/services/chatwoot.service.ts

Lines changed: 18 additions & 142 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import Jimp from 'jimp';
66
import mimeTypes from 'mime-types';
77
import path from 'path';
88

9-
import { Chatwoot, ConfigService } from '../../config/env.config';
9+
import { ConfigService } from '../../config/env.config';
1010
import { Logger } from '../../config/logger.config';
1111
import { ROOT_DIR } from '../../config/path.config';
1212
import { ChatwootDto } from '../dto/chatwoot.dto';
@@ -613,8 +613,6 @@ export class ChatwootService {
613613
conversationId: number,
614614
content: string,
615615
messageType: 'incoming' | 'outgoing' | undefined,
616-
source_id?: string,
617-
source_reply_id?: string,
618616
privateMessage?: boolean,
619617
attachments?: {
620618
content: unknown;
@@ -640,8 +638,6 @@ export class ChatwootService {
640638
message_type: messageType,
641639
attachments: attachments,
642640
private: privateMessage || false,
643-
source_id: source_id,
644-
source_reply_id: source_reply_id,
645641
},
646642
});
647643

@@ -737,8 +733,6 @@ export class ChatwootService {
737733
file: string,
738734
messageType: 'incoming' | 'outgoing' | undefined,
739735
content?: string,
740-
source_id?: string,
741-
source_reply_id?: string,
742736
) {
743737
this.logger.verbose('send data to chatwoot');
744738

@@ -755,16 +749,6 @@ export class ChatwootService {
755749
this.logger.verbose('temp file found');
756750
data.append('attachments[]', createReadStream(file));
757751

758-
if (source_id) {
759-
this.logger.verbose('source_id found');
760-
data.append('source_id', source_id);
761-
}
762-
763-
if (source_reply_id) {
764-
this.logger.verbose('source_reply_id found');
765-
data.append('source_reply_id', source_reply_id);
766-
}
767-
768752
this.logger.verbose('get client to instance: ' + this.provider.instanceName);
769753
const config = {
770754
method: 'post',
@@ -930,10 +914,10 @@ export class ChatwootService {
930914
},
931915
};
932916

933-
const audioWhatsapp = await waInstance?.audioWhatsapp(data);
917+
await waInstance?.audioWhatsapp(data);
934918

935919
this.logger.verbose('audio sent');
936-
return audioWhatsapp;
920+
return;
937921
}
938922

939923
this.logger.verbose('send media to instance: ' + waInstance.instanceName);
@@ -955,51 +939,17 @@ export class ChatwootService {
955939
data.mediaMessage.caption = caption;
956940
}
957941

958-
const mediaMessage = await waInstance?.mediaMessage(data);
942+
await waInstance?.mediaMessage(data);
959943

960944
this.logger.verbose('media sent');
961-
return mediaMessage;
945+
return;
962946
} catch (error) {
963947
this.logger.error(error);
964948
}
965949
}
966950

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

1005955
this.logger.verbose('receive webhook to chatwoot instance: ' + instance.instanceName);
@@ -1097,9 +1047,6 @@ export class ChatwootService {
10971047
}
10981048

10991049
for (const message of body.conversation.messages) {
1100-
const messageId = message?.id;
1101-
const conversationId = message?.conversation_id;
1102-
const accountId = message?.account_id;
11031050
this.logger.verbose('check if message is media');
11041051
if (message.attachments && message.attachments.length > 0) {
11051052
this.logger.verbose('message is media');
@@ -1110,8 +1057,7 @@ export class ChatwootService {
11101057
formatText = null;
11111058
}
11121059

1113-
const mediaMessage = await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
1114-
await this.updateMessage(instance, accountId, conversationId, messageId, mediaMessage?.key?.id);
1060+
await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
11151061
}
11161062
} else {
11171063
this.logger.verbose('message is text');
@@ -1128,8 +1074,7 @@ export class ChatwootService {
11281074
},
11291075
};
11301076

1131-
const message = await waInstance?.textMessage(data);
1132-
await this.updateMessage(instance, accountId, conversationId, messageId, message?.key?.id);
1077+
await waInstance?.textMessage(data);
11331078
}
11341079
}
11351080
}
@@ -1187,7 +1132,7 @@ export class ChatwootService {
11871132
thumbnailUrl: string;
11881133
sourceUrl: string;
11891134
}
1190-
let adsMessage: AdsMessage | undefined = msg.extendedTextMessage?.contextInfo.externalAdReply;
1135+
const adsMessage: AdsMessage | undefined = msg.extendedTextMessage?.contextInfo.externalAdReply;
11911136

11921137
this.logger.verbose('Get ads message if it exist');
11931138
adsMessage && this.logger.verbose('Ads message: ' + adsMessage);
@@ -1218,38 +1163,6 @@ export class ChatwootService {
12181163
return types;
12191164
}
12201165

1221-
private getContextIdTypeMessage(msg: any) {
1222-
this.logger.verbose('get type message');
1223-
1224-
const types = {
1225-
conversation: msg.conversation?.contextInfo?.stanzaId,
1226-
imageMessage: msg.imageMessage?.contextInfo?.stanzaId,
1227-
videoMessage: msg.videoMessage?.contextInfo?.stanzaId,
1228-
extendedTextMessage: msg.extendedTextMessage?.contextInfo?.stanzaId,
1229-
messageContextInfo: msg.messageContextInfo?.stanzaId,
1230-
stickerMessage: undefined,
1231-
documentMessage: msg.documentMessage?.contextInfo?.stanzaId,
1232-
documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.contextInfo?.stanzaId,
1233-
audioMessage: msg.audioMessage?.contextInfo?.stanzaId,
1234-
contactMessage: msg.contactMessage?.contextInfo?.stanzaId,
1235-
contactsArrayMessage: msg.contactsArrayMessage?.contextInfo?.stanzaId,
1236-
locationMessage: msg.locationMessage?.contextInfo?.stanzaId,
1237-
liveLocationMessage: msg.liveLocationMessage?.contextInfo?.stanzaId,
1238-
};
1239-
1240-
this.logger.verbose('type message: ' + types);
1241-
1242-
return types;
1243-
}
1244-
1245-
private getContextMessageContent(types: any) {
1246-
this.logger.verbose('get message context content');
1247-
const typeKey = Object.keys(types).find((key) => types[key] !== undefined && types[key] !== '');
1248-
1249-
const result = typeKey ? types[typeKey] : undefined;
1250-
return result;
1251-
}
1252-
12531166
private getMessageContent(types: any) {
12541167
this.logger.verbose('get message content');
12551168
const typeKey = Object.keys(types).find((key) => types[key] !== undefined);
@@ -1349,18 +1262,6 @@ export class ChatwootService {
13491262
return messageContent;
13501263
}
13511264

1352-
private getContextConversationMessage(msg: any) {
1353-
this.logger.verbose('get context conversation message');
1354-
1355-
const types = this.getContextIdTypeMessage(msg);
1356-
1357-
const messageContext = this.getContextMessageContent(types);
1358-
1359-
this.logger.verbose('context conversation message: ' + messageContext);
1360-
1361-
return messageContext;
1362-
}
1363-
13641265
public async eventWhatsapp(event: string, instance: InstanceDto, body: any) {
13651266
this.logger.verbose('event whatsapp to instance: ' + instance.instanceName);
13661267
try {
@@ -1389,8 +1290,6 @@ export class ChatwootService {
13891290
this.logger.verbose('get conversation message');
13901291
const bodyMessage = await this.getConversationMessage(body.message);
13911292

1392-
const source_reply_id = this.getContextConversationMessage(body.message);
1393-
13941293
const isMedia = this.isMediaMessage(body.message);
13951294

13961295
const adsMessage = this.getAdsMessage(body.message);
@@ -1410,8 +1309,6 @@ export class ChatwootService {
14101309

14111310
const messageType = body.key.fromMe ? 'outgoing' : 'incoming';
14121311

1413-
const source_id = body.key?.id;
1414-
14151312
this.logger.verbose('message type: ' + messageType);
14161313

14171314
this.logger.verbose('is media: ' + isMedia);
@@ -1456,7 +1353,7 @@ export class ChatwootService {
14561353
}
14571354

14581355
this.logger.verbose('send data to chatwoot');
1459-
const send = await this.sendData(getConversation, fileName, messageType, content, source_id, source_reply_id);
1356+
const send = await this.sendData(getConversation, fileName, messageType, content);
14601357

14611358
if (!send) {
14621359
this.logger.warn('message not sent');
@@ -1477,14 +1374,7 @@ export class ChatwootService {
14771374
this.logger.verbose('message is not group');
14781375

14791376
this.logger.verbose('send data to chatwoot');
1480-
const send = await this.sendData(
1481-
getConversation,
1482-
fileName,
1483-
messageType,
1484-
bodyMessage,
1485-
source_id,
1486-
source_reply_id,
1487-
);
1377+
const send = await this.sendData(getConversation, fileName, messageType, bodyMessage);
14881378

14891379
if (!send) {
14901380
this.logger.warn('message not sent');
@@ -1581,14 +1471,7 @@ export class ChatwootService {
15811471
}
15821472

15831473
this.logger.verbose('send data to chatwoot');
1584-
const send = await this.createMessage(
1585-
instance,
1586-
getConversation,
1587-
content,
1588-
messageType,
1589-
source_id,
1590-
source_reply_id,
1591-
);
1474+
const send = await this.createMessage(instance, getConversation, content, messageType);
15921475

15931476
if (!send) {
15941477
this.logger.warn('message not sent');
@@ -1609,14 +1492,7 @@ export class ChatwootService {
16091492
this.logger.verbose('message is not group');
16101493

16111494
this.logger.verbose('send data to chatwoot');
1612-
const send = await this.createMessage(
1613-
instance,
1614-
getConversation,
1615-
bodyMessage,
1616-
messageType,
1617-
source_id,
1618-
source_reply_id,
1619-
);
1495+
const send = await this.createMessage(instance, getConversation, bodyMessage, messageType);
16201496

16211497
if (!send) {
16221498
this.logger.warn('message not sent');
@@ -1653,14 +1529,14 @@ export class ChatwootService {
16531529
}
16541530

16551531
// if (event === 'connection.update') {
1656-
// this.logger.verbose('event connection.update');
1532+
// this.logger.verbose('event connection.update');
16571533

1658-
// if (body.status === 'open') {
1659-
// const msgConnection = `🚀 Connection successfully established!`;
1534+
// if (body.status === 'open') {
1535+
// const msgConnection = `🚀 Connection successfully established!`;
16601536

1661-
// this.logger.verbose('send message to chatwoot');
1662-
// await this.createBotMessage(instance, msgConnection, 'incoming');
1663-
// }
1537+
// this.logger.verbose('send message to chatwoot');
1538+
// await this.createBotMessage(instance, msgConnection, 'incoming');
1539+
// }
16641540
// }
16651541

16661542
if (event === 'qrcode.updated') {

src/whatsapp/services/whatsapp.service.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1434,8 +1434,9 @@ export class WAStartupService {
14341434

14351435
if (
14361436
type !== 'notify' ||
1437-
!received.message ||
1437+
!received?.message ||
14381438
received.message?.protocolMessage ||
1439+
received.message.senderKeyDistributionMessage ||
14391440
received.message?.pollUpdateMessage
14401441
) {
14411442
this.logger.verbose('message rejected');

0 commit comments

Comments
 (0)