chat-adapter-wwebjs 0.1.4 → 0.2.0
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 +24 -0
- package/README.md +41 -13
- package/dist/index.d.ts +46 -10
- package/dist/index.js +213 -54
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# chat-adapter-wwebjs
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- With `receiveOwnMessages`, what the account's owner does on the phone or another linked device reaches your handlers as a person's: `isMe` and `isBot` are `false` and the author is `botUserId`, so `message.author.userId === adapter.botUserId` tells them apart. Everything the account sent used to count as the bot's own, so the Chat SDK skipped its messages, edits, reactions and commands, and only its deletes came through. What the adapter itself sends stays its own, even when WhatsApp echoes a send before it returns: its messages, an edit of one, a reaction it made and a forward. Its messages are recorded in the Chat SDK state for as long as `catchUpMs` reaches back, so catching up after a restart never hands the bot its own; from a position recorded before 0.2.0 or with the option off, which kept no such record, it skips the account's messages altogether. History still counts everything the account sent as the bot's.
|
|
8
|
+
- With `receiveOwnMessages`, the owner answers a modal opened for them and runs slash commands like anyone, and quoting the account's own message is no longer a mention. The adapter's own echoes never answer a modal or run a command; one could have answered a modal with its own question.
|
|
9
|
+
- `numberedActions()` skips whatever the paired account sends, so its owner never picks a contact's option.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- `manageClient: true` on a client you already started called `initialize()` again, launching a second browser on the same profile that never became ready. Its session is now adopted, as a bridged one is, and the adapter runs it from then on.
|
|
14
|
+
- A signal's 8 seconds could end the process while the browser was still closing, leaving Chromium running with the profile locked. A browser still closing then is now ended outright first.
|
|
15
|
+
- A process killed outright, by `kill -9`, the OOM killer or a process manager, left its browser running with the profile locked, and every start failed with "The browser is already running" until someone ended it. The next start now ends it and opens the session, but only a browser on the same host and profile whose launching process is gone, never one another process runs.
|
|
16
|
+
- A catch-up that could not read its position from the Chat SDK state, or list the chats, never ran again until the session reconnected, and a position that could not be written waited for the next message. The watchdog now tries both again, and `disconnect()` writes a failed position once more. Two catch-ups no longer run at once after quick reconnects.
|
|
17
|
+
- An attempt to open the session that a newer one replaced could finish late and take over the newer one's watch on its browser, so closing that browser on purpose read as a crash and opened the session again. A replaced attempt now leaves the session alone, and a bridged client connected again no longer stacks a second watch.
|
|
18
|
+
|
|
19
|
+
## 0.1.5
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- The README and the example imported `LocalAuth` by name, which throws under Node: whatsapp-web.js is CommonJS, so ESM sees only its default export. They now import it as `wwebjs` and take `LocalAuth` from it.
|
|
24
|
+
- The README's install failed on pnpm 10, which refuses to build whatsapp-web.js from GitHub and skips Puppeteer's Chromium download until both are allowed in `onlyBuiltDependencies`. It now installs the tested commit in one command and says how to allow both.
|
|
25
|
+
- The README now warns that the `LocalAuth` directory signs in as your WhatsApp account and belongs out of version control.
|
|
26
|
+
|
|
3
27
|
## 0.1.4
|
|
4
28
|
|
|
5
29
|
### Changed
|
package/README.md
CHANGED
|
@@ -22,12 +22,20 @@ Documentation: [chat-sdk.dev/adapters/community/wwebjs](https://chat-sdk.dev/ada
|
|
|
22
22
|
## Installation
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
|
-
pnpm add chat-adapter-wwebjs
|
|
25
|
+
pnpm add chat-adapter-wwebjs chat @chat-adapter/shared github:pedroslopez/whatsapp-web.js#064a3d5
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
ESM only, Node >= 20. `chat`, `@chat-adapter/shared` and `whatsapp-web.js` are peers, so you control their versions. whatsapp-web.js
|
|
28
|
+
ESM only, Node >= 20. `chat`, `@chat-adapter/shared` and `whatsapp-web.js` are peers, so you control their versions. WhatsApp Web renamed the IDs whatsapp-web.js reads, and 1.34.7 cannot send or find chats since, so until a release carries the fix, install the commit this adapter is tested against, as above.
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
whatsapp-web.js builds when installed from GitHub, and Puppeteer downloads a Chromium build on install. pnpm 10 and later run those scripts only when you allow them, in `pnpm-workspace.yaml`:
|
|
31
|
+
|
|
32
|
+
```yaml
|
|
33
|
+
onlyBuiltDependencies:
|
|
34
|
+
- whatsapp-web.js
|
|
35
|
+
- puppeteer
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
pnpm pins the commit in the lockfile rather than in `package.json`, so commit the lockfile.
|
|
31
39
|
|
|
32
40
|
## Usage
|
|
33
41
|
|
|
@@ -36,7 +44,9 @@ import { createMemoryState } from "@chat-adapter/state-memory";
|
|
|
36
44
|
import { Chat } from "chat";
|
|
37
45
|
import { createWWebJSAdapter } from "chat-adapter-wwebjs";
|
|
38
46
|
import qrcode from "qrcode-terminal";
|
|
39
|
-
import
|
|
47
|
+
import wwebjs from "whatsapp-web.js";
|
|
48
|
+
|
|
49
|
+
const { LocalAuth } = wwebjs;
|
|
40
50
|
|
|
41
51
|
const whatsapp = createWWebJSAdapter({
|
|
42
52
|
adapterName: "whatsapp",
|
|
@@ -75,7 +85,7 @@ Puppeteer's bundled Chromium covers most machines. On slim Linux images install
|
|
|
75
85
|
|
|
76
86
|
### 2. Keep the session
|
|
77
87
|
|
|
78
|
-
Pick an auth strategy from whatsapp-web.js. `LocalAuth` stores the session in a directory, `RemoteAuth` in a store you provide. Persist it, or you scan again on every start.
|
|
88
|
+
Pick an auth strategy from whatsapp-web.js. `LocalAuth` stores the session in a directory, `RemoteAuth` in a store you provide. Persist it, or you scan again on every start. The session signs in as your WhatsApp account, so keep its directory out of version control, for example by adding `.wwebjs-auth` to `.gitignore`.
|
|
79
89
|
|
|
80
90
|
### 3. Link the device
|
|
81
91
|
|
|
@@ -95,16 +105,16 @@ This is a live browser session, not a webhook: `handleWebhook` answers `501`. A
|
|
|
95
105
|
| `client` | — | An existing whatsapp-web.js `Client`, exposed as `adapter.client`. One already started is bridged; one never started is the adapter's to run. See [Bridging your own client](#bridging-your-own-client). When omitted, one is built from `clientOptions`. |
|
|
96
106
|
| `clientOptions` | `{}` | Options for the client the adapter builds: `authStrategy`, `puppeteer`, `webVersionCache`, and so on. Ignored when `client` is set. |
|
|
97
107
|
| `connectTimeoutMs` | 2 minutes | How long opening the session may take before it is abandoned and, with `reconnect`, tried again. Once a QR or pairing code is shown, it waits for the scan. |
|
|
98
|
-
| `handleSignals` | `true` | Close the session on SIGINT, SIGTERM and SIGHUP, then let the signal end the process — unless your app listens for it and shuts down itself. Closing is given 8 seconds.
|
|
108
|
+
| `handleSignals` | `true` | Close the session on SIGINT, SIGTERM and SIGHUP, then let the signal end the process — unless your app listens for it and shuts down itself. Closing is given 8 seconds; a browser still closing then is ended outright. |
|
|
99
109
|
| `logger` | `ConsoleLogger` | Logger used until `Chat` hands over its own. |
|
|
100
110
|
| `modalTexts` | English | The phrases a conversational modal sends, such as its _cancel_ and _skip_ words, to put them in your users' language. See [Modals](#modals). |
|
|
101
|
-
| `manageClient` | by state | Force who runs a `client` you passed: `true` has the adapter reconnect it, close it on `disconnect()` and on a signal,
|
|
111
|
+
| `manageClient` | by state | Force who runs a `client` you passed: `true` has the adapter reconnect it, close it on `disconnect()` and on a signal, adopting one you started without a second browser; `false` only bridges it, even if you didn't. |
|
|
102
112
|
| `markSeen` | `false` | Send a read receipt for every inbound message as it arrives. |
|
|
103
113
|
| `maxMediaBytes` | 64 MB | Largest media read into memory, inbound or fetched from a `url`. The size is checked before reading and the bytes are counted as they arrive, whatever size the sender claims. |
|
|
104
114
|
| `onPairingCode` | — | Receives the 8-character pairing code when `phoneNumber` is set. |
|
|
105
115
|
| `onQR` | — | Receives the QR string during login. Render it with `qrcode-terminal` or similar. |
|
|
106
116
|
| `phoneNumber` | — | Log in with a pairing code instead of a QR. E.164 without the leading `+`. |
|
|
107
|
-
| `receiveOwnMessages` | `false` |
|
|
117
|
+
| `receiveOwnMessages` | `false` | Deliver what the account's owner does on the phone — messages, edits, deletes and reactions — as a person's, from `botUserId`. What the adapter sends stays its own. See [Messages from the phone](#messages-from-the-phone). |
|
|
108
118
|
| `richContent` | `false` | Imitate what WhatsApp lacks: cards in its markup with their images as media, and modals as conversations. Off, a card is plain text and the adapter has no `openModal`. See [Rich content](#rich-content). |
|
|
109
119
|
| `recommendedArgs` | `true` | Start Chromium with `RECOMMENDED_CHROMIUM_ARGS`: one renderer process, no GPU, no component updates. |
|
|
110
120
|
| `reconnect` | `true` | Open the session again when WhatsApp drops it, backing off from 5 seconds to 5 minutes. A logout is never retried. |
|
|
@@ -232,7 +242,7 @@ bot.onAction("approve", async (event) => {
|
|
|
232
242
|
});
|
|
233
243
|
```
|
|
234
244
|
|
|
235
|
-
The options of a thread's latest card answer for a day (`ttlMs`) and live in the Chat SDK state. The first pick ends them, so a repeated answer runs nothing twice; a reply quoting another message is not a pick, and neither is anything the
|
|
245
|
+
The options of a thread's latest card answer for a day (`ttlMs`) and live in the Chat SDK state. The first pick ends them, so a repeated answer runs nothing twice; a reply quoting another message is not a pick, and neither is anything the paired account sends, its owner's messages included. In a group anyone can answer, and `event.user` says who did. The reply that picked an option is not delivered as a message unless `keepMessage` is set.
|
|
236
246
|
|
|
237
247
|
An addon is a plain object with optional `renderCard`, `cardSent` and `onMessage` hooks, so other layers fit the same way.
|
|
238
248
|
|
|
@@ -333,7 +343,7 @@ What the adapter does with it depends on whether it was started when you passed
|
|
|
333
343
|
- **Already started**, as above, it is bridged as it is. `connect()` adopts its session without a second `initialize()`, or waits for it if it is still starting. Its options and listeners are left alone, and its lifecycle stays yours: the adapter never reconnects or destroys it, nor closes it on a signal, and `disconnect()` only detaches the adapter.
|
|
334
344
|
- **Never started**, it is the adapter's to run, exactly as one it built: `connect()` starts it, and the adapter reconnects it, closes it on `disconnect()` and on a signal.
|
|
335
345
|
|
|
336
|
-
`manageClient` forces either way: `true` hands even a client you started to the adapter, and `false` keeps even an unstarted one a bridge, which `connect()` starts but never reconnects or closes.
|
|
346
|
+
`manageClient` forces either way: `true` hands even a client you started to the adapter, which adopts its session without a second `initialize()` and runs it from then on, and `false` keeps even an unstarted one a bridge, which `connect()` starts but never reconnects or closes.
|
|
337
347
|
|
|
338
348
|
## Message history
|
|
339
349
|
|
|
@@ -343,7 +353,24 @@ What the adapter does with it depends on whether it was started when you passed
|
|
|
343
353
|
|
|
344
354
|
## Catching up after downtime
|
|
345
355
|
|
|
346
|
-
WhatsApp Web loads what arrived while the session was down without firing an event for each message, so the adapter catches up on its own once the session is back: it gathers what every recent chat missed, oldest first, and hands each message to your handlers. The position lives in the Chat SDK state with the account it belongs to, so a restart starts where the last process stopped, and pairing a new number starts afresh. A restart part-way through delivers again rather than skip, and a message that arrives live while it is caught up is handled once. The first run starts counting and replays nothing older. A chat outside the 100 most recent, or more than 50 messages behind, is not caught up in full, and the adapter logs a warning when that happens.
|
|
356
|
+
WhatsApp Web loads what arrived while the session was down without firing an event for each message, so the adapter catches up on its own once the session is back: it gathers what every recent chat missed, oldest first, and hands each message to your handlers. The position lives in the Chat SDK state with the account it belongs to, so a restart starts where the last process stopped, and pairing a new number starts afresh. A restart part-way through delivers again rather than skip, and a message that arrives live while it is caught up is handled once. The first run starts counting and replays nothing older. A chat outside the 100 most recent, or more than 50 messages behind, is not caught up in full, and the adapter logs a warning when that happens. A catch-up that could not read its position or list the chats, and a position that could not be recorded, are tried again on the watchdog's next check.
|
|
357
|
+
|
|
358
|
+
## Messages from the phone
|
|
359
|
+
|
|
360
|
+
The paired account is someone's WhatsApp, and they may keep using it. By default nothing the account sends reaches your handlers. With `receiveOwnMessages`, what its owner does on the phone or another linked device — messages, edits, deletes and reactions — arrives as a person's, from the bot's own account:
|
|
361
|
+
|
|
362
|
+
```typescript
|
|
363
|
+
const whatsapp = createWWebJSAdapter({ receiveOwnMessages: true });
|
|
364
|
+
|
|
365
|
+
bot.onSubscribedMessage(async (thread, message) => {
|
|
366
|
+
if (message.author.userId === whatsapp.botUserId) return thread.unsubscribe(); // the owner took over
|
|
367
|
+
await thread.post(`You said: ${message.text}`);
|
|
368
|
+
});
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
What the adapter itself sends stays its own, `isMe`, which the Chat SDK skips. It knows each message it sent, even one WhatsApp echoes back before the send returns, and records it in the Chat SDK state for as long as `catchUpMs` reaches back, so a restart that catches up on the account's messages still skips its own. Catching up from a position recorded without that record, before 0.2.0 or with the option off, skips the account's messages altogether. An edit is its own when it edits a message the adapter sent, a reaction when the adapter reacted to that message, and a forward when its echo answers one the adapter made. Deletes carry no author, so the adapter's come through too.
|
|
372
|
+
|
|
373
|
+
The owner answers a modal opened for them and runs your slash commands like anyone, while the adapter's own echoes never do. Nothing the account sends picks a card's numbered option, and the owner quoting the account's own message is no mention. History — `fetchMessages` and the like — still counts everything the account sent as the bot's own, since what the adapter sent is remembered only that long.
|
|
347
374
|
|
|
348
375
|
## Multiple accounts
|
|
349
376
|
|
|
@@ -396,7 +423,8 @@ Examples: `wwebjs:15551234567@c.us` (DM by phone), `wwebjs:99990000111122@lid` (
|
|
|
396
423
|
### "The browser is already running"
|
|
397
424
|
|
|
398
425
|
- Another process holds the same `LocalAuth` profile. The adapter ends every browser it launches before reopening, even one whatsapp-web.js never handed over; a client you started yourself is yours to close.
|
|
399
|
-
- A process killed outright, by `kill -9
|
|
426
|
+
- A process killed outright, by `kill -9`, the OOM killer or a process manager out of patience, leaves its browser running. The next start ends it when it runs on the same host, on the same profile, with the process that launched it gone, found through `ps`, which slim images may lack.
|
|
427
|
+
- A lock left on the profile by another host, as by a container recreated with a new hostname, is never cleared, since that browser may still run there. Give the container a fixed `hostname`, or remove the profile's `SingletonLock` once you are sure.
|
|
400
428
|
|
|
401
429
|
### The session drops
|
|
402
430
|
|
|
@@ -407,7 +435,7 @@ Examples: `wwebjs:15551234567@c.us` (DM by phone), `wwebjs:99990000111122@lid` (
|
|
|
407
435
|
- **Unofficial.** It automates WhatsApp Web, which WhatsApp may block or change at any time.
|
|
408
436
|
- **One session per number**, as WhatsApp Web itself allows.
|
|
409
437
|
- **No scheduling or ephemeral messages.** `postEphemeral` falls back to a DM; `thread.schedule()` throws.
|
|
410
|
-
- **
|
|
438
|
+
- **History counts everything the paired account sent as the bot's own.** Only what arrives, live or caught up, tells its owner's messages from the adapter's; see [Messages from the phone](#messages-from-the-phone).
|
|
411
439
|
- **An attachment given only by `url` is fetched over HTTPS**, never from a private or internal address, with a 30-second timeout and `maxMediaBytes` as its limit.
|
|
412
440
|
- **A bare `@number` in outgoing text stays text.** Mention someone with `thread.mentionUser(id)`.
|
|
413
441
|
- **`forwardMessage` and event call links fail on current WhatsApp Web.** whatsapp-web.js still calls modules WhatsApp has renamed; both return once it catches up. `sendEvent` without `callType` attaches no link and works.
|
package/dist/index.d.ts
CHANGED
|
@@ -73,8 +73,9 @@ interface WWebJSAdapterConfig {
|
|
|
73
73
|
/**
|
|
74
74
|
* Close the session on SIGINT, SIGTERM and SIGHUP, then let the signal end
|
|
75
75
|
* the process as it otherwise would — unless the app listens for it, and
|
|
76
|
-
* shuts down itself.
|
|
77
|
-
* process
|
|
76
|
+
* shuts down itself. A browser still closing after 8 seconds is ended
|
|
77
|
+
* outright first, so it never outlives the process. Puppeteer alone closes
|
|
78
|
+
* the browser and leaves the process running. Defaults to `true`.
|
|
78
79
|
*/
|
|
79
80
|
handleSignals?: boolean;
|
|
80
81
|
/** Logger instance. Replaced by the Chat SDK logger once initialized. */
|
|
@@ -82,8 +83,8 @@ interface WWebJSAdapterConfig {
|
|
|
82
83
|
/**
|
|
83
84
|
* Force who runs a `client` you passed, whatever its state: `true` has the
|
|
84
85
|
* adapter reconnect it, destroy it on `disconnect()` and close it on a
|
|
85
|
-
* signal
|
|
86
|
-
* omitted.
|
|
86
|
+
* signal, adopting one already started rather than starting it twice;
|
|
87
|
+
* `false` only bridges it. Decided by whether it was started when omitted.
|
|
87
88
|
*/
|
|
88
89
|
manageClient?: boolean;
|
|
89
90
|
/** The few phrases a conversational modal sends, to put them in your users' language. */
|
|
@@ -114,9 +115,13 @@ interface WWebJSAdapterConfig {
|
|
|
114
115
|
*/
|
|
115
116
|
maxMediaBytes?: number;
|
|
116
117
|
/**
|
|
117
|
-
* Deliver
|
|
118
|
-
*
|
|
119
|
-
*
|
|
118
|
+
* Deliver what the paired account's owner does from the phone or another
|
|
119
|
+
* linked device — messages, edits, deletes and reactions — as a person's,
|
|
120
|
+
* from `botUserId`, so `message.author.userId === adapter.botUserId` tells
|
|
121
|
+
* them apart. What this adapter sends, edits or reacts with stays its own,
|
|
122
|
+
* `isMe`, which the Chat SDK skips, after a restart too for as long as
|
|
123
|
+
* `catchUpMs` reaches back. Deletes carry no author, so the adapter's come
|
|
124
|
+
* through too. Defaults to `false`.
|
|
120
125
|
*/
|
|
121
126
|
receiveOwnMessages?: boolean;
|
|
122
127
|
/**
|
|
@@ -340,6 +345,14 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
|
|
|
340
345
|
private _behind?;
|
|
341
346
|
private readonly _recent;
|
|
342
347
|
private _saving;
|
|
348
|
+
private _unsaved;
|
|
349
|
+
/** Catch-ups run in turn, so two never hold or move the position at once. */
|
|
350
|
+
private _catching;
|
|
351
|
+
private _owed;
|
|
352
|
+
/** What this adapter sent or reacted to, so the account's echo of it is told apart from what its owner does. */
|
|
353
|
+
private readonly _own;
|
|
354
|
+
private readonly _sending;
|
|
355
|
+
private _forwards;
|
|
343
356
|
constructor(config?: WWebJSAdapterConfig);
|
|
344
357
|
/** Where the session stands; a health check reads `connection === "connected"`. */
|
|
345
358
|
get connection(): WWebJSConnection;
|
|
@@ -375,6 +388,8 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
|
|
|
375
388
|
deleteMessage(threadId: string, messageId: string): Promise<void>;
|
|
376
389
|
addReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
|
|
377
390
|
removeReaction(threadId: string, messageId: string, _emoji: EmojiValue | string): Promise<void>;
|
|
391
|
+
/** Marked before it is sent, since its echo can arrive before `react()` returns. */
|
|
392
|
+
private _react;
|
|
378
393
|
fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
|
|
379
394
|
fetchChannelMessages(channelId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
|
|
380
395
|
fetchMessage(threadId: string, messageId: string): Promise<Message$1<Message> | null>;
|
|
@@ -461,7 +476,11 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
|
|
|
461
476
|
private _running;
|
|
462
477
|
/** Closes the browser this adapter runs; closing it on purpose is not a crash to recover from. */
|
|
463
478
|
private _close;
|
|
464
|
-
/**
|
|
479
|
+
/**
|
|
480
|
+
* `destroy()` closes only a browser it still sees connected, so one that
|
|
481
|
+
* dropped keeps its profile locked. It is ended at once, as a signal whose
|
|
482
|
+
* time runs out needs, and the promise waits for it to exit.
|
|
483
|
+
*/
|
|
465
484
|
private _killBrowser;
|
|
466
485
|
private _listen;
|
|
467
486
|
private _unlisten;
|
|
@@ -478,21 +497,27 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
|
|
|
478
497
|
private _addons;
|
|
479
498
|
private _context;
|
|
480
499
|
private _seenKey;
|
|
481
|
-
/** Writes run in turn, so an older position never lands after a newer one. */
|
|
500
|
+
/** Writes run in turn, so an older position never lands after a newer one; one that fails is written again by the watchdog. */
|
|
482
501
|
private _save;
|
|
483
502
|
/** While a catch-up runs the position holds still, so a crash part-way replays rather than skips. */
|
|
484
503
|
private _remember;
|
|
485
504
|
private _advance;
|
|
505
|
+
private _position;
|
|
506
|
+
/** One that fails, reading its position or the chats, is owed, and the watchdog runs it again. */
|
|
507
|
+
private _catchUpNext;
|
|
486
508
|
/** WhatsApp Web loads what arrived while the session was down without announcing every message. */
|
|
487
509
|
private _catchUp;
|
|
510
|
+
/** The account's edit of a message this adapter sent is the adapter's own; any other is the operator's. */
|
|
488
511
|
private _onEdit;
|
|
489
512
|
private _onRevoke;
|
|
513
|
+
/** The account's reaction to a message this adapter reacted to is the adapter's own; any other is the operator's. */
|
|
490
514
|
private _onReaction;
|
|
491
515
|
private _onAck;
|
|
492
516
|
private _onGroup;
|
|
493
517
|
private _onVote;
|
|
494
518
|
private _dispatch;
|
|
495
519
|
private _parse;
|
|
520
|
+
/** The account's own messages come from `botUserId`, whether the adapter sent them or its owner did. */
|
|
496
521
|
private _author;
|
|
497
522
|
private _indicator;
|
|
498
523
|
/** Groups address the bot by its LID or its phone number, whichever they know it by. */
|
|
@@ -516,6 +541,16 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
|
|
|
516
541
|
private _cardSent;
|
|
517
542
|
private _send;
|
|
518
543
|
private _sendContent;
|
|
544
|
+
/** Every send goes through here, under way before it starts, so its echo stays the adapter's own even when it arrives before the id. */
|
|
545
|
+
private _post;
|
|
546
|
+
/** Kept in state too, for as long as a catch-up reaches back, so an echo replayed after a restart is still its own. */
|
|
547
|
+
private _mark;
|
|
548
|
+
private _marked;
|
|
549
|
+
private _ownKey;
|
|
550
|
+
/** whatsapp-web.js can emit a send's echo before `sendMessage()` returns its id, so the sends under way settle first. */
|
|
551
|
+
private _echo;
|
|
552
|
+
/** Claimed on arrival, by a forward the adapter made that no echo has claimed yet. */
|
|
553
|
+
private _forwarded;
|
|
519
554
|
private _raw;
|
|
520
555
|
private _page;
|
|
521
556
|
private _findChat;
|
|
@@ -588,4 +623,5 @@ interface NumberedActionsOptions {
|
|
|
588
623
|
*/
|
|
589
624
|
declare function numberedActions(options?: NumberedActionsOptions): WWebJSAddon;
|
|
590
625
|
|
|
591
|
-
export {
|
|
626
|
+
export { RECOMMENDED_CHROMIUM_ARGS, WWebJSAdapter, WWebJSFormatConverter, createWWebJSAdapter, download, extractMentions, isAudio, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, numberedActions, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser, triggerIdOf };
|
|
627
|
+
export type { NumberedActionsOptions, WWebJSAck, WWebJSAckHandler, WWebJSAckStatus, WWebJSAdapterConfig, WWebJSAddon, WWebJSAddonContext, WWebJSCallHandler, WWebJSConnection, WWebJSGroupEvent, WWebJSGroupEventHandler, WWebJSGroupParticipant, WWebJSModalTexts, WWebJSPollVote, WWebJSPollVoteHandler, WWebJSSendEventArgs, WWebJSSendLocationArgs, WWebJSSendPollArgs, WWebJSThreadId };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// src/adapter.ts
|
|
2
2
|
import { randomUUID } from "crypto";
|
|
3
|
-
import { once } from "events";
|
|
4
3
|
import { extractCard, ResourceNotFoundError, ValidationError as ValidationError3 } from "@chat-adapter/shared";
|
|
5
4
|
import {
|
|
6
5
|
ConsoleLogger,
|
|
@@ -451,21 +450,66 @@ function flattenOptions(result) {
|
|
|
451
450
|
return (result ?? []).flatMap((entry) => "options" in entry ? entry.options : [entry]);
|
|
452
451
|
}
|
|
453
452
|
|
|
453
|
+
// src/profile.ts
|
|
454
|
+
import { execFile } from "child_process";
|
|
455
|
+
import { readlink } from "fs/promises";
|
|
456
|
+
import { hostname } from "os";
|
|
457
|
+
import { join, resolve as resolvePath } from "path";
|
|
458
|
+
var EXIT_WAIT_MS = 2e3;
|
|
459
|
+
var POLL_MS = 100;
|
|
460
|
+
async function freeProfile(dir) {
|
|
461
|
+
if (!dir) return false;
|
|
462
|
+
const profile = resolvePath(dir);
|
|
463
|
+
const lock = await readlink(join(profile, "SingletonLock")).catch(() => "");
|
|
464
|
+
const [, host, pid] = /^(.+)-(\d+)$/.exec(lock) ?? [];
|
|
465
|
+
if (!pid || host !== hostname()) return false;
|
|
466
|
+
const [, parent, args] = /^(\d+)\s+(.*)$/.exec(await commandOf(pid)) ?? [];
|
|
467
|
+
if (parent !== "1" || !`${args} `.includes(` --user-data-dir=${profile} `)) return false;
|
|
468
|
+
try {
|
|
469
|
+
process.kill(-Number(pid), "SIGKILL");
|
|
470
|
+
} catch {
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
for (let waited = 0; alive(Number(pid)) && waited < EXIT_WAIT_MS; waited += POLL_MS) {
|
|
474
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
|
475
|
+
}
|
|
476
|
+
return true;
|
|
477
|
+
}
|
|
478
|
+
function commandOf(pid) {
|
|
479
|
+
return new Promise(
|
|
480
|
+
(resolve) => execFile(
|
|
481
|
+
"ps",
|
|
482
|
+
["-ww", "-o", "ppid=,args=", "-p", pid],
|
|
483
|
+
(error, stdout) => resolve(error ? "" : stdout.trim())
|
|
484
|
+
)
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
function alive(pid) {
|
|
488
|
+
try {
|
|
489
|
+
process.kill(pid, 0);
|
|
490
|
+
return true;
|
|
491
|
+
} catch {
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
454
496
|
// src/shutdown.ts
|
|
455
497
|
var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
|
|
456
498
|
var CLOSE_TIMEOUT_MS = 8e3;
|
|
457
|
-
var sessions = /* @__PURE__ */ new
|
|
499
|
+
var sessions = /* @__PURE__ */ new Map();
|
|
458
500
|
async function onSignal(signal) {
|
|
459
501
|
for (const name of SIGNALS) process.off(name, onSignal);
|
|
502
|
+
const closing = [...sessions];
|
|
460
503
|
await Promise.race([
|
|
461
|
-
Promise.allSettled(
|
|
504
|
+
Promise.allSettled(closing.map(([close]) => close())),
|
|
462
505
|
new Promise((resolve) => setTimeout(resolve, CLOSE_TIMEOUT_MS).unref())
|
|
463
506
|
]);
|
|
507
|
+
for (const [, kill] of closing) kill();
|
|
464
508
|
if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
|
|
465
509
|
}
|
|
466
|
-
function closeOnSignal(close) {
|
|
510
|
+
function closeOnSignal(close, kill) {
|
|
467
511
|
if (sessions.size === 0) for (const name of SIGNALS) process.on(name, onSignal);
|
|
468
|
-
sessions.
|
|
512
|
+
sessions.set(close, kill);
|
|
469
513
|
return () => {
|
|
470
514
|
sessions.delete(close);
|
|
471
515
|
if (sessions.size === 0) for (const name of SIGNALS) process.off(name, onSignal);
|
|
@@ -566,6 +610,14 @@ var WWebJSAdapter = class {
|
|
|
566
610
|
_behind;
|
|
567
611
|
_recent = /* @__PURE__ */ new Set();
|
|
568
612
|
_saving = Promise.resolve();
|
|
613
|
+
_unsaved = false;
|
|
614
|
+
/** Catch-ups run in turn, so two never hold or move the position at once. */
|
|
615
|
+
_catching = Promise.resolve();
|
|
616
|
+
_owed = false;
|
|
617
|
+
/** What this adapter sent or reacted to, so the account's echo of it is told apart from what its owner does. */
|
|
618
|
+
_own = /* @__PURE__ */ new Set();
|
|
619
|
+
_sending = /* @__PURE__ */ new Set();
|
|
620
|
+
_forwards = 0;
|
|
569
621
|
constructor(config = {}) {
|
|
570
622
|
const name = config.adapterName ?? "wwebjs";
|
|
571
623
|
if (name.includes(":")) {
|
|
@@ -615,7 +667,10 @@ var WWebJSAdapter = class {
|
|
|
615
667
|
if (this._listeners.length === 0) this._listen();
|
|
616
668
|
this._watch();
|
|
617
669
|
if (this._owned && this._config.handleSignals !== false) {
|
|
618
|
-
this._unsignal ??= closeOnSignal(
|
|
670
|
+
this._unsignal ??= closeOnSignal(
|
|
671
|
+
() => this.disconnect(),
|
|
672
|
+
() => void this._killBrowser()
|
|
673
|
+
);
|
|
619
674
|
}
|
|
620
675
|
if (this._connection) return this._connection;
|
|
621
676
|
const attempt = ++this._attempts;
|
|
@@ -638,7 +693,7 @@ var WWebJSAdapter = class {
|
|
|
638
693
|
this._connection = null;
|
|
639
694
|
this._unsignal?.();
|
|
640
695
|
this._unsignal = void 0;
|
|
641
|
-
await this._saving;
|
|
696
|
+
await (this._unsaved ? this._save() : this._saving);
|
|
642
697
|
if (!this._owned) return this._unlisten();
|
|
643
698
|
await this._close();
|
|
644
699
|
}
|
|
@@ -751,10 +806,16 @@ var WWebJSAdapter = class {
|
|
|
751
806
|
await (await this._requireMessage(messageId, threadId)).delete(true);
|
|
752
807
|
}
|
|
753
808
|
async addReaction(threadId, messageId, emoji) {
|
|
754
|
-
await
|
|
809
|
+
await this._react(threadId, messageId, defaultEmojiResolver.toGChat(emoji));
|
|
755
810
|
}
|
|
756
811
|
async removeReaction(threadId, messageId, _emoji) {
|
|
757
|
-
await
|
|
812
|
+
await this._react(threadId, messageId, "");
|
|
813
|
+
}
|
|
814
|
+
/** Marked before it is sent, since its echo can arrive before `react()` returns. */
|
|
815
|
+
async _react(threadId, messageId, reaction) {
|
|
816
|
+
const target = await this._requireMessage(messageId, threadId);
|
|
817
|
+
await this._mark(`reacted:${serialize(target.id)}`);
|
|
818
|
+
await target.react(reaction);
|
|
758
819
|
}
|
|
759
820
|
async fetchMessages(threadId, options) {
|
|
760
821
|
return this._page(await this._requireChat(threadId), options);
|
|
@@ -913,7 +974,13 @@ var WWebJSAdapter = class {
|
|
|
913
974
|
/** Forward an existing message into another thread. */
|
|
914
975
|
async forwardMessage(messageId, targetThreadId) {
|
|
915
976
|
const { chatId } = this.decodeThreadId(targetThreadId);
|
|
916
|
-
|
|
977
|
+
const message = await this._requireMessage(messageId);
|
|
978
|
+
const claims = this._config.receiveOwnMessages ? 1 : 0;
|
|
979
|
+
this._forwards += claims;
|
|
980
|
+
await message.forward(chatId).catch((error) => {
|
|
981
|
+
this._forwards -= claims;
|
|
982
|
+
throw error;
|
|
983
|
+
});
|
|
917
984
|
}
|
|
918
985
|
/** Pin a message for the given number of seconds. */
|
|
919
986
|
async pinMessage(messageId, seconds) {
|
|
@@ -1056,7 +1123,7 @@ var WWebJSAdapter = class {
|
|
|
1056
1123
|
this.client.once("qr", waiting);
|
|
1057
1124
|
this.client.once("code", waiting);
|
|
1058
1125
|
try {
|
|
1059
|
-
await Promise.race([this._open(), timedOut]);
|
|
1126
|
+
await Promise.race([this._open(attempt), timedOut]);
|
|
1060
1127
|
} catch (error) {
|
|
1061
1128
|
if (this._owned && attempt === this._attempts) await this._close().catch(() => void 0);
|
|
1062
1129
|
throw error;
|
|
@@ -1066,12 +1133,16 @@ var WWebJSAdapter = class {
|
|
|
1066
1133
|
this.client.off("code", waiting);
|
|
1067
1134
|
}
|
|
1068
1135
|
}
|
|
1069
|
-
async _open() {
|
|
1136
|
+
async _open(attempt) {
|
|
1070
1137
|
this._state = this._initialized ? "reconnecting" : "connecting";
|
|
1071
|
-
|
|
1138
|
+
const adopted = this._owned ? !this._initialized && !!this.client.pupBrowser?.isConnected() : !!this.client.pupBrowser;
|
|
1139
|
+
if (adopted && await this._running()) {
|
|
1140
|
+
if (attempt !== this._attempts) return;
|
|
1141
|
+
this._initialized = true;
|
|
1072
1142
|
this._watchBrowser();
|
|
1073
1143
|
return this._onReady();
|
|
1074
1144
|
}
|
|
1145
|
+
const options = this.client.options;
|
|
1075
1146
|
let onReady;
|
|
1076
1147
|
let onFailure;
|
|
1077
1148
|
const ready = new Promise((resolve, reject) => {
|
|
@@ -1084,16 +1155,21 @@ var WWebJSAdapter = class {
|
|
|
1084
1155
|
try {
|
|
1085
1156
|
if (this._owned && this._initialized) await this._close().catch(() => void 0);
|
|
1086
1157
|
this._initialized = true;
|
|
1087
|
-
if (
|
|
1088
|
-
this.
|
|
1089
|
-
|
|
1090
|
-
|
|
1158
|
+
if (!adopted) {
|
|
1159
|
+
if (this._owned) {
|
|
1160
|
+
this._launch = new AbortController();
|
|
1161
|
+
options.puppeteer = { ...options.puppeteer, signal: this._launch.signal };
|
|
1162
|
+
}
|
|
1163
|
+
await this.client.initialize().catch(async (error) => {
|
|
1164
|
+
if (!this._owned || !await freeProfile(options.puppeteer?.userDataDir)) throw error;
|
|
1165
|
+
await this.client.initialize();
|
|
1166
|
+
});
|
|
1091
1167
|
}
|
|
1092
|
-
if (this._owned || !this.client.pupBrowser) await this.client.initialize();
|
|
1093
1168
|
if (this._closed) {
|
|
1094
1169
|
if (this._owned) await this._close();
|
|
1095
1170
|
return;
|
|
1096
1171
|
}
|
|
1172
|
+
if (attempt !== this._attempts) return;
|
|
1097
1173
|
this._watchBrowser();
|
|
1098
1174
|
await ready;
|
|
1099
1175
|
} finally {
|
|
@@ -1103,6 +1179,7 @@ var WWebJSAdapter = class {
|
|
|
1103
1179
|
}
|
|
1104
1180
|
/** A crashed browser ends the session without WhatsApp ever reporting a disconnect. */
|
|
1105
1181
|
_watchBrowser() {
|
|
1182
|
+
this._unwatch?.();
|
|
1106
1183
|
const browser = this.client.pupBrowser;
|
|
1107
1184
|
if (!browser) return;
|
|
1108
1185
|
const onClose = () => this._onDisconnected("BROWSER_CLOSED");
|
|
@@ -1124,21 +1201,27 @@ var WWebJSAdapter = class {
|
|
|
1124
1201
|
await this._killBrowser();
|
|
1125
1202
|
}
|
|
1126
1203
|
}
|
|
1127
|
-
/**
|
|
1128
|
-
|
|
1204
|
+
/**
|
|
1205
|
+
* `destroy()` closes only a browser it still sees connected, so one that
|
|
1206
|
+
* dropped keeps its profile locked. It is ended at once, as a signal whose
|
|
1207
|
+
* time runs out needs, and the promise waits for it to exit.
|
|
1208
|
+
*/
|
|
1209
|
+
_killBrowser() {
|
|
1129
1210
|
this._launch?.abort();
|
|
1130
1211
|
const browser = this.client.pupBrowser?.process?.();
|
|
1131
|
-
if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null)
|
|
1132
|
-
|
|
1212
|
+
if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null) {
|
|
1213
|
+
return Promise.resolve();
|
|
1214
|
+
}
|
|
1215
|
+
const exited = new Promise((resolve) => {
|
|
1216
|
+
browser.once("exit", resolve);
|
|
1217
|
+
setTimeout(resolve, KILL_WAIT_MS).unref?.();
|
|
1218
|
+
});
|
|
1133
1219
|
try {
|
|
1134
1220
|
process.kill(process.platform === "win32" ? browser.pid : -browser.pid, "SIGKILL");
|
|
1135
1221
|
} catch {
|
|
1136
1222
|
browser.kill("SIGKILL");
|
|
1137
1223
|
}
|
|
1138
|
-
|
|
1139
|
-
exited,
|
|
1140
|
-
new Promise((resolve) => setTimeout(resolve, KILL_WAIT_MS).unref?.())
|
|
1141
|
-
]);
|
|
1224
|
+
return exited;
|
|
1142
1225
|
}
|
|
1143
1226
|
_listen() {
|
|
1144
1227
|
const { onPairingCode, onQR } = this._config;
|
|
@@ -1152,9 +1235,12 @@ var WWebJSAdapter = class {
|
|
|
1152
1235
|
on("ready", () => this._onReady());
|
|
1153
1236
|
on("disconnected", (reason) => this._onDisconnected(String(reason)));
|
|
1154
1237
|
on("message_create", (message) => this._guard("message", this._onMessage(message)));
|
|
1155
|
-
on(
|
|
1238
|
+
on(
|
|
1239
|
+
"message_edit",
|
|
1240
|
+
(message, _new, previous) => this._guard("edit", this._onEdit(message, String(previous)))
|
|
1241
|
+
);
|
|
1156
1242
|
on("message_revoke_everyone", (message, revoked) => this._onRevoke(message, revoked));
|
|
1157
|
-
on("message_reaction", (reaction) => this._onReaction(reaction));
|
|
1243
|
+
on("message_reaction", (reaction) => this._guard("reaction", this._onReaction(reaction)));
|
|
1158
1244
|
on("message_ack", (message, ack) => this._onAck(message, ack));
|
|
1159
1245
|
on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
|
|
1160
1246
|
on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
|
|
@@ -1174,7 +1260,7 @@ var WWebJSAdapter = class {
|
|
|
1174
1260
|
}
|
|
1175
1261
|
this._logger.info("WhatsApp session ready", { userId: this.botUserId });
|
|
1176
1262
|
void this._learnLid();
|
|
1177
|
-
this.
|
|
1263
|
+
this._catchUpNext();
|
|
1178
1264
|
}
|
|
1179
1265
|
async _onMessage(raw) {
|
|
1180
1266
|
if (!this._chat || this._isOwn(raw.fromMe)) return;
|
|
@@ -1182,22 +1268,22 @@ var WWebJSAdapter = class {
|
|
|
1182
1268
|
if (raw.isStatus || isBroadcastId(chatId) || SYSTEM_TYPES.has(raw.type)) return;
|
|
1183
1269
|
const id = serialize(raw.id);
|
|
1184
1270
|
if (this._recent.has(id)) return;
|
|
1185
|
-
this._recent
|
|
1186
|
-
if (this._recent.size > MAX_RECENT) this._recent.delete(this._recent.values().next().value);
|
|
1271
|
+
addRecent(this._recent, id);
|
|
1187
1272
|
const threadId = this.encodeThreadId({ chatId });
|
|
1188
1273
|
if (this._config.markSeen && !raw.fromMe) {
|
|
1189
1274
|
await this.markAsRead(threadId).catch(
|
|
1190
1275
|
(error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
|
|
1191
1276
|
);
|
|
1192
1277
|
}
|
|
1193
|
-
const
|
|
1194
|
-
|
|
1278
|
+
const isMe = raw.fromMe && (this._forwarded(raw) || await this._echo(id));
|
|
1279
|
+
const author = this._author(raw, isMe);
|
|
1280
|
+
if (!author.isMe && (await this._answer(raw, threadId, author) || this._command(raw, threadId, author))) {
|
|
1195
1281
|
await this._remember(raw);
|
|
1196
1282
|
return;
|
|
1197
1283
|
}
|
|
1198
|
-
const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
|
|
1284
|
+
const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw, author) : void 0;
|
|
1199
1285
|
if (!parsed || !await this._claimed(parsed, threadId)) {
|
|
1200
|
-
await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
|
|
1286
|
+
await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw, author)));
|
|
1201
1287
|
}
|
|
1202
1288
|
await this._remember(raw);
|
|
1203
1289
|
}
|
|
@@ -1344,12 +1430,16 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1344
1430
|
_seenKey() {
|
|
1345
1431
|
return `wwebjs:${this.name}:seen`;
|
|
1346
1432
|
}
|
|
1347
|
-
/** Writes run in turn, so an older position never lands after a newer one. */
|
|
1433
|
+
/** Writes run in turn, so an older position never lands after a newer one; one that fails is written again by the watchdog. */
|
|
1348
1434
|
_save() {
|
|
1349
1435
|
const state = this._chat?.getState();
|
|
1350
1436
|
if (!state) return Promise.resolve();
|
|
1351
|
-
this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).
|
|
1352
|
-
(
|
|
1437
|
+
this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).then(
|
|
1438
|
+
() => this._unsaved = false,
|
|
1439
|
+
(error) => {
|
|
1440
|
+
this._unsaved = true;
|
|
1441
|
+
this._logger.warn("Could not record the last message delivered", { error });
|
|
1442
|
+
}
|
|
1353
1443
|
);
|
|
1354
1444
|
return this._saving;
|
|
1355
1445
|
}
|
|
@@ -1365,9 +1455,23 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1365
1455
|
const at = Math.min(raw.timestamp, Math.floor(Date.now() / 1e3) + CLOCK_SKEW_S);
|
|
1366
1456
|
const { ids } = this._seen;
|
|
1367
1457
|
if (at < this._seen.at || at === this._seen.at && ids.includes(id)) return false;
|
|
1368
|
-
this._seen =
|
|
1458
|
+
this._seen = this._position(at, at === this._seen.at ? [...ids, id] : [id]);
|
|
1369
1459
|
return true;
|
|
1370
1460
|
}
|
|
1461
|
+
_position(at, ids) {
|
|
1462
|
+
return { at, ids, own: this._config.receiveOwnMessages || void 0, wid: this.botUserId };
|
|
1463
|
+
}
|
|
1464
|
+
/** One that fails, reading its position or the chats, is owed, and the watchdog runs it again. */
|
|
1465
|
+
_catchUpNext() {
|
|
1466
|
+
this._owed = false;
|
|
1467
|
+
this._catching = this._catching.then(() => this._catchUp()).then(
|
|
1468
|
+
() => this._owed = false,
|
|
1469
|
+
(error) => {
|
|
1470
|
+
this._owed = true;
|
|
1471
|
+
this._logger.warn("Inbound catch-up was not handled", { error });
|
|
1472
|
+
}
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1371
1475
|
/** WhatsApp Web loads what arrived while the session was down without announcing every message. */
|
|
1372
1476
|
async _catchUp() {
|
|
1373
1477
|
const windowMs = this._config.catchUpMs ?? CATCH_UP_MS;
|
|
@@ -1377,7 +1481,7 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1377
1481
|
if (this._seen?.wid && this._seen.wid !== this.botUserId) this._seen = null;
|
|
1378
1482
|
const seen = this._seen;
|
|
1379
1483
|
if (!seen) {
|
|
1380
|
-
this._seen =
|
|
1484
|
+
this._seen = this._position(Math.floor(Date.now() / 1e3), []);
|
|
1381
1485
|
await this._save();
|
|
1382
1486
|
return;
|
|
1383
1487
|
}
|
|
@@ -1398,7 +1502,7 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1398
1502
|
});
|
|
1399
1503
|
const behind = messages.filter(unseen);
|
|
1400
1504
|
truncated ||= behind.length === MAX_CATCH_UP_MESSAGES;
|
|
1401
|
-
missed.push(...behind);
|
|
1505
|
+
missed.push(...behind.filter((message) => seen.own || !message.fromMe));
|
|
1402
1506
|
}
|
|
1403
1507
|
if (truncated) {
|
|
1404
1508
|
this._logger.warn(
|
|
@@ -1419,13 +1523,16 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1419
1523
|
if (delivered.map((message) => this._advance(message)).some(Boolean)) await this._save();
|
|
1420
1524
|
}
|
|
1421
1525
|
}
|
|
1422
|
-
|
|
1526
|
+
/** The account's edit of a message this adapter sent is the adapter's own; any other is the operator's. */
|
|
1527
|
+
async _onEdit(raw, previousBody) {
|
|
1423
1528
|
if (this._isOwn(raw.fromMe)) return;
|
|
1529
|
+
const author = this._author(raw, raw.fromMe && await this._echo(serialize(raw.id)));
|
|
1424
1530
|
this._chat?.processMessageUpdated({
|
|
1425
1531
|
adapter: this,
|
|
1426
|
-
message: () => this._parse(raw),
|
|
1532
|
+
message: () => this._parse(raw, author),
|
|
1427
1533
|
previousMessage: async () => {
|
|
1428
1534
|
const previous = this.parseMessage(raw);
|
|
1535
|
+
previous.author = author;
|
|
1429
1536
|
previous.text = previousBody;
|
|
1430
1537
|
previous.formatted = this._converter.toAst(previousBody);
|
|
1431
1538
|
return previous;
|
|
@@ -1446,17 +1553,20 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1446
1553
|
threadId
|
|
1447
1554
|
});
|
|
1448
1555
|
}
|
|
1449
|
-
|
|
1556
|
+
/** The account's reaction to a message this adapter reacted to is the adapter's own; any other is the operator's. */
|
|
1557
|
+
async _onReaction(reaction) {
|
|
1450
1558
|
if (this._isOwn(reaction.id.fromMe)) return;
|
|
1559
|
+
const messageId = serialize(reaction.msgId);
|
|
1560
|
+
const isMe = reaction.id.fromMe && await this._marked(`reacted:${messageId}`);
|
|
1451
1561
|
this._chat?.processReaction({
|
|
1452
1562
|
adapter: this,
|
|
1453
1563
|
added: reaction.reaction.length > 0,
|
|
1454
1564
|
emoji: defaultEmojiResolver.fromGChat(reaction.reaction),
|
|
1455
|
-
messageId
|
|
1565
|
+
messageId,
|
|
1456
1566
|
raw: reaction,
|
|
1457
1567
|
rawEmoji: reaction.reaction,
|
|
1458
1568
|
threadId: this.encodeThreadId({ chatId: serialize(reaction.id.remote) }),
|
|
1459
|
-
user: participantAuthor(serialize(reaction.senderId),
|
|
1569
|
+
user: participantAuthor(serialize(reaction.senderId), isMe)
|
|
1460
1570
|
});
|
|
1461
1571
|
}
|
|
1462
1572
|
_onAck(raw, ack) {
|
|
@@ -1522,8 +1632,9 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1522
1632
|
}
|
|
1523
1633
|
}
|
|
1524
1634
|
}
|
|
1525
|
-
async _parse(raw) {
|
|
1635
|
+
async _parse(raw, author) {
|
|
1526
1636
|
const parsed = this.parseMessage(raw);
|
|
1637
|
+
parsed.author = author;
|
|
1527
1638
|
const bot = this._botUsers();
|
|
1528
1639
|
const others = [
|
|
1529
1640
|
...new Set((raw.mentionedIds ?? []).map(serialize).filter((id) => !bot.has(toUser(id))))
|
|
@@ -1541,18 +1652,19 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1541
1652
|
if (raw.hasQuotedMsg) {
|
|
1542
1653
|
const quoted = await within(raw.getQuotedMessage());
|
|
1543
1654
|
if (quoted) parsed.replyTo = this.parseMessage(quoted);
|
|
1544
|
-
if (quoted?.fromMe) parsed.isMention = true;
|
|
1655
|
+
if (quoted?.fromMe && !raw.fromMe) parsed.isMention = true;
|
|
1545
1656
|
}
|
|
1546
1657
|
return parsed;
|
|
1547
1658
|
}
|
|
1548
|
-
|
|
1659
|
+
/** The account's own messages come from `botUserId`, whether the adapter sent them or its owner did. */
|
|
1660
|
+
_author(raw, isMe = raw.fromMe) {
|
|
1549
1661
|
const chatId = chatIdOf(raw);
|
|
1550
1662
|
const userId = raw.fromMe ? this.botUserId ?? chatId : isGroupId(chatId) ? raw.author ?? chatId : chatId;
|
|
1551
1663
|
const pushName = raw.rawData?.notifyName;
|
|
1552
1664
|
return {
|
|
1553
1665
|
fullName: pushName ?? "",
|
|
1554
|
-
isBot:
|
|
1555
|
-
isMe
|
|
1666
|
+
isBot: isMe,
|
|
1667
|
+
isMe,
|
|
1556
1668
|
userId,
|
|
1557
1669
|
userName: pushName || toUser(userId)
|
|
1558
1670
|
};
|
|
@@ -1645,6 +1757,8 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1645
1757
|
return;
|
|
1646
1758
|
}
|
|
1647
1759
|
if (this._state !== "connected") return;
|
|
1760
|
+
if (this._owed) this._catchUpNext();
|
|
1761
|
+
if (this._unsaved) void this._save();
|
|
1648
1762
|
const state = await within(this.client.getState());
|
|
1649
1763
|
if (state === "CONNECTED") {
|
|
1650
1764
|
this._strikes = 0;
|
|
@@ -1706,7 +1820,7 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1706
1820
|
});
|
|
1707
1821
|
let first;
|
|
1708
1822
|
for (const [content, sendOptions] of payloads) {
|
|
1709
|
-
const sent = await this.
|
|
1823
|
+
const sent = await this._post(
|
|
1710
1824
|
chatId,
|
|
1711
1825
|
content,
|
|
1712
1826
|
first ? { ...sendOptions, quotedMessageId: void 0 } : sendOptions
|
|
@@ -1719,7 +1833,48 @@ ${questionOf(first, retry, texts)}`);
|
|
|
1719
1833
|
}
|
|
1720
1834
|
async _sendContent(threadId, content, options) {
|
|
1721
1835
|
const { chatId } = this.decodeThreadId(threadId);
|
|
1722
|
-
return this._raw(await this.
|
|
1836
|
+
return this._raw(await this._post(chatId, content, options), threadId);
|
|
1837
|
+
}
|
|
1838
|
+
/** Every send goes through here, under way before it starts, so its echo stays the adapter's own even when it arrives before the id. */
|
|
1839
|
+
async _post(chatId, content, options) {
|
|
1840
|
+
if (!this._config.receiveOwnMessages) return this.client.sendMessage(chatId, content, options);
|
|
1841
|
+
let settle;
|
|
1842
|
+
const sending = new Promise((resolve) => settle = resolve);
|
|
1843
|
+
this._sending.add(sending);
|
|
1844
|
+
try {
|
|
1845
|
+
const sent = await this.client.sendMessage(chatId, content, options);
|
|
1846
|
+
if (sent) await this._mark(`sent:${serialize(sent.id)}`);
|
|
1847
|
+
return sent;
|
|
1848
|
+
} finally {
|
|
1849
|
+
this._sending.delete(sending);
|
|
1850
|
+
settle();
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
/** Kept in state too, for as long as a catch-up reaches back, so an echo replayed after a restart is still its own. */
|
|
1854
|
+
async _mark(key) {
|
|
1855
|
+
if (!this._config.receiveOwnMessages) return;
|
|
1856
|
+
addRecent(this._own, key);
|
|
1857
|
+
await this._chat?.getState().set(this._ownKey(key), true, this._config.catchUpMs || CATCH_UP_MS).catch(
|
|
1858
|
+
(error) => this._logger.warn("Could not record what the adapter did", { error, key })
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
async _marked(key) {
|
|
1862
|
+
return this._own.has(key) || !!await this._chat?.getState().get(this._ownKey(key));
|
|
1863
|
+
}
|
|
1864
|
+
_ownKey(key) {
|
|
1865
|
+
return `wwebjs:${this.name}:${key}`;
|
|
1866
|
+
}
|
|
1867
|
+
/** whatsapp-web.js can emit a send's echo before `sendMessage()` returns its id, so the sends under way settle first. */
|
|
1868
|
+
async _echo(id) {
|
|
1869
|
+
await Promise.allSettled(this._sending);
|
|
1870
|
+
return this._marked(`sent:${id}`);
|
|
1871
|
+
}
|
|
1872
|
+
/** Claimed on arrival, by a forward the adapter made that no echo has claimed yet. */
|
|
1873
|
+
_forwarded(raw) {
|
|
1874
|
+
if (!raw.isForwarded || this._forwards === 0) return false;
|
|
1875
|
+
this._forwards--;
|
|
1876
|
+
void this._mark(`sent:${serialize(raw.id)}`);
|
|
1877
|
+
return true;
|
|
1723
1878
|
}
|
|
1724
1879
|
_raw(sent, threadId) {
|
|
1725
1880
|
if (!sent) {
|
|
@@ -1789,6 +1944,10 @@ function chatIdOf(message) {
|
|
|
1789
1944
|
function locationText({ address, latitude, longitude, name }) {
|
|
1790
1945
|
return [name, address, `https://maps.google.com/?q=${latitude},${longitude}`].filter(Boolean).join("\n");
|
|
1791
1946
|
}
|
|
1947
|
+
function addRecent(ids, id) {
|
|
1948
|
+
ids.add(id);
|
|
1949
|
+
if (ids.size > MAX_RECENT) ids.delete(ids.values().next().value);
|
|
1950
|
+
}
|
|
1792
1951
|
function within(lookup) {
|
|
1793
1952
|
return Promise.race([
|
|
1794
1953
|
lookup.catch(() => null),
|
|
@@ -1868,7 +2027,7 @@ function numberedActions(options = {}) {
|
|
|
1868
2027
|
await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
|
|
1869
2028
|
},
|
|
1870
2029
|
async onMessage(message, context) {
|
|
1871
|
-
if (message.
|
|
2030
|
+
if (message.raw.fromMe || !context.chat) return false;
|
|
1872
2031
|
const state = context.chat.getState();
|
|
1873
2032
|
const offer = await state.get(keyOf(context));
|
|
1874
2033
|
if (!offer || message.replyTo && message.replyTo.id !== offer.messageId) return false;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "chat-adapter-wwebjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "WhatsApp adapter for Chat SDK, backed by whatsapp-web.js",
|
|
5
5
|
"author": "nivandres",
|
|
6
6
|
"license": "MIT",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"oxlint": "^1.61.0",
|
|
61
61
|
"prettier": "^3.8.3",
|
|
62
62
|
"qrcode-terminal": "^0.12.0",
|
|
63
|
-
"tsup": "^
|
|
63
|
+
"tsup": "^9.0.0",
|
|
64
64
|
"typescript": "^5.7.0",
|
|
65
65
|
"vitest": "^5.1.0",
|
|
66
66
|
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#064a3d5"
|