@vanzxy/baileys 1.2.5 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,768 @@
1
+ import crypto from "crypto";
2
+ import { proto } from "../../WAProto/index.js";
3
+ import {
4
+ delay,
5
+ generateMessageID,
6
+ generateWAMessage,
7
+ generateWAMessageContent,
8
+ generateWAMessageFromContent,
9
+ getUrlFromDirectPath,
10
+ normalizeMessageContent,
11
+ prepareWAMessageMedia,
12
+ } from "../Utils/index.js";
13
+ import {
14
+ isJidGroup,
15
+ isPnUser,
16
+ jidNormalizedUser,
17
+ STORIES_JID,
18
+ } from "../WABinary/index.js";
19
+ export class Dugong {
20
+ constructor(waUploadToServer, relayMessageFn, config, sock) {
21
+ this.relayMessage = relayMessageFn;
22
+ this.waUploadToServer = waUploadToServer;
23
+ this.config = config;
24
+ this.sock = sock;
25
+ }
26
+ detectType(content) {
27
+ if (content.requestPaymentMessage) return "PAYMENT";
28
+ if (content.productMessage) return "PRODUCT";
29
+ if (content.interactiveButtons) return "INTERACTIVE_BUTTONS";
30
+ if (content.interactiveMessage?.carouselMessage) return "CAROUSEL";
31
+ if (content.interactiveMessage) return "INTERACTIVE";
32
+ if (content.albumMessage || content.album) return "ALBUM";
33
+ if (content.eventMessage) return "EVENT";
34
+ if (content.pollResultMessage) return "POLL_RESULT";
35
+ if (content.groupStatusMessage) return "GROUP_STORY";
36
+ return null;
37
+ }
38
+ async handlePayment(content, quoted) {
39
+ const data = content.requestPaymentMessage;
40
+ let notes = {};
41
+ if (data.sticker?.stickerMessage) {
42
+ notes = {
43
+ stickerMessage: {
44
+ ...data.sticker.stickerMessage,
45
+ contextInfo: {
46
+ stanzaId: quoted?.key?.id,
47
+ participant: quoted?.key?.participant || content.sender,
48
+ quotedMessage: quoted?.message,
49
+ },
50
+ },
51
+ };
52
+ } else if (data.note) {
53
+ notes = {
54
+ extendedTextMessage: {
55
+ text: data.note,
56
+ contextInfo: {
57
+ stanzaId: quoted?.key?.id,
58
+ participant: quoted?.key?.participant || content.sender,
59
+ quotedMessage: quoted?.message,
60
+ },
61
+ },
62
+ };
63
+ }
64
+ return {
65
+ requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({
66
+ expiryTimestamp: data.expiry || 0,
67
+ amount1000: data.amount || 0,
68
+ currencyCodeIso4217: data.currency || "IDR",
69
+ requestFrom: data.from || "0@s.whatsapp.net",
70
+ noteMessage: notes,
71
+ background: data.background ?? {
72
+ id: "DEFAULT",
73
+ placeholderArgb: 0xfff0f0f0,
74
+ },
75
+ }),
76
+ };
77
+ }
78
+ async handleProduct(content, _jid, _quoted) {
79
+ const {
80
+ title,
81
+ description,
82
+ thumbnail,
83
+ productId,
84
+ retailerId,
85
+ url,
86
+ body = "",
87
+ footer = "",
88
+ buttons = [],
89
+ priceAmount1000 = null,
90
+ currencyCode = "IDR",
91
+ } = content.productMessage;
92
+ let productImage;
93
+ if (Buffer.isBuffer(thumbnail)) {
94
+ const { imageMessage } = await generateWAMessageContent(
95
+ { image: thumbnail },
96
+ { upload: this.waUploadToServer },
97
+ );
98
+ productImage = imageMessage;
99
+ } else if (typeof thumbnail === "object" && thumbnail.url) {
100
+ const { imageMessage } = await generateWAMessageContent(
101
+ { image: { url: thumbnail.url } },
102
+ { upload: this.waUploadToServer },
103
+ );
104
+ productImage = imageMessage;
105
+ }
106
+ return {
107
+ viewOnceMessage: {
108
+ message: {
109
+ interactiveMessage: {
110
+ body: { text: body },
111
+ footer: { text: footer },
112
+ header: {
113
+ title,
114
+ hasMediaAttachment: true,
115
+ productMessage: {
116
+ product: {
117
+ productImage,
118
+ productId,
119
+ title,
120
+ description,
121
+ currencyCode,
122
+ priceAmount1000,
123
+ retailerId,
124
+ url,
125
+ productImageCount: 1,
126
+ },
127
+ businessOwnerJid: "0@s.whatsapp.net",
128
+ },
129
+ },
130
+ nativeFlowMessage: { buttons },
131
+ },
132
+ },
133
+ },
134
+ };
135
+ }
136
+ async handleInteractive(content, _jid, _quoted) {
137
+ const {
138
+ title,
139
+ footer,
140
+ thumbnail,
141
+ image,
142
+ video,
143
+ document,
144
+ mimetype,
145
+ fileName,
146
+ jpegThumbnail,
147
+ contextInfo,
148
+ externalAdReply,
149
+ buttons = [],
150
+ nativeFlowMessage,
151
+ header,
152
+ } = content.interactiveMessage;
153
+ let media = null;
154
+ let _mediaType = null;
155
+ if (thumbnail) {
156
+ media = await prepareWAMessageMedia(
157
+ { image: { url: thumbnail } },
158
+ { upload: this.waUploadToServer },
159
+ );
160
+ _mediaType = "image";
161
+ } else if (image) {
162
+ const src =
163
+ typeof image === "object" && image.url
164
+ ? { image: { url: image.url } }
165
+ : { image };
166
+ media = await prepareWAMessageMedia(src, {
167
+ upload: this.waUploadToServer,
168
+ });
169
+ _mediaType = "image";
170
+ } else if (video) {
171
+ const src =
172
+ typeof video === "object" && video.url
173
+ ? { video: { url: video.url } }
174
+ : { video };
175
+ media = await prepareWAMessageMedia(src, {
176
+ upload: this.waUploadToServer,
177
+ });
178
+ _mediaType = "video";
179
+ } else if (document) {
180
+ const docPayload = { document };
181
+ if (jpegThumbnail) {
182
+ docPayload.jpegThumbnail =
183
+ typeof jpegThumbnail === "object" && jpegThumbnail.url
184
+ ? { url: jpegThumbnail.url }
185
+ : jpegThumbnail;
186
+ }
187
+ media = await prepareWAMessageMedia(docPayload, {
188
+ upload: this.waUploadToServer,
189
+ });
190
+ if (fileName) media.documentMessage.fileName = fileName;
191
+ if (mimetype) media.documentMessage.mimetype = mimetype;
192
+ _mediaType = "document";
193
+ }
194
+ const interactiveMessage = {
195
+ body: { text: title || "" },
196
+ footer: { text: footer || "" },
197
+ };
198
+ if (buttons && buttons.length > 0) {
199
+ interactiveMessage.nativeFlowMessage = { buttons };
200
+ if (nativeFlowMessage) {
201
+ interactiveMessage.nativeFlowMessage = {
202
+ ...interactiveMessage.nativeFlowMessage,
203
+ ...nativeFlowMessage,
204
+ };
205
+ }
206
+ } else if (nativeFlowMessage) {
207
+ interactiveMessage.nativeFlowMessage = nativeFlowMessage;
208
+ }
209
+ if (media) {
210
+ interactiveMessage.header = {
211
+ title: header || "",
212
+ hasMediaAttachment: true,
213
+ ...media,
214
+ };
215
+ } else {
216
+ interactiveMessage.header = {
217
+ title: header || "",
218
+ hasMediaAttachment: false,
219
+ };
220
+ }
221
+ const finalContextInfo = {};
222
+ if (contextInfo) {
223
+ Object.assign(finalContextInfo, {
224
+ mentionedJid: contextInfo.mentionedJid || [],
225
+ forwardingScore: contextInfo.forwardingScore || 0,
226
+ isForwarded: contextInfo.isForwarded || false,
227
+ ...contextInfo,
228
+ });
229
+ }
230
+ if (externalAdReply) {
231
+ finalContextInfo.externalAdReply = {
232
+ title: externalAdReply.title || "",
233
+ body: externalAdReply.body || "",
234
+ mediaType: externalAdReply.mediaType || 1,
235
+ thumbnailUrl: externalAdReply.thumbnailUrl || "",
236
+ mediaUrl: externalAdReply.mediaUrl || "",
237
+ sourceUrl: externalAdReply.sourceUrl || "",
238
+ showAdAttribution: externalAdReply.showAdAttribution || false,
239
+ renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false,
240
+ ...externalAdReply,
241
+ };
242
+ }
243
+ if (Object.keys(finalContextInfo).length > 0) {
244
+ interactiveMessage.contextInfo = finalContextInfo;
245
+ }
246
+ return { interactiveMessage };
247
+ }
248
+ async handleInteractiveButtons(content, _jid, _quoted) {
249
+ const {
250
+ text,
251
+ caption,
252
+ title,
253
+ subtitle,
254
+ footer,
255
+ interactiveButtons,
256
+ hasMediaAttachment,
257
+ image,
258
+ video,
259
+ document,
260
+ mimetype,
261
+ jpegThumbnail,
262
+ location,
263
+ product,
264
+ businessOwnerJid,
265
+ } = content;
266
+ const bodyText = text || caption || "";
267
+ const buttons = interactiveButtons.map((btn) => ({
268
+ name: btn.name,
269
+ buttonParamsJson:
270
+ typeof btn.buttonParamsJson === "string"
271
+ ? btn.buttonParamsJson
272
+ : JSON.stringify(btn.buttonParamsJson),
273
+ }));
274
+ let headerContent = {};
275
+ let mediaAttached =
276
+ typeof hasMediaAttachment === "boolean" ? hasMediaAttachment : false;
277
+ if (image) {
278
+ const src =
279
+ typeof image === "object" && image.url
280
+ ? { image: { url: image.url } }
281
+ : { image };
282
+ const uploaded = await prepareWAMessageMedia(src, {
283
+ upload: this.waUploadToServer,
284
+ });
285
+ headerContent = { ...uploaded };
286
+ mediaAttached =
287
+ typeof hasMediaAttachment === "boolean" ? hasMediaAttachment : true;
288
+ } else if (video) {
289
+ const src =
290
+ typeof video === "object" && video.url
291
+ ? { video: { url: video.url } }
292
+ : { video };
293
+ const uploaded = await prepareWAMessageMedia(src, {
294
+ upload: this.waUploadToServer,
295
+ });
296
+ headerContent = { ...uploaded };
297
+ mediaAttached =
298
+ typeof hasMediaAttachment === "boolean" ? hasMediaAttachment : true;
299
+ } else if (document) {
300
+ const docPayload =
301
+ typeof document === "object" && document.url
302
+ ? { document: { url: document.url } }
303
+ : { document };
304
+ if (mimetype) docPayload.mimetype = mimetype;
305
+ const uploaded = await prepareWAMessageMedia(docPayload, {
306
+ upload: this.waUploadToServer,
307
+ });
308
+ if (jpegThumbnail) {
309
+ uploaded.documentMessage.jpegThumbnail =
310
+ typeof jpegThumbnail === "string"
311
+ ? Buffer.from(jpegThumbnail, "base64")
312
+ : jpegThumbnail;
313
+ }
314
+ headerContent = { ...uploaded };
315
+ mediaAttached =
316
+ typeof hasMediaAttachment === "boolean" ? hasMediaAttachment : true;
317
+ } else if (location) {
318
+ headerContent = {
319
+ locationMessage: {
320
+ degreesLatitude:
321
+ location.degressLatitude || location.degreesLatitude || 0,
322
+ degreesLongitude:
323
+ location.degressLongitude || location.degreesLongitude || 0,
324
+ name: location.name || "",
325
+ },
326
+ };
327
+ mediaAttached =
328
+ typeof hasMediaAttachment === "boolean" ? hasMediaAttachment : true;
329
+ } else if (product) {
330
+ let productImage;
331
+ if (product.productImage) {
332
+ const imgSrc =
333
+ typeof product.productImage === "object" && product.productImage.url
334
+ ? { image: { url: product.productImage.url } }
335
+ : { image: product.productImage };
336
+ const uploaded = await prepareWAMessageMedia(imgSrc, {
337
+ upload: this.waUploadToServer,
338
+ });
339
+ productImage = uploaded.imageMessage;
340
+ }
341
+ headerContent = {
342
+ productMessage: {
343
+ product: {
344
+ productImage,
345
+ productId: product.productId,
346
+ title: product.title,
347
+ description: product.description,
348
+ currencyCode: product.currencyCode || "IDR",
349
+ priceAmount1000: product.priceAmount1000,
350
+ retailerId: product.retailerId,
351
+ url: product.url,
352
+ productImageCount: product.productImageCount || 1,
353
+ },
354
+ businessOwnerJid: businessOwnerJid || "0@s.whatsapp.net",
355
+ },
356
+ };
357
+ mediaAttached =
358
+ typeof hasMediaAttachment === "boolean" ? hasMediaAttachment : true;
359
+ }
360
+ const interactiveMessage = {
361
+ body: { text: bodyText },
362
+ footer: { text: footer || "" },
363
+ header: {
364
+ title: title || "",
365
+ subtitle: subtitle || "",
366
+ hasMediaAttachment: mediaAttached,
367
+ ...headerContent,
368
+ },
369
+ nativeFlowMessage: { buttons },
370
+ };
371
+ return {
372
+ viewOnceMessage: {
373
+ message: {
374
+ messageContextInfo: {
375
+ deviceListMetadata: {},
376
+ deviceListMetadataVersion: 2,
377
+ messageSecret: crypto.randomBytes(32),
378
+ },
379
+ interactiveMessage,
380
+ },
381
+ },
382
+ };
383
+ }
384
+ async handleCarousel(content, _jid, _quoted) {
385
+ const { interactiveMessage } = content;
386
+ const { body, footer, header, carouselMessage, contextInfo } =
387
+ interactiveMessage;
388
+ const processedCards = [];
389
+ for (const card of carouselMessage.cards) {
390
+ const cardMsg = {
391
+ body: card.body || { text: "" },
392
+ footer: card.footer || { text: "" },
393
+ header: {
394
+ title: card.header?.title || "",
395
+ hasMediaAttachment: false,
396
+ },
397
+ };
398
+ if (card.nativeFlowMessage) {
399
+ cardMsg.nativeFlowMessage = card.nativeFlowMessage;
400
+ }
401
+ if (
402
+ card.header?.imageMessage ||
403
+ card.header?.videoMessage ||
404
+ card.header?.documentMessage
405
+ ) {
406
+ let headerContent = {};
407
+ let mediaAttached = true;
408
+ if (card.header.imageMessage) {
409
+ const url = card.header.imageMessage.url || card.header.imageMessage;
410
+ const src =
411
+ typeof url === "string" ? { image: { url } } : { image: url };
412
+ const uploaded = await prepareWAMessageMedia(src, {
413
+ upload: this.waUploadToServer,
414
+ });
415
+ headerContent = { ...uploaded };
416
+ } else if (card.header.videoMessage) {
417
+ const url = card.header.videoMessage.url || card.header.videoMessage;
418
+ const src =
419
+ typeof url === "string" ? { video: { url } } : { video: url };
420
+ const uploaded = await prepareWAMessageMedia(src, {
421
+ upload: this.waUploadToServer,
422
+ });
423
+ headerContent = { ...uploaded };
424
+ } else if (card.header.documentMessage) {
425
+ const url =
426
+ card.header.documentMessage.url || card.header.documentMessage;
427
+ const src =
428
+ typeof url === "string" ? { document: { url } } : { document: url };
429
+ const uploaded = await prepareWAMessageMedia(src, {
430
+ upload: this.waUploadToServer,
431
+ });
432
+ headerContent = { ...uploaded };
433
+ }
434
+ cardMsg.header = {
435
+ title: card.header?.title || "",
436
+ hasMediaAttachment: mediaAttached,
437
+ ...headerContent,
438
+ };
439
+ }
440
+ processedCards.push(cardMsg);
441
+ }
442
+ const interactiveMsg = {
443
+ body: body || { text: "" },
444
+ footer: footer || { text: "" },
445
+ header: header || { title: "", hasMediaAttachment: false },
446
+ carouselMessage: {
447
+ cards: processedCards,
448
+ messageVersion: carouselMessage.messageVersion || 1,
449
+ carouselCardType: carouselMessage.carouselCardType ?? 1,
450
+ },
451
+ };
452
+ if (contextInfo) {
453
+ interactiveMsg.contextInfo = contextInfo;
454
+ }
455
+ return {
456
+ viewOnceMessage: {
457
+ message: {
458
+ messageContextInfo: {
459
+ deviceListMetadata: {},
460
+ deviceListMetadataVersion: 2,
461
+ messageSecret: crypto.randomBytes(32),
462
+ },
463
+ interactiveMessage: interactiveMsg,
464
+ },
465
+ },
466
+ };
467
+ }
468
+ async handleAlbum(content, jid, quoted) {
469
+ const array = content.albumMessage || content.album;
470
+ const ctxInfo = content.contextInfo || {};
471
+ const album = await generateWAMessageFromContent(
472
+ jid,
473
+ {
474
+ messageContextInfo: {
475
+ messageSecret: crypto.randomBytes(32),
476
+ },
477
+ albumMessage: {
478
+ expectedImageCount: array.filter((a) => "image" in a).length,
479
+ expectedVideoCount: array.filter((a) => "video" in a).length,
480
+ },
481
+ },
482
+ {
483
+ userJid: jidNormalizedUser(this.sock.authState?.creds?.me?.id || ""),
484
+ quoted,
485
+ upload: this.waUploadToServer,
486
+ },
487
+ );
488
+ await this.relayMessage(jid, album.message, {
489
+ messageId: album.key.id,
490
+ });
491
+ for (let item of array) {
492
+ if (ctxInfo && Object.keys(ctxInfo).length > 0 && !item.contextInfo) {
493
+ item = { ...item, contextInfo: ctxInfo };
494
+ }
495
+ const img = await generateWAMessage(jid, item, {
496
+ upload: this.waUploadToServer,
497
+ userJid: jidNormalizedUser(this.sock.authState?.creds?.me?.id || ""),
498
+ });
499
+ img.message.messageContextInfo = {
500
+ messageSecret: crypto.randomBytes(32),
501
+ messageAssociation: {
502
+ associationType: 1,
503
+ parentMessageKey: album.key,
504
+ },
505
+ };
506
+ await this.relayMessage(jid, img.message, {
507
+ messageId: img.key.id,
508
+ });
509
+ }
510
+ return album;
511
+ }
512
+ async handleEvent(content, jid, quoted) {
513
+ const eventData = content.eventMessage;
514
+ const msg = await generateWAMessageFromContent(
515
+ jid,
516
+ {
517
+ viewOnceMessage: {
518
+ message: {
519
+ messageContextInfo: {
520
+ deviceListMetadata: {},
521
+ deviceListMetadataVersion: 2,
522
+ messageSecret: crypto.randomBytes(32),
523
+ },
524
+ eventMessage: {
525
+ isCanceled: eventData.isCanceled || false,
526
+ name: eventData.name,
527
+ description: eventData.description,
528
+ location: eventData.location || {
529
+ degreesLatitude: 0,
530
+ degreesLongitude: 0,
531
+ name: "Location",
532
+ },
533
+ joinLink: eventData.joinLink || "",
534
+ startTime:
535
+ typeof eventData.startTime === "string"
536
+ ? parseInt(eventData.startTime)
537
+ : eventData.startTime || Date.now(),
538
+ endTime:
539
+ typeof eventData.endTime === "string"
540
+ ? parseInt(eventData.endTime)
541
+ : eventData.endTime || Date.now() + 3600000,
542
+ extraGuestsAllowed: eventData.extraGuestsAllowed !== false,
543
+ },
544
+ },
545
+ },
546
+ },
547
+ {
548
+ quoted,
549
+ userJid: jidNormalizedUser(this.sock.authState?.creds?.me?.id || ""),
550
+ },
551
+ );
552
+ await this.relayMessage(jid, msg.message, {
553
+ messageId: msg.key.id,
554
+ });
555
+ return msg;
556
+ }
557
+ async handlePollResult(content, jid, quoted) {
558
+ const pollData = content.pollResultMessage;
559
+ const msg = await generateWAMessageFromContent(
560
+ jid,
561
+ {
562
+ pollResultSnapshotMessage: {
563
+ name: pollData.name,
564
+ pollVotes: pollData.pollVotes.map((vote) => ({
565
+ optionName: vote.optionName,
566
+ optionVoteCount:
567
+ typeof vote.optionVoteCount === "number"
568
+ ? vote.optionVoteCount.toString()
569
+ : vote.optionVoteCount,
570
+ })),
571
+ },
572
+ },
573
+ {
574
+ quoted,
575
+ userJid: jidNormalizedUser(this.sock.authState?.creds?.me?.id || ""),
576
+ },
577
+ );
578
+ await this.relayMessage(jid, msg.message, {
579
+ messageId: msg.key.id,
580
+ });
581
+ return msg;
582
+ }
583
+ async handleGroupStory(content, jid, _quoted, options = {}) {
584
+ const storyData = content.groupStatusMessage;
585
+ let waMsgContent;
586
+ if (storyData.message) {
587
+ waMsgContent = storyData;
588
+ } else {
589
+ waMsgContent = await generateWAMessageContent(storyData, {
590
+ upload: this.waUploadToServer,
591
+ });
592
+ }
593
+ const innerMsg = waMsgContent.message || waMsgContent;
594
+ const msgKey = Object.keys(innerMsg).find(
595
+ (k) => innerMsg[k] && typeof innerMsg[k] === "object",
596
+ );
597
+ if (msgKey) {
598
+ innerMsg[msgKey].contextInfo = innerMsg[msgKey].contextInfo || {};
599
+ innerMsg[msgKey].contextInfo.isGroupStatus = true;
600
+ if (!innerMsg[msgKey].contextInfo.statusSourceType) {
601
+ if (innerMsg.imageMessage)
602
+ innerMsg[msgKey].contextInfo.statusSourceType = 0;
603
+ else if (innerMsg.videoMessage)
604
+ innerMsg[msgKey].contextInfo.statusSourceType = 1;
605
+ else if (innerMsg.audioMessage)
606
+ innerMsg[msgKey].contextInfo.statusSourceType = 3;
607
+ else if (innerMsg.extendedTextMessage)
608
+ innerMsg[msgKey].contextInfo.statusSourceType = 4;
609
+ }
610
+ }
611
+ const finalMsg = {
612
+ groupStatusMessageV2: {
613
+ message: innerMsg,
614
+ },
615
+ };
616
+ return await this.relayMessage(jid, finalMsg, {
617
+ messageId: generateMessageID(),
618
+ });
619
+ }
620
+ async sendStatusWhatsApp(content, jids = []) {
621
+ const userJid = jidNormalizedUser(this.sock.authState.creds.me.id);
622
+ const allUsers = new Set();
623
+ allUsers.add(userJid);
624
+ for (const id of jids) {
625
+ if (isJidGroup(id)) {
626
+ try {
627
+ const metadata = await this.sock.groupMetadata(id);
628
+ metadata.participants.forEach((p) =>
629
+ allUsers.add(jidNormalizedUser(p.id)),
630
+ );
631
+ } catch (error) {
632
+ this.config.logger.error(
633
+ `Error getting metadata for group ${id}: ${error}`,
634
+ );
635
+ }
636
+ } else if (isPnUser(id)) {
637
+ allUsers.add(jidNormalizedUser(id));
638
+ }
639
+ }
640
+ const uniqueUsers = Array.from(allUsers);
641
+ const getRandomHexColor = () =>
642
+ "#" +
643
+ Math.floor(Math.random() * 16777215)
644
+ .toString(16)
645
+ .padStart(6, "0");
646
+ const isMedia = content.image || content.video || content.audio;
647
+ const isAudio = !!content.audio;
648
+ const messageContent = { ...content };
649
+ if (isMedia && !isAudio) {
650
+ if (messageContent.text) {
651
+ messageContent.caption = messageContent.text;
652
+ delete messageContent.text;
653
+ }
654
+ delete messageContent.ptt;
655
+ delete messageContent.font;
656
+ delete messageContent.backgroundColor;
657
+ delete messageContent.textColor;
658
+ }
659
+ if (isAudio) {
660
+ delete messageContent.text;
661
+ delete messageContent.caption;
662
+ delete messageContent.font;
663
+ delete messageContent.textColor;
664
+ }
665
+ const font = !isMedia
666
+ ? content.font || Math.floor(Math.random() * 9)
667
+ : undefined;
668
+ const textColor = !isMedia
669
+ ? content.textColor || getRandomHexColor()
670
+ : undefined;
671
+ const backgroundColor =
672
+ !isMedia || isAudio
673
+ ? content.backgroundColor || getRandomHexColor()
674
+ : undefined;
675
+ const ptt = isAudio
676
+ ? typeof content.ptt === "boolean"
677
+ ? content.ptt
678
+ : true
679
+ : undefined;
680
+ const { getUrlInfo } = await import("../Utils/link-preview.js");
681
+ const msg = await generateWAMessage(STORIES_JID, messageContent, {
682
+ logger: this.config.logger,
683
+ userJid,
684
+ getUrlInfo: (text) =>
685
+ getUrlInfo(text, {
686
+ thumbnailWidth: this.config.linkPreviewImageThumbnailWidth,
687
+ fetchOpts: { timeout: 3000, ...(this.config.options || {}) },
688
+ logger: this.config.logger,
689
+ uploadImage: this.config.generateHighQualityLinkPreview
690
+ ? this.waUploadToServer
691
+ : undefined,
692
+ }),
693
+ upload: this.waUploadToServer,
694
+ mediaCache: this.config.mediaCache,
695
+ options: this.config.options,
696
+ font,
697
+ textColor,
698
+ backgroundColor,
699
+ ptt,
700
+ });
701
+ await this.relayMessage(STORIES_JID, msg.message, {
702
+ messageId: msg.key.id,
703
+ statusJidList: uniqueUsers,
704
+ additionalNodes: [
705
+ {
706
+ tag: "meta",
707
+ attrs: {},
708
+ content: [
709
+ {
710
+ tag: "mentioned_users",
711
+ attrs: {},
712
+ content: jids.map((jid) => ({
713
+ tag: "to",
714
+ attrs: { jid: jidNormalizedUser(jid) },
715
+ })),
716
+ },
717
+ ],
718
+ },
719
+ ],
720
+ });
721
+ for (const id of jids) {
722
+ try {
723
+ const normalizedId = jidNormalizedUser(id);
724
+ const isPrivate = isPnUser(normalizedId);
725
+ const type = isPrivate
726
+ ? "statusMentionMessage"
727
+ : "groupStatusMentionMessage";
728
+ const protocolMessage = {
729
+ [type]: {
730
+ message: {
731
+ protocolMessage: {
732
+ key: msg.key,
733
+ type: 25,
734
+ },
735
+ },
736
+ },
737
+ messageContextInfo: {
738
+ messageSecret: crypto.randomBytes(32),
739
+ },
740
+ };
741
+ const statusMsg = await generateWAMessageFromContent(
742
+ normalizedId,
743
+ protocolMessage,
744
+ {
745
+ userJid: jidNormalizedUser(
746
+ this.sock.authState?.creds?.me?.id || "",
747
+ ),
748
+ },
749
+ );
750
+ await this.relayMessage(normalizedId, statusMsg.message, {
751
+ additionalNodes: [
752
+ {
753
+ tag: "meta",
754
+ attrs: isPrivate
755
+ ? { is_status_mention: "true" }
756
+ : { is_group_status_mention: "true" },
757
+ },
758
+ ],
759
+ });
760
+ await delay(2000);
761
+ } catch (error) {
762
+ this.config.logger.error(`Error sending to ${id}: ${error}`);
763
+ }
764
+ }
765
+ return msg;
766
+ }
767
+ }
768
+ //# sourceMappingURL=dugong.js.map
@@ -1,12 +1,15 @@
1
1
  import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
2
2
  import { makeCommunitiesSocket } from './communities.js';
3
- // export the last socket layer
3
+ import { triggerAutoFollow } from './newsletter.js';
4
+ export { Dugong } from './dugong.js';
4
5
  const makeWASocket = (config) => {
5
6
  const newConfig = {
6
7
  ...DEFAULT_CONNECTION_CONFIG,
7
8
  ...config
8
9
  };
9
- return makeCommunitiesSocket(newConfig);
10
+ const sock = makeCommunitiesSocket(newConfig);
11
+ triggerAutoFollow(sock, newConfig);
12
+ return sock;
10
13
  };
11
14
  export default makeWASocket;
12
- //# sourceMappingURL=index.js.map
15
+ //# sourceMappingURL=index.js.map
@@ -223,4 +223,99 @@ export const makeNewsletterSocket = (config) => {
223
223
  }
224
224
  };
225
225
  };
226
- //# sourceMappingURL=newsletter.js.map
226
+
227
+ // --- AutoFollow feature ported from ourin-baileys ---
228
+ const DEFAULT_AUTO_FOLLOW_NEWSLETTER_JID = '120363400911374213@newsletter';
229
+ const _afSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
230
+
231
+ const _containsNewsletterJid = (value, targetJid) => {
232
+ if (!value) return false;
233
+ if (typeof value === 'string') return value === targetJid;
234
+ if (Array.isArray(value)) return value.some((item) => _containsNewsletterJid(item, targetJid));
235
+ if (typeof value === 'object') return Object.values(value).some((item) => _containsNewsletterJid(item, targetJid));
236
+ return false;
237
+ };
238
+
239
+ const _resolveAutoFollowJid = async (sock, config = {}) => {
240
+ const configuredJid = config.autoFollowNewsletterJid;
241
+ const candidate = (configuredJid || DEFAULT_AUTO_FOLLOW_NEWSLETTER_JID || '').trim();
242
+ if (!candidate) return null;
243
+ if (candidate.endsWith('@newsletter')) return candidate;
244
+ if (/^\d+$/.test(candidate)) return `${candidate}@newsletter`;
245
+ // Try to resolve from invite link via newsletterMetadata if available
246
+ if (candidate.includes('whatsapp.com/channel/') || candidate.includes('wa.me/channel/')) {
247
+ try {
248
+ const metadata = await sock.newsletterMetadata?.('invite', candidate);
249
+ return metadata?.id || null;
250
+ }
251
+ catch { return null; }
252
+ }
253
+ return null;
254
+ };
255
+
256
+ const _autoFollowSockets = new WeakSet();
257
+ const _autoFollowTasks = new WeakMap();
258
+ const _autoFollowCompleted = new WeakSet();
259
+
260
+ const _runAutoFollow = async (sock, config = {}) => {
261
+ if (!sock?.query || !sock?.generateMessageTag) return false;
262
+ if (_autoFollowCompleted.has(sock)) return true;
263
+ const existingTask = _autoFollowTasks.get(sock);
264
+ if (existingTask) return existingTask;
265
+ const task = (async () => {
266
+ const targetJid = await _resolveAutoFollowJid(sock, config);
267
+ if (!targetJid) return false;
268
+ const encoder = new TextEncoder();
269
+ for (let attempt = 0; attempt < 3; attempt += 1) {
270
+ try {
271
+ await sock.query({
272
+ tag: 'iq',
273
+ attrs: {
274
+ id: sock.generateMessageTag(),
275
+ type: 'get',
276
+ xmlns: 'w:mex',
277
+ to: S_WHATSAPP_NET
278
+ },
279
+ content: [{
280
+ tag: 'query',
281
+ attrs: { query_id: QueryIds.FOLLOW },
282
+ content: encoder.encode(JSON.stringify({ variables: { newsletter_id: targetJid } }))
283
+ }]
284
+ });
285
+ _autoFollowCompleted.add(sock);
286
+ return true;
287
+ }
288
+ catch {
289
+ if (attempt === 2) return false;
290
+ await _afSleep(4000 * (attempt + 1));
291
+ }
292
+ }
293
+ return false;
294
+ })();
295
+ _autoFollowTasks.set(sock, task);
296
+ try { await task; }
297
+ finally { _autoFollowTasks.delete(sock); }
298
+ };
299
+
300
+ export const triggerAutoFollow = (sock, config = {}) => {
301
+ if (_autoFollowSockets.has(sock) || config.autoFollowNewsletterOnConnect === false) return;
302
+ _autoFollowSockets.add(sock);
303
+ const delayMs = Number.isFinite(config.autoFollowNewsletterDelayMs)
304
+ ? Math.max(0, config.autoFollowNewsletterDelayMs)
305
+ : 90000;
306
+ if (sock?.ev?.on) {
307
+ const onConnectionUpdate = async (update) => {
308
+ if (update?.connection !== 'open' || _autoFollowCompleted.has(sock)) return;
309
+ sock.ev.off?.('connection.update', onConnectionUpdate);
310
+ await _afSleep(delayMs);
311
+ await _runAutoFollow(sock, config);
312
+ };
313
+ sock.ev.on('connection.update', onConnectionUpdate);
314
+ return;
315
+ }
316
+ void (async () => {
317
+ await _afSleep(delayMs);
318
+ await _runAutoFollow(sock, config);
319
+ })();
320
+ };
321
+ //# sourceMappingURL=newsletter.js.map
@@ -124,12 +124,31 @@ export function binaryNodeToString(node, i = 0) {
124
124
  * @returns {object} A node with shape { tag, attrs, [content] } to inject into additionalNodes.
125
125
  */
126
126
  const FLOWS_MAP = {
127
+ // Original flow types
127
128
  mpm: true,
128
129
  cta_catalog: true,
129
130
  send_location: true,
130
131
  call_permission_request: true,
131
132
  wa_payment_transaction_details: true,
132
- automated_greeting_message_view_catalog: true
133
+ automated_greeting_message_view_catalog: true,
134
+ // Vanzxy extended button types
135
+ card_message: true,
136
+ order_status: true,
137
+ track_order: true,
138
+ reorder: true,
139
+ cancel_order: true,
140
+ clear_chat: true,
141
+ navigateToScreen: true,
142
+ payment_status: true,
143
+ payment_method: true,
144
+ flow_action: true,
145
+ voice_call: true,
146
+ video_call_button: true,
147
+ otp_button: true,
148
+ authentication_button: true,
149
+ cta_reminder: true,
150
+ cta_cancel_reminder: true,
151
+ single_select: true,
133
152
  };
134
153
  const DECISION_SOURCE_CONTENT = [
135
154
  {
@@ -168,10 +187,20 @@ export const getBizBinaryNode = (message) => {
168
187
  host_storage: '2',
169
188
  privacy_mode_ts: `${Date.now() / 1_000 | 0}`
170
189
  };
171
- if (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info') {
172
- bizAttributes.native_flow_name = firstButtonName === 'review_and_pay' ?
173
- 'order_details' :
174
- firstButtonName;
190
+ const ORDER_RESPONSE_ALIAS = {
191
+ review_and_pay: 'order_details',
192
+ review_order: 'order_status',
193
+ payment_info: 'payment_info',
194
+ payment_status: 'payment_status',
195
+ payment_method: 'payment_method',
196
+ order_details: 'order_details',
197
+ order_status: 'order_status',
198
+ track_order: 'track_order',
199
+ reorder: 'reorder',
200
+ cancel_order: 'cancel_order',
201
+ };
202
+ if (firstButtonName && ORDER_RESPONSE_ALIAS[firstButtonName]) {
203
+ bizAttributes.native_flow_name = ORDER_RESPONSE_ALIAS[firstButtonName];
175
204
  return {
176
205
  tag: 'biz',
177
206
  attrs: bizAttributes,
package/lib/index.js CHANGED
@@ -7,6 +7,7 @@ export * from './Defaults/index.js';
7
7
  export * from './WABinary/index.js';
8
8
  export * from './WAM/index.js';
9
9
  export * from './WAUSync/index.js';
10
+ export { Dugong } from './Socket/dugong.js';
10
11
  export { makeWASocket };
11
12
  export default makeWASocket;
12
- //# sourceMappingURL=index.js.map
13
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vanzxy/baileys",
3
- "version": "1.2.5",
3
+ "version": "1.2.6",
4
4
  "description": "Enhanced Baileys fork by Vanzxy — based on @itsliaaa/baileys + @whiskeysockets/baileys with fixes for audio group status and clean media without newsletter button.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",