chat-adapter-wwebjs 0.1.2 → 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 +32 -0
- package/README.md +312 -99
- package/dist/index.d.ts +117 -21
- package/dist/index.js +637 -119
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# chat-adapter-wwebjs
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- A `client` you already started is bridged as it is: its session is adopted without a second `initialize()`, which used to open a second browser on the same profile and never become ready. Its lifecycle stays yours — the adapter no longer reconnects or destroys it, nor closes it on a signal, and `disconnect()` only detaches the adapter's listeners. A client never started is the adapter's to run, as before, and `manageClient` forces either way.
|
|
8
|
+
- `streaming` picks how a streamed reply goes out: `"buffer"`, the default, sends it once, whole; `"edit"` edits one message as it grows, at most once a second. The SDK's fallback edited twice a second, which floods a WhatsApp chat.
|
|
9
|
+
- Modals, as conversations with `richContent`: `openModal()` asks each field in turn — text, numbers, dates, numbered selects, and searches through `onOptionsLoad` — and hands the answers to `onModalSubmit`, asking again for any field the handler rejects. `modalTexts` puts its phrases in your users' language, and `triggerIdOf()` opens one for anyone.
|
|
10
|
+
- `slashCommands` turns messages naming the commands you declare into `onSlashCommand` events, with a trigger to open a modal from.
|
|
11
|
+
- `listChats()` lists every chat for an inbox, newest first, and `listThreads()` returns a chat's own thread.
|
|
12
|
+
- `richContent` imitates what WhatsApp lacks, and is off by default: a card's images go out as media with the card as caption, the card in WhatsApp's markup — a bold title, `*Label:* value` fields and monospaced tables — and modals as conversations. Off, a card is plain lines and the adapter has no `openModal`, so the SDK knows a modal cannot open. Numbered answers carry a trigger, so an action can open a modal.
|
|
13
|
+
- `voiceNotes` also takes `"ogg"`, to send only OGG/Opus audio, which every phone plays, as a voice note. All audio still goes as one by default.
|
|
14
|
+
- A `client` from another installed copy of whatsapp-web.js than the adapter's is warned about at once: whatsapp-web.js tells media, locations and polls apart with `instanceof`, so every one it sent would otherwise fail with an opaque error inside the page.
|
|
15
|
+
- A location arrives as the place, its address and a map link. Its body used to be the map thumbnail, base64-encoded.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- A bare `@number` in outgoing text no longer mentions that person, so echoing what someone wrote cannot ping others. `thread.mentionUser(id)` still does.
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- A session whose browser dropped could not be reopened: whatsapp-web.js closes the browser only while it still sees it connected, and hands it over only once its page is set up, so a browser that dropped, or one whose attempt failed or timed out before then, stayed running with the profile locked, and every attempt failed with "The browser is already running" until someone ended it by hand. The adapter now launches each browser with a Puppeteer abort signal and ends the one it started, handed over or not — when reopening, when an attempt fails or times out, and on `disconnect()` — waiting for one handed over to exit before opening the next.
|
|
24
|
+
- Reopening a session could start a storm of reconnects: the adapter read its own closing of the old browser as a crash, and each new attempt tore down the one before. One unresponsive session could start dozens of browsers. The adapter's own closing is no longer a crash, and a superseded attempt leaves the newer one alone.
|
|
25
|
+
- An authentication failure after a start that failed could end the process with an unhandled rejection, and so could a QR or pairing-code handler that threw.
|
|
26
|
+
- Catching up could lose messages: one failing chat or handler stopped it, and live messages moved the position past chats it had not reached. Every chat's missed messages are now gathered and delivered oldest first, each on its own, and the position moves only once the catch-up ends. A truncated catch-up is logged.
|
|
27
|
+
- A message delivered live and caught up again reached addons twice, so a numbered answer could run its action twice.
|
|
28
|
+
- A numbered answer could run its action again when repeated, and answered the latest card even when it quoted another message or came from the bot's own account. The first pick now ends a card's options.
|
|
29
|
+
- A position recorded for one number was reused after pairing another under the same `adapterName`, replaying up to a day of chats. It now belongs to the account that recorded it.
|
|
30
|
+
- An attachment given by `url` was fetched from any address, internal ones included. It is now fetched over HTTPS only, never from a private or internal address, with redirects checked.
|
|
31
|
+
- Inbound media whose real size is over `maxMediaBytes` is refused before it is streamed, whatever size the sender declared.
|
|
32
|
+
- Editing, deleting, reacting to or fetching a message checked only its ID, so a group's message could be touched through another thread. A group's messages must now belong to the thread.
|
|
33
|
+
- A signal now gives sessions 8 seconds to close before it ends the process, inside the grace period Docker and Kubernetes allow.
|
|
34
|
+
|
|
3
35
|
## 0.1.2
|
|
4
36
|
|
|
5
37
|
### Added
|
package/README.md
CHANGED
|
@@ -1,31 +1,38 @@
|
|
|
1
|
+
[](https://chat-sdk.dev/adapters/community/wwebjs)
|
|
2
|
+
|
|
1
3
|
# chat-adapter-wwebjs
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
[
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/chat-adapter-wwebjs)
|
|
8
|
+
[](https://www.npmjs.com/package/chat-adapter-wwebjs)
|
|
9
|
+
[](./LICENSE)
|
|
10
|
+
|
|
11
|
+
WhatsApp adapter for [Chat SDK](https://chat-sdk.dev), backed by [whatsapp-web.js](https://wwebjs.dev). It links to an ordinary WhatsApp account as a device, so it reaches DMs and groups, reads real history, and edits, deletes and reacts like a person would.
|
|
6
12
|
|
|
7
|
-
|
|
13
|
+
Documentation: [chat-sdk.dev/adapters/community/wwebjs](https://chat-sdk.dev/adapters/community/wwebjs)
|
|
8
14
|
|
|
9
15
|
> [!WARNING]
|
|
10
16
|
> whatsapp-web.js drives WhatsApp Web in a real browser. It is not an official
|
|
11
17
|
> WhatsApp or Meta API, it can break when WhatsApp changes its web client, and
|
|
12
18
|
> WhatsApp may ban numbers that automate an ordinary account. Evaluate that
|
|
13
|
-
> before putting it in front of users.
|
|
19
|
+
> before putting it in front of users. For the official API, use
|
|
20
|
+
> [`@chat-adapter/whatsapp`](https://chat-sdk.dev/adapters/official/whatsapp).
|
|
14
21
|
|
|
15
|
-
##
|
|
22
|
+
## Installation
|
|
16
23
|
|
|
17
24
|
```bash
|
|
18
|
-
|
|
25
|
+
pnpm add chat-adapter-wwebjs whatsapp-web.js chat @chat-adapter/shared
|
|
19
26
|
```
|
|
20
27
|
|
|
21
28
|
ESM only, Node >= 20. `chat`, `@chat-adapter/shared` and `whatsapp-web.js` are peers, so you control their versions. whatsapp-web.js downloads a Chromium build through Puppeteer on install.
|
|
22
29
|
|
|
23
|
-
WhatsApp Web renamed the IDs whatsapp-web.js reads, and 1.34.7 cannot send or find chats since. Until a release carries the fix, install the commit this adapter is tested against: `
|
|
30
|
+
WhatsApp Web renamed the IDs whatsapp-web.js reads, and 1.34.7 cannot send or find chats since. Until a release carries the fix, install the commit this adapter is tested against: `pnpm add github:pedroslopez/whatsapp-web.js#064a3d5`.
|
|
24
31
|
|
|
25
|
-
##
|
|
32
|
+
## Usage
|
|
26
33
|
|
|
27
|
-
```
|
|
28
|
-
import {
|
|
34
|
+
```typescript
|
|
35
|
+
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
29
36
|
import { Chat } from "chat";
|
|
30
37
|
import { createWWebJSAdapter } from "chat-adapter-wwebjs";
|
|
31
38
|
import qrcode from "qrcode-terminal";
|
|
@@ -35,95 +42,165 @@ const whatsapp = createWWebJSAdapter({
|
|
|
35
42
|
adapterName: "whatsapp",
|
|
36
43
|
clientOptions: { authStrategy: new LocalAuth({ dataPath: "./.wwebjs-auth" }) },
|
|
37
44
|
onQR: (qr) => qrcode.generate(qr, { small: true }),
|
|
38
|
-
userName: "my-bot",
|
|
39
45
|
});
|
|
40
46
|
|
|
41
47
|
const bot = new Chat({
|
|
48
|
+
userName: "mybot",
|
|
42
49
|
adapters: { whatsapp },
|
|
43
|
-
state:
|
|
44
|
-
userName: "my-bot",
|
|
50
|
+
state: createMemoryState(),
|
|
45
51
|
});
|
|
46
52
|
|
|
47
|
-
bot.
|
|
48
|
-
await thread.subscribe();
|
|
53
|
+
bot.onDirectMessage(async (thread, message) => {
|
|
49
54
|
await thread.post(`Hello ${message.author.userName}!`);
|
|
50
55
|
});
|
|
51
56
|
|
|
52
|
-
bot.
|
|
53
|
-
await thread.
|
|
54
|
-
await thread.post(
|
|
57
|
+
bot.onNewMention(async (thread) => {
|
|
58
|
+
await thread.subscribe();
|
|
59
|
+
await thread.post("Hello from WhatsApp!");
|
|
55
60
|
});
|
|
56
61
|
|
|
57
62
|
await bot.initialize();
|
|
58
63
|
await whatsapp.connect();
|
|
59
64
|
```
|
|
60
65
|
|
|
61
|
-
Register the adapter under the same key as its `adapterName
|
|
66
|
+
Register the adapter under the same key as its `adapterName`: that key is the thread ID prefix the SDK resolves threads by, so `adapters: { whatsapp }` needs `adapterName: "whatsapp"`.
|
|
62
67
|
|
|
63
68
|
Register your handlers and call `bot.initialize()` **before** `whatsapp.connect()`. Messages that arrive before the SDK is initialized are dropped, and the adapter logs a warning if you connect too early.
|
|
64
69
|
|
|
65
|
-
|
|
70
|
+
## WhatsApp setup
|
|
66
71
|
|
|
67
|
-
|
|
72
|
+
### 1. Run a browser
|
|
73
|
+
|
|
74
|
+
Puppeteer's bundled Chromium covers most machines. On slim Linux images install the usual shared libraries, or point `clientOptions.puppeteer.executablePath` at your own browser. Chromium starts with `RECOMMENDED_CHROMIUM_ARGS`, which keep a single WhatsApp tab lean in a container; flags in `clientOptions.puppeteer.args` come after them, so yours win.
|
|
75
|
+
|
|
76
|
+
### 2. Keep the session
|
|
77
|
+
|
|
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.
|
|
68
79
|
|
|
69
|
-
|
|
80
|
+
### 3. Link the device
|
|
81
|
+
|
|
82
|
+
Start the process, then on the phone open WhatsApp → **Linked devices** → **Link a device** and scan the QR handed to `onQR`. To link without a camera, set `phoneNumber` and enter the code handed to `onPairingCode` under **Link with phone number**. Once a QR or code is shown, the adapter waits for it however long it takes.
|
|
83
|
+
|
|
84
|
+
### 4. Keep the process alive
|
|
85
|
+
|
|
86
|
+
This is a live browser session, not a webhook: `handleWebhook` answers `501`. A SIGTERM closes the browser and ends the process, so `docker stop` is clean. With a signal handler of your own, call `bot.shutdown()` or the adapter's `disconnect()` and exit when you are done.
|
|
70
87
|
|
|
71
88
|
## Configuration
|
|
72
89
|
|
|
73
|
-
|
|
|
74
|
-
| -------------------- |
|
|
75
|
-
| `adapterName` | `
|
|
76
|
-
| `addons` | `
|
|
77
|
-
| `catchUpMs` |
|
|
78
|
-
| `client` |
|
|
79
|
-
| `clientOptions` | `
|
|
80
|
-
| `connectTimeoutMs` |
|
|
81
|
-
| `handleSignals` | `
|
|
82
|
-
| `logger` | `
|
|
83
|
-
| `
|
|
84
|
-
| `
|
|
85
|
-
| `
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
88
|
-
| `
|
|
89
|
-
| `
|
|
90
|
-
| `
|
|
91
|
-
| `
|
|
92
|
-
| `
|
|
93
|
-
| `
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
90
|
+
| Option | Default | Description |
|
|
91
|
+
| -------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
92
|
+
| `adapterName` | `"wwebjs"` | Adapter identity, thread ID prefix and state key prefix. Must match the key it is registered under in `Chat`, must not contain `:`, and must be unique per account when several share a `Chat` or a state store. |
|
|
93
|
+
| `addons` | `[]` | Layers over how cards are sent and messages received, such as `numberedActions()`. |
|
|
94
|
+
| `catchUpMs` | 1 day | Messages that arrived while the session was down are delivered once it is back, up to this old, oldest first. `false` turns it off. |
|
|
95
|
+
| `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
|
+
| `clientOptions` | `{}` | Options for the client the adapter builds: `authStrategy`, `puppeteer`, `webVersionCache`, and so on. Ignored when `client` is set. |
|
|
97
|
+
| `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. |
|
|
99
|
+
| `logger` | `ConsoleLogger` | Logger used until `Chat` hands over its own. |
|
|
100
|
+
| `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, even if you started it; `false` only bridges it, even if you didn't. |
|
|
102
|
+
| `markSeen` | `false` | Send a read receipt for every inbound message as it arrives. |
|
|
103
|
+
| `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
|
+
| `onPairingCode` | — | Receives the 8-character pairing code when `phoneNumber` is set. |
|
|
105
|
+
| `onQR` | — | Receives the QR string during login. Render it with `qrcode-terminal` or similar. |
|
|
106
|
+
| `phoneNumber` | — | Log in with a pairing code instead of a QR. E.164 without the leading `+`. |
|
|
107
|
+
| `receiveOwnMessages` | `false` | Pass what the paired account did — its messages, edits, deletes and reactions — to the Chat SDK, which still skips most of its own. |
|
|
108
|
+
| `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
|
+
| `recommendedArgs` | `true` | Start Chromium with `RECOMMENDED_CHROMIUM_ARGS`: one renderer process, no GPU, no component updates. |
|
|
110
|
+
| `reconnect` | `true` | Open the session again when WhatsApp drops it, backing off from 5 seconds to 5 minutes. A logout is never retried. |
|
|
111
|
+
| `slashCommands` | — | Commands, such as `"/help"`, whose messages reach `onSlashCommand`. See [Slash commands](#slash-commands). |
|
|
112
|
+
| `streaming` | `"buffer"` | How a streamed reply goes out: `"buffer"` sends it once, whole; `"edit"` sends the first words and edits the message as the rest arrives, at most once a second. |
|
|
113
|
+
| `userName` | `"wwebjs-bot"` | Bot display name. When unset, the account's WhatsApp push name is adopted once the session is ready. |
|
|
114
|
+
| `voiceNotes` | `true` | Send audio as a voice note, played inline with a waveform: `true` for all audio, `"ogg"` for OGG/Opus only, which every phone plays as one, `false` for none. |
|
|
115
|
+
| `watchdogIntervalMs` | 1 minute | How often a connected session is asked whether WhatsApp still answers; two failed checks count as a disconnect. `false` turns it off. |
|
|
116
|
+
|
|
117
|
+
## Environment variables
|
|
118
|
+
|
|
119
|
+
None. A WhatsApp Web session is a browser profile, not an API token, so there is nothing to put in the environment. Persist it with `LocalAuth` or `RemoteAuth` instead.
|
|
101
120
|
|
|
102
121
|
## Features
|
|
103
122
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
|
107
|
-
|
|
|
108
|
-
| Post
|
|
109
|
-
|
|
|
110
|
-
|
|
|
111
|
-
|
|
|
112
|
-
|
|
|
113
|
-
|
|
|
114
|
-
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
|
119
|
-
|
|
|
120
|
-
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
+
### Messaging
|
|
124
|
+
|
|
125
|
+
| Feature | Supported |
|
|
126
|
+
| ------------------ | ---------------------------------------------------------------------------------------- |
|
|
127
|
+
| Post message | Yes |
|
|
128
|
+
| Message replies | Yes (native quoted bubble) |
|
|
129
|
+
| Edit message | Yes (your own messages, within WhatsApp's 15-minute window) |
|
|
130
|
+
| Delete message | Yes (for everyone) |
|
|
131
|
+
| File uploads | Yes (images, video, audio, voice notes, documents, stickers) |
|
|
132
|
+
| Streaming | Yes (`streaming: "buffer"` sends it once, whole; `"edit"` edits one message as it grows) |
|
|
133
|
+
| Scheduled messages | No |
|
|
134
|
+
|
|
135
|
+
### Rich content
|
|
136
|
+
|
|
137
|
+
| Feature | Supported |
|
|
138
|
+
| --------------- | ---------------------------------------------------------------------- |
|
|
139
|
+
| Card format | Partial (plain text; WhatsApp markup with `richContent`) |
|
|
140
|
+
| Buttons | Partial (answered by number with [`numberedActions()`](#card-actions)) |
|
|
141
|
+
| Link buttons | Partial (`Label: url` lines) |
|
|
142
|
+
| Select menus | Partial (answered by number with `numberedActions()`) |
|
|
143
|
+
| Tables | Partial (ASCII in a code block) |
|
|
144
|
+
| Charts | Partial (text) |
|
|
145
|
+
| Fields | Partial (`Label: value` lines) |
|
|
146
|
+
| Images in cards | Partial (as media, with `richContent`) |
|
|
147
|
+
| Modals | Partial (conversational, with `richContent`; see [Modals](#modals)) |
|
|
148
|
+
|
|
149
|
+
### Conversations
|
|
150
|
+
|
|
151
|
+
| Feature | Supported |
|
|
152
|
+
| --------------------- | ------------------------------------------------------------------------- |
|
|
153
|
+
| Slash commands | Partial (the commands you declare, see [Slash commands](#slash-commands)) |
|
|
154
|
+
| Mentions | Yes (by number or LID in, `thread.mentionUser()` out) |
|
|
155
|
+
| Add reactions | Yes |
|
|
156
|
+
| Remove reactions | Yes |
|
|
157
|
+
| Typing indicator | Yes (`startTyping()` composes, `startTyping("recording")` records) |
|
|
158
|
+
| Mark as read | Yes (the whole chat), or `markSeen` for every inbound message |
|
|
159
|
+
| Message edit events | Yes (with the body it replaced) |
|
|
160
|
+
| Message delete events | Yes (with the original message) |
|
|
161
|
+
| DMs | Yes (a phone number resolves to the chat WhatsApp uses for it) |
|
|
162
|
+
| Ephemeral messages | No (the SDK falls back to a DM) |
|
|
163
|
+
| User lookup | Yes (name, push name, number, profile picture) |
|
|
164
|
+
| Native client | Yes (`adapter.client` is the whatsapp-web.js `Client`) |
|
|
165
|
+
| Group joins | Yes (`onMemberJoinedChannel`) |
|
|
166
|
+
|
|
167
|
+
### Message history
|
|
168
|
+
|
|
169
|
+
| Feature | Supported |
|
|
170
|
+
| ---------------------- | -------------------------------------------------------------------------- |
|
|
171
|
+
| Fetch messages | Yes (synced history, forward and backward pagination) |
|
|
172
|
+
| Fetch single message | Yes |
|
|
173
|
+
| Fetch thread info | Yes |
|
|
174
|
+
| Fetch channel messages | Yes |
|
|
175
|
+
| List threads | Partial (a chat lists itself; `listChats()` lists every chat for an inbox) |
|
|
176
|
+
| Fetch channel info | Yes (group name and member count) |
|
|
177
|
+
| Post channel message | Yes |
|
|
178
|
+
|
|
179
|
+
### Incoming message types
|
|
180
|
+
|
|
181
|
+
| Type | Supported |
|
|
182
|
+
| ------------------- | ------------------------------------------ |
|
|
183
|
+
| Text | Yes |
|
|
184
|
+
| Images | Yes (with captions) |
|
|
185
|
+
| Video | Yes (with captions) |
|
|
186
|
+
| Audio / Voice notes | Yes |
|
|
187
|
+
| Documents | Yes (with captions) |
|
|
188
|
+
| Stickers | Yes (as images) |
|
|
189
|
+
| Locations | Yes (place, address and a map link) |
|
|
190
|
+
| Contacts | Partial (a single contact's vCard as text) |
|
|
191
|
+
| Poll votes | Yes (`onPollVote`) |
|
|
192
|
+
| Reactions | Yes |
|
|
193
|
+
| Edits and deletes | Yes |
|
|
194
|
+
|
|
195
|
+
Statuses, broadcast lists and WhatsApp's own notifications never reach your handlers.
|
|
196
|
+
|
|
197
|
+
### WhatsApp extensions
|
|
198
|
+
|
|
199
|
+
Past the shared interface, the adapter carries what WhatsApp adds:
|
|
123
200
|
|
|
124
201
|
`sendPoll` · `onPollVote` · `sendLocation` · `sendEvent` · `sendSticker` · `forwardMessage` · `pinMessage` · `starMessage` · `fetchPinnedMessages` · `searchMessages` · `fetchGroupParticipants` · `getProfilePicUrl` · `setPresence` · `markAsUnread` · `muteThread` · `archiveThread` · `pinThread` · `onCall` · `onAck` · `onGroupEvent`
|
|
125
202
|
|
|
126
|
-
```
|
|
203
|
+
```typescript
|
|
127
204
|
import { requireWWebJSAdapter } from "chat-adapter-wwebjs";
|
|
128
205
|
|
|
129
206
|
bot.onSubscribedMessage(async (thread) => {
|
|
@@ -139,39 +216,140 @@ bot.onSubscribedMessage(async (thread) => {
|
|
|
139
216
|
});
|
|
140
217
|
```
|
|
141
218
|
|
|
142
|
-
Anything not wrapped
|
|
219
|
+
Anything not wrapped is still reachable through `adapter.client`.
|
|
220
|
+
|
|
221
|
+
## Card actions
|
|
222
|
+
|
|
223
|
+
WhatsApp Web cannot send buttons, so a card's buttons would be dropped from its text. Add `numberedActions()` and they are listed by number instead, select options included, and a reply with a number — or a label — reaches `onAction` as a click would. Link buttons keep their URL; a button that opens a modal is left out, since WhatsApp has none.
|
|
143
224
|
|
|
144
|
-
|
|
225
|
+
```typescript
|
|
226
|
+
import { createWWebJSAdapter, numberedActions } from "chat-adapter-wwebjs";
|
|
145
227
|
|
|
146
|
-
|
|
228
|
+
const whatsapp = createWWebJSAdapter({ addons: [numberedActions()] });
|
|
147
229
|
|
|
148
|
-
|
|
230
|
+
bot.onAction("approve", async (event) => {
|
|
231
|
+
await event.thread?.post(`Approved by ${event.user.userName}`);
|
|
232
|
+
});
|
|
233
|
+
```
|
|
149
234
|
|
|
150
|
-
|
|
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 bot's own account sends. 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.
|
|
151
236
|
|
|
152
|
-
|
|
237
|
+
An addon is a plain object with optional `renderCard`, `cardSent` and `onMessage` hooks, so other layers fit the same way.
|
|
153
238
|
|
|
154
|
-
|
|
239
|
+
## Rich content
|
|
155
240
|
|
|
156
|
-
WhatsApp Web
|
|
241
|
+
WhatsApp Web has no cards, buttons or modals, so the adapter can only imitate them, and by default it doesn't: a card goes out as plain lines, and the adapter has no `openModal`, so `event.openModal()` resolves to `undefined` and your bot can tell. Set `richContent: true` to imitate them: cards in WhatsApp's markup, a bold title, `*Label:* value` fields and monospaced tables, with their images sent as media and the card as caption, and [modals](#modals) as conversations. Buttons answered by number are a separate opt-in, [`numberedActions()`](#card-actions).
|
|
157
242
|
|
|
158
|
-
|
|
159
|
-
import { createWWebJSAdapter, numberedActions } from "chat-adapter-wwebjs";
|
|
243
|
+
## Streaming
|
|
160
244
|
|
|
161
|
-
|
|
245
|
+
WhatsApp cannot stream, so `streaming` picks how a streamed reply — `thread.post(textStream)` — reaches it. `"buffer"`, the default, sends the reply once it is complete, as WhatsApp's own Cloud API adapter does. `"edit"` sends the first words, then edits that one message as the rest arrives, at most once a second, so the person watches it being written; an edit WhatsApp refuses part-way only delays the words, and the last one always lands. WhatsApp allows edits for 15 minutes, which a reply never outlasts.
|
|
162
246
|
|
|
163
|
-
|
|
164
|
-
|
|
247
|
+
## Slash commands
|
|
248
|
+
|
|
249
|
+
WhatsApp has no slash commands, so declare the ones you handle and their messages become commands:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
const whatsapp = createWWebJSAdapter({ slashCommands: ["/help", "/agent"] });
|
|
253
|
+
|
|
254
|
+
bot.onSlashCommand("/help", async (event) => {
|
|
255
|
+
await event.channel.post(`Help with ${event.text || "anything"}`);
|
|
165
256
|
});
|
|
166
257
|
```
|
|
167
258
|
|
|
168
|
-
|
|
259
|
+
`/help billing` arrives as command `/help` with text `"billing"`, matched without regard to case. Any other text starting with `/`, such as a path or `/shrug`, stays an ordinary message. A command can open a modal with `event.openModal()`.
|
|
260
|
+
|
|
261
|
+
## Modals
|
|
262
|
+
|
|
263
|
+
With `richContent`, WhatsApp having no modals, `openModal()` turns one into a conversation with the person who triggered it: the title and any text it shows, then each field in turn.
|
|
264
|
+
|
|
265
|
+
```typescript
|
|
266
|
+
bot.onAction("book", (event) =>
|
|
267
|
+
event.openModal(
|
|
268
|
+
Modal({
|
|
269
|
+
callbackId: "booking",
|
|
270
|
+
title: "Booking",
|
|
271
|
+
children: [
|
|
272
|
+
TextInput({ id: "name", label: "Name" }),
|
|
273
|
+
Select({
|
|
274
|
+
id: "day",
|
|
275
|
+
label: "Day",
|
|
276
|
+
options: [
|
|
277
|
+
SelectOption({ label: "Mon", value: "mon" }),
|
|
278
|
+
SelectOption({ label: "Tue", value: "tue" }),
|
|
279
|
+
],
|
|
280
|
+
}),
|
|
281
|
+
],
|
|
282
|
+
}),
|
|
283
|
+
),
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
bot.onModalSubmit("booking", (event) =>
|
|
287
|
+
event.relatedThread?.post(`Booked for ${event.values.day}`),
|
|
288
|
+
);
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
| Input | Answered with |
|
|
292
|
+
| ----------------------- | ------------------------------------------------------------------------------ |
|
|
293
|
+
| `TextInput` | Any text, within `maxLength` |
|
|
294
|
+
| `NumberInput` | A number, within `min` and `max`, whole unless `decimal` |
|
|
295
|
+
| `DateInput` | A date as `YYYY-MM-DD` |
|
|
296
|
+
| `Select`, `RadioSelect` | An option's number or label |
|
|
297
|
+
| `ExternalSelect` | Words to search, which reach `onOptionsLoad`, then a number from what it found |
|
|
298
|
+
|
|
299
|
+
An optional field, or one with an initial value, can be answered _skip_. _cancel_, or the modal's `closeLabel`, stops it, and reaches `onModalClose` when the modal sets `notifyOnClose`. An answer that doesn't fit is asked again with the reason. When every field is answered, `onModalSubmit` receives the values: return `{ action: "errors", errors }` and only those fields are asked again, with your messages; return `{ action: "update", modal }` or `{ action: "push", modal }` and the new modal starts. A modal left unanswered stops waiting after a day.
|
|
300
|
+
|
|
301
|
+
Modals open from actions — `numberedActions()` answers carry a trigger — and from slash commands. To open one for someone without either, pass `triggerIdOf(threadId, userId)` to `adapter.openModal()`. Put the phrases a modal sends in your users' language with `modalTexts`:
|
|
302
|
+
|
|
303
|
+
```typescript
|
|
304
|
+
createWWebJSAdapter({
|
|
305
|
+
modalTexts: {
|
|
306
|
+
cancel: "cancelar",
|
|
307
|
+
cancelHint: "Envía *cancelar* para parar.",
|
|
308
|
+
cancelled: "Cancelado.",
|
|
309
|
+
invalid: "Eso no encaja. Intenta de nuevo:",
|
|
310
|
+
noResults: "No encontré nada. Prueba otras palabras:",
|
|
311
|
+
search: "Envía unas palabras para buscar.",
|
|
312
|
+
skip: "omitir",
|
|
313
|
+
skipHint: "Envía *omitir* para dejarlo como está.",
|
|
314
|
+
},
|
|
315
|
+
});
|
|
316
|
+
```
|
|
169
317
|
|
|
170
|
-
|
|
318
|
+
## Bridging your own client
|
|
171
319
|
|
|
172
|
-
|
|
320
|
+
Pass a whatsapp-web.js `Client` you already run and the adapter bridges it as it is:
|
|
173
321
|
|
|
174
|
-
```
|
|
322
|
+
```typescript
|
|
323
|
+
const client = new Client({ authStrategy: new LocalAuth() });
|
|
324
|
+
client.on("message", handleItYourself);
|
|
325
|
+
await client.initialize();
|
|
326
|
+
|
|
327
|
+
const whatsapp = createWWebJSAdapter({ client });
|
|
328
|
+
await whatsapp.connect(); // already running: adopted, without starting it again
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
What the adapter does with it depends on whether it was started when you passed it:
|
|
332
|
+
|
|
333
|
+
- **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
|
+
- **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
|
+
|
|
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.
|
|
337
|
+
|
|
338
|
+
## Message history
|
|
339
|
+
|
|
340
|
+
`listChats()` lists every chat the account has, newest first, each with its latest message, paged with `limit` and `cursor`: the list an inbox shows. `listThreads(channelId)` returns the chat's own thread, since a WhatsApp chat is one conversation.
|
|
341
|
+
|
|
342
|
+
`fetchMessages` reads real WhatsApp history, so `thread.messages` and the SDK's history API work. Backward cursors (the default) carry the oldest message they returned, so a message arriving between pages shifts nothing. Forward reads load the whole conversation and slice it, since WhatsApp offers no oldest-first cursor; use them for one-off backfills. Both see what the web client has synced, and one read reaches back at most 1,000 messages.
|
|
343
|
+
|
|
344
|
+
## Catching up after downtime
|
|
345
|
+
|
|
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.
|
|
347
|
+
|
|
348
|
+
## Multiple accounts
|
|
349
|
+
|
|
350
|
+
Give each adapter its own `adapterName`, matching the key it is registered under. It prefixes thread IDs and state keys, so `sales:…` and `support:…` never collide, on one `Chat` or in one shared store.
|
|
351
|
+
|
|
352
|
+
```typescript
|
|
175
353
|
const sales = createWWebJSAdapter({
|
|
176
354
|
adapterName: "sales",
|
|
177
355
|
clientOptions: { authStrategy: new LocalAuth({ clientId: "sales" }) },
|
|
@@ -181,23 +359,58 @@ const support = createWWebJSAdapter({
|
|
|
181
359
|
clientOptions: { authStrategy: new LocalAuth({ clientId: "support" }) },
|
|
182
360
|
});
|
|
183
361
|
|
|
184
|
-
const bot = new Chat({ adapters: { sales, support }, state
|
|
362
|
+
const bot = new Chat({ userName: "mybot", adapters: { sales, support }, state });
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
## Running the session apart from your bot
|
|
366
|
+
|
|
367
|
+
The session needs a long-lived process with a browser, which serverless bots cannot hold. [`chat-adapter-remote`](https://github.com/nivandres/chat-adapter-remote) runs this adapter in its own process and bridges it to your bot over signed HTTP. `adapter.connection` reports where the session stands — `connected`, `reconnecting`, `logged_out` and so on — for its health check:
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
serveAdapter(whatsapp, { healthy: () => whatsapp.connection === "connected" });
|
|
185
371
|
```
|
|
186
372
|
|
|
187
|
-
##
|
|
373
|
+
## Formatting
|
|
374
|
+
|
|
375
|
+
Markdown is converted to WhatsApp's markup: `*bold*`, `_italic_`, `~strikethrough~`, `` `code` ``, fenced blocks, `>` quotes and lists. WhatsApp has no link syntax, so links render as `text (url)`, and no tables, so tables render as ASCII inside a code block.
|
|
376
|
+
|
|
377
|
+
## Thread ID format
|
|
378
|
+
|
|
379
|
+
```
|
|
380
|
+
{adapterName}:{chatId}
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
Examples: `wwebjs:15551234567@c.us` (DM by phone), `wwebjs:99990000111122@lid` (DM by LID), `wwebjs:1234567890-1234567890@g.us` (group). A channel is its own thread.
|
|
384
|
+
|
|
385
|
+
## Troubleshooting
|
|
386
|
+
|
|
387
|
+
### The QR never appears
|
|
388
|
+
|
|
389
|
+
- Check that Chromium can start: run locally with `clientOptions.puppeteer.headless: false`, or look for missing shared libraries on Linux.
|
|
390
|
+
- WhatsApp replaces the QR every 20 seconds or so; render each one `onQR` receives.
|
|
391
|
+
|
|
392
|
+
### Sends fail or chats are not found
|
|
393
|
+
|
|
394
|
+
- whatsapp-web.js 1.34.7 cannot read current WhatsApp Web. Install `github:pedroslopez/whatsapp-web.js#064a3d5`.
|
|
395
|
+
|
|
396
|
+
### "The browser is already running"
|
|
397
|
+
|
|
398
|
+
- 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` or the OOM killer, leaves its browser running. End it before starting again: on Linux and macOS the profile's `SingletonLock` points at `<host>-<pid>`.
|
|
400
|
+
|
|
401
|
+
### The session drops
|
|
402
|
+
|
|
403
|
+
- `adapter.connection` turns `reconnecting` and the adapter reopens it with backoff. `logged_out` means the device was unlinked on the phone and needs a new scan.
|
|
404
|
+
|
|
405
|
+
## Limitations
|
|
188
406
|
|
|
189
|
-
- **
|
|
407
|
+
- **Unofficial.** It automates WhatsApp Web, which WhatsApp may block or change at any time.
|
|
190
408
|
- **One session per number**, as WhatsApp Web itself allows.
|
|
191
|
-
- **No
|
|
192
|
-
- **No ephemeral messages, scheduling, or modals.** `postEphemeral` falls back to a DM; `thread.schedule()` throws.
|
|
193
|
-
- **No sub-threads.** A WhatsApp conversation is one flat stream, so `listThreads` is always empty and a channel is its own thread.
|
|
409
|
+
- **No scheduling or ephemeral messages.** `postEphemeral` falls back to a DM; `thread.schedule()` throws.
|
|
194
410
|
- **`receiveOwnMessages` includes the adapter's own sends.** Turn it on only if your handlers can tell them apart.
|
|
195
|
-
- **
|
|
196
|
-
- **
|
|
197
|
-
- **`adapter.connection` tells where the session stands** — `connected`, `reconnecting`, `logged_out` and so on — for a health check, such as `chat-adapter-remote`'s `healthy: () => adapter.connection === "connected"`.
|
|
198
|
-
- **Statuses, broadcast lists and WhatsApp's own notifications never reach your handlers.**
|
|
411
|
+
- **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
|
+
- **A bare `@number` in outgoing text stays text.** Mention someone with `thread.mentionUser(id)`.
|
|
199
413
|
- **`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.
|
|
200
|
-
- **Messages received while the session was down are caught up from history** once it is back, since WhatsApp Web fires no event for them. The position is kept in the Chat SDK state, so a restart starts where the last process stopped; 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.
|
|
201
414
|
|
|
202
415
|
## License
|
|
203
416
|
|