@ruthless-imperium/baileys 1.0.2 → 1.0.3

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,561 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+ const crypto = __def(require("crypto"));
6
+ const { proto } = require("../../WAProto/index.js");
7
+ const { generateWAMessageFromContent, prepareWAMessageMedia } = require("../Utils/index.js");
8
+
9
+ const makeMessageBuilderSocket = (sock) => {
10
+ const { relayMessage, sendMessage, waUploadToServer } = sock;
11
+
12
+ // per-socket-instance poll state: id -> [{ vote, action }]
13
+ const pollActionStore = new Map();
14
+
15
+ /**
16
+ * Relay an arbitrary raw message content object, bypassing the normal
17
+ * content-type detection in sendMessage(). Useful when you've already
18
+ * built a proto-shaped message (e.g. from generateWAMessageFromContent)
19
+ * and just need it sent as-is.
20
+ */
21
+ const sendJsonMessage = async (jid, content = {}, options = {}) => {
22
+ const msg = generateWAMessageFromContent(jid, content, {});
23
+ return relayMessage(jid, msg.message, { messageId: msg.key.id, ...options });
24
+ };
25
+
26
+ /**
27
+ * Sends an HTML GenAI primitive rich response message.
28
+ * html: string template/raw HTML markup to be rendered.
29
+ */
30
+ const sendHtml = async (jid, html = '', options = {}) => {
31
+ const payloadData = Buffer.from(
32
+ JSON.stringify({
33
+ __typename: "GenAIUnifiedResponse",
34
+ response_id: crypto.randomUUID(),
35
+ sections: [
36
+ {
37
+ __typename: "GenAIUnifiedResponseSection",
38
+ view_model: {
39
+ __typename: "GenAISingleLayoutViewModel",
40
+ primitive: {
41
+ __typename: "FOAHtmlPrimitiveDemoDONOTUSE",
42
+ trusted_sources: [],
43
+ payload: String(html).trim()
44
+ }
45
+ }
46
+ }
47
+ ]
48
+ })
49
+ ).toString("base64");
50
+
51
+ const messageContent = {
52
+ botForwardedMessage: {
53
+ message: {
54
+ richResponseMessage: {
55
+ messageType: 1,
56
+ unifiedResponse: {
57
+ data: payloadData
58
+ },
59
+ contextInfo: {
60
+ isForwarded: true,
61
+ forwardOrigin: 4
62
+ }
63
+ }
64
+ }
65
+ }
66
+ };
67
+
68
+ return sendJsonMessage(jid, messageContent, options);
69
+ };
70
+
71
+ /**
72
+ * Sends a WA poll and remembers which "action" each option maps to.
73
+ */
74
+ const sendActionPoll = async (jid, name = '', pollOptions = [], options = {}) => {
75
+ const values = pollOptions.map(o => o.vote);
76
+ const pollMsg = await sendMessage(jid, { poll: { name, values, selectableCount: options.selectableCount || 1 } }, options);
77
+ pollActionStore.set(pollMsg.key.id, pollOptions);
78
+ return pollMsg;
79
+ };
80
+
81
+ /**
82
+ * Resolves selected poll option action.
83
+ */
84
+ const resolvePollAction = (pollMessageId, selectedVoteLabel) => {
85
+ const options = pollActionStore.get(pollMessageId);
86
+ return options?.find(o => o.vote === selectedVoteLabel)?.action;
87
+ };
88
+
89
+ /**
90
+ * Sends a set of media files as a single WA album.
91
+ */
92
+ const sendAlbumMessage = async (jid, media = [], contextInfo = {}) => {
93
+ const albumMsg = generateWAMessageFromContent(jid, proto.Message.fromObject({
94
+ albumMessage: {
95
+ expectedImageCount: media.filter(m => !/\.mp4$/i.test(m)).length,
96
+ expectedVideoCount: media.filter(m => /\.mp4$/i.test(m)).length,
97
+ contextInfo
98
+ }
99
+ }), {});
100
+
101
+ const albumKey = {
102
+ id: await relayMessage(jid, albumMsg.message, { messageId: albumMsg.key.id }),
103
+ remoteJid: jid,
104
+ fromMe: true
105
+ };
106
+
107
+ const keys = { album: albumKey };
108
+ let i = 1;
109
+
110
+ const mimetypes = {
111
+ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png',
112
+ gif: 'image/gif', webp: 'image/webp', mp4: 'video/mp4'
113
+ };
114
+ const messagetypes = {
115
+ jpg: 'imageMessage', jpeg: 'imageMessage', png: 'imageMessage',
116
+ gif: 'imageMessage', webp: 'imageMessage', mp4: 'videoMessage'
117
+ };
118
+
119
+ for (const source of media) {
120
+ const ext = source.split('.').pop().toLowerCase();
121
+ const mimetype = mimetypes[ext];
122
+ const type = messagetypes[ext];
123
+
124
+ if (!mimetype || !type) {
125
+ continue;
126
+ }
127
+
128
+ const msg = await prepareWAMessageMedia(
129
+ { [type.startsWith('image') ? 'image' : 'video']: { url: source }, mimetype },
130
+ { upload: waUploadToServer }
131
+ );
132
+
133
+ const mediaMessage = generateWAMessageFromContent(jid, proto.Message.fromObject({
134
+ associatedChildMessage: {
135
+ message: {
136
+ messageContextInfo: {
137
+ messageSecret: crypto.randomBytes(32),
138
+ messageAssociation: {
139
+ associationType: 'MEDIA_ALBUM',
140
+ parentMessageKey: albumKey
141
+ }
142
+ },
143
+ [type]: { ...msg[type] }
144
+ }
145
+ }
146
+ }), {});
147
+
148
+ keys[`media_${i++}`] = {
149
+ id: await relayMessage(jid, mediaMessage.message, { messageId: mediaMessage.key.id }),
150
+ fromMe: true,
151
+ remoteJid: jid
152
+ };
153
+ }
154
+
155
+ return keys;
156
+ };
157
+
158
+ /**
159
+ * Posts status mention.
160
+ */
161
+ const sendStatusMention = async (jid, content) => {
162
+ const media = generateWAMessageFromContent('status@broadcast', content, {});
163
+
164
+ const additionalNodes = [
165
+ {
166
+ tag: 'meta',
167
+ attrs: {},
168
+ content: [
169
+ {
170
+ tag: 'mentioned_users',
171
+ attrs: {},
172
+ content: [{ tag: 'to', attrs: { jid }, content: undefined }]
173
+ }
174
+ ]
175
+ }
176
+ ];
177
+
178
+ await relayMessage('status@broadcast', media.message, {
179
+ messageId: media.key.id,
180
+ statusJidList: [jid, sock.user?.id],
181
+ additionalNodes
182
+ });
183
+
184
+ return media;
185
+ };
186
+
187
+ /**
188
+ * Builds and sends a "rich response" menu card (WA GenAI style).
189
+ * Supports both structured content (header/body/footer) AND raw custom sections array.
190
+ */
191
+ const sendRich = async (jid, content = {}) => {
192
+ let contextInfoExtra = {};
193
+ let sections = [];
194
+
195
+ // 1. Jika pengguna mengirimkan array 'sections' secara langsung
196
+ if (content?.sections && Array.isArray(content.sections)) {
197
+ sections = content.sections;
198
+ } else {
199
+ // 2. Logic pembentukan sections dari header, body, dan footer
200
+ let header = content?.header;
201
+ let body = content?.body;
202
+ let footer = content?.footer;
203
+
204
+ const randomToolId = () => crypto.randomBytes(8).toString('hex');
205
+
206
+ if (header) {
207
+ const { disclaimer = false, disclaimerText = ' ', image = { inline: false }, title = '' } = header ?? {};
208
+
209
+ if (disclaimer) {
210
+ contextInfoExtra = {
211
+ messageContextInfo: {
212
+ botMetadata: {
213
+ messageDisclaimerText: disclaimerText
214
+ }
215
+ }
216
+ };
217
+ }
218
+
219
+ if (title) {
220
+ sections.push({
221
+ __typename: 'GenAIUnifiedResponseSection',
222
+ view_model: {
223
+ __typename: 'GenAISingleLayoutViewModel',
224
+ primitive: {
225
+ __typename: 'FOATextPrimitive',
226
+ text: '# ' + title
227
+ }
228
+ }
229
+ });
230
+ }
231
+
232
+ if (image?.url) {
233
+ if (image?.inline) {
234
+ sections.push({
235
+ __typename: 'GenAIUnifiedResponseSection',
236
+ view_model: {
237
+ __typename: 'GenAISingleLayoutViewModel',
238
+ primitive: {
239
+ __typename: 'GenAIMarkdownTextUXPrimitive',
240
+ text: '{{header}}.{{/header}}',
241
+ inline_entities: [{
242
+ __typename: 'GenAITextInlineEntity',
243
+ key: 'header',
244
+ metadata: {
245
+ __typename: 'GenAILatexItem',
246
+ latex_expression: '.',
247
+ font_height: 24,
248
+ padding: 4,
249
+ latex_image: {
250
+ __typename: 'GenAIMediaItem',
251
+ mime_type: image.mime_type || 'image/png',
252
+ url: image.url,
253
+ url_fallback: image.url,
254
+ width: image.width || 500,
255
+ height: image.height || 500,
256
+ expiration_timestamp_ms: Date.now() + 86400000
257
+ }
258
+ }
259
+ }]
260
+ }
261
+ }
262
+ });
263
+ } else {
264
+ sections.push({
265
+ __typename: 'GenAIUnifiedResponseSection',
266
+ view_model: {
267
+ __typename: 'GenAISingleLayoutViewModel',
268
+ primitive: {
269
+ __typename: 'GenAIImagePrimitive',
270
+ preview_image: {
271
+ __typename: 'GenAIMediaItem',
272
+ mime_type: image.mime_type || 'image/png',
273
+ url: image.url
274
+ },
275
+ full_image: {
276
+ __typename: 'GenAIMediaItem',
277
+ mime_type: image.mime_type || 'image/png',
278
+ url: image.url
279
+ }
280
+ }
281
+ }
282
+ });
283
+ }
284
+ }
285
+ }
286
+
287
+ if (body) {
288
+ const { cards = null, buttons = null, title = '', toast = '', carousel = false, row = false } = body ?? {};
289
+
290
+ if ((carousel || row) && cards?.length >= 1) {
291
+ sections.push({
292
+ __typename: 'GenAIUnifiedResponseSection',
293
+ view_model: {
294
+ primitives: cards.map((card) => ({
295
+ __typename: 'GenAI3PExtWidgetPrimitive',
296
+ header: {
297
+ __typename: 'GenAI3PExtWidgetStandardHeader',
298
+ title: card?.title || ''
299
+ },
300
+ body: {
301
+ __typename: 'GenAI3PExtCalendarEventList',
302
+ ctas: (card?.buttons || []).map((text) => ({
303
+ label: text,
304
+ state: 'PENDING',
305
+ kind: 'OTHER',
306
+ tool_call_id: randomToolId(),
307
+ toast: {
308
+ label: card?.toast || '',
309
+ __typename: 'GenAI3PExtWidgetToast'
310
+ },
311
+ __typename: 'GenAI3PExtWidgetCTA'
312
+ })),
313
+ sections: []
314
+ }
315
+ })),
316
+ __typename: carousel ? 'GenAIHScrollLayoutViewModel' : 'GenAIActionRowLayoutViewModel'
317
+ }
318
+ });
319
+ } else if (buttons?.length) {
320
+ sections.push({
321
+ __typename: 'GenAIUnifiedResponseSection',
322
+ view_model: {
323
+ primitive: {
324
+ __typename: 'GenAI3PExtWidgetPrimitive',
325
+ header: {
326
+ __typename: 'GenAI3PExtWidgetStandardHeader',
327
+ title: title || ''
328
+ },
329
+ body: {
330
+ __typename: 'GenAI3PExtCalendarEventList',
331
+ ctas: buttons.map((text) => ({
332
+ label: text,
333
+ state: 'PENDING',
334
+ kind: 'OTHER',
335
+ tool_call_id: randomToolId(),
336
+ toast: {
337
+ label: toast,
338
+ __typename: 'GenAI3PExtWidgetToast'
339
+ },
340
+ __typename: 'GenAI3PExtWidgetCTA'
341
+ })),
342
+ sections: []
343
+ }
344
+ },
345
+ __typename: 'GenAISingleLayoutViewModel'
346
+ }
347
+ });
348
+ }
349
+ }
350
+
351
+ if (footer) {
352
+ const { text = '', url = '', image = {} } = footer ?? {};
353
+ let img = [];
354
+ if (image?.url) {
355
+ img.push({
356
+ __typename: 'GenAIMarkdownTextUXPrimitive',
357
+ text: '{{header}}.{{/header}}',
358
+ inline_entities: [{
359
+ __typename: 'GenAITextInlineEntity',
360
+ key: 'header',
361
+ metadata: {
362
+ __typename: 'GenAILatexItem',
363
+ latex_expression: '.',
364
+ font_height: 24,
365
+ padding: -5,
366
+ latex_image: {
367
+ __typename: 'GenAIMediaItem',
368
+ mime_type: image.mime_type || 'image/png',
369
+ url: image.url,
370
+ url_fallback: image.url,
371
+ width: image.width || 100,
372
+ height: image.height || 100,
373
+ expiration_timestamp_ms: Date.now() + 86400000
374
+ }
375
+ }
376
+ }]
377
+ });
378
+ }
379
+ sections.push({
380
+ view_model: {
381
+ primitives: [
382
+ {
383
+ cta_text: text || 'Link',
384
+ cta_type: 'OPEN_URL',
385
+ cta_url: url || '',
386
+ __typename: 'GenAIFooterActionPrimitive'
387
+ },
388
+ ...img
389
+ ],
390
+ __typename: 'GenAIActionRowLayoutViewModel'
391
+ }
392
+ });
393
+ }
394
+ }
395
+
396
+ const waMsg = generateWAMessageFromContent(jid, {
397
+ ...contextInfoExtra,
398
+ botForwardedMessage: {
399
+ message: {
400
+ richResponseMessage: {
401
+ messageType: 1,
402
+ submessages: [],
403
+ unifiedResponse: {
404
+ data: Buffer.from(JSON.stringify({ sections })).toString('base64')
405
+ },
406
+ contextInfo: {
407
+ isForwarded: true,
408
+ forwardOrigin: 4,
409
+ ...(content?.contextInfo ?? {})
410
+ }
411
+ }
412
+ }
413
+ }
414
+ }, {});
415
+
416
+ await relayMessage(jid, waMsg.message, { messageId: waMsg.key.id });
417
+ return waMsg;
418
+ };
419
+
420
+ /**
421
+ * Native quick-reply buttons.
422
+ */
423
+ const sendButtonsMessage = async (jid, { text = '', footer = '', buttons = [] } = {}, options = {}) => {
424
+ const interactiveMessage = {
425
+ body: { text },
426
+ ...(footer ? { footer: { text: footer } } : {}),
427
+ nativeFlowMessage: {
428
+ buttons: buttons.map(b => ({
429
+ name: b.name || 'quick_reply',
430
+ buttonParamsJson: JSON.stringify({ display_text: b.text, id: b.id })
431
+ }))
432
+ }
433
+ };
434
+ return sendJsonMessage(jid, { viewOnceMessage: { message: { interactiveMessage } } }, options);
435
+ };
436
+
437
+ /**
438
+ * Native single-select list.
439
+ */
440
+ const sendListMessage = async (jid, { text = '', footer = '', buttonText = 'Menu', sections = [] } = {}, options = {}) => {
441
+ const interactiveMessage = {
442
+ body: { text },
443
+ ...(footer ? { footer: { text: footer } } : {}),
444
+ nativeFlowMessage: {
445
+ buttons: [{
446
+ name: 'single_select',
447
+ buttonParamsJson: JSON.stringify({ title: buttonText, sections })
448
+ }]
449
+ }
450
+ };
451
+ return sendJsonMessage(jid, { viewOnceMessage: { message: { interactiveMessage } } }, options);
452
+ };
453
+
454
+ /**
455
+ * Native carousel.
456
+ */
457
+ const sendCarouselMessage = async (jid, { text = '', footer = '', cards = [] } = {}, options = {}) => {
458
+ const cardMessages = [];
459
+
460
+ for (const card of cards) {
461
+ let headerMedia = {};
462
+ if (card.image) {
463
+ const uploaded = await prepareWAMessageMedia(
464
+ { image: { url: card.image }, mimetype: card.mimetype || 'image/jpeg' },
465
+ { upload: waUploadToServer }
466
+ );
467
+ headerMedia = { imageMessage: uploaded.imageMessage };
468
+ }
469
+
470
+ cardMessages.push({
471
+ header: { title: card.title || '', hasMediaAttachment: !!card.image, ...headerMedia },
472
+ body: { text: card.body || '' },
473
+ nativeFlowMessage: {
474
+ buttons: (card.buttons || []).map(b => ({
475
+ name: b.name || 'quick_reply',
476
+ buttonParamsJson: JSON.stringify({ display_text: b.text, id: b.id })
477
+ }))
478
+ }
479
+ });
480
+ }
481
+
482
+ const message = {
483
+ viewOnceMessage: {
484
+ message: {
485
+ interactiveMessage: {
486
+ body: { text },
487
+ ...(footer ? { footer: { text: footer } } : {}),
488
+ carouselMessage: { cards: cardMessages, messageVersion: 1 }
489
+ }
490
+ }
491
+ }
492
+ };
493
+ return sendJsonMessage(jid, message, options);
494
+ };
495
+
496
+ /**
497
+ * Forward message.
498
+ */
499
+ const forwardMessage = async (jid, message, options = {}) => {
500
+ return sendMessage(jid, { forward: message, force: options.force }, options);
501
+ };
502
+
503
+ /**
504
+ * Send vCard contact.
505
+ */
506
+ const sendVCard = async (jid, contacts, options = {}) => {
507
+ const list = Array.isArray(contacts) ? contacts : [contacts];
508
+ const built = list.map(c => {
509
+ const waid = c.waid || c.phone;
510
+ const vcard = 'BEGIN:VCARD\n'
511
+ + 'VERSION:3.0\n'
512
+ + `FN:${c.name || 'Unknown'}\n`
513
+ + (c.organization ? `ORG:${c.organization};\n` : '')
514
+ + `TEL;type=CELL;type=VOICE;waid=${waid}:+${c.phone}\n`
515
+ + 'END:VCARD';
516
+ return { displayName: c.name || 'Unknown', vcard };
517
+ });
518
+
519
+ if (built.length === 1) {
520
+ return sendMessage(jid, { contacts: { contacts: built } }, options);
521
+ }
522
+ return sendMessage(jid, { contacts: { displayName: `${built.length} contacts`, contacts: built } }, options);
523
+ };
524
+
525
+ /**
526
+ * Broadcast message.
527
+ */
528
+ const broadcastMessage = async (jids, content, options = {}) => {
529
+ const { delayMs = 0, ...sendOptions } = options;
530
+ const results = [];
531
+ for (const jid of jids) {
532
+ try {
533
+ const result = await sendMessage(jid, content, sendOptions);
534
+ results.push({ jid, ok: true, result });
535
+ } catch (error) {
536
+ results.push({ jid, ok: false, error });
537
+ }
538
+ if (delayMs) await new Promise(resolve => setTimeout(resolve, delayMs));
539
+ }
540
+ return results;
541
+ };
542
+
543
+ return {
544
+ ...sock,
545
+ sendJsonMessage,
546
+ sendActionPoll,
547
+ resolvePollAction,
548
+ sendAlbumMessage,
549
+ sendStatusMention,
550
+ sendRich,
551
+ richMenu: sendRich,
552
+ sendButtonsMessage,
553
+ sendListMessage,
554
+ sendCarouselMessage,
555
+ sendHtml,
556
+ forwardMessage,
557
+ sendVCard,
558
+ broadcastMessage
559
+ };
560
+ };
561
+ exports.makeMessageBuilderSocket = makeMessageBuilderSocket;
@@ -14,9 +14,10 @@ const link_preview_1 = require("../Utils/link-preview");
14
14
  const WABinary_1 = require("../WABinary");
15
15
  const WAUSync_1 = require("../WAUSync");
16
16
  const newsletter_1 = require("./newsletter");
17
+ const username_1 = require("./username");
17
18
  const makeMessagesSocket = (config) => {
18
19
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, albumMessageItemDelayMs = 0, } = config;
19
- const sock = (0, newsletter_1.makeNewsletterSocket)(config);
20
+ const sock = (0, username_1.makeUsernameSocket)(config);
20
21
  const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
21
22
  const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
22
23
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const __def = (m) => (m && m.__esModule) ? m.default : m;
4
+ const __exportStar = (m, e) => { for (const k in m) if (k !== "default" && !Object.prototype.hasOwnProperty.call(e, k)) e[k] = m[k]; };
5
+ const { Boom } = require("@hapi/boom");
6
+ const { S_WHATSAPP_NET, getBinaryNodeChild } = require("../WABinary/index.js");
7
+
8
+ const wMexQuery = (variables, queryId, query, generateMessageTag) => {
9
+ return query({
10
+ tag: 'iq',
11
+ attrs: {
12
+ id: generateMessageTag(),
13
+ type: 'get',
14
+ to: S_WHATSAPP_NET,
15
+ xmlns: 'w:mex'
16
+ },
17
+ content: [
18
+ {
19
+ tag: 'query',
20
+ attrs: { query_id: queryId },
21
+ content: Buffer.from(JSON.stringify({ variables }), 'utf-8')
22
+ }
23
+ ]
24
+ })
25
+ }
26
+
27
+ const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
28
+ const result = await wMexQuery(variables, queryId, query, generateMessageTag)
29
+ const child = getBinaryNodeChild(result, 'result')
30
+ if (child?.content) {
31
+ const str = child.content.toString('utf-8').replace(/^\x00+/, '').trim()
32
+ let data
33
+ try {
34
+ data = JSON.parse(str)
35
+ } catch {
36
+ data = str
37
+ }
38
+ if (typeof data === 'string') {
39
+ return data
40
+ }
41
+ if (data.errors && data.errors.length > 0) {
42
+ const errorMessages = data.errors.map(err => err.message || 'Unknown error').join(', ')
43
+ const firstError = data.errors[0]
44
+ const errorCode = firstError.extensions?.error_code || 400
45
+ throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError })
46
+ }
47
+
48
+ const response = dataPath ? data?.data?.[dataPath] : data?.data
49
+ if (typeof response !== 'undefined') {
50
+ return response
51
+ }
52
+ }
53
+
54
+ const action = (dataPath || '').startsWith('xwa2_')
55
+ ? dataPath.substring(5).replace(/_/g, '')
56
+ : dataPath?.replace(/_/g, '')
57
+ throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result })
58
+ }
59
+ exports.executeWMexQuery = executeWMexQuery;