Skip to content

Commit 7103a95

Browse files
committed
feat: Added connection with pairing code in chatwoot
1 parent bcada5d commit 7103a95

8 files changed

Lines changed: 76 additions & 39 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* Created settings controller
88
* Added reject call and send text message when receiving a call
99
* Added setting to ignore group messages
10+
* Added connection with pairing code in chatwoot
1011

1112
### Fixed
1213

src/whatsapp/controllers/instance.controller.ts

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -103,16 +103,10 @@ export class InstanceController {
103103

104104
if (!chatwoot_account_id || !chatwoot_token || !chatwoot_url) {
105105
let getQrcode: wa.QrCode;
106-
let getPairingCode: string;
107106

108107
if (qrcode) {
109108
this.logger.verbose('creating qrcode');
110-
await instance.connectToWhatsapp();
111-
if (number) {
112-
this.logger.verbose('creating number');
113-
await delay(5000);
114-
getPairingCode = await instance.client.requestPairingCode(number);
115-
}
109+
await instance.connectToWhatsapp(number);
116110
await delay(2000);
117111
getQrcode = instance.qrCode;
118112
}
@@ -126,14 +120,9 @@ export class InstanceController {
126120
webhook,
127121
webhook_by_events,
128122
events: getEvents,
123+
qrcode: getQrcode,
129124
};
130125

131-
if (getPairingCode) {
132-
result['pairingCode'] = getPairingCode;
133-
} else {
134-
result['qrcode'] = getQrcode;
135-
}
136-
137126
this.logger.verbose('instance created');
138127
this.logger.verbose(result);
139128

@@ -166,13 +155,15 @@ export class InstanceController {
166155
url: chatwoot_url,
167156
sign_msg: chatwoot_sign_msg || false,
168157
name_inbox: instance.instanceName,
158+
number,
169159
});
170160

171161
this.chatwootService.initInstanceChatwoot(
172162
instance,
173163
instance.instanceName,
174164
`${urlServer}/chatwoot/webhook/${instance.instanceName}`,
175165
qrcode,
166+
number,
176167
);
177168
} catch (error) {
178169
this.logger.log(error);
@@ -193,6 +184,7 @@ export class InstanceController {
193184
token: chatwoot_token,
194185
url: chatwoot_url,
195186
sign_msg: chatwoot_sign_msg || false,
187+
number,
196188
name_inbox: instance.instanceName,
197189
webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
198190
},
@@ -220,19 +212,7 @@ export class InstanceController {
220212

221213
if (state == 'close') {
222214
this.logger.verbose('connecting');
223-
await instance.connectToWhatsapp();
224-
let pairingCode = null;
225-
if (number) {
226-
this.logger.verbose('creating pairing code');
227-
await delay(5000);
228-
pairingCode = await instance.client.requestPairingCode(number);
229-
}
230-
231-
if (pairingCode) {
232-
return {
233-
pairingCode,
234-
};
235-
}
215+
await instance.connectToWhatsapp(number);
236216

237217
await delay(2000);
238218
return instance.qrCode;

src/whatsapp/dto/chatwoot.dto.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ export class ChatwootDto {
55
url?: string;
66
name_inbox?: string;
77
sign_msg?: boolean;
8+
number?: string;
89
}

src/whatsapp/models/chatwoot.model.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export class ChatwootRaw {
99
url?: string;
1010
name_inbox?: string;
1111
sign_msg?: boolean;
12+
number?: string;
1213
}
1314

1415
const chatwootSchema = new Schema<ChatwootRaw>({
@@ -19,6 +20,7 @@ const chatwootSchema = new Schema<ChatwootRaw>({
1920
url: { type: String, required: true },
2021
name_inbox: { type: String, required: true },
2122
sign_msg: { type: Boolean, required: true },
23+
number: { type: String, required: true },
2224
});
2325

2426
export const ChatwootModel = dbserver?.model(

src/whatsapp/services/chatwoot.service.ts

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { SendAudioDto } from '../dto/sendMessage.dto';
1313
import { SendMediaDto } from '../dto/sendMessage.dto';
1414
import { ROOT_DIR } from '../../config/path.config';
1515
import { ConfigService, HttpServer } from '../../config/env.config';
16+
import { delay } from '@whiskeysockets/baileys';
1617

1718
export class ChatwootService {
1819
private messageCacheFile: string;
@@ -154,6 +155,7 @@ export class ChatwootService {
154155
inboxName: string,
155156
webhookUrl: string,
156157
qrcode: boolean,
158+
number: string,
157159
) {
158160
this.logger.verbose('init instance chatwoot: ' + instance.instanceName);
159161

@@ -243,11 +245,18 @@ export class ChatwootService {
243245
}
244246

245247
this.logger.verbose('create message for init instance in chatwoot');
248+
249+
let contentMsg = '/init';
250+
251+
if (number) {
252+
contentMsg = `/init:${number}`;
253+
}
254+
246255
const message = await client.messages.create({
247256
accountId: this.provider.account_id,
248257
conversationId: conversation.id,
249258
data: {
250-
content: '/init',
259+
content: contentMsg,
251260
message_type: 'outgoing',
252261
},
253262
});
@@ -953,13 +962,14 @@ export class ChatwootService {
953962

954963
const command = messageReceived.replace('/', '');
955964

956-
if (command === 'init' || command === 'iniciar') {
965+
if (command.includes('init') || command.includes('iniciar')) {
957966
this.logger.verbose('command init found');
958967
const state = waInstance?.connectionStatus?.state;
959968

960969
if (state !== 'open') {
961970
this.logger.verbose('connect to whatsapp');
962-
await waInstance.connectToWhatsapp();
971+
const number = command.split(':')[1];
972+
await waInstance.connectToWhatsapp(number);
963973
} else {
964974
this.logger.verbose('whatsapp already connected');
965975
await this.createBotMessage(
@@ -1556,7 +1566,16 @@ export class ChatwootService {
15561566
fileName,
15571567
);
15581568

1559-
const msgQrCode = `⚡️ QRCode successfully generated!\n\nScan this QR code within the next 40 seconds:`;
1569+
let msgQrCode = `⚡️ QRCode successfully generated!\n\nScan this QR code within the next 40 seconds.`;
1570+
1571+
if (body?.qrcode?.pairingCode) {
1572+
msgQrCode =
1573+
msgQrCode +
1574+
`\n\n*Pairing Code:* ${body.qrcode.pairingCode.substring(
1575+
0,
1576+
4,
1577+
)}-${body.qrcode.pairingCode.substring(4, 8)}`;
1578+
}
15601579

15611580
this.logger.verbose('send message to chatwoot');
15621581
await this.createBotMessage(instance, msgQrCode, 'incoming');

src/whatsapp/services/monitor.service.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
ContactModel,
2626
MessageModel,
2727
MessageUpModel,
28+
SettingsModel,
2829
WebhookModel,
2930
} from '../models';
3031

@@ -241,6 +242,7 @@ export class WAMonitoringService {
241242
execSync(`rm -rf ${join(STORE_DIR, 'auth', 'apikey', instanceName + '.json')}`);
242243
execSync(`rm -rf ${join(STORE_DIR, 'webhook', instanceName + '.json')}`);
243244
execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`);
245+
execSync(`rm -rf ${join(STORE_DIR, 'settings', instanceName + '*')}`);
244246

245247
return;
246248
}
@@ -254,6 +256,7 @@ export class WAMonitoringService {
254256
await AuthModel.deleteMany({ _id: instanceName });
255257
await WebhookModel.deleteMany({ _id: instanceName });
256258
await ChatwootModel.deleteMany({ _id: instanceName });
259+
await SettingsModel.deleteMany({ _id: instanceName });
257260

258261
return;
259262
}

src/whatsapp/services/whatsapp.service.ts

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ export class WAStartupService {
152152
private endSession = false;
153153
private logBaileys = this.configService.get<Log>('LOG').BAILEYS;
154154

155+
private phoneNumber: string;
156+
155157
private chatwootService = new ChatwootService(waMonitor, this.configService);
156158

157159
public set instanceName(name: string) {
@@ -241,6 +243,12 @@ export class WAStartupService {
241243

242244
public get qrCode(): wa.QrCode {
243245
this.logger.verbose('Getting qrcode');
246+
if (this.instance.qrcode?.pairingCode) {
247+
return {
248+
pairingCode: this.instance.qrcode?.pairingCode,
249+
};
250+
}
251+
244252
return {
245253
code: this.instance.qrcode?.code,
246254
base64: this.instance.qrcode?.base64,
@@ -588,11 +596,6 @@ export class WAStartupService {
588596
return this.eventEmitter.emit('no.connection', this.instance.name);
589597
}
590598

591-
// pairing code
592-
// await delay(5000);
593-
// const code = await this.client.requestPairingCode('557499879409');
594-
// console.log(`Pairing code: ${code}`);
595-
596599
this.logger.verbose('Incrementing QR code count');
597600
this.instance.qrcode.count++;
598601

@@ -603,6 +606,13 @@ export class WAStartupService {
603606
color: { light: '#ffffff', dark: '#198754' },
604607
};
605608

609+
if (this.phoneNumber) {
610+
await delay(2000);
611+
this.instance.qrcode.pairingCode = await this.client.requestPairingCode(
612+
this.phoneNumber,
613+
);
614+
}
615+
606616
this.logger.verbose('Generating QR code');
607617
qrcode.toDataURL(qr, optsQrcode, (error, base64) => {
608618
if (error) {
@@ -614,15 +624,25 @@ export class WAStartupService {
614624
this.instance.qrcode.code = qr;
615625

616626
this.sendDataWebhook(Events.QRCODE_UPDATED, {
617-
qrcode: { instance: this.instance.name, code: qr, base64 },
627+
qrcode: {
628+
instance: this.instance.name,
629+
pairingCode: this.instance.qrcode.pairingCode,
630+
code: qr,
631+
base64,
632+
},
618633
});
619634

620635
if (this.localChatwoot.enabled) {
621636
this.chatwootService.eventWhatsapp(
622637
Events.QRCODE_UPDATED,
623638
{ instanceName: this.instance.name },
624639
{
625-
qrcode: { instance: this.instance.name, code: qr, base64 },
640+
qrcode: {
641+
instance: this.instance.name,
642+
pairingCode: this.instance.qrcode.pairingCode,
643+
code: qr,
644+
base64,
645+
},
626646
},
627647
);
628648
}
@@ -631,7 +651,7 @@ export class WAStartupService {
631651
this.logger.verbose('Generating QR code in terminal');
632652
qrcodeTerminal.generate(qr, { small: true }, (qrcode) =>
633653
this.logger.log(
634-
`\n{ instance: ${this.instance.name}, qrcodeCount: ${this.instance.qrcode.count} }\n` +
654+
`\n{ instance: ${this.instance.name} pairingCode: ${this.instance.qrcode.pairingCode}, qrcodeCount: ${this.instance.qrcode.count} }\n` +
635655
qrcode,
636656
),
637657
);
@@ -798,7 +818,7 @@ export class WAStartupService {
798818
return await useMultiFileAuthState(join(INSTANCE_DIR, this.instance.name));
799819
}
800820

801-
public async connectToWhatsapp(): Promise<WASocket> {
821+
public async connectToWhatsapp(number?: string): Promise<WASocket> {
802822
this.logger.verbose('Connecting to whatsapp');
803823
try {
804824
this.loadWebhook();
@@ -872,6 +892,15 @@ export class WAStartupService {
872892

873893
this.logger.verbose('Socket event handler initialized');
874894

895+
this.phoneNumber = number;
896+
897+
// if (number) {
898+
// this.logger.verbose('creating pairing code');
899+
// await delay(5000);
900+
// this.phoneNumber = number;
901+
// this.instance.qrcode.pairingCode = await this.client.requestPairingCode(number);
902+
// }
903+
875904
return this.client;
876905
} catch (error) {
877906
this.logger.error(error);

src/whatsapp/types/wa.types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,13 @@ export enum Events {
2727
export declare namespace wa {
2828
export type QrCode = {
2929
count?: number;
30+
pairingCode?: string;
3031
base64?: string;
3132
code?: string;
3233
};
3334
export type Instance = {
3435
qrcode?: QrCode;
36+
pairingCode?: string;
3537
authState?: { state: AuthenticationState; saveCreds: () => void };
3638
name?: string;
3739
wuid?: string;

0 commit comments

Comments
 (0)