chat-adapter-wwebjs 0.1.0 → 0.1.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.
- package/CHANGELOG.md +51 -0
- package/README.md +320 -85
- package/dist/index.d.ts +190 -19
- package/dist/index.js +834 -108
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
// src/adapter.ts
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
ResourceNotFoundError,
|
|
6
|
-
ValidationError as ValidationError2
|
|
7
|
-
} from "@chat-adapter/shared";
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import { once } from "events";
|
|
4
|
+
import { extractCard, ResourceNotFoundError, ValidationError as ValidationError3 } from "@chat-adapter/shared";
|
|
8
5
|
import {
|
|
9
6
|
ConsoleLogger,
|
|
10
7
|
defaultEmojiResolver,
|
|
@@ -14,11 +11,15 @@ import {
|
|
|
14
11
|
// src/format-converter.ts
|
|
15
12
|
import {
|
|
16
13
|
BaseFormatConverter,
|
|
14
|
+
cardChildToFallbackText,
|
|
15
|
+
chartElementToFallbackText,
|
|
17
16
|
getNodeChildren,
|
|
18
17
|
parseMarkdown,
|
|
18
|
+
tableElementToAscii,
|
|
19
19
|
tableToAscii
|
|
20
20
|
} from "chat";
|
|
21
21
|
var MAX_MARKDOWN_LENGTH = 16e3;
|
|
22
|
+
var DIVIDER = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
|
|
22
23
|
function plain(value) {
|
|
23
24
|
return { children: [{ children: [{ type: "text", value }], type: "paragraph" }], type: "root" };
|
|
24
25
|
}
|
|
@@ -70,7 +71,7 @@ ${node.value}
|
|
|
70
71
|
${tableToAscii(node)}
|
|
71
72
|
\`\`\``;
|
|
72
73
|
case "thematicBreak":
|
|
73
|
-
return
|
|
74
|
+
return DIVIDER;
|
|
74
75
|
default:
|
|
75
76
|
return this.defaultNodeToText(node, (child) => this.toWhatsApp(child));
|
|
76
77
|
}
|
|
@@ -79,6 +80,40 @@ ${tableToAscii(node)}
|
|
|
79
80
|
return getNodeChildren(node).map((child) => this.toWhatsApp(child)).join(separator);
|
|
80
81
|
}
|
|
81
82
|
};
|
|
83
|
+
function childText(child) {
|
|
84
|
+
switch (child.type) {
|
|
85
|
+
case "text":
|
|
86
|
+
return child.style === "bold" ? `*${child.content}*` : child.style === "muted" ? `_${child.content}_` : child.content;
|
|
87
|
+
case "link":
|
|
88
|
+
return `${child.label}: ${child.url}`;
|
|
89
|
+
case "fields":
|
|
90
|
+
return child.children.map(({ label, value }) => `*${label}:* ${value}`).join("\n");
|
|
91
|
+
case "table":
|
|
92
|
+
return `\`\`\`
|
|
93
|
+
${tableElementToAscii(child.headers, child.rows)}
|
|
94
|
+
\`\`\``;
|
|
95
|
+
case "chart":
|
|
96
|
+
return chartElementToFallbackText(child);
|
|
97
|
+
case "section":
|
|
98
|
+
return child.children.map(childText).filter(Boolean).join("\n");
|
|
99
|
+
case "divider":
|
|
100
|
+
return DIVIDER;
|
|
101
|
+
default:
|
|
102
|
+
return "";
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function cardToText(card) {
|
|
106
|
+
return [card.title && `*${card.title}*`, card.subtitle, ...card.children.map(childText)].filter(Boolean).join("\n");
|
|
107
|
+
}
|
|
108
|
+
function cardToPlainText(card) {
|
|
109
|
+
return [card.title, card.subtitle, ...card.children.map(cardChildToFallbackText)].filter(Boolean).join("\n");
|
|
110
|
+
}
|
|
111
|
+
function cardImages(card) {
|
|
112
|
+
const inside = (children) => children.flatMap(
|
|
113
|
+
(child) => child.type === "image" ? [child.url] : child.type === "section" ? inside(child.children) : []
|
|
114
|
+
);
|
|
115
|
+
return [...card.imageUrl ? [card.imageUrl] : [], ...inside(card.children)];
|
|
116
|
+
}
|
|
82
117
|
|
|
83
118
|
// src/jid.ts
|
|
84
119
|
var BROADCAST_SUFFIX = "@broadcast";
|
|
@@ -115,15 +150,16 @@ function extractMentions(text) {
|
|
|
115
150
|
mentions.add(chatId);
|
|
116
151
|
return `@${toUser(chatId)}`;
|
|
117
152
|
});
|
|
118
|
-
const named = new Set([...mentions].map(toUser));
|
|
119
|
-
for (const [, user] of rendered.matchAll(/@(\d{6,})\b/g)) {
|
|
120
|
-
if (user && !named.has(user)) mentions.add(`${user}${USER_SUFFIX}`);
|
|
121
|
-
}
|
|
122
153
|
return { mentions: [...mentions], text: rendered };
|
|
123
154
|
}
|
|
124
155
|
|
|
125
156
|
// src/media.ts
|
|
126
|
-
import {
|
|
157
|
+
import {
|
|
158
|
+
downloadAttachment,
|
|
159
|
+
extractFiles,
|
|
160
|
+
extractPostableAttachments,
|
|
161
|
+
ValidationError
|
|
162
|
+
} from "@chat-adapter/shared";
|
|
127
163
|
|
|
128
164
|
// src/wwebjs.ts
|
|
129
165
|
import wwebjs from "whatsapp-web.js";
|
|
@@ -158,7 +194,6 @@ var MIME_TYPES = {
|
|
|
158
194
|
};
|
|
159
195
|
var DEFAULT_MIME_TYPE = "application/octet-stream";
|
|
160
196
|
var DEFAULT_MAX_MEDIA_BYTES = 64 * 1024 * 1024;
|
|
161
|
-
var URL_TIMEOUT_MS = 3e4;
|
|
162
197
|
function toAttachments(message, maxBytes) {
|
|
163
198
|
if (!message.hasMedia) return [];
|
|
164
199
|
const data = message.rawData ?? {};
|
|
@@ -183,6 +218,9 @@ async function download(message, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
|
|
|
183
218
|
if (downloadMediaStream) {
|
|
184
219
|
const streamed = await downloadMediaStream.call(message);
|
|
185
220
|
if (!streamed) throw unavailable(message.id._serialized);
|
|
221
|
+
if (streamed.blobSize && streamed.blobSize > maxBytes) {
|
|
222
|
+
throw tooLarge(message.id._serialized, streamed.blobSize, maxBytes);
|
|
223
|
+
}
|
|
186
224
|
return collect(streamed.stream, maxBytes, message.id._serialized);
|
|
187
225
|
}
|
|
188
226
|
const media = await message.downloadMedia();
|
|
@@ -221,20 +259,29 @@ async function toMedia(source, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
|
|
|
221
259
|
);
|
|
222
260
|
}
|
|
223
261
|
function isCaptionable(media) {
|
|
224
|
-
return !media
|
|
262
|
+
return !isAudio(media);
|
|
263
|
+
}
|
|
264
|
+
function isAudio(media) {
|
|
265
|
+
return media.mimetype.startsWith("audio/");
|
|
266
|
+
}
|
|
267
|
+
function isVoiceNote(media) {
|
|
268
|
+
return media.mimetype.startsWith("audio/ogg");
|
|
225
269
|
}
|
|
226
270
|
function mimeTypeOf(filename) {
|
|
227
271
|
const extension = filename?.split(".").pop()?.toLowerCase();
|
|
228
272
|
return extension && Object.hasOwn(MIME_TYPES, extension) && MIME_TYPES[extension] || DEFAULT_MIME_TYPE;
|
|
229
273
|
}
|
|
230
274
|
async function fetchMedia(url, source, maxBytes) {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
275
|
+
let contentType;
|
|
276
|
+
const data = await downloadAttachment(url, {
|
|
277
|
+
adapter: "wwebjs",
|
|
278
|
+
limit: maxBytes,
|
|
279
|
+
onResponse: (response) => {
|
|
280
|
+
contentType = response.headers["content-type"]?.split(";")[0];
|
|
281
|
+
}
|
|
282
|
+
});
|
|
236
283
|
const name = source.name ?? new URL(url).pathname.split("/").pop() ?? null;
|
|
237
|
-
const mimeType = source.mimeType ??
|
|
284
|
+
const mimeType = source.mimeType ?? contentType ?? mimeTypeOf(name ?? void 0);
|
|
238
285
|
return new MessageMedia(mimeType, data.toString("base64"), name);
|
|
239
286
|
}
|
|
240
287
|
async function collect(stream, maxBytes, label) {
|
|
@@ -265,6 +312,156 @@ async function toBase64(data) {
|
|
|
265
312
|
return Buffer.from(await data.arrayBuffer()).toString("base64");
|
|
266
313
|
}
|
|
267
314
|
|
|
315
|
+
// src/modals.ts
|
|
316
|
+
import { ValidationError as ValidationError2 } from "@chat-adapter/shared";
|
|
317
|
+
var DEFAULT_MODAL_TEXTS = {
|
|
318
|
+
cancel: "cancel",
|
|
319
|
+
cancelHint: "Send *cancel* to stop.",
|
|
320
|
+
cancelled: "Cancelled.",
|
|
321
|
+
invalid: "That doesn't fit. Try again:",
|
|
322
|
+
noResults: "Nothing matched. Try other words:",
|
|
323
|
+
search: "Send a few words to search.",
|
|
324
|
+
skip: "skip",
|
|
325
|
+
skipHint: "Send *skip* to leave it as it is."
|
|
326
|
+
};
|
|
327
|
+
var INPUTS = /* @__PURE__ */ new Set([
|
|
328
|
+
"date_input",
|
|
329
|
+
"external_select",
|
|
330
|
+
"number_input",
|
|
331
|
+
"radio_select",
|
|
332
|
+
"select",
|
|
333
|
+
"text_input"
|
|
334
|
+
]);
|
|
335
|
+
function triggerIdOf(threadId, userId) {
|
|
336
|
+
return JSON.stringify([threadId, userId]);
|
|
337
|
+
}
|
|
338
|
+
function fromTrigger(triggerId) {
|
|
339
|
+
let ids;
|
|
340
|
+
try {
|
|
341
|
+
ids = JSON.parse(triggerId);
|
|
342
|
+
} catch {
|
|
343
|
+
ids = void 0;
|
|
344
|
+
}
|
|
345
|
+
const [threadId, userId] = Array.isArray(ids) ? ids : [];
|
|
346
|
+
if (typeof threadId === "string" && typeof userId === "string") return [threadId, userId];
|
|
347
|
+
throw new ValidationError2("wwebjs", `Not a trigger this adapter issued: ${triggerId}`);
|
|
348
|
+
}
|
|
349
|
+
function createForm(modal, viewId, contextId) {
|
|
350
|
+
const fields = modal.children.filter((child) => INPUTS.has(child.type));
|
|
351
|
+
return {
|
|
352
|
+
callbackId: modal.callbackId,
|
|
353
|
+
closeLabel: modal.closeLabel,
|
|
354
|
+
contextId,
|
|
355
|
+
fields,
|
|
356
|
+
notifyOnClose: modal.notifyOnClose,
|
|
357
|
+
pending: fields.map(({ id }) => id),
|
|
358
|
+
privateMetadata: modal.privateMetadata,
|
|
359
|
+
values: {},
|
|
360
|
+
viewId
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function introOf(modal, texts) {
|
|
364
|
+
const shown = modal.children.filter((child) => child.type === "text" || child.type === "fields");
|
|
365
|
+
return [
|
|
366
|
+
cardToText({ children: shown, title: modal.title, type: "card" }),
|
|
367
|
+
`_${texts.cancelHint}_`
|
|
368
|
+
].filter(Boolean).join("\n\n");
|
|
369
|
+
}
|
|
370
|
+
function currentField(form) {
|
|
371
|
+
return form.fields.find(({ id }) => id === form.pending[0]);
|
|
372
|
+
}
|
|
373
|
+
function optionsOf(field, form) {
|
|
374
|
+
if (field.type === "select" || field.type === "radio_select") return field.options;
|
|
375
|
+
return field.type === "external_select" ? form.found : void 0;
|
|
376
|
+
}
|
|
377
|
+
function initialOf(field) {
|
|
378
|
+
switch (field.type) {
|
|
379
|
+
case "select":
|
|
380
|
+
case "radio_select":
|
|
381
|
+
return field.initialOption;
|
|
382
|
+
case "external_select":
|
|
383
|
+
return field.initialOption?.value;
|
|
384
|
+
case "number_input":
|
|
385
|
+
return field.initialValue === void 0 ? void 0 : String(field.initialValue);
|
|
386
|
+
default:
|
|
387
|
+
return field.initialValue;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function questionOf(field, form, texts) {
|
|
391
|
+
const options = optionsOf(field, form);
|
|
392
|
+
const initial = initialOf(field);
|
|
393
|
+
const shown = field.type === "external_select" ? field.initialOption?.label : options?.find(({ value }) => value === initial)?.label ?? initial;
|
|
394
|
+
const range = field.type === "number_input" && [field.min, field.max].some((n) => n !== void 0);
|
|
395
|
+
return [
|
|
396
|
+
`*${field.label}*`,
|
|
397
|
+
"placeholder" in field && field.placeholder && `_${field.placeholder}_`,
|
|
398
|
+
options?.map(
|
|
399
|
+
(option, index) => [`${index + 1}. ${option.label}`, option.description].filter(Boolean).join(": ")
|
|
400
|
+
).join("\n"),
|
|
401
|
+
field.type === "date_input" && "_YYYY-MM-DD_",
|
|
402
|
+
range && `_${field.min ?? "\u2026"} \u2013 ${field.max ?? "\u2026"}_`,
|
|
403
|
+
field.type === "external_select" && !options && `_${texts.search}_`,
|
|
404
|
+
(field.optional || initial !== void 0) && `_${texts.skipHint}_${shown === void 0 ? "" : ` (${shown})`}`
|
|
405
|
+
].filter(Boolean).join("\n");
|
|
406
|
+
}
|
|
407
|
+
function pick(options, text) {
|
|
408
|
+
return /^\d+$/.test(text) ? options[Number(text) - 1] : options.find(({ label }) => label.toLowerCase() === text.toLowerCase());
|
|
409
|
+
}
|
|
410
|
+
function answerOf(field, form, text, texts) {
|
|
411
|
+
const invalid = { error: texts.invalid };
|
|
412
|
+
if (text.toLowerCase() === texts.skip.toLowerCase()) {
|
|
413
|
+
const initial = initialOf(field);
|
|
414
|
+
return field.optional || initial !== void 0 ? { value: initial } : invalid;
|
|
415
|
+
}
|
|
416
|
+
switch (field.type) {
|
|
417
|
+
case "text_input":
|
|
418
|
+
return text && text.length <= (field.maxLength ?? Infinity) ? { value: text } : invalid;
|
|
419
|
+
case "number_input": {
|
|
420
|
+
const number = Number(text.replace(",", "."));
|
|
421
|
+
const fits = text !== "" && Number.isFinite(number) && (field.decimal || Number.isInteger(number)) && number >= (field.min ?? -Infinity) && number <= (field.max ?? Infinity);
|
|
422
|
+
return fits ? { value: String(number) } : invalid;
|
|
423
|
+
}
|
|
424
|
+
case "date_input": {
|
|
425
|
+
const date = /* @__PURE__ */ new Date(`${text}T00:00:00Z`);
|
|
426
|
+
const valid = /^\d{4}-\d{2}-\d{2}$/.test(text) && !Number.isNaN(date.getTime()) && date.toISOString().startsWith(text);
|
|
427
|
+
return valid ? { value: text } : invalid;
|
|
428
|
+
}
|
|
429
|
+
case "external_select": {
|
|
430
|
+
const chosen = form.found && pick(form.found, text);
|
|
431
|
+
if (chosen) return { value: chosen.value };
|
|
432
|
+
return text.length >= (field.minQueryLength ?? 1) ? { search: text } : invalid;
|
|
433
|
+
}
|
|
434
|
+
default: {
|
|
435
|
+
const chosen = pick(field.options, text);
|
|
436
|
+
return chosen ? { value: chosen.value } : invalid;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
function flattenOptions(result) {
|
|
441
|
+
return (result ?? []).flatMap((entry) => "options" in entry ? entry.options : [entry]);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/shutdown.ts
|
|
445
|
+
var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
|
|
446
|
+
var CLOSE_TIMEOUT_MS = 8e3;
|
|
447
|
+
var sessions = /* @__PURE__ */ new Set();
|
|
448
|
+
async function onSignal(signal) {
|
|
449
|
+
for (const name of SIGNALS) process.off(name, onSignal);
|
|
450
|
+
await Promise.race([
|
|
451
|
+
Promise.allSettled([...sessions].map((close) => close())),
|
|
452
|
+
new Promise((resolve) => setTimeout(resolve, CLOSE_TIMEOUT_MS).unref())
|
|
453
|
+
]);
|
|
454
|
+
if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
|
|
455
|
+
}
|
|
456
|
+
function closeOnSignal(close) {
|
|
457
|
+
if (sessions.size === 0) for (const name of SIGNALS) process.on(name, onSignal);
|
|
458
|
+
sessions.add(close);
|
|
459
|
+
return () => {
|
|
460
|
+
sessions.delete(close);
|
|
461
|
+
if (sessions.size === 0) for (const name of SIGNALS) process.off(name, onSignal);
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
268
465
|
// src/adapter.ts
|
|
269
466
|
var ACK_STATUSES = {
|
|
270
467
|
[-1]: "error",
|
|
@@ -305,14 +502,34 @@ var CONNECT_TIMEOUT_MS = 12e4;
|
|
|
305
502
|
var WATCHDOG_INTERVAL_MS = 6e4;
|
|
306
503
|
var RECONNECT_MIN_MS = 5e3;
|
|
307
504
|
var RECONNECT_MAX_MS = 3e5;
|
|
505
|
+
var KILL_WAIT_MS = 2e3;
|
|
506
|
+
var STREAM_EDIT_MS = 1e3;
|
|
507
|
+
var FORM_TTL_MS = 864e5;
|
|
308
508
|
var MAX_POLL_OPTIONS = 12;
|
|
309
509
|
var MIN_POLL_OPTIONS = 2;
|
|
510
|
+
var CATCH_UP_MS = 864e5;
|
|
511
|
+
var MAX_CATCH_UP_CHATS = 100;
|
|
512
|
+
var MAX_CATCH_UP_MESSAGES = 50;
|
|
513
|
+
var MAX_RECENT = 1e3;
|
|
514
|
+
var CLOCK_SKEW_S = 60;
|
|
515
|
+
var RECOMMENDED_CHROMIUM_ARGS = [
|
|
516
|
+
"--renderer-process-limit=1",
|
|
517
|
+
"--disable-gpu",
|
|
518
|
+
"--disable-component-update"
|
|
519
|
+
];
|
|
310
520
|
var WWebJSAdapter = class {
|
|
311
521
|
name;
|
|
312
522
|
lockScope = "channel";
|
|
313
523
|
/** The underlying whatsapp-web.js client, for anything this adapter does not wrap. */
|
|
314
524
|
client;
|
|
315
525
|
userName;
|
|
526
|
+
/**
|
|
527
|
+
* WhatsApp has no modals, so with `richContent` one becomes a conversation:
|
|
528
|
+
* each field is asked in turn, a select by number, and the answers reach
|
|
529
|
+
* `onModalSubmit`. `cancel`, or the modal's `closeLabel`, stops it. Absent
|
|
530
|
+
* otherwise, so the SDK knows a modal cannot open.
|
|
531
|
+
*/
|
|
532
|
+
openModal;
|
|
316
533
|
_config;
|
|
317
534
|
_converter = new WWebJSFormatConverter();
|
|
318
535
|
_ackHandlers = [];
|
|
@@ -329,16 +546,33 @@ var WWebJSAdapter = class {
|
|
|
329
546
|
_state = "idle";
|
|
330
547
|
_watchdog;
|
|
331
548
|
_strikes = 0;
|
|
549
|
+
_owned;
|
|
550
|
+
_attempts = 0;
|
|
551
|
+
_launch;
|
|
552
|
+
_unwatch;
|
|
553
|
+
_listeners = [];
|
|
554
|
+
_unsignal;
|
|
555
|
+
_seen;
|
|
556
|
+
_behind;
|
|
557
|
+
_recent = /* @__PURE__ */ new Set();
|
|
558
|
+
_saving = Promise.resolve();
|
|
332
559
|
constructor(config = {}) {
|
|
333
560
|
const name = config.adapterName ?? "wwebjs";
|
|
334
561
|
if (name.includes(":")) {
|
|
335
|
-
throw new
|
|
562
|
+
throw new ValidationError3("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
|
|
336
563
|
}
|
|
337
564
|
this._config = config;
|
|
338
565
|
this.name = name;
|
|
339
566
|
this.userName = config.userName ?? "wwebjs-bot";
|
|
340
567
|
this._logger = config.logger ?? new ConsoleLogger("info").child(name);
|
|
341
568
|
this.client = config.client ?? new Client(this._clientOptions());
|
|
569
|
+
if (config.client?.constructor.name === "Client" && !(config.client instanceof Client)) {
|
|
570
|
+
this._logger.warn(
|
|
571
|
+
"This client comes from another copy of whatsapp-web.js than the adapter's, so the media, locations and polls it sends will fail. Install a single copy: it is a peer dependency."
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
this._owned = config.manageClient ?? !config.client?.pupBrowser?.isConnected();
|
|
575
|
+
if (config.richContent) this.openModal = (...args) => this._openModal(...args);
|
|
342
576
|
this._listen();
|
|
343
577
|
}
|
|
344
578
|
/** Where the session stands; a health check reads `connection === "connected"`. */
|
|
@@ -368,15 +602,23 @@ var WWebJSAdapter = class {
|
|
|
368
602
|
this._closed = false;
|
|
369
603
|
clearTimeout(this._retry);
|
|
370
604
|
this._retry = void 0;
|
|
605
|
+
if (this._listeners.length === 0) this._listen();
|
|
371
606
|
this._watch();
|
|
372
|
-
this.
|
|
373
|
-
this.
|
|
374
|
-
|
|
607
|
+
if (this._owned && this._config.handleSignals !== false) {
|
|
608
|
+
this._unsignal ??= closeOnSignal(() => this.disconnect());
|
|
609
|
+
}
|
|
610
|
+
if (this._connection) return this._connection;
|
|
611
|
+
const attempt = ++this._attempts;
|
|
612
|
+
this._connection = this._connect(attempt).catch((error) => {
|
|
613
|
+
if (attempt === this._attempts) {
|
|
614
|
+
this._connection = null;
|
|
615
|
+
if (this._state !== "logged_out" && !this._closed) this._state = "disconnected";
|
|
616
|
+
}
|
|
375
617
|
throw error;
|
|
376
618
|
});
|
|
377
619
|
return this._connection;
|
|
378
620
|
}
|
|
379
|
-
/** Close the browser session. */
|
|
621
|
+
/** Close the browser session, or only detach from a client the adapter does not manage. */
|
|
380
622
|
async disconnect() {
|
|
381
623
|
this._closed = true;
|
|
382
624
|
this._state = "closed";
|
|
@@ -384,7 +626,11 @@ var WWebJSAdapter = class {
|
|
|
384
626
|
clearInterval(this._watchdog);
|
|
385
627
|
this._watchdog = void 0;
|
|
386
628
|
this._connection = null;
|
|
387
|
-
|
|
629
|
+
this._unsignal?.();
|
|
630
|
+
this._unsignal = void 0;
|
|
631
|
+
await this._saving;
|
|
632
|
+
if (!this._owned) return this._unlisten();
|
|
633
|
+
await this._close();
|
|
388
634
|
}
|
|
389
635
|
encodeThreadId(platformData) {
|
|
390
636
|
return `${this.name}:${platformData.chatId}`;
|
|
@@ -392,7 +638,7 @@ var WWebJSAdapter = class {
|
|
|
392
638
|
decodeThreadId(threadId) {
|
|
393
639
|
const prefix = `${this.name}:`;
|
|
394
640
|
if (!threadId.startsWith(prefix)) {
|
|
395
|
-
throw new
|
|
641
|
+
throw new ValidationError3("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
|
|
396
642
|
}
|
|
397
643
|
return { chatId: threadId.slice(prefix.length) };
|
|
398
644
|
}
|
|
@@ -421,7 +667,7 @@ var WWebJSAdapter = class {
|
|
|
421
667
|
parseMessage(raw) {
|
|
422
668
|
const bot = this._botUsers();
|
|
423
669
|
const text = this._named(
|
|
424
|
-
raw.body ?? "",
|
|
670
|
+
raw.location ? locationText(raw.location) : raw.body ?? "",
|
|
425
671
|
this._mentioned(raw).filter((user) => bot.has(user)),
|
|
426
672
|
() => this.userName
|
|
427
673
|
);
|
|
@@ -452,8 +698,9 @@ var WWebJSAdapter = class {
|
|
|
452
698
|
return this._send(threadId, message, { quotedMessageId: messageId });
|
|
453
699
|
}
|
|
454
700
|
async editMessage(threadId, messageId, message) {
|
|
455
|
-
const {
|
|
456
|
-
const
|
|
701
|
+
const { card, text: rendered } = this._render(message, threadId);
|
|
702
|
+
const { mentions, text } = extractMentions(rendered);
|
|
703
|
+
const target = await this._requireMessage(messageId, threadId);
|
|
457
704
|
const edit = () => target.edit(text, mentions.length > 0 ? { mentions } : void 0);
|
|
458
705
|
let edited = await edit();
|
|
459
706
|
const fresh = target.fromMe && Date.now() - target.timestamp * 1e3 < FRESH_MS;
|
|
@@ -462,21 +709,42 @@ var WWebJSAdapter = class {
|
|
|
462
709
|
edited = await edit();
|
|
463
710
|
}
|
|
464
711
|
if (!edited) {
|
|
465
|
-
throw new
|
|
712
|
+
throw new ValidationError3(
|
|
466
713
|
"wwebjs",
|
|
467
714
|
`Message ${messageId} could not be edited. WhatsApp only allows editing your own messages within 15 minutes.`
|
|
468
715
|
);
|
|
469
716
|
}
|
|
470
|
-
|
|
717
|
+
const raw = this._raw(edited, threadId);
|
|
718
|
+
await this._cardSent(card, raw.id, threadId);
|
|
719
|
+
return raw;
|
|
720
|
+
}
|
|
721
|
+
/** WhatsApp cannot stream, and editing twice a second as the SDK otherwise would floods the chat; the reply goes out once, whole. */
|
|
722
|
+
async stream(threadId, textStream) {
|
|
723
|
+
const edits = this._config.streaming === "edit";
|
|
724
|
+
let text = "";
|
|
725
|
+
let sent;
|
|
726
|
+
let shown = "";
|
|
727
|
+
let at = 0;
|
|
728
|
+
for await (const chunk of textStream) {
|
|
729
|
+
if (typeof chunk === "string") text += chunk;
|
|
730
|
+
else if (chunk.type === "markdown_text") text += chunk.text;
|
|
731
|
+
if (!edits || !text.trim() || Date.now() - at < STREAM_EDIT_MS) continue;
|
|
732
|
+
sent = sent ? await this.editMessage(threadId, sent.id, { markdown: text }).catch(() => sent) : await this.postMessage(threadId, { markdown: text });
|
|
733
|
+
shown = text;
|
|
734
|
+
at = Date.now();
|
|
735
|
+
}
|
|
736
|
+
if (!text.trim()) return null;
|
|
737
|
+
if (!sent) return this.postMessage(threadId, { markdown: text });
|
|
738
|
+
return text === shown ? sent : this.editMessage(threadId, sent.id, { markdown: text });
|
|
471
739
|
}
|
|
472
|
-
async deleteMessage(
|
|
473
|
-
await (await this._requireMessage(messageId)).delete(true);
|
|
740
|
+
async deleteMessage(threadId, messageId) {
|
|
741
|
+
await (await this._requireMessage(messageId, threadId)).delete(true);
|
|
474
742
|
}
|
|
475
|
-
async addReaction(
|
|
476
|
-
await (await this._requireMessage(messageId)).react(defaultEmojiResolver.toGChat(emoji));
|
|
743
|
+
async addReaction(threadId, messageId, emoji) {
|
|
744
|
+
await (await this._requireMessage(messageId, threadId)).react(defaultEmojiResolver.toGChat(emoji));
|
|
477
745
|
}
|
|
478
|
-
async removeReaction(
|
|
479
|
-
await (await this._requireMessage(messageId)).react("");
|
|
746
|
+
async removeReaction(threadId, messageId, _emoji) {
|
|
747
|
+
await (await this._requireMessage(messageId, threadId)).react("");
|
|
480
748
|
}
|
|
481
749
|
async fetchMessages(threadId, options) {
|
|
482
750
|
return this._page(await this._requireChat(threadId), options);
|
|
@@ -484,8 +752,8 @@ var WWebJSAdapter = class {
|
|
|
484
752
|
async fetchChannelMessages(channelId, options) {
|
|
485
753
|
return this.fetchMessages(channelId, options);
|
|
486
754
|
}
|
|
487
|
-
async fetchMessage(
|
|
488
|
-
const message = await this.
|
|
755
|
+
async fetchMessage(threadId, messageId) {
|
|
756
|
+
const message = await this._findMessage(messageId, threadId);
|
|
489
757
|
return message ? this.parseMessage(message) : null;
|
|
490
758
|
}
|
|
491
759
|
async fetchThread(threadId) {
|
|
@@ -512,9 +780,39 @@ var WWebJSAdapter = class {
|
|
|
512
780
|
name: chat?.name
|
|
513
781
|
};
|
|
514
782
|
}
|
|
515
|
-
/** WhatsApp
|
|
516
|
-
async listThreads() {
|
|
517
|
-
|
|
783
|
+
/** A WhatsApp chat is one flat conversation, so a channel holds just its own thread. */
|
|
784
|
+
async listThreads(channelId) {
|
|
785
|
+
const chat = await this._findChat(this.decodeThreadId(channelId).chatId);
|
|
786
|
+
return { threads: chat ? this._summaries([chat]) : [] };
|
|
787
|
+
}
|
|
788
|
+
/** Every chat the account has, newest first, with its latest message: an inbox's list. */
|
|
789
|
+
async listChats(options) {
|
|
790
|
+
const chats = (await this.client.getChats()).filter(
|
|
791
|
+
(chat) => !isBroadcastId(serialize(chat.id))
|
|
792
|
+
);
|
|
793
|
+
const start = Number(options?.cursor) || 0;
|
|
794
|
+
const end = start + Math.max(1, options?.limit ?? DEFAULT_LIMIT);
|
|
795
|
+
return {
|
|
796
|
+
nextCursor: end < chats.length ? String(end) : void 0,
|
|
797
|
+
threads: this._summaries(chats.slice(start, end))
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
_summaries(chats) {
|
|
801
|
+
return chats.flatMap(
|
|
802
|
+
(chat) => chat.lastMessage ? [
|
|
803
|
+
{
|
|
804
|
+
id: this.encodeThreadId({ chatId: serialize(chat.id) }),
|
|
805
|
+
lastReplyAt: new Date(chat.lastMessage.timestamp * 1e3),
|
|
806
|
+
rootMessage: this.parseMessage(chat.lastMessage)
|
|
807
|
+
}
|
|
808
|
+
] : []
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
async _openModal(triggerId, modal, contextId) {
|
|
812
|
+
const [threadId, userId] = fromTrigger(triggerId);
|
|
813
|
+
const form = createForm(modal, randomUUID(), contextId);
|
|
814
|
+
await this._start(threadId, userId, modal, form);
|
|
815
|
+
return { viewId: form.viewId };
|
|
518
816
|
}
|
|
519
817
|
async getUser(userId) {
|
|
520
818
|
const contact = await this.client.getContactById(toChatId(userId)).catch(() => null);
|
|
@@ -574,7 +872,7 @@ var WWebJSAdapter = class {
|
|
|
574
872
|
/** Send a native WhatsApp poll. Between 2 and 12 options. */
|
|
575
873
|
async sendPoll(args) {
|
|
576
874
|
if (args.options.length < MIN_POLL_OPTIONS || args.options.length > MAX_POLL_OPTIONS) {
|
|
577
|
-
throw new
|
|
875
|
+
throw new ValidationError3(
|
|
578
876
|
"wwebjs",
|
|
579
877
|
`sendPoll: WhatsApp polls need between ${MIN_POLL_OPTIONS} and ${MAX_POLL_OPTIONS} options. Received ${args.options.length}.`
|
|
580
878
|
);
|
|
@@ -642,7 +940,7 @@ var WWebJSAdapter = class {
|
|
|
642
940
|
async fetchGroupParticipants(threadId) {
|
|
643
941
|
const chat = await this._requireChat(threadId);
|
|
644
942
|
if (!isGroupChat(chat)) {
|
|
645
|
-
throw new
|
|
943
|
+
throw new ValidationError3("wwebjs", "fetchGroupParticipants: thread is not a group.");
|
|
646
944
|
}
|
|
647
945
|
return chat.participants.map((participant) => ({
|
|
648
946
|
isAdmin: participant.isAdmin || participant.isSuperAdmin,
|
|
@@ -692,7 +990,7 @@ var WWebJSAdapter = class {
|
|
|
692
990
|
return;
|
|
693
991
|
}
|
|
694
992
|
if (!second) {
|
|
695
|
-
throw new
|
|
993
|
+
throw new ValidationError3(
|
|
696
994
|
"wwebjs",
|
|
697
995
|
"onPollVote: a handler is required when filtering by poll message ID."
|
|
698
996
|
);
|
|
@@ -716,6 +1014,16 @@ var WWebJSAdapter = class {
|
|
|
716
1014
|
}
|
|
717
1015
|
_clientOptions() {
|
|
718
1016
|
const options = { ...this._config.clientOptions };
|
|
1017
|
+
const puppeteer = options.puppeteer ?? {};
|
|
1018
|
+
options.puppeteer = {
|
|
1019
|
+
// Puppeteer's handlers close the browser on a signal and keep the process alive; closeOnSignal does both.
|
|
1020
|
+
...this._config.handleSignals === false ? {} : { handleSIGHUP: false, handleSIGINT: false, handleSIGTERM: false },
|
|
1021
|
+
...puppeteer,
|
|
1022
|
+
args: [
|
|
1023
|
+
...this._config.recommendedArgs === false ? [] : RECOMMENDED_CHROMIUM_ARGS,
|
|
1024
|
+
...puppeteer.args ?? []
|
|
1025
|
+
]
|
|
1026
|
+
};
|
|
719
1027
|
if (this._config.phoneNumber) {
|
|
720
1028
|
options.pairWithPhoneNumber = {
|
|
721
1029
|
phoneNumber: this._config.phoneNumber,
|
|
@@ -724,92 +1032,382 @@ var WWebJSAdapter = class {
|
|
|
724
1032
|
}
|
|
725
1033
|
return options;
|
|
726
1034
|
}
|
|
727
|
-
async _connect() {
|
|
1035
|
+
async _connect(attempt) {
|
|
728
1036
|
const timeoutMs = this._config.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
|
|
729
1037
|
let timer;
|
|
730
1038
|
const timedOut = new Promise((_resolve, reject) => {
|
|
731
1039
|
timer = setTimeout(
|
|
732
|
-
() => reject(new
|
|
1040
|
+
() => reject(new ValidationError3("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
|
|
733
1041
|
timeoutMs
|
|
734
1042
|
);
|
|
735
1043
|
timer.unref?.();
|
|
736
1044
|
});
|
|
1045
|
+
const waiting = () => clearTimeout(timer);
|
|
1046
|
+
this.client.once("qr", waiting);
|
|
1047
|
+
this.client.once("code", waiting);
|
|
737
1048
|
try {
|
|
738
1049
|
await Promise.race([this._open(), timedOut]);
|
|
739
1050
|
} catch (error) {
|
|
740
|
-
await this.
|
|
1051
|
+
if (this._owned && attempt === this._attempts) await this._close().catch(() => void 0);
|
|
741
1052
|
throw error;
|
|
742
1053
|
} finally {
|
|
743
1054
|
clearTimeout(timer);
|
|
1055
|
+
this.client.off("qr", waiting);
|
|
1056
|
+
this.client.off("code", waiting);
|
|
744
1057
|
}
|
|
745
1058
|
}
|
|
746
1059
|
async _open() {
|
|
747
1060
|
this._state = this._initialized ? "reconnecting" : "connecting";
|
|
1061
|
+
if (!this._owned && await this._running()) {
|
|
1062
|
+
this._watchBrowser();
|
|
1063
|
+
return this._onReady();
|
|
1064
|
+
}
|
|
1065
|
+
let onReady;
|
|
1066
|
+
let onFailure;
|
|
748
1067
|
const ready = new Promise((resolve, reject) => {
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
() => reject(new ValidationError2("wwebjs", `WhatsApp authentication failed: ${message}`))
|
|
752
|
-
);
|
|
753
|
-
const settle = (finish) => {
|
|
754
|
-
this.client.off("ready", onReady);
|
|
755
|
-
this.client.off("auth_failure", onFailure);
|
|
756
|
-
finish();
|
|
757
|
-
};
|
|
758
|
-
this.client.on("ready", onReady);
|
|
759
|
-
this.client.on("auth_failure", onFailure);
|
|
1068
|
+
onReady = resolve;
|
|
1069
|
+
onFailure = (message) => reject(new ValidationError3("wwebjs", `WhatsApp authentication failed: ${message}`));
|
|
760
1070
|
});
|
|
761
|
-
|
|
762
|
-
this.
|
|
763
|
-
|
|
764
|
-
|
|
1071
|
+
ready.catch(() => void 0);
|
|
1072
|
+
this.client.on("ready", onReady);
|
|
1073
|
+
this.client.on("auth_failure", onFailure);
|
|
1074
|
+
try {
|
|
1075
|
+
if (this._owned && this._initialized) await this._close().catch(() => void 0);
|
|
1076
|
+
this._initialized = true;
|
|
1077
|
+
if (this._owned) {
|
|
1078
|
+
this._launch = new AbortController();
|
|
1079
|
+
const options = this.client.options;
|
|
1080
|
+
options.puppeteer = { ...options.puppeteer, signal: this._launch.signal };
|
|
1081
|
+
}
|
|
1082
|
+
if (this._owned || !this.client.pupBrowser) await this.client.initialize();
|
|
1083
|
+
if (this._closed) {
|
|
1084
|
+
if (this._owned) await this._close();
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
this._watchBrowser();
|
|
1088
|
+
await ready;
|
|
1089
|
+
} finally {
|
|
1090
|
+
this.client.off("ready", onReady);
|
|
1091
|
+
this.client.off("auth_failure", onFailure);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
/** A crashed browser ends the session without WhatsApp ever reporting a disconnect. */
|
|
1095
|
+
_watchBrowser() {
|
|
1096
|
+
const browser = this.client.pupBrowser;
|
|
1097
|
+
if (!browser) return;
|
|
1098
|
+
const onClose = () => this._onDisconnected("BROWSER_CLOSED");
|
|
1099
|
+
browser.once("disconnected", onClose);
|
|
1100
|
+
this._unwatch = () => browser.off("disconnected", onClose);
|
|
1101
|
+
}
|
|
1102
|
+
/** A client started elsewhere is up when its browser is connected and WhatsApp answers. */
|
|
1103
|
+
async _running() {
|
|
1104
|
+
if (!this.client.pupBrowser?.isConnected()) return false;
|
|
1105
|
+
return await within(this.client.getState()) === "CONNECTED";
|
|
1106
|
+
}
|
|
1107
|
+
/** Closes the browser this adapter runs; closing it on purpose is not a crash to recover from. */
|
|
1108
|
+
async _close() {
|
|
1109
|
+
this._unwatch?.();
|
|
1110
|
+
this._unwatch = void 0;
|
|
1111
|
+
try {
|
|
765
1112
|
await this.client.destroy();
|
|
766
|
-
|
|
1113
|
+
} finally {
|
|
1114
|
+
await this._killBrowser();
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
/** `destroy()` closes only a browser it still sees connected, so one that dropped keeps its profile locked. */
|
|
1118
|
+
async _killBrowser() {
|
|
1119
|
+
this._launch?.abort();
|
|
1120
|
+
const browser = this.client.pupBrowser?.process?.();
|
|
1121
|
+
if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null) return;
|
|
1122
|
+
const exited = once(browser, "exit");
|
|
1123
|
+
try {
|
|
1124
|
+
process.kill(process.platform === "win32" ? browser.pid : -browser.pid, "SIGKILL");
|
|
1125
|
+
} catch {
|
|
1126
|
+
browser.kill("SIGKILL");
|
|
767
1127
|
}
|
|
768
|
-
|
|
769
|
-
|
|
1128
|
+
await Promise.race([
|
|
1129
|
+
exited,
|
|
1130
|
+
new Promise((resolve) => setTimeout(resolve, KILL_WAIT_MS).unref?.())
|
|
1131
|
+
]);
|
|
770
1132
|
}
|
|
771
1133
|
_listen() {
|
|
772
1134
|
const { onPairingCode, onQR } = this._config;
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
this.
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
);
|
|
790
|
-
this.client.on(
|
|
791
|
-
"message_revoke_everyone",
|
|
792
|
-
(message, revoked) => this._onRevoke(message, revoked)
|
|
793
|
-
);
|
|
794
|
-
this.client.on("message_reaction", (reaction) => this._onReaction(reaction));
|
|
795
|
-
this.client.on("message_ack", (message, ack) => this._onAck(message, ack));
|
|
796
|
-
this.client.on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
|
|
797
|
-
this.client.on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
|
|
1135
|
+
const on = (event, listener) => {
|
|
1136
|
+
this._listeners.push([event, listener]);
|
|
1137
|
+
return this.client.on(event, listener);
|
|
1138
|
+
};
|
|
1139
|
+
if (onQR) on("qr", (qr) => void this._dispatch([onQR], qr, "onQR"));
|
|
1140
|
+
if (onPairingCode)
|
|
1141
|
+
on("code", (code) => void this._dispatch([onPairingCode], code, "onPairingCode"));
|
|
1142
|
+
on("ready", () => this._onReady());
|
|
1143
|
+
on("disconnected", (reason) => this._onDisconnected(String(reason)));
|
|
1144
|
+
on("message_create", (message) => this._guard("message", this._onMessage(message)));
|
|
1145
|
+
on("message_edit", (message, _new, previous) => this._onEdit(message, String(previous)));
|
|
1146
|
+
on("message_revoke_everyone", (message, revoked) => this._onRevoke(message, revoked));
|
|
1147
|
+
on("message_reaction", (reaction) => this._onReaction(reaction));
|
|
1148
|
+
on("message_ack", (message, ack) => this._onAck(message, ack));
|
|
1149
|
+
on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
|
|
1150
|
+
on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
|
|
798
1151
|
for (const [event, type] of Object.entries(GROUP_EVENTS)) {
|
|
799
|
-
|
|
1152
|
+
on(event, (notification) => this._onGroup(type, notification));
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
_unlisten() {
|
|
1156
|
+
for (const [event, listener] of this._listeners) this.client.off(event, listener);
|
|
1157
|
+
this._listeners = [];
|
|
1158
|
+
}
|
|
1159
|
+
_onReady() {
|
|
1160
|
+
this._state = "connected";
|
|
1161
|
+
this._strikes = 0;
|
|
1162
|
+
if (!this._config.userName && this.client.info?.pushname) {
|
|
1163
|
+
this.userName = this.client.info.pushname;
|
|
800
1164
|
}
|
|
1165
|
+
this._logger.info("WhatsApp session ready", { userId: this.botUserId });
|
|
1166
|
+
void this._learnLid();
|
|
1167
|
+
this._guard("catch-up", this._catchUp());
|
|
801
1168
|
}
|
|
802
1169
|
async _onMessage(raw) {
|
|
803
1170
|
if (!this._chat || this._isOwn(raw.fromMe)) return;
|
|
804
1171
|
const chatId = chatIdOf(raw);
|
|
805
1172
|
if (raw.isStatus || isBroadcastId(chatId) || SYSTEM_TYPES.has(raw.type)) return;
|
|
1173
|
+
const id = serialize(raw.id);
|
|
1174
|
+
if (this._recent.has(id)) return;
|
|
1175
|
+
this._recent.add(id);
|
|
1176
|
+
if (this._recent.size > MAX_RECENT) this._recent.delete(this._recent.values().next().value);
|
|
806
1177
|
const threadId = this.encodeThreadId({ chatId });
|
|
807
1178
|
if (this._config.markSeen && !raw.fromMe) {
|
|
808
1179
|
await this.markAsRead(threadId).catch(
|
|
809
1180
|
(error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
|
|
810
1181
|
);
|
|
811
1182
|
}
|
|
812
|
-
|
|
1183
|
+
const author = this._author(raw);
|
|
1184
|
+
if (await this._answer(raw, threadId, author) || this._command(raw, threadId, author)) {
|
|
1185
|
+
await this._remember(raw);
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
|
|
1189
|
+
if (!parsed || !await this._claimed(parsed, threadId)) {
|
|
1190
|
+
await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
|
|
1191
|
+
}
|
|
1192
|
+
await this._remember(raw);
|
|
1193
|
+
}
|
|
1194
|
+
_formKey(threadId, userId) {
|
|
1195
|
+
return `wwebjs:${this.name}:form:${threadId}:${userId}`;
|
|
1196
|
+
}
|
|
1197
|
+
_texts() {
|
|
1198
|
+
return { ...DEFAULT_MODAL_TEXTS, ...this._config.modalTexts };
|
|
1199
|
+
}
|
|
1200
|
+
async _start(threadId, userId, modal, form) {
|
|
1201
|
+
if (!this._chat) throw new ValidationError3("wwebjs", "A modal needs Chat to be initialized.");
|
|
1202
|
+
const field = currentField(form);
|
|
1203
|
+
await this._chat.getState().set(this._formKey(threadId, userId), form, FORM_TTL_MS);
|
|
1204
|
+
const intro = introOf(modal, this._texts());
|
|
1205
|
+
await this.postMessage(
|
|
1206
|
+
threadId,
|
|
1207
|
+
field ? `${intro}
|
|
1208
|
+
|
|
1209
|
+
${questionOf(field, form, this._texts())}` : intro
|
|
1210
|
+
);
|
|
1211
|
+
}
|
|
1212
|
+
/** A reply from someone filling in a modal answers it, before anything else sees it. */
|
|
1213
|
+
async _answer(raw, threadId, user) {
|
|
1214
|
+
const state = this._chat.getState();
|
|
1215
|
+
const key = this._formKey(threadId, user.userId);
|
|
1216
|
+
const form = await state.get(key);
|
|
1217
|
+
const field = form && currentField(form);
|
|
1218
|
+
if (!form || !field) return false;
|
|
1219
|
+
const texts = this._texts();
|
|
1220
|
+
const text = (raw.body ?? "").trim();
|
|
1221
|
+
const event = { adapter: this, callbackId: form.callbackId, raw, user, viewId: form.viewId };
|
|
1222
|
+
if (text.toLowerCase() === (form.closeLabel ?? texts.cancel).toLowerCase()) {
|
|
1223
|
+
await state.delete(key);
|
|
1224
|
+
await this.postMessage(threadId, texts.cancelled);
|
|
1225
|
+
if (form.notifyOnClose) {
|
|
1226
|
+
await this._chat.processModalClose(
|
|
1227
|
+
{ ...event, privateMetadata: form.privateMetadata },
|
|
1228
|
+
form.contextId
|
|
1229
|
+
);
|
|
1230
|
+
}
|
|
1231
|
+
return true;
|
|
1232
|
+
}
|
|
1233
|
+
const answer = answerOf(field, form, text, texts);
|
|
1234
|
+
if ("search" in answer) {
|
|
1235
|
+
const found = flattenOptions(
|
|
1236
|
+
await this._chat.processOptionsLoad({
|
|
1237
|
+
actionId: field.id,
|
|
1238
|
+
adapter: this,
|
|
1239
|
+
query: answer.search,
|
|
1240
|
+
raw,
|
|
1241
|
+
user
|
|
1242
|
+
})
|
|
1243
|
+
);
|
|
1244
|
+
const next2 = { ...form, found: found.length > 0 ? found : void 0 };
|
|
1245
|
+
await state.set(key, next2, FORM_TTL_MS);
|
|
1246
|
+
const question = questionOf(field, next2, texts);
|
|
1247
|
+
await this.postMessage(
|
|
1248
|
+
threadId,
|
|
1249
|
+
found.length > 0 ? question : `${texts.noResults}
|
|
1250
|
+
|
|
1251
|
+
${question}`
|
|
1252
|
+
);
|
|
1253
|
+
return true;
|
|
1254
|
+
}
|
|
1255
|
+
if ("error" in answer) {
|
|
1256
|
+
await this.postMessage(threadId, `${answer.error}
|
|
1257
|
+
|
|
1258
|
+
${questionOf(field, form, texts)}`);
|
|
1259
|
+
return true;
|
|
1260
|
+
}
|
|
1261
|
+
const { [field.id]: _previous, ...rest } = form.values;
|
|
1262
|
+
const next = {
|
|
1263
|
+
...form,
|
|
1264
|
+
found: void 0,
|
|
1265
|
+
pending: form.pending.slice(1),
|
|
1266
|
+
values: answer.value === void 0 ? rest : { ...rest, [field.id]: answer.value }
|
|
1267
|
+
};
|
|
1268
|
+
const following = currentField(next);
|
|
1269
|
+
if (following) {
|
|
1270
|
+
await state.set(key, next, FORM_TTL_MS);
|
|
1271
|
+
await this.postMessage(threadId, questionOf(following, next, texts));
|
|
1272
|
+
return true;
|
|
1273
|
+
}
|
|
1274
|
+
await state.delete(key);
|
|
1275
|
+
const response = await this._chat.processModalSubmit(
|
|
1276
|
+
{ ...event, privateMetadata: next.privateMetadata, values: next.values },
|
|
1277
|
+
next.contextId
|
|
1278
|
+
);
|
|
1279
|
+
if (response?.action === "errors") {
|
|
1280
|
+
const retry = {
|
|
1281
|
+
...next,
|
|
1282
|
+
pending: next.fields.map(({ id }) => id).filter((id) => id in response.errors)
|
|
1283
|
+
};
|
|
1284
|
+
const first = currentField(retry);
|
|
1285
|
+
if (first) {
|
|
1286
|
+
await state.set(key, retry, FORM_TTL_MS);
|
|
1287
|
+
const reasons = Object.values(response.errors).join("\n");
|
|
1288
|
+
await this.postMessage(threadId, `${reasons}
|
|
1289
|
+
|
|
1290
|
+
${questionOf(first, retry, texts)}`);
|
|
1291
|
+
}
|
|
1292
|
+
} else if (response?.action === "update" || response?.action === "push") {
|
|
1293
|
+
const viewId = response.action === "update" ? next.viewId : randomUUID();
|
|
1294
|
+
await this._start(
|
|
1295
|
+
threadId,
|
|
1296
|
+
user.userId,
|
|
1297
|
+
response.modal,
|
|
1298
|
+
createForm(response.modal, viewId, next.contextId)
|
|
1299
|
+
);
|
|
1300
|
+
}
|
|
1301
|
+
return true;
|
|
1302
|
+
}
|
|
1303
|
+
/** WhatsApp has no slash commands, so a message naming a declared one becomes one. */
|
|
1304
|
+
_command(raw, threadId, user) {
|
|
1305
|
+
const match = /^(\/\S+)(?:\s+([\s\S]*))?$/.exec((raw.body ?? "").trim());
|
|
1306
|
+
const command = match && this._config.slashCommands?.find((name) => name.toLowerCase() === match[1].toLowerCase());
|
|
1307
|
+
if (!command) return false;
|
|
1308
|
+
this._chat.processSlashCommand(
|
|
1309
|
+
{
|
|
1310
|
+
adapter: this,
|
|
1311
|
+
channelId: threadId,
|
|
1312
|
+
command,
|
|
1313
|
+
raw,
|
|
1314
|
+
text: match[2] ?? "",
|
|
1315
|
+
triggerId: triggerIdOf(threadId, user.userId),
|
|
1316
|
+
user
|
|
1317
|
+
},
|
|
1318
|
+
void 0
|
|
1319
|
+
);
|
|
1320
|
+
return true;
|
|
1321
|
+
}
|
|
1322
|
+
async _claimed(message, threadId) {
|
|
1323
|
+
for (const addon of this._addons("onMessage")) {
|
|
1324
|
+
if (await addon.onMessage(message, this._context(threadId))) return true;
|
|
1325
|
+
}
|
|
1326
|
+
return false;
|
|
1327
|
+
}
|
|
1328
|
+
_addons(hook) {
|
|
1329
|
+
return (this._config.addons ?? []).filter((addon) => addon[hook]);
|
|
1330
|
+
}
|
|
1331
|
+
_context(threadId) {
|
|
1332
|
+
return { adapter: this, chat: this._chat, threadId };
|
|
1333
|
+
}
|
|
1334
|
+
_seenKey() {
|
|
1335
|
+
return `wwebjs:${this.name}:seen`;
|
|
1336
|
+
}
|
|
1337
|
+
/** Writes run in turn, so an older position never lands after a newer one. */
|
|
1338
|
+
_save() {
|
|
1339
|
+
const state = this._chat?.getState();
|
|
1340
|
+
if (!state) return Promise.resolve();
|
|
1341
|
+
this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).catch(
|
|
1342
|
+
(error) => this._logger.warn("Could not record the last message delivered", { error })
|
|
1343
|
+
);
|
|
1344
|
+
return this._saving;
|
|
1345
|
+
}
|
|
1346
|
+
/** While a catch-up runs the position holds still, so a crash part-way replays rather than skips. */
|
|
1347
|
+
async _remember(raw) {
|
|
1348
|
+
if (this._config.catchUpMs === false) return;
|
|
1349
|
+
if (this._behind) this._behind.push(raw);
|
|
1350
|
+
else if (this._advance(raw)) await this._save();
|
|
1351
|
+
}
|
|
1352
|
+
_advance(raw) {
|
|
1353
|
+
if (!this._seen) return false;
|
|
1354
|
+
const id = serialize(raw.id);
|
|
1355
|
+
const at = Math.min(raw.timestamp, Math.floor(Date.now() / 1e3) + CLOCK_SKEW_S);
|
|
1356
|
+
const { ids } = this._seen;
|
|
1357
|
+
if (at < this._seen.at || at === this._seen.at && ids.includes(id)) return false;
|
|
1358
|
+
this._seen = { at, ids: at === this._seen.at ? [...ids, id] : [id], wid: this.botUserId };
|
|
1359
|
+
return true;
|
|
1360
|
+
}
|
|
1361
|
+
/** WhatsApp Web loads what arrived while the session was down without announcing every message. */
|
|
1362
|
+
async _catchUp() {
|
|
1363
|
+
const windowMs = this._config.catchUpMs ?? CATCH_UP_MS;
|
|
1364
|
+
const state = this._chat?.getState();
|
|
1365
|
+
if (windowMs === false || !state) return;
|
|
1366
|
+
this._seen ??= await state.get(this._seenKey());
|
|
1367
|
+
if (this._seen?.wid && this._seen.wid !== this.botUserId) this._seen = null;
|
|
1368
|
+
const seen = this._seen;
|
|
1369
|
+
if (!seen) {
|
|
1370
|
+
this._seen = { at: Math.floor(Date.now() / 1e3), ids: [], wid: this.botUserId };
|
|
1371
|
+
await this._save();
|
|
1372
|
+
return;
|
|
1373
|
+
}
|
|
1374
|
+
const oldest = Math.max(seen.at, Math.floor((Date.now() - windowMs) / 1e3));
|
|
1375
|
+
const unseen = (message) => message.timestamp > oldest || message.timestamp === seen.at && !seen.ids.includes(serialize(message.id));
|
|
1376
|
+
this._behind = [];
|
|
1377
|
+
try {
|
|
1378
|
+
const chats = (await this.client.getChats()).filter((chat) => chat.timestamp >= oldest);
|
|
1379
|
+
const missed = [];
|
|
1380
|
+
let truncated = chats.length > MAX_CATCH_UP_CHATS;
|
|
1381
|
+
for (const chat of chats.slice(0, MAX_CATCH_UP_CHATS)) {
|
|
1382
|
+
const messages = await chat.fetchMessages({ limit: MAX_CATCH_UP_MESSAGES }).catch((error) => {
|
|
1383
|
+
this._logger.warn("Could not catch up on a chat", {
|
|
1384
|
+
chatId: serialize(chat.id),
|
|
1385
|
+
error
|
|
1386
|
+
});
|
|
1387
|
+
return [];
|
|
1388
|
+
});
|
|
1389
|
+
const behind = messages.filter(unseen);
|
|
1390
|
+
truncated ||= behind.length === MAX_CATCH_UP_MESSAGES;
|
|
1391
|
+
missed.push(...behind);
|
|
1392
|
+
}
|
|
1393
|
+
if (truncated) {
|
|
1394
|
+
this._logger.warn(
|
|
1395
|
+
`Caught up on the ${MAX_CATCH_UP_CHATS} most recent chats and ${MAX_CATCH_UP_MESSAGES} messages each; older ones were missed`
|
|
1396
|
+
);
|
|
1397
|
+
}
|
|
1398
|
+
for (const message of missed.sort((a, b) => a.timestamp - b.timestamp)) {
|
|
1399
|
+
await this._onMessage(message).catch(
|
|
1400
|
+
(error) => this._logger.warn("A missed message was not handled", {
|
|
1401
|
+
error,
|
|
1402
|
+
messageId: serialize(message.id)
|
|
1403
|
+
})
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
} finally {
|
|
1407
|
+
const delivered = this._behind;
|
|
1408
|
+
this._behind = void 0;
|
|
1409
|
+
if (delivered.map((message) => this._advance(message)).some(Boolean)) await this._save();
|
|
1410
|
+
}
|
|
813
1411
|
}
|
|
814
1412
|
_onEdit(raw, previousBody) {
|
|
815
1413
|
if (this._isOwn(raw.fromMe)) return;
|
|
@@ -996,7 +1594,7 @@ var WWebJSAdapter = class {
|
|
|
996
1594
|
_onDisconnected(reason) {
|
|
997
1595
|
if (this._closed) return;
|
|
998
1596
|
this._connection = null;
|
|
999
|
-
this._state = this.
|
|
1597
|
+
this._state = this._reconnects() ? "reconnecting" : "disconnected";
|
|
1000
1598
|
if (reason === "LOGOUT") {
|
|
1001
1599
|
this._state = "logged_out";
|
|
1002
1600
|
this._logger.error("WhatsApp logged this session out; pair it again to reconnect", {
|
|
@@ -1007,8 +1605,11 @@ var WWebJSAdapter = class {
|
|
|
1007
1605
|
this._logger.warn("WhatsApp disconnected", { reason });
|
|
1008
1606
|
this._reconnect(RECONNECT_MIN_MS);
|
|
1009
1607
|
}
|
|
1608
|
+
_reconnects() {
|
|
1609
|
+
return this._owned && this._config.reconnect !== false;
|
|
1610
|
+
}
|
|
1010
1611
|
_reconnect(delayMs) {
|
|
1011
|
-
if (this._closed || this.
|
|
1612
|
+
if (this._closed || !this._reconnects()) return;
|
|
1012
1613
|
clearTimeout(this._retry);
|
|
1013
1614
|
this._state = "reconnecting";
|
|
1014
1615
|
this._retry = setTimeout(() => {
|
|
@@ -1043,23 +1644,55 @@ var WWebJSAdapter = class {
|
|
|
1043
1644
|
this._strikes = 0;
|
|
1044
1645
|
this._onDisconnected(`UNRESPONSIVE (${state ?? "no answer"})`);
|
|
1045
1646
|
}
|
|
1046
|
-
_render(message) {
|
|
1647
|
+
_render(message, threadId) {
|
|
1047
1648
|
const card = extractCard(message);
|
|
1048
|
-
|
|
1649
|
+
if (!card) return { text: this._converter.renderPostable(message) };
|
|
1650
|
+
for (const addon of this._addons("renderCard")) {
|
|
1651
|
+
const text = addon.renderCard(card, this._context(threadId));
|
|
1652
|
+
if (text !== void 0) return { card, text };
|
|
1653
|
+
}
|
|
1654
|
+
return {
|
|
1655
|
+
card,
|
|
1656
|
+
text: this._config.richContent ? cardToText(card) : cardToPlainText(card)
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
/** The card is already on WhatsApp, so an addon failing here must not fail the send. */
|
|
1660
|
+
async _cardSent(card, messageId, threadId) {
|
|
1661
|
+
if (!card) return;
|
|
1662
|
+
for (const addon of this._addons("cardSent")) {
|
|
1663
|
+
try {
|
|
1664
|
+
await addon.cardSent(card, messageId, this._context(threadId));
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
this._logger.warn("An addon failed after a card was sent", { error, threadId });
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1049
1669
|
}
|
|
1050
1670
|
async _send(threadId, message, options = {}) {
|
|
1051
1671
|
const { chatId } = this.decodeThreadId(threadId);
|
|
1052
|
-
const {
|
|
1053
|
-
const
|
|
1672
|
+
const { card, text: rendered } = this._render(message, threadId);
|
|
1673
|
+
const { mentions, text } = extractMentions(rendered);
|
|
1674
|
+
const media = [
|
|
1675
|
+
...await toMediaList(message, this._config.maxMediaBytes),
|
|
1676
|
+
...await Promise.all(
|
|
1677
|
+
(card && this._config.richContent ? cardImages(card) : []).map(
|
|
1678
|
+
(url) => toMedia({ type: "image", url }, this._config.maxMediaBytes)
|
|
1679
|
+
)
|
|
1680
|
+
)
|
|
1681
|
+
];
|
|
1054
1682
|
const send = {
|
|
1055
1683
|
...options,
|
|
1056
1684
|
...mentions.length > 0 ? { mentions } : {}
|
|
1057
1685
|
};
|
|
1686
|
+
const voice = this._config.voiceNotes ?? true;
|
|
1058
1687
|
const captionIndex = text ? media.findIndex(isCaptionable) : -1;
|
|
1059
1688
|
const payloads = [];
|
|
1060
1689
|
if (media.length === 0 || text && captionIndex === -1) payloads.push([text, send]);
|
|
1061
1690
|
media.forEach((item, index) => {
|
|
1062
|
-
|
|
1691
|
+
const itemOptions = index === captionIndex ? { ...send, caption: text } : send;
|
|
1692
|
+
payloads.push([
|
|
1693
|
+
item,
|
|
1694
|
+
(voice === "ogg" ? isVoiceNote(item) : voice && isAudio(item)) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
|
|
1695
|
+
]);
|
|
1063
1696
|
});
|
|
1064
1697
|
let first;
|
|
1065
1698
|
for (const [content, sendOptions] of payloads) {
|
|
@@ -1070,7 +1703,9 @@ var WWebJSAdapter = class {
|
|
|
1070
1703
|
);
|
|
1071
1704
|
first ??= sent;
|
|
1072
1705
|
}
|
|
1073
|
-
|
|
1706
|
+
const raw = this._raw(first, threadId);
|
|
1707
|
+
await this._cardSent(card, raw.id, threadId);
|
|
1708
|
+
return raw;
|
|
1074
1709
|
}
|
|
1075
1710
|
async _sendContent(threadId, content, options) {
|
|
1076
1711
|
const { chatId } = this.decodeThreadId(threadId);
|
|
@@ -1078,7 +1713,7 @@ var WWebJSAdapter = class {
|
|
|
1078
1713
|
}
|
|
1079
1714
|
_raw(sent, threadId) {
|
|
1080
1715
|
if (!sent) {
|
|
1081
|
-
throw new
|
|
1716
|
+
throw new ValidationError3(
|
|
1082
1717
|
"wwebjs",
|
|
1083
1718
|
"WhatsApp did not return the sent message. whatsapp-web.js 1.34.7 and older cannot read current WhatsApp Web; install github:pedroslopez/whatsapp-web.js#064a3d5."
|
|
1084
1719
|
);
|
|
@@ -1119,8 +1754,16 @@ var WWebJSAdapter = class {
|
|
|
1119
1754
|
}
|
|
1120
1755
|
return chat;
|
|
1121
1756
|
}
|
|
1122
|
-
|
|
1757
|
+
/** A DM can be addressed by phone or by LID, so only a group's messages must match the thread exactly. */
|
|
1758
|
+
async _findMessage(messageId, threadId) {
|
|
1123
1759
|
const message = await this.client.getMessageById(messageId).catch(() => null);
|
|
1760
|
+
if (!message || !threadId) return message;
|
|
1761
|
+
const chatId = chatIdOf(message);
|
|
1762
|
+
const expected = this.decodeThreadId(threadId).chatId;
|
|
1763
|
+
return chatId === expected || !(isGroupId(chatId) || isGroupId(expected)) ? message : null;
|
|
1764
|
+
}
|
|
1765
|
+
async _requireMessage(messageId, threadId) {
|
|
1766
|
+
const message = await this._findMessage(messageId, threadId);
|
|
1124
1767
|
if (!message) {
|
|
1125
1768
|
throw new ResourceNotFoundError("wwebjs", "message", messageId);
|
|
1126
1769
|
}
|
|
@@ -1133,6 +1776,9 @@ function createWWebJSAdapter(config = {}) {
|
|
|
1133
1776
|
function chatIdOf(message) {
|
|
1134
1777
|
return message.id?.remote || (message.fromMe ? message.to : message.from);
|
|
1135
1778
|
}
|
|
1779
|
+
function locationText({ address, latitude, longitude, name }) {
|
|
1780
|
+
return [name, address, `https://maps.google.com/?q=${latitude},${longitude}`].filter(Boolean).join("\n");
|
|
1781
|
+
}
|
|
1136
1782
|
function within(lookup) {
|
|
1137
1783
|
return Promise.race([
|
|
1138
1784
|
lookup.catch(() => null),
|
|
@@ -1147,7 +1793,7 @@ function participantAuthor(userId, isMe) {
|
|
|
1147
1793
|
}
|
|
1148
1794
|
function assertRange(label, value, bound) {
|
|
1149
1795
|
if (!Number.isFinite(value) || value < -bound || value > bound) {
|
|
1150
|
-
throw new
|
|
1796
|
+
throw new ValidationError3(
|
|
1151
1797
|
"wwebjs",
|
|
1152
1798
|
`sendLocation: ${label} must be between -${bound} and ${bound}. Received ${value}.`
|
|
1153
1799
|
);
|
|
@@ -1155,30 +1801,110 @@ function assertRange(label, value, bound) {
|
|
|
1155
1801
|
}
|
|
1156
1802
|
|
|
1157
1803
|
// src/guards.ts
|
|
1158
|
-
import { ValidationError as
|
|
1804
|
+
import { ValidationError as ValidationError4 } from "@chat-adapter/shared";
|
|
1159
1805
|
function isWWebJSAdapter(value) {
|
|
1160
1806
|
return value instanceof WWebJSAdapter;
|
|
1161
1807
|
}
|
|
1162
1808
|
function requireWWebJSAdapter(value) {
|
|
1163
1809
|
const adapter = value && typeof value === "object" && "adapter" in value ? value.adapter : value;
|
|
1164
1810
|
if (isWWebJSAdapter(adapter)) return adapter;
|
|
1165
|
-
throw new
|
|
1811
|
+
throw new ValidationError4("wwebjs", "This context does not belong to a wwebjs adapter.");
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// src/numbered-actions.ts
|
|
1815
|
+
var TTL_MS = 864e5;
|
|
1816
|
+
function actionsOf(children) {
|
|
1817
|
+
return children.flatMap(
|
|
1818
|
+
(child) => child.type === "actions" ? [child] : child.type === "section" ? actionsOf(child.children) : []
|
|
1819
|
+
);
|
|
1820
|
+
}
|
|
1821
|
+
function layout(card) {
|
|
1822
|
+
const choices = [];
|
|
1823
|
+
const lines = [];
|
|
1824
|
+
const offer = (choice) => {
|
|
1825
|
+
choices.push(choice);
|
|
1826
|
+
lines.push(`${choices.length}. ${choice.label}`);
|
|
1827
|
+
};
|
|
1828
|
+
for (const { children } of actionsOf(card.children)) {
|
|
1829
|
+
for (const action of children) {
|
|
1830
|
+
if (action.type === "link-button") lines.push(`${action.label}: ${action.url}`);
|
|
1831
|
+
else if (action.type === "button") {
|
|
1832
|
+
if (!action.disabled && action.actionType !== "modal") {
|
|
1833
|
+
offer({ actionId: action.id, label: action.label, value: action.value });
|
|
1834
|
+
}
|
|
1835
|
+
} else {
|
|
1836
|
+
lines.push(`*${action.label}*`);
|
|
1837
|
+
for (const option of action.options) {
|
|
1838
|
+
offer({ actionId: action.id, label: option.label, value: option.value });
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
return { choices, lines };
|
|
1844
|
+
}
|
|
1845
|
+
function keyOf({ adapter, threadId }) {
|
|
1846
|
+
return `wwebjs:${adapter.name}:offer:${threadId}`;
|
|
1847
|
+
}
|
|
1848
|
+
function numberedActions(options = {}) {
|
|
1849
|
+
return {
|
|
1850
|
+
renderCard(card) {
|
|
1851
|
+
const { lines } = layout(card);
|
|
1852
|
+
if (lines.length === 0) return void 0;
|
|
1853
|
+
return [cardToText(card), lines.join("\n")].filter(Boolean).join("\n\n");
|
|
1854
|
+
},
|
|
1855
|
+
async cardSent(card, messageId, context) {
|
|
1856
|
+
const { choices } = layout(card);
|
|
1857
|
+
if (choices.length === 0 || !context.chat) return;
|
|
1858
|
+
await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
|
|
1859
|
+
},
|
|
1860
|
+
async onMessage(message, context) {
|
|
1861
|
+
if (message.author.isMe || !context.chat) return false;
|
|
1862
|
+
const state = context.chat.getState();
|
|
1863
|
+
const offer = await state.get(keyOf(context));
|
|
1864
|
+
if (!offer || message.replyTo && message.replyTo.id !== offer.messageId) return false;
|
|
1865
|
+
const reply = message.text.trim();
|
|
1866
|
+
const choice = /^\d+$/.test(reply) ? offer.choices[Number(reply) - 1] : offer.choices.find(({ label }) => label.toLowerCase() === reply.toLowerCase());
|
|
1867
|
+
if (!choice) return false;
|
|
1868
|
+
const ttlMs = options.ttlMs ?? TTL_MS;
|
|
1869
|
+
if (!await state.setIfNotExists(`${keyOf(context)}:${offer.messageId}`, true, ttlMs)) {
|
|
1870
|
+
return false;
|
|
1871
|
+
}
|
|
1872
|
+
await context.chat.processAction(
|
|
1873
|
+
{
|
|
1874
|
+
actionId: choice.actionId,
|
|
1875
|
+
adapter: context.adapter,
|
|
1876
|
+
messageId: offer.messageId,
|
|
1877
|
+
raw: message.raw,
|
|
1878
|
+
threadId: context.threadId,
|
|
1879
|
+
triggerId: triggerIdOf(context.threadId, message.author.userId),
|
|
1880
|
+
user: message.author,
|
|
1881
|
+
value: choice.value
|
|
1882
|
+
},
|
|
1883
|
+
void 0
|
|
1884
|
+
);
|
|
1885
|
+
return !options.keepMessage;
|
|
1886
|
+
}
|
|
1887
|
+
};
|
|
1166
1888
|
}
|
|
1167
1889
|
export {
|
|
1890
|
+
RECOMMENDED_CHROMIUM_ARGS,
|
|
1168
1891
|
WWebJSAdapter,
|
|
1169
1892
|
WWebJSFormatConverter,
|
|
1170
1893
|
createWWebJSAdapter,
|
|
1171
1894
|
download,
|
|
1172
1895
|
extractMentions,
|
|
1896
|
+
isAudio,
|
|
1173
1897
|
isCaptionable,
|
|
1174
1898
|
isGroupId,
|
|
1175
1899
|
isNewsletterId,
|
|
1176
1900
|
isUserId,
|
|
1177
1901
|
isWWebJSAdapter,
|
|
1902
|
+
numberedActions,
|
|
1178
1903
|
requireWWebJSAdapter,
|
|
1179
1904
|
toAttachments,
|
|
1180
1905
|
toChatId,
|
|
1181
1906
|
toMedia,
|
|
1182
1907
|
toMediaList,
|
|
1183
|
-
toUser
|
|
1908
|
+
toUser,
|
|
1909
|
+
triggerIdOf
|
|
1184
1910
|
};
|