@vinzsocket/baileys 3.2.5 → 3.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.
@@ -1,115 +1,71 @@
1
1
  // dugong.js — extended message builders
2
- // Handles: Request Payment, Product, Interactive (buttons/native flow/external ad reply/
3
- // document+thumbnail), Album, Event, Poll Result, Group Status V2 (group story),
4
- // List Message (legacy flat + nested multi-section), Nested Section List.
5
- // Ported from baileys-lily (Socket/dugong.js), adapted to ESM for Harps-Baileys.
6
- // v7 native-flow button shapes fully supported: cta_url, cta_call, cta_copy, cta_reminder,
7
- // cta_cancel_reminder, address_message, send_location, quick_reply, single_select,
8
- // review_and_pay, review_order, mpm (Multi-Product Message).
2
+ // Handles: Request Payment, Product, Interactive (NF V7 full), Album, Event,
3
+ // Poll Result, Group Status V2, Nested Legacy List, Multi-Select (chained list engine).
4
+ //
5
+ // Native Flow V7 button shapes:
6
+ // cta_url, cta_call, cta_copy, cta_reminder, cta_cancel_reminder,
7
+ // address_message, send_location, quick_reply, single_select,
8
+ // review_and_pay, review_order, mpm
9
9
 
10
10
  import { randomBytes } from 'crypto';
11
11
  import { proto } from '../../WAProto/index.js';
12
12
  import { normalizeMentions } from '../Utils/mention.js';
13
13
 
14
- // ─── Native Flow Button Builders (V7) ────────────────────────────────────────
15
- /**
16
- * Semua builder di bawah ini menghasilkan objek yang langsung dipakai di
17
- * interactiveMessage.nativeFlowMessage.buttons[]
18
- * atau di conn.sendInteractive({ buttons: [...] })
19
- */
14
+ // ─── NF V7 Button Builders ────────────────────────────────────────────────────
20
15
 
21
- /** Tombol buka URL */
22
- export const nfButtonUrl = ({ id = '', displayText, url, merchantUrl = url }) => ({
16
+ export const nfButtonUrl = ({ id, displayText, url, merchantUrl }) => ({
23
17
  name: 'cta_url',
24
- buttonParamsJson: JSON.stringify({
25
- display_text: displayText,
26
- url,
27
- merchant_url: merchantUrl
28
- }),
18
+ buttonParamsJson: JSON.stringify({ display_text: displayText, url, merchant_url: merchantUrl || url }),
29
19
  ...(id ? { id } : {})
30
20
  });
31
21
 
32
- /** Tombol telepon */
33
- export const nfButtonCall = ({ id = '', displayText, phoneNumber }) => ({
22
+ export const nfButtonCall = ({ id, displayText, phoneNumber }) => ({
34
23
  name: 'cta_call',
35
- buttonParamsJson: JSON.stringify({
36
- display_text: displayText,
37
- phone_number: phoneNumber
38
- }),
24
+ buttonParamsJson: JSON.stringify({ display_text: displayText, phone_number: phoneNumber }),
39
25
  ...(id ? { id } : {})
40
26
  });
41
27
 
42
- /** Tombol salin teks / kode */
43
- export const nfButtonCopy = ({ id = '', displayText, copyCode }) => ({
28
+ export const nfButtonCopy = ({ id, displayText, copyCode }) => ({
44
29
  name: 'cta_copy',
45
- buttonParamsJson: JSON.stringify({
46
- display_text: displayText,
47
- copy_code: copyCode
48
- }),
30
+ buttonParamsJson: JSON.stringify({ display_text: displayText, copy_code: copyCode }),
49
31
  ...(id ? { id } : {})
50
32
  });
51
33
 
52
- /** Tombol set reminder */
53
- export const nfButtonReminder = ({ id = '', displayText, title, notes, startTime, endTime, timezone = 'Asia/Jakarta' }) => ({
34
+ export const nfButtonReminder = ({ id, displayText, title, notes, startTime, endTime, timezone = 'Asia/Jakarta' }) => ({
54
35
  name: 'cta_reminder',
55
- buttonParamsJson: JSON.stringify({
56
- display_text: displayText,
57
- title,
58
- notes,
59
- start_timestamp: startTime,
60
- end_timestamp: endTime,
61
- timezone
62
- }),
36
+ buttonParamsJson: JSON.stringify({ display_text: displayText, title, notes, start_timestamp: startTime, end_timestamp: endTime, timezone }),
63
37
  ...(id ? { id } : {})
64
38
  });
65
39
 
66
- /** Tombol batalkan reminder */
67
- export const nfButtonCancelReminder = ({ id = '', displayText, reminderKey }) => ({
40
+ export const nfButtonCancelReminder = ({ id, displayText, reminderKey }) => ({
68
41
  name: 'cta_cancel_reminder',
69
- buttonParamsJson: JSON.stringify({
70
- display_text: displayText,
71
- reminder_key: reminderKey
72
- }),
42
+ buttonParamsJson: JSON.stringify({ display_text: displayText, reminder_key: reminderKey }),
73
43
  ...(id ? { id } : {})
74
44
  });
75
45
 
76
- /** Tombol isi alamat */
77
- export const nfButtonAddress = ({ id = '', displayText, label = '' }) => ({
46
+ export const nfButtonAddress = ({ id, displayText, label = '' }) => ({
78
47
  name: 'address_message',
79
- buttonParamsJson: JSON.stringify({
80
- display_text: displayText,
81
- label
82
- }),
48
+ buttonParamsJson: JSON.stringify({ display_text: displayText, label }),
83
49
  ...(id ? { id } : {})
84
50
  });
85
51
 
86
- /** Tombol kirim lokasi */
87
- export const nfButtonLocation = ({ id = '', displayText }) => ({
52
+ export const nfButtonLocation = ({ id, displayText }) => ({
88
53
  name: 'send_location',
89
- buttonParamsJson: JSON.stringify({
90
- display_text: displayText
91
- }),
54
+ buttonParamsJson: JSON.stringify({ display_text: displayText }),
92
55
  ...(id ? { id } : {})
93
56
  });
94
57
 
95
- /** Tombol quick reply (balas cepat dengan payload custom) */
96
- export const nfButtonQuickReply = ({ id = '', displayText, payload = '' }) => ({
58
+ export const nfButtonQuickReply = ({ id, displayText, payload }) => ({
97
59
  name: 'quick_reply',
98
- buttonParamsJson: JSON.stringify({
99
- display_text: displayText,
100
- id: id || payload
101
- }),
60
+ buttonParamsJson: JSON.stringify({ display_text: displayText, id: id || payload || displayText }),
102
61
  ...(id ? { id } : {})
103
62
  });
104
63
 
105
64
  /**
106
- * Tombol dropdown single-select (bottom sheet list pilihan)
107
- * @param {Object} opts
108
- * @param {string} opts.displayText - label tombol
109
- * @param {Array} opts.sections - array section, format:
110
- * [{ title: 'Section Title', highlight_label: '', rows: [{ id, title, description? }] }]
65
+ * Single-select dropdown — 1 tombol yang buka bottom sheet list.
66
+ * sections: [{ title, highlight_label?, rows: [{ id, title, description? }] }]
111
67
  */
112
- export const nfButtonSingleSelect = ({ id = '', displayText, sections = [] }) => ({
68
+ export const nfButtonSingleSelect = ({ id, displayText, sections = [] }) => ({
113
69
  name: 'single_select',
114
70
  buttonParamsJson: JSON.stringify({
115
71
  title: displayText,
@@ -117,8 +73,8 @@ export const nfButtonSingleSelect = ({ id = '', displayText, sections = [] }) =>
117
73
  title: sec.title || '',
118
74
  highlight_label: sec.highlight_label || '',
119
75
  rows: (sec.rows || []).map(r => ({
120
- id: r.id,
121
- title: r.title,
76
+ id: r.id || r.rowId || '',
77
+ title: r.title || '',
122
78
  ...(r.description ? { description: r.description } : {})
123
79
  }))
124
80
  }))
@@ -126,41 +82,30 @@ export const nfButtonSingleSelect = ({ id = '', displayText, sections = [] }) =>
126
82
  ...(id ? { id } : {})
127
83
  });
128
84
 
129
- /** Tombol review & bayar */
130
- export const nfButtonReviewPay = ({ id = '', currency = 'IDR', totalAmount1000, subtotal, tax, items = [], merchant = {} }) => ({
85
+ /**
86
+ * Multi-select: array dari beberapa single_select button sekaligus.
87
+ * selectors: [{ id?, displayText, sections: [...] }]
88
+ */
89
+ export const nfButtonMultiSelect = (selectors = []) =>
90
+ selectors.map((sel, i) => nfButtonSingleSelect({
91
+ id: sel.id || `select_${i}`,
92
+ displayText: sel.displayText,
93
+ sections: sel.sections
94
+ }));
95
+
96
+ export const nfButtonReviewPay = ({ id, currency = 'IDR', totalAmount1000, subtotal, tax, items = [], merchant = {} }) => ({
131
97
  name: 'review_and_pay',
132
- buttonParamsJson: JSON.stringify({
133
- currency,
134
- total_amount: { value: totalAmount1000, offset: 1000 },
135
- subtotal,
136
- tax,
137
- items,
138
- order: {
139
- status: 'pending',
140
- items
141
- },
142
- merchant
143
- }),
98
+ buttonParamsJson: JSON.stringify({ currency, total_amount: { value: totalAmount1000, offset: 1000 }, subtotal, tax, items, order: { status: 'pending', items }, merchant }),
144
99
  ...(id ? { id } : {})
145
100
  });
146
101
 
147
- /** Tombol review order */
148
- export const nfButtonReviewOrder = ({ id = '', referenceId, type = 'ORDER', orderId }) => ({
102
+ export const nfButtonReviewOrder = ({ id, referenceId, type = 'ORDER', orderId }) => ({
149
103
  name: 'review_order',
150
- buttonParamsJson: JSON.stringify({
151
- reference_id: referenceId,
152
- type,
153
- order_id: orderId
154
- }),
104
+ buttonParamsJson: JSON.stringify({ reference_id: referenceId, type, order_id: orderId }),
155
105
  ...(id ? { id } : {})
156
106
  });
157
107
 
158
- /**
159
- * Multi-Product Message (MPM) button — tampilkan katalog produk
160
- * @param {Object} opts
161
- * @param {Array} opts.sections - [{ title, productItems: [{ productId }] }]
162
- */
163
- export const nfButtonMPM = ({ id = '', sections = [] }) => ({
108
+ export const nfButtonMPM = ({ id, sections = [] }) => ({
164
109
  name: 'mpm',
165
110
  buttonParamsJson: JSON.stringify({
166
111
  sections: sections.map(sec => ({
@@ -171,43 +116,22 @@ export const nfButtonMPM = ({ id = '', sections = [] }) => ({
171
116
  ...(id ? { id } : {})
172
117
  });
173
118
 
174
- // ─── Nested Section List ──────────────────────────────────────────────────────
119
+ // ─── Nested Legacy List Helper ────────────────────────────────────────────────
120
+
175
121
  /**
176
- * Build legacy `listMessage` payload — kompatibel dengan semua WhatsApp client.
177
- *
178
- * Mendukung DUA mode:
179
- * 1. **Flat (sendList lama)** — sections berisi rows langsung.
180
- * 2. **Nested** — rows punya field `rows` sendiri (sub-list / list dalam list).
181
- * Nested rows di-flatten ke satu section baru ber-title = row.title induk.
122
+ * Build raw proto listMessage payload dengan nested row flattening.
123
+ * Row yang punya field `rows` sendiri otomatis dijadikan section baru.
182
124
  *
183
- * @param {Object} opts
184
- * @param {string} opts.title - judul pesan
185
- * @param {string} opts.buttonText - label tombol buka list
186
- * @param {string} [opts.footer] - footer pesan
187
- * @param {Array} opts.sections - array section:
188
- * {
189
- * title: 'Section Title',
190
- * rows: [
191
- * // flat row:
192
- * { rowId, title, description? },
193
- * // nested row (list dalam list):
194
- * { rowId?, title: 'Parent Label', rows: [{ rowId, title, description? }] }
195
- * ]
196
- * }
197
- *
198
- * @returns {Object} raw proto listMessage payload
125
+ * sections: [{ title, rows: [ {rowId,title,description?} | {title, rows:[...]} ] }]
199
126
  */
200
127
  export const buildNestedListMessage = ({ title, buttonText, footer = '', sections = [] }) => {
201
- const flattenedSections = [];
202
-
128
+ const flat = [];
203
129
  for (const section of sections) {
204
130
  const topRows = [];
205
- const nestedSections = [];
206
-
131
+ const childSections = [];
207
132
  for (const row of (section.rows || [])) {
208
133
  if (Array.isArray(row.rows) && row.rows.length > 0) {
209
- // Nested row → jadikan section baru dengan title = row.title
210
- nestedSections.push({
134
+ childSections.push({
211
135
  title: row.title || '',
212
136
  rows: row.rows.map(r => ({
213
137
  rowId: r.rowId || r.id || '',
@@ -216,44 +140,30 @@ export const buildNestedListMessage = ({ title, buttonText, footer = '', section
216
140
  }))
217
141
  });
218
142
  } else {
219
- topRows.push({
220
- rowId: row.rowId || row.id || '',
221
- title: row.title || '',
222
- description: row.description || ''
223
- });
143
+ topRows.push({ rowId: row.rowId || row.id || '', title: row.title || '', description: row.description || '' });
224
144
  }
225
145
  }
226
-
227
- if (topRows.length > 0) {
228
- flattenedSections.push({
229
- title: section.title || '',
230
- rows: topRows
231
- });
232
- }
233
-
234
- for (const ns of nestedSections) {
235
- flattenedSections.push(ns);
236
- }
146
+ if (topRows.length > 0) flat.push({ title: section.title || '', rows: topRows });
147
+ for (const cs of childSections) flat.push(cs);
237
148
  }
238
-
239
149
  return {
240
150
  listMessage: {
241
151
  title,
242
152
  description: footer,
243
153
  buttonText,
244
154
  listType: 1, // SINGLE_SELECT
245
- sections: flattenedSections
155
+ sections: flat
246
156
  }
247
157
  };
248
158
  };
249
159
 
250
160
  // ─── ExtendedMessageBuilder ───────────────────────────────────────────────────
161
+
251
162
  export class ExtendedMessageBuilder {
252
163
  constructor(utils, waUploadToServer, relayMessageFn) {
253
164
  this.utils = utils;
254
165
  this.relayMessage = relayMessageFn;
255
166
  this.waUploadToServer = waUploadToServer;
256
-
257
167
  this.bail = {
258
168
  generateWAMessageContent: this.utils.generateWAMessageContent,
259
169
  generateMessageID: this.utils.generateMessageID,
@@ -263,45 +173,25 @@ export class ExtendedMessageBuilder {
263
173
 
264
174
  detectType(content) {
265
175
  if (content.requestPaymentMessage) return 'PAYMENT';
266
- if (content.productMessage) return 'PRODUCT';
267
- if (content.interactiveMessage) return 'INTERACTIVE';
268
- if (content.albumMessage) return 'ALBUM';
269
- if (content.eventMessage) return 'EVENT';
270
- if (content.pollResultMessage) return 'POLL_RESULT';
271
- if (content.groupStatusMessage) return 'GROUP_STORY';
272
- if (content.nestedListMessage) return 'NESTED_LIST';
176
+ if (content.productMessage) return 'PRODUCT';
177
+ if (content.interactiveMessage) return 'INTERACTIVE';
178
+ if (content.albumMessage) return 'ALBUM';
179
+ if (content.eventMessage) return 'EVENT';
180
+ if (content.pollResultMessage) return 'POLL_RESULT';
181
+ if (content.groupStatusMessage) return 'GROUP_STORY';
182
+ if (content.nestedListMessage) return 'NESTED_LIST';
183
+ if (content.multiSelectMessage) return 'MULTI_SELECT';
273
184
  return null;
274
185
  }
275
186
 
276
- /** Request Payment — tagihan pembayaran + sticker/note & background */
277
187
  async handlePayment(content, quoted) {
278
188
  const data = content.requestPaymentMessage;
279
189
  let notes = {};
280
-
281
190
  if (data.sticker?.stickerMessage) {
282
- notes = {
283
- stickerMessage: {
284
- ...data.sticker.stickerMessage,
285
- contextInfo: {
286
- stanzaId: quoted?.key?.id,
287
- participant: quoted?.key?.participant || content.sender,
288
- quotedMessage: quoted?.message
289
- }
290
- }
291
- };
191
+ notes = { stickerMessage: { ...data.sticker.stickerMessage, contextInfo: { stanzaId: quoted?.key?.id, participant: quoted?.key?.participant || content.sender, quotedMessage: quoted?.message } } };
292
192
  } else if (data.note) {
293
- notes = {
294
- extendedTextMessage: {
295
- text: data.note,
296
- contextInfo: {
297
- stanzaId: quoted?.key?.id,
298
- participant: quoted?.key?.participant || content.sender,
299
- quotedMessage: quoted?.message
300
- }
301
- }
302
- };
193
+ notes = { extendedTextMessage: { text: data.note, contextInfo: { stanzaId: quoted?.key?.id, participant: quoted?.key?.participant || content.sender, quotedMessage: quoted?.message } } };
303
194
  }
304
-
305
195
  return {
306
196
  requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({
307
197
  expiryTimestamp: data.expiry || 0,
@@ -309,70 +199,27 @@ export class ExtendedMessageBuilder {
309
199
  currencyCodeIso4217: data.currency || 'IDR',
310
200
  requestFrom: data.from || '0@s.whatsapp.net',
311
201
  noteMessage: notes,
312
- background: data.background ?? {
313
- id: 'DEFAULT',
314
- placeholderArgb: 0xFFF0F0F0
315
- }
202
+ background: data.background ?? { id: 'DEFAULT', placeholderArgb: 0xFFF0F0F0 }
316
203
  })
317
204
  };
318
205
  }
319
206
 
320
- /** Product Message — katalog produk */
321
207
  async handleProduct(content, jid, quoted) {
322
- const {
323
- title,
324
- description,
325
- thumbnail,
326
- productId,
327
- retailerId,
328
- url,
329
- body = '',
330
- footer = '',
331
- buttons = [],
332
- priceAmount1000 = null,
333
- currencyCode = 'IDR'
334
- } = content.productMessage;
335
-
208
+ const { title, description, thumbnail, productId, retailerId, url, body = '', footer = '', buttons = [], priceAmount1000 = null, currencyCode = 'IDR' } = content.productMessage;
336
209
  let productImage;
337
-
338
210
  if (Buffer.isBuffer(thumbnail)) {
339
- const { imageMessage } = await this.utils.generateWAMessageContent(
340
- { image: thumbnail },
341
- { upload: this.waUploadToServer }
342
- );
211
+ const { imageMessage } = await this.utils.generateWAMessageContent({ image: thumbnail }, { upload: this.waUploadToServer });
343
212
  productImage = imageMessage;
344
- } else if (typeof thumbnail === 'object' && thumbnail?.url) {
345
- const { imageMessage } = await this.utils.generateWAMessageContent(
346
- { image: { url: thumbnail.url } },
347
- { upload: this.waUploadToServer }
348
- );
213
+ } else if (thumbnail?.url) {
214
+ const { imageMessage } = await this.utils.generateWAMessageContent({ image: { url: thumbnail.url } }, { upload: this.waUploadToServer });
349
215
  productImage = imageMessage;
350
216
  }
351
-
352
217
  return {
353
218
  viewOnceMessage: {
354
219
  message: {
355
220
  interactiveMessage: {
356
- body: { text: body },
357
- footer: { text: footer },
358
- header: {
359
- title,
360
- hasMediaAttachment: true,
361
- productMessage: {
362
- product: {
363
- productImage,
364
- productId,
365
- title,
366
- description,
367
- currencyCode,
368
- priceAmount1000,
369
- retailerId,
370
- url,
371
- productImageCount: 1
372
- },
373
- businessOwnerJid: '0@s.whatsapp.net'
374
- }
375
- },
221
+ body: { text: body }, footer: { text: footer },
222
+ header: { title, hasMediaAttachment: true, productMessage: { product: { productImage, productId, title, description, currencyCode, priceAmount1000, retailerId, url, productImageCount: 1 }, businessOwnerJid: '0@s.whatsapp.net' } },
376
223
  nativeFlowMessage: { buttons }
377
224
  }
378
225
  }
@@ -380,314 +227,159 @@ export class ExtendedMessageBuilder {
380
227
  };
381
228
  }
382
229
 
383
- /**
384
- * Interactive Message — button, copy code, native flow, bottom sheet,
385
- * limited time offer, document+thumbnail, external ad reply.
386
- * Semua V7 native-flow button shape didukung via helper exports di atas.
387
- */
388
230
  async handleInteractive(content, jid, quoted, options = {}) {
389
- const {
390
- title,
391
- footer,
392
- thumbnail,
393
- image,
394
- video,
395
- document,
396
- mimetype,
397
- fileName,
398
- jpegThumbnail,
399
- contextInfo = {},
400
- externalAdReply,
401
- buttons = [],
402
- nativeFlowMessage,
403
- header
404
- } = content.interactiveMessage;
405
-
231
+ const { title, footer, thumbnail, image, video, document, mimetype, fileName, jpegThumbnail, contextInfo = {}, externalAdReply, buttons = [], nativeFlowMessage, header } = content.interactiveMessage;
406
232
  let media = null;
407
-
408
- // Media handling (image, video, document)
409
233
  if (thumbnail || image) {
410
- const imgSource = thumbnail || image;
411
- const imgObj = typeof imgSource === 'object' && imgSource.url ? { url: imgSource.url } : imgSource;
412
- media = await this.utils.prepareWAMessageMedia(
413
- { image: imgObj },
414
- { upload: this.waUploadToServer }
415
- );
234
+ const src = thumbnail || image;
235
+ media = await this.utils.prepareWAMessageMedia({ image: src?.url ? { url: src.url } : src }, { upload: this.waUploadToServer });
416
236
  } else if (video) {
417
- const vidObj = typeof video === 'object' && video.url ? { url: video.url } : video;
418
- media = await this.utils.prepareWAMessageMedia(
419
- { video: vidObj },
420
- { upload: this.waUploadToServer }
421
- );
237
+ media = await this.utils.prepareWAMessageMedia({ video: video?.url ? { url: video.url } : video }, { upload: this.waUploadToServer });
422
238
  } else if (document) {
423
- // Document + Thumbnail: kirim PDF/dokumen dengan preview
424
- let documentPayload = { document };
425
- if (jpegThumbnail) {
426
- documentPayload.jpegThumbnail = typeof jpegThumbnail === 'object' && jpegThumbnail.url
427
- ? { url: jpegThumbnail.url }
428
- : jpegThumbnail;
429
- }
430
- media = await this.utils.prepareWAMessageMedia(
431
- documentPayload,
432
- { upload: this.waUploadToServer }
433
- );
239
+ let dp = { document };
240
+ if (jpegThumbnail) dp.jpegThumbnail = jpegThumbnail?.url ? { url: jpegThumbnail.url } : jpegThumbnail;
241
+ media = await this.utils.prepareWAMessageMedia(dp, { upload: this.waUploadToServer });
434
242
  if (fileName && media.documentMessage) media.documentMessage.fileName = fileName;
435
243
  if (mimetype && media.documentMessage) media.documentMessage.mimetype = mimetype;
436
244
  }
437
245
 
438
- // Build interactive message
439
- let interactiveMessage = {
440
- body: { text: title || '' },
441
- footer: { text: footer || '' }
442
- };
443
-
444
- // Buttons / nativeFlowMessage
246
+ let im = { body: { text: title || '' }, footer: { text: footer || '' } };
445
247
  if (buttons && buttons.length > 0) {
446
- interactiveMessage.nativeFlowMessage = { buttons };
447
- if (nativeFlowMessage) {
448
- interactiveMessage.nativeFlowMessage = {
449
- ...interactiveMessage.nativeFlowMessage,
450
- ...nativeFlowMessage
451
- };
452
- }
248
+ im.nativeFlowMessage = { buttons };
249
+ if (nativeFlowMessage) im.nativeFlowMessage = { ...im.nativeFlowMessage, ...nativeFlowMessage };
453
250
  } else if (nativeFlowMessage) {
454
- interactiveMessage.nativeFlowMessage = nativeFlowMessage;
455
- }
456
-
457
- // Header with media
458
- if (media) {
459
- interactiveMessage.header = {
460
- title: header || '',
461
- hasMediaAttachment: true,
462
- ...media
463
- };
464
- } else {
465
- interactiveMessage.header = {
466
- title: header || '',
467
- hasMediaAttachment: false
468
- };
251
+ im.nativeFlowMessage = nativeFlowMessage;
469
252
  }
253
+ im.header = media ? { title: header || '', hasMediaAttachment: true, ...media } : { title: header || '', hasMediaAttachment: false };
470
254
 
471
- // contextInfo (mentions + external ad reply)
472
- let finalContextInfo = {
473
- forwardingScore: contextInfo.forwardingScore || 0,
474
- isForwarded: contextInfo.isForwarded || false,
475
- ...contextInfo,
476
- mentionedJid: normalizeMentions(contextInfo.mentionedJid || options.mentions || [])
477
- };
478
-
479
- if (externalAdReply) {
480
- finalContextInfo.externalAdReply = {
481
- title: externalAdReply.title || '',
482
- body: externalAdReply.body || '',
483
- mediaType: externalAdReply.mediaType || 1,
484
- thumbnailUrl: externalAdReply.thumbnailUrl || '',
485
- mediaUrl: externalAdReply.mediaUrl || '',
486
- sourceUrl: externalAdReply.sourceUrl || '',
487
- showAdAttribution: externalAdReply.showAdAttribution || false,
488
- renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false,
489
- ...externalAdReply
490
- };
491
- }
492
-
493
- if (finalContextInfo.mentionedJid && !Array.isArray(finalContextInfo.mentionedJid)) {
494
- finalContextInfo.mentionedJid = [finalContextInfo.mentionedJid];
495
- }
496
-
497
- if (Object.keys(finalContextInfo).length > 0) {
498
- interactiveMessage.contextInfo = finalContextInfo;
499
- }
255
+ let ci = { forwardingScore: contextInfo.forwardingScore || 0, isForwarded: contextInfo.isForwarded || false, ...contextInfo, mentionedJid: normalizeMentions(contextInfo.mentionedJid || options.mentions || []) };
256
+ if (externalAdReply) ci.externalAdReply = { title: '', body: '', mediaType: 1, thumbnailUrl: '', mediaUrl: '', sourceUrl: '', showAdAttribution: false, renderLargerThumbnail: false, ...externalAdReply };
257
+ if (!Array.isArray(ci.mentionedJid)) ci.mentionedJid = [ci.mentionedJid].filter(Boolean);
258
+ if (Object.keys(ci).length > 0) im.contextInfo = ci;
259
+ return { interactiveMessage: im };
260
+ }
500
261
 
501
- return { interactiveMessage };
262
+ /**
263
+ * Multi-Select — satu pesan dengan BEBERAPA tombol single_select terpisah.
264
+ * Tiap selector membuka bottom sheet sendiri dengan sections & rows di dalamnya.
265
+ *
266
+ * content.multiSelectMessage = {
267
+ * title, footer?, header?, image?,
268
+ * selectors: [{ id?, displayText, sections: [{title, rows:[{id,title,description?}]}] }],
269
+ * extraButtons?: [ nfButtonQuickReply(...), ... ]
270
+ * }
271
+ */
272
+ async handleMultiSelect(content, jid, quoted, options = {}) {
273
+ const { title, footer, image, video, thumbnail, selectors = [], extraButtons = [], contextInfo = {}, header } = content.multiSelectMessage;
274
+ const buttons = [
275
+ ...nfButtonMultiSelect(selectors),
276
+ ...extraButtons
277
+ ];
278
+ return this.handleInteractive({
279
+ interactiveMessage: { title, footer, image, video, thumbnail, header, contextInfo, buttons }
280
+ }, jid, quoted, options);
502
281
  }
503
282
 
504
283
  /**
505
- * Nested List Message — list yang isinya ada list lagi.
506
- * Flat sections biasa juga tetap jalan.
284
+ * Nested List — legacy listMessage dengan auto-flatten nested rows.
507
285
  *
508
286
  * content.nestedListMessage = {
509
287
  * title, buttonText, footer?,
510
- * sections: [
511
- * { title: 'Kategori A', rows: [
512
- * { rowId: 'a1', title: 'Item A1', description: '...' },
513
- * // nested:
514
- * { title: 'Sub-Kategori', rows: [
515
- * { rowId: 'b1', title: 'Item B1' },
516
- * { rowId: 'b2', title: 'Item B2' }
517
- * ]}
518
- * ]}
519
- * ]
288
+ * sections: [{ title, rows: [ flat_row | { title, rows:[...] } ] }]
520
289
  * }
521
290
  */
522
291
  async handleNestedList(content, jid, quoted) {
523
- const opts = content.nestedListMessage;
524
- const payload = buildNestedListMessage(opts);
525
-
526
- const msg = await this.utils.generateWAMessageFromContent(jid, {
292
+ const payload = buildNestedListMessage(content.nestedListMessage);
293
+ return await this.utils.generateWAMessageFromContent(jid, {
527
294
  viewOnceMessage: {
528
295
  message: {
529
- messageContextInfo: {
530
- deviceListMetadata: {},
531
- deviceListMetadataVersion: 2
532
- },
296
+ messageContextInfo: { deviceListMetadata: {}, deviceListMetadataVersion: 2 },
533
297
  ...payload
534
298
  }
535
299
  }
536
300
  }, { quoted });
537
-
538
- return msg;
539
301
  }
540
302
 
541
- /** Album Message — kirim banyak foto/video sekaligus */
542
303
  async handleAlbum(content, jid, quoted) {
543
304
  const array = content.albumMessage;
544
305
  const album = await this.utils.generateWAMessageFromContent(jid, {
545
- messageContextInfo: {
546
- messageSecret: randomBytes(32)
547
- },
306
+ messageContextInfo: { messageSecret: randomBytes(32) },
548
307
  albumMessage: {
549
- expectedImageCount: array.filter((a) => Object.prototype.hasOwnProperty.call(a, 'image')).length,
550
- expectedVideoCount: array.filter((a) => Object.prototype.hasOwnProperty.call(a, 'video')).length
308
+ expectedImageCount: array.filter(a => Object.hasOwn(a, 'image')).length,
309
+ expectedVideoCount: array.filter(a => Object.hasOwn(a, 'video')).length
551
310
  }
552
- }, {
553
- userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
554
- quoted,
555
- upload: this.waUploadToServer
556
- });
311
+ }, { userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net', quoted, upload: this.waUploadToServer });
557
312
 
558
- await this.relayMessage(jid, album.message, {
559
- messageId: album.key.id
560
- });
313
+ await this.relayMessage(jid, album.message, { messageId: album.key.id });
561
314
 
562
315
  for (const item of array) {
563
- const img = await this.utils.generateWAMessage(jid, item, {
564
- upload: this.waUploadToServer
565
- });
566
-
316
+ const img = await this.utils.generateWAMessage(jid, item, { upload: this.waUploadToServer });
567
317
  img.message.messageContextInfo = {
568
318
  messageSecret: randomBytes(32),
569
- messageAssociation: {
570
- associationType: 1,
571
- parentMessageKey: album.key
572
- },
573
- participant: jid,
574
- forwardingScore: 0,
575
- isForwarded: false
319
+ messageAssociation: { associationType: 1, parentMessageKey: album.key },
320
+ participant: jid, forwardingScore: 0, isForwarded: false
576
321
  };
577
-
578
322
  await this.relayMessage(jid, img.message, {
579
323
  messageId: img.key.id,
580
- quoted: {
581
- key: {
582
- remoteJid: album.key.remoteJid,
583
- id: album.key.id,
584
- fromMe: true,
585
- participant: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net'
586
- },
587
- message: album.message
588
- }
324
+ quoted: { key: { remoteJid: album.key.remoteJid, id: album.key.id, fromMe: true, participant: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net' }, message: album.message }
589
325
  });
590
326
  }
591
327
  return album;
592
328
  }
593
329
 
594
- /** Event Message — undangan acara dengan lokasi & waktu */
595
330
  async handleEvent(content, jid, quoted) {
596
- const eventData = content.eventMessage;
597
-
331
+ const e = content.eventMessage;
598
332
  const msg = await this.utils.generateWAMessageFromContent(jid, {
599
333
  viewOnceMessage: {
600
334
  message: {
601
- messageContextInfo: {
602
- deviceListMetadata: {},
603
- deviceListMetadataVersion: 2,
604
- messageSecret: randomBytes(32),
605
- supportPayload: JSON.stringify({
606
- version: 2,
607
- is_ai_message: true,
608
- should_show_system_message: true,
609
- ticket_id: randomBytes(16).toString('hex')
610
- })
611
- },
335
+ messageContextInfo: { deviceListMetadata: {}, deviceListMetadataVersion: 2, messageSecret: randomBytes(32), supportPayload: JSON.stringify({ version: 2, is_ai_message: true, should_show_system_message: true, ticket_id: randomBytes(16).toString('hex') }) },
612
336
  eventMessage: {
613
- contextInfo: {
614
- mentionedJid: [jid],
615
- participant: jid,
616
- remoteJid: 'status@broadcast'
617
- },
618
- isCanceled: eventData.isCanceled || false,
619
- name: eventData.name,
620
- description: eventData.description,
621
- location: eventData.location || {
622
- degreesLatitude: 0,
623
- degreesLongitude: 0,
624
- name: 'Location'
625
- },
626
- joinLink: eventData.joinLink || '',
627
- startTime: typeof eventData.startTime === 'string' ? parseInt(eventData.startTime, 10) : eventData.startTime || Date.now(),
628
- endTime: typeof eventData.endTime === 'string' ? parseInt(eventData.endTime, 10) : eventData.endTime || Date.now() + 3600000,
629
- extraGuestsAllowed: eventData.extraGuestsAllowed !== false
337
+ contextInfo: { mentionedJid: [jid], participant: jid, remoteJid: 'status@broadcast' },
338
+ isCanceled: e.isCanceled || false, name: e.name, description: e.description,
339
+ location: e.location || { degreesLatitude: 0, degreesLongitude: 0, name: 'Location' },
340
+ joinLink: e.joinLink || '',
341
+ startTime: typeof e.startTime === 'string' ? parseInt(e.startTime, 10) : e.startTime || Date.now(),
342
+ endTime: typeof e.endTime === 'string' ? parseInt(e.endTime, 10) : e.endTime || Date.now() + 3600000,
343
+ extraGuestsAllowed: e.extraGuestsAllowed !== false
630
344
  }
631
345
  }
632
346
  }
633
347
  }, { quoted });
634
-
635
- await this.relayMessage(jid, msg.message, {
636
- messageId: msg.key.id
637
- });
348
+ await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
638
349
  return msg;
639
350
  }
640
351
 
641
- /** Poll Result Message — tampilkan hasil polling */
642
352
  async handlePollResult(content, jid, quoted) {
643
- const pollData = content.pollResultMessage;
644
-
353
+ const p = content.pollResultMessage;
645
354
  const msg = await this.utils.generateWAMessageFromContent(jid, {
646
355
  pollResultSnapshotMessage: {
647
- name: pollData.name,
648
- pollVotes: pollData.pollVotes.map(vote => ({
649
- optionName: vote.optionName,
650
- optionVoteCount: typeof vote.optionVoteCount === 'number'
651
- ? vote.optionVoteCount.toString()
652
- : vote.optionVoteCount
653
- }))
356
+ name: p.name,
357
+ pollVotes: p.pollVotes.map(v => ({ optionName: v.optionName, optionVoteCount: typeof v.optionVoteCount === 'number' ? v.optionVoteCount.toString() : v.optionVoteCount }))
654
358
  }
655
- }, {
656
- userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
657
- quoted
658
- });
659
-
660
- await this.relayMessage(jid, msg.message, {
661
- messageId: msg.key.id
662
- });
663
-
359
+ }, { userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net', quoted });
360
+ await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
664
361
  return msg;
665
362
  }
666
363
 
667
- /** Group Status V2 — status di grup */
364
+ /**
365
+ * Group Status V2 — story ke grup.
366
+ * 3 mode:
367
+ * { message: <inner WAMessage> } → pakai langsung
368
+ * { raw: <msgPayload> } → relay langsung
369
+ * { image/video/text/... } → generate dulu
370
+ */
668
371
  async handleGroupStory(content, jid, quoted) {
669
372
  const storyData = content.groupStatusMessage;
670
- let waMsgContent;
671
-
373
+ let innerMessage;
672
374
  if (storyData.message) {
673
- waMsgContent = storyData;
375
+ innerMessage = storyData.message;
376
+ } else if (storyData.raw) {
377
+ return await this.relayMessage(jid, storyData.raw, { messageId: this.bail.generateMessageID() });
674
378
  } else {
675
- waMsgContent = await this.bail.generateWAMessageContent(storyData, {
676
- upload: this.waUploadToServer
677
- });
379
+ const generated = await this.bail.generateWAMessageContent(storyData, { upload: this.waUploadToServer });
380
+ innerMessage = generated;
678
381
  }
679
-
680
- const msg = {
681
- message: {
682
- groupStatusMessageV2: {
683
- message: waMsgContent.message || waMsgContent
684
- }
685
- }
686
- };
687
-
688
- return await this.relayMessage(jid, msg.message, {
689
- messageId: this.bail.generateMessageID()
690
- });
382
+ return await this.relayMessage(jid, { groupStatusMessageV2: { message: innerMessage } }, { messageId: this.bail.generateMessageID() });
691
383
  }
692
384
  }
693
385