chat-adapter-wwebjs 0.0.0-stage → 0.1.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 +22 -0
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/dist/index.d.ts +418 -0
- package/dist/index.js +1184 -0
- package/package.json +76 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# chat-adapter-wwebjs
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
Initial release, tested against live WhatsApp in DMs and groups through `chat-adapter-remote`.
|
|
6
|
+
|
|
7
|
+
- Full Chat SDK `Adapter` surface over whatsapp-web.js: posting, editing, deleting, quoted replies, reactions, typing and recording indicators, read receipts, attachments, thread and channel metadata, contact lookup and DM opening.
|
|
8
|
+
- Real message history with forward and backward pagination over `chat.fetchMessages`.
|
|
9
|
+
- Inbound bridging for messages, edits, deletes, reactions and group joins. The bot's own edits, deletes and reactions stay out unless `receiveOwnMessages` is on, and so do contacts' statuses, broadcast lists and WhatsApp's own notifications.
|
|
10
|
+
- Mentions by number or LID reach `onNewMention`, the bot's LID learned once the session is ready, and a reply to one of the bot's messages counts as one. A mention reads as `@` and the name in `message.text`.
|
|
11
|
+
- A dropped session is opened again with backoff, including one whose browser crashed, which WhatsApp never reports; see `reconnect`. A logout is never retried. A connection that never becomes ready is abandoned after `connectTimeoutMs`, and a watchdog reopens a session WhatsApp stopped answering without any event.
|
|
12
|
+
- `adapter.connection` reports where the session stands, for health checks.
|
|
13
|
+
- `maxMediaBytes` bounds the media read into memory at 64 MB, counting the bytes as they stream rather than trusting the size the sender declared. Attachments given by `url` are fetched with a timeout, refused on an error status, and held to the same limit.
|
|
14
|
+
- Inbound text from anyone is safe to handle: a failing handler is logged rather than ending the process, mention names stay literal, contact lookups per message are capped, and markdown too long or too deep for the parser stays plain.
|
|
15
|
+
- WhatsApp extras: polls with decrypted votes, locations, scheduled events, stickers, forwarding, pinning, starring, message search, group participants, presence, and chat state.
|
|
16
|
+
- `sendEvent` attaches no call link unless `callType` asks for one.
|
|
17
|
+
- One DM thread per person: `openDM` resolves a number and its `@c.us` id alike, to the chat WhatsApp uses — often a LID.
|
|
18
|
+
- Deleted messages keep their own id, and history cursors stay put when messages arrive between pages.
|
|
19
|
+
- A bare URL or address is printed once, not followed by itself in parentheses.
|
|
20
|
+
- A message can be edited right after it is sent: WhatsApp refuses for a few hundred milliseconds, so a fresh message of the bot's own is retried briefly.
|
|
21
|
+
- A contact or quoted message WhatsApp never returns holds a message back at most 5 seconds.
|
|
22
|
+
- `adapter.client` exposes the underlying whatsapp-web.js client.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nivandres
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,182 @@
|
|
|
1
|
-
#
|
|
1
|
+
# chat-adapter-wwebjs
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/chat-adapter-wwebjs)
|
|
4
|
+
[](https://www.npmjs.com/package/chat-adapter-wwebjs)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
7
|
+
WhatsApp adapter for the [Chat SDK](https://chat-sdk.dev), backed by [whatsapp-web.js](https://wwebjs.dev).
|
|
8
|
+
|
|
9
|
+
> [!WARNING]
|
|
10
|
+
> whatsapp-web.js drives WhatsApp Web in a real browser. It is not an official
|
|
11
|
+
> WhatsApp or Meta API, it can break when WhatsApp changes its web client, and
|
|
12
|
+
> WhatsApp may ban numbers that automate an ordinary account. Evaluate that
|
|
13
|
+
> before putting it in front of users.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm i chat-adapter-wwebjs whatsapp-web.js chat @chat-adapter/shared
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
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
|
+
|
|
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: `npm i github:pedroslopez/whatsapp-web.js#064a3d5`.
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { MemoryStateAdapter } from "@chat-adapter/state-memory";
|
|
29
|
+
import { Chat } from "chat";
|
|
30
|
+
import { createWWebJSAdapter } from "chat-adapter-wwebjs";
|
|
31
|
+
import qrcode from "qrcode-terminal";
|
|
32
|
+
import { LocalAuth } from "whatsapp-web.js";
|
|
33
|
+
|
|
34
|
+
const whatsapp = createWWebJSAdapter({
|
|
35
|
+
adapterName: "whatsapp",
|
|
36
|
+
clientOptions: { authStrategy: new LocalAuth({ dataPath: "./.wwebjs-auth" }) },
|
|
37
|
+
onQR: (qr) => qrcode.generate(qr, { small: true }),
|
|
38
|
+
userName: "my-bot",
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const bot = new Chat({
|
|
42
|
+
adapters: { whatsapp },
|
|
43
|
+
state: new MemoryStateAdapter(),
|
|
44
|
+
userName: "my-bot",
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
bot.onNewMention(async (thread, message) => {
|
|
48
|
+
await thread.subscribe();
|
|
49
|
+
await thread.post(`Hello ${message.author.userName}!`);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
bot.onSubscribedMessage(async (thread, message) => {
|
|
53
|
+
await thread.startTyping();
|
|
54
|
+
await thread.post(`You said: ${message.text}`);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
await bot.initialize();
|
|
58
|
+
await whatsapp.connect();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
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
|
+
|
|
63
|
+
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
|
+
|
|
65
|
+
Scan the QR with WhatsApp → **Linked devices** → **Link a device**. `LocalAuth` keeps the session on disk, so later starts skip the scan.
|
|
66
|
+
|
|
67
|
+
## Environment variables
|
|
68
|
+
|
|
69
|
+
None. This adapter takes no credentials from the environment — a WhatsApp Web session is a browser profile, not an API token. Persist it with `LocalAuth` (a directory) or `RemoteAuth` (your own store), both from `whatsapp-web.js`.
|
|
70
|
+
|
|
71
|
+
## Configuration
|
|
72
|
+
|
|
73
|
+
| Field | Type | Default | Description |
|
|
74
|
+
| -------------------- | --------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
|
75
|
+
| `adapterName` | `string` | `"wwebjs"` | Adapter identity and thread-ID prefix. Must match the key it is registered under in `Chat`, and must not contain `:`. |
|
|
76
|
+
| `client` | `Client` | — | An existing whatsapp-web.js client to drive. When omitted, one is built from `clientOptions`. |
|
|
77
|
+
| `clientOptions` | `ClientOptions` | `{}` | Options for the client the adapter builds — `authStrategy`, `puppeteer`, `webVersionCache`, and so on. Ignored when `client` is set. |
|
|
78
|
+
| `connectTimeoutMs` | `number` | 2 minutes | How long opening the session may take before it is abandoned and, with `reconnect`, tried again. |
|
|
79
|
+
| `logger` | `Logger` | `ConsoleLogger` | Logger used until `Chat` hands over its own. |
|
|
80
|
+
| `markSeen` | `boolean` | `false` | Send a read receipt for every inbound message as it arrives. |
|
|
81
|
+
| `maxMediaBytes` | `number` | 64 MB | Largest media read into memory, inbound or fetched from a `url`. Bytes are counted as they arrive, whatever size the sender claims. |
|
|
82
|
+
| `onPairingCode` | `(code: string) => unknown` | — | Receives the 8-character pairing code when `phoneNumber` is set. |
|
|
83
|
+
| `onQR` | `(qr: string) => unknown` | — | Receives the QR string during login. Render it with `qrcode-terminal` or similar. |
|
|
84
|
+
| `phoneNumber` | `string` | — | Log in with a pairing code instead of a QR. E.164 without the leading `+`. |
|
|
85
|
+
| `receiveOwnMessages` | `boolean` | `false` | Pass what the paired account did — its messages, edits, deletes and reactions — to the Chat SDK, which still skips most of its own. |
|
|
86
|
+
| `reconnect` | `boolean` | `true` | Open the session again when WhatsApp drops it, backing off from 5 seconds to 5 minutes. A logout is never retried. |
|
|
87
|
+
| `watchdogIntervalMs` | `number \| false` | 1 minute | How often a connected session is asked whether WhatsApp still answers; two failed checks count as a disconnect. |
|
|
88
|
+
| `userName` | `string` | `"wwebjs-bot"` | Bot display name. When unset, the account's WhatsApp push name is adopted once the session is ready. |
|
|
89
|
+
|
|
90
|
+
## Platform setup
|
|
91
|
+
|
|
92
|
+
1. Install a Chromium that Puppeteer can launch. The bundled download covers most machines; on slim Linux images install the usual shared libraries, or point `clientOptions.puppeteer.executablePath` at your own browser.
|
|
93
|
+
2. Pick an auth strategy. `LocalAuth` stores the session in a directory; `RemoteAuth` stores it in a database you provide. Persist it — without one you re-scan on every start.
|
|
94
|
+
3. Start the process and link the device: scan the QR from `onQR`, or set `phoneNumber` and enter the code from `onPairingCode` under WhatsApp → **Linked devices** → **Link with phone number**.
|
|
95
|
+
4. Keep the process alive. This is a live browser session, not a webhook — `handleWebhook` always answers `501`.
|
|
96
|
+
|
|
97
|
+
## Features
|
|
98
|
+
|
|
99
|
+
Everything in the Chat SDK `Adapter` interface that WhatsApp can express:
|
|
100
|
+
|
|
101
|
+
| Capability | Notes |
|
|
102
|
+
| ------------------- | -------------------------------------------------------------------------------------------- |
|
|
103
|
+
| Post, edit, delete | Editing is WhatsApp's own 15-minute window on your own messages; delete is for everyone. |
|
|
104
|
+
| Reply | `thread.reply()` produces a native quoted bubble. |
|
|
105
|
+
| Fetch messages | Real history with forward and backward pagination — see [History](#history). |
|
|
106
|
+
| Fetch a message | By ID, via `getMessageById`. |
|
|
107
|
+
| Reactions | Send, remove, and receive, normalized to the SDK's `EmojiValue`. |
|
|
108
|
+
| Typing and presence | `startTyping()` composes, `startTyping("recording")` records, `endTyping()` clears. |
|
|
109
|
+
| Read receipts | `thread.markAsRead()`, or `markSeen: true` for every inbound message. |
|
|
110
|
+
| Attachments | Images, video, audio, voice notes, stickers and documents, in and out, downloaded on demand. |
|
|
111
|
+
| Mentions | `thread.mentionUser(id)` renders `@number` and registers the mention with WhatsApp. |
|
|
112
|
+
| Threads, channels | Metadata, group member counts, DMs opened by phone number, contact lookup. |
|
|
113
|
+
| Edits and deletes | `onMessageUpdated` carries the body it replaced; `onMessageDeleted` carries the original. |
|
|
114
|
+
| Group joins | Bridged to `onMemberJoinedChannel`. |
|
|
115
|
+
|
|
116
|
+
WhatsApp-specific extras live on the adapter, past the shared interface:
|
|
117
|
+
|
|
118
|
+
`sendPoll` · `onPollVote` · `sendLocation` · `sendEvent` · `sendSticker` · `forwardMessage` · `pinMessage` · `starMessage` · `fetchPinnedMessages` · `searchMessages` · `fetchGroupParticipants` · `getProfilePicUrl` · `setPresence` · `markAsUnread` · `muteThread` · `archiveThread` · `pinThread` · `onCall` · `onAck` · `onGroupEvent`
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { requireWWebJSAdapter } from "chat-adapter-wwebjs";
|
|
122
|
+
|
|
123
|
+
bot.onSubscribedMessage(async (thread) => {
|
|
124
|
+
const wa = requireWWebJSAdapter(thread);
|
|
125
|
+
const poll = await wa.sendPoll({
|
|
126
|
+
options: ["Tacos", "Sushi", "Ramen"],
|
|
127
|
+
question: "Lunch?",
|
|
128
|
+
threadId: thread.id,
|
|
129
|
+
});
|
|
130
|
+
wa.onPollVote(poll.id, (vote) => {
|
|
131
|
+
console.log(`${vote.voter.userName} picked ${vote.selectedOptions.join(", ")}`);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Anything not wrapped here is still reachable: `adapter.client` is the whatsapp-web.js `Client` itself.
|
|
137
|
+
|
|
138
|
+
### History
|
|
139
|
+
|
|
140
|
+
`fetchMessages` reads real WhatsApp history, so `thread.messages` and the SDK's history API work. Cursors are offsets from the newest message.
|
|
141
|
+
|
|
142
|
+
Backward (the default) asks WhatsApp for `offset + limit` messages and returns the page — cheap, and what a chat view wants. Forward loads the whole conversation and slices, because WhatsApp offers no oldest-first cursor; use it for one-off backfills, not per-request paging. Both only see what the web client has synced.
|
|
143
|
+
|
|
144
|
+
### Formatting
|
|
145
|
+
|
|
146
|
+
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. Cards fall back to text.
|
|
147
|
+
|
|
148
|
+
### Multiple accounts
|
|
149
|
+
|
|
150
|
+
Give each adapter its own `adapterName`, matching the key it is registered under. It becomes the thread-ID prefix, so `sales:…` and `support:…` never collide on one `Chat` instance.
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
const sales = createWWebJSAdapter({
|
|
154
|
+
adapterName: "sales",
|
|
155
|
+
clientOptions: { authStrategy: new LocalAuth({ clientId: "sales" }) },
|
|
156
|
+
});
|
|
157
|
+
const support = createWWebJSAdapter({
|
|
158
|
+
adapterName: "support",
|
|
159
|
+
clientOptions: { authStrategy: new LocalAuth({ clientId: "support" }) },
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const bot = new Chat({ adapters: { sales, support }, state, userName: "my-bot" });
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Limits
|
|
166
|
+
|
|
167
|
+
- **Not a webhook adapter.** It needs a long-lived process with a browser attached. `handleWebhook` answers `501`. To split the session from your bot logic, put it behind [`chat-adapter-remote`](https://github.com/nivandres/chat-adapter-remote).
|
|
168
|
+
- **One session per number**, as WhatsApp Web itself allows.
|
|
169
|
+
- **No streaming.** WhatsApp has no streaming API, so the SDK's post-and-edit fallback applies — and each edit is a real WhatsApp edit, bounded by the 15-minute window.
|
|
170
|
+
- **No ephemeral messages, scheduling, or modals.** `postEphemeral` falls back to a DM; `thread.schedule()` throws.
|
|
171
|
+
- **No sub-threads.** A WhatsApp conversation is one flat stream, so `listThreads` is always empty and a channel is its own thread.
|
|
172
|
+
- **`receiveOwnMessages` includes the adapter's own sends.** Turn it on only if your handlers can tell them apart.
|
|
173
|
+
- **History is what the web client synced**, not WhatsApp's full server-side archive, and one read reaches back at most 1,000 messages.
|
|
174
|
+
- **An attachment given only by `url` is fetched from the host's network**, with a 30-second timeout and `maxMediaBytes` as its limit. Never pass one an end user chose.
|
|
175
|
+
- **`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"`.
|
|
176
|
+
- **Statuses, broadcast lists and WhatsApp's own notifications never reach your handlers.**
|
|
177
|
+
- **`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.
|
|
178
|
+
- **Messages received while the session was down are not replayed.** WhatsApp Web syncs them into history, where `fetchMessages` finds them, but no event fires for them.
|
|
179
|
+
|
|
180
|
+
## License
|
|
181
|
+
|
|
182
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { Attachment, FileUpload, AdapterPostableMessage, Logger, Author, Adapter, LockScope, ChatInstance, ChannelVisibility, WebhookOptions, Message as Message$1, RawMessage, EmojiValue, FetchOptions, FetchResult, ThreadInfo, ChannelInfo, ListThreadsResult, UserInfo, FormattedContent, BaseFormatConverter, Root } from 'chat';
|
|
2
|
+
import { MessageMedia, Message, Client, ClientOptions, PollVote, Call, GroupNotification } from 'whatsapp-web.js';
|
|
3
|
+
|
|
4
|
+
/** Describe an inbound message's media as a Chat SDK attachment. */
|
|
5
|
+
declare function toAttachments(message: Message, maxBytes?: number): Attachment[];
|
|
6
|
+
/** Download an inbound message's media as raw bytes, refusing media larger than `maxBytes`. */
|
|
7
|
+
declare function download(message: Message, maxBytes?: number): Promise<Buffer>;
|
|
8
|
+
/** Convert every attachment and file on a postable message into WhatsApp media. */
|
|
9
|
+
declare function toMediaList(message: AdapterPostableMessage, maxBytes?: number): Promise<MessageMedia[]>;
|
|
10
|
+
/**
|
|
11
|
+
* Convert a single attachment or file upload into WhatsApp media. An attachment
|
|
12
|
+
* given only by `url` is fetched from the host's own network, so never pass one
|
|
13
|
+
* an end user chose.
|
|
14
|
+
*/
|
|
15
|
+
declare function toMedia(source: Attachment | FileUpload, maxBytes?: number): Promise<MessageMedia>;
|
|
16
|
+
/** WhatsApp renders a caption on every media kind except audio. */
|
|
17
|
+
declare function isCaptionable(media: MessageMedia): boolean;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Where the WhatsApp session stands. Only `connected` can send and receive;
|
|
21
|
+
* `logged_out` needs a new pairing, and `closed` follows `disconnect()`.
|
|
22
|
+
*/
|
|
23
|
+
type WWebJSConnection = "closed" | "connected" | "connecting" | "disconnected" | "idle" | "logged_out" | "reconnecting";
|
|
24
|
+
/** Decoded thread ID components for WhatsApp. */
|
|
25
|
+
interface WWebJSThreadId {
|
|
26
|
+
/** WhatsApp chat ID, e.g. `"15551234567@c.us"` or `"1234567890-1234@g.us"`. */
|
|
27
|
+
chatId: string;
|
|
28
|
+
}
|
|
29
|
+
/** Configuration for the whatsapp-web.js adapter. */
|
|
30
|
+
interface WWebJSAdapterConfig {
|
|
31
|
+
/**
|
|
32
|
+
* Adapter identity used by Chat SDK serialization and thread ID prefixes.
|
|
33
|
+
* Set a unique value per account when several run on one `Chat` instance.
|
|
34
|
+
* Must not contain `:`. Defaults to `"wwebjs"`.
|
|
35
|
+
*/
|
|
36
|
+
adapterName?: string;
|
|
37
|
+
/**
|
|
38
|
+
* An existing whatsapp-web.js client to drive. When omitted the adapter
|
|
39
|
+
* constructs one from {@link WWebJSAdapterConfig.clientOptions}.
|
|
40
|
+
*/
|
|
41
|
+
client?: Client;
|
|
42
|
+
/** Options for the client the adapter constructs. Ignored when `client` is set. */
|
|
43
|
+
clientOptions?: ClientOptions;
|
|
44
|
+
/**
|
|
45
|
+
* How long opening the session may take before it is abandoned — and, with
|
|
46
|
+
* `reconnect`, tried again. whatsapp-web.js itself never gives up. Defaults
|
|
47
|
+
* to 2 minutes.
|
|
48
|
+
*/
|
|
49
|
+
connectTimeoutMs?: number;
|
|
50
|
+
/** Logger instance. Replaced by the Chat SDK logger once initialized. */
|
|
51
|
+
logger?: Logger;
|
|
52
|
+
/**
|
|
53
|
+
* Acknowledge inbound messages automatically, so the sender sees blue ticks
|
|
54
|
+
* as soon as the bot receives them. Defaults to `false`.
|
|
55
|
+
*/
|
|
56
|
+
markSeen?: boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Called with the 8-character pairing code when
|
|
59
|
+
* {@link WWebJSAdapterConfig.phoneNumber} is set.
|
|
60
|
+
*/
|
|
61
|
+
onPairingCode?: (code: string) => unknown;
|
|
62
|
+
/**
|
|
63
|
+
* Called with the QR string emitted during login. Render it with a library
|
|
64
|
+
* like `qrcode-terminal`.
|
|
65
|
+
*/
|
|
66
|
+
onQR?: (qr: string) => unknown;
|
|
67
|
+
/**
|
|
68
|
+
* Phone number for pairing-code login, in E.164 format without the leading
|
|
69
|
+
* `+`. Shorthand for `clientOptions.pairWithPhoneNumber`.
|
|
70
|
+
*/
|
|
71
|
+
phoneNumber?: string;
|
|
72
|
+
/**
|
|
73
|
+
* Largest inbound media, in bytes, that `fetchData()` downloads. Larger
|
|
74
|
+
* media is refused before it is read into memory. Defaults to 64 MB.
|
|
75
|
+
*/
|
|
76
|
+
maxMediaBytes?: number;
|
|
77
|
+
/**
|
|
78
|
+
* Deliver messages the paired account sent — from the phone or from this
|
|
79
|
+
* adapter — to the Chat SDK, along with its own edits, deletes and
|
|
80
|
+
* reactions. Defaults to `false`.
|
|
81
|
+
*/
|
|
82
|
+
receiveOwnMessages?: boolean;
|
|
83
|
+
/**
|
|
84
|
+
* Open the session again when WhatsApp drops it, waiting longer after each
|
|
85
|
+
* failed attempt. A logout is never retried, since it needs a new pairing.
|
|
86
|
+
* Defaults to `true`.
|
|
87
|
+
*/
|
|
88
|
+
reconnect?: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* How often a connected session is asked whether WhatsApp still answers.
|
|
91
|
+
* Two failed checks in a row count as a disconnect, which `reconnect` then
|
|
92
|
+
* handles. Catches a session that died without any event. Defaults to 1
|
|
93
|
+
* minute; `false` turns it off.
|
|
94
|
+
*/
|
|
95
|
+
watchdogIntervalMs?: number | false;
|
|
96
|
+
/** Bot display name. Defaults to `"wwebjs-bot"`. */
|
|
97
|
+
userName?: string;
|
|
98
|
+
}
|
|
99
|
+
/** Delivery state of a sent message, reported by {@link WWebJSAdapter.onAck}. */
|
|
100
|
+
type WWebJSAckStatus = "delivered" | "error" | "pending" | "played" | "read" | "sent";
|
|
101
|
+
/** A delivery-state change for a message the bot sent. */
|
|
102
|
+
interface WWebJSAck {
|
|
103
|
+
/** Message ID whose delivery state changed. */
|
|
104
|
+
messageId: string;
|
|
105
|
+
/** Raw whatsapp-web.js message. */
|
|
106
|
+
raw: Message;
|
|
107
|
+
/** New delivery state. */
|
|
108
|
+
status: WWebJSAckStatus;
|
|
109
|
+
/** Encoded thread ID the message belongs to. */
|
|
110
|
+
threadId: string;
|
|
111
|
+
}
|
|
112
|
+
/** A participant returned by {@link WWebJSAdapter.fetchGroupParticipants}. */
|
|
113
|
+
interface WWebJSGroupParticipant {
|
|
114
|
+
/** True for both admin and super-admin roles. */
|
|
115
|
+
isAdmin: boolean;
|
|
116
|
+
/** True only for the group creator. */
|
|
117
|
+
isSuperAdmin: boolean;
|
|
118
|
+
/** The participant's chat ID, e.g. `"15551234567@c.us"`. */
|
|
119
|
+
userId: string;
|
|
120
|
+
}
|
|
121
|
+
/** Membership or metadata change in a group. */
|
|
122
|
+
interface WWebJSGroupEvent {
|
|
123
|
+
/** Chat ID of whoever performed the action, when WhatsApp reports one. */
|
|
124
|
+
authorId?: string;
|
|
125
|
+
/** Raw whatsapp-web.js notification. */
|
|
126
|
+
raw: GroupNotification;
|
|
127
|
+
/** Encoded thread ID of the group. */
|
|
128
|
+
threadId: string;
|
|
129
|
+
/** What happened. */
|
|
130
|
+
type: "admin_changed" | "join" | "leave" | "membership_request" | "update";
|
|
131
|
+
/** Chat IDs the action applies to. */
|
|
132
|
+
userIds: string[];
|
|
133
|
+
}
|
|
134
|
+
/** A vote on a poll the bot sent, delivered to {@link WWebJSAdapter.onPollVote}. */
|
|
135
|
+
interface WWebJSPollVote {
|
|
136
|
+
/** Original poll options, in send order. */
|
|
137
|
+
options: string[];
|
|
138
|
+
/** Message ID of the poll being voted on. */
|
|
139
|
+
pollMessageId: string;
|
|
140
|
+
/** Original poll question. */
|
|
141
|
+
question: string;
|
|
142
|
+
/** Raw whatsapp-web.js vote. */
|
|
143
|
+
raw: PollVote;
|
|
144
|
+
/** Options the voter currently has selected. Empty when the vote was cleared. */
|
|
145
|
+
selectedOptions: string[];
|
|
146
|
+
/** Encoded thread ID where the poll lives. */
|
|
147
|
+
threadId: string;
|
|
148
|
+
/** Author info for the voter. */
|
|
149
|
+
voter: Author;
|
|
150
|
+
}
|
|
151
|
+
/** Named arguments for {@link WWebJSAdapter.sendLocation}. */
|
|
152
|
+
interface WWebJSSendLocationArgs {
|
|
153
|
+
/** Street address shown below the place name. */
|
|
154
|
+
address?: string;
|
|
155
|
+
/** Latitude in decimal degrees (WGS 84). */
|
|
156
|
+
latitude: number;
|
|
157
|
+
/** Longitude in decimal degrees (WGS 84). */
|
|
158
|
+
longitude: number;
|
|
159
|
+
/** Place name shown on the pin. */
|
|
160
|
+
name?: string;
|
|
161
|
+
/** Encoded thread ID that should receive the pin. */
|
|
162
|
+
threadId: string;
|
|
163
|
+
/** URL shown within the location message. */
|
|
164
|
+
url?: string;
|
|
165
|
+
}
|
|
166
|
+
/** Named arguments for {@link WWebJSAdapter.sendPoll}. */
|
|
167
|
+
interface WWebJSSendPollArgs {
|
|
168
|
+
/** Let voters pick more than one option. Defaults to `false`. */
|
|
169
|
+
allowMultipleAnswers?: boolean;
|
|
170
|
+
/** Poll options, between 2 and 12. */
|
|
171
|
+
options: string[];
|
|
172
|
+
/** Poll question. */
|
|
173
|
+
question: string;
|
|
174
|
+
/** Encoded thread ID that should receive the poll. */
|
|
175
|
+
threadId: string;
|
|
176
|
+
}
|
|
177
|
+
/** Named arguments for {@link WWebJSAdapter.sendEvent}. */
|
|
178
|
+
interface WWebJSSendEventArgs {
|
|
179
|
+
/** Type of WhatsApp call link to attach. Defaults to `"none"`. */
|
|
180
|
+
callType?: "none" | "video" | "voice";
|
|
181
|
+
/** Event description. */
|
|
182
|
+
description?: string;
|
|
183
|
+
/** When the event ends. */
|
|
184
|
+
endTime?: Date;
|
|
185
|
+
/** Where the event takes place. */
|
|
186
|
+
location?: string;
|
|
187
|
+
/** Event name. */
|
|
188
|
+
name: string;
|
|
189
|
+
/** When the event starts. */
|
|
190
|
+
startTime: Date;
|
|
191
|
+
/** Encoded thread ID that should receive the event. */
|
|
192
|
+
threadId: string;
|
|
193
|
+
}
|
|
194
|
+
/** Handler for delivery-state changes. */
|
|
195
|
+
type WWebJSAckHandler = (ack: WWebJSAck) => unknown;
|
|
196
|
+
/** Handler for incoming calls. */
|
|
197
|
+
type WWebJSCallHandler = (call: Call) => unknown;
|
|
198
|
+
/** Handler for group membership and metadata changes. */
|
|
199
|
+
type WWebJSGroupEventHandler = (event: WWebJSGroupEvent) => unknown;
|
|
200
|
+
/** Handler for poll votes. */
|
|
201
|
+
type WWebJSPollVoteHandler = (vote: WWebJSPollVote) => unknown;
|
|
202
|
+
|
|
203
|
+
declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
|
|
204
|
+
readonly name: string;
|
|
205
|
+
readonly lockScope: LockScope;
|
|
206
|
+
/** The underlying whatsapp-web.js client, for anything this adapter does not wrap. */
|
|
207
|
+
readonly client: Client;
|
|
208
|
+
userName: string;
|
|
209
|
+
private readonly _config;
|
|
210
|
+
private readonly _converter;
|
|
211
|
+
private readonly _ackHandlers;
|
|
212
|
+
private readonly _callHandlers;
|
|
213
|
+
private readonly _groupHandlers;
|
|
214
|
+
private readonly _pollVoteHandlers;
|
|
215
|
+
private _chat;
|
|
216
|
+
private _logger;
|
|
217
|
+
private _connection;
|
|
218
|
+
private _botLid?;
|
|
219
|
+
private _closed;
|
|
220
|
+
private _retry?;
|
|
221
|
+
private _initialized;
|
|
222
|
+
private _state;
|
|
223
|
+
private _watchdog?;
|
|
224
|
+
private _strikes;
|
|
225
|
+
constructor(config?: WWebJSAdapterConfig);
|
|
226
|
+
/** Where the session stands; a health check reads `connection === "connected"`. */
|
|
227
|
+
get connection(): WWebJSConnection;
|
|
228
|
+
get botUserId(): string | undefined;
|
|
229
|
+
initialize(chat: ChatInstance): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Launch the browser session and wait until WhatsApp is ready.
|
|
232
|
+
*
|
|
233
|
+
* Call this after registering handlers on your `Chat` instance, so no
|
|
234
|
+
* message arrives before there is something to receive it. Repeated calls
|
|
235
|
+
* share one connection attempt.
|
|
236
|
+
*/
|
|
237
|
+
connect(): Promise<void>;
|
|
238
|
+
/** Close the browser session. */
|
|
239
|
+
disconnect(): Promise<void>;
|
|
240
|
+
encodeThreadId(platformData: WWebJSThreadId): string;
|
|
241
|
+
decodeThreadId(threadId: string): WWebJSThreadId;
|
|
242
|
+
channelIdFromThreadId(threadId: string): string;
|
|
243
|
+
isDM(threadId: string): boolean;
|
|
244
|
+
getChannelVisibility(threadId: string): ChannelVisibility;
|
|
245
|
+
/**
|
|
246
|
+
* whatsapp-web.js drives a browser session rather than inbound HTTP, so this
|
|
247
|
+
* always answers 501. Call {@link WWebJSAdapter.connect} to receive messages.
|
|
248
|
+
*/
|
|
249
|
+
handleWebhook(_request: Request, _options?: WebhookOptions): Promise<Response>;
|
|
250
|
+
parseMessage(raw: Message): Message$1<Message>;
|
|
251
|
+
postMessage(threadId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
|
|
252
|
+
postChannelMessage(channelId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
|
|
253
|
+
reply(threadId: string, messageId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
|
|
254
|
+
editMessage(threadId: string, messageId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
|
|
255
|
+
deleteMessage(_threadId: string, messageId: string): Promise<void>;
|
|
256
|
+
addReaction(_threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
|
|
257
|
+
removeReaction(_threadId: string, messageId: string, _emoji: EmojiValue | string): Promise<void>;
|
|
258
|
+
fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
|
|
259
|
+
fetchChannelMessages(channelId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
|
|
260
|
+
fetchMessage(_threadId: string, messageId: string): Promise<Message$1<Message> | null>;
|
|
261
|
+
fetchThread(threadId: string): Promise<ThreadInfo>;
|
|
262
|
+
fetchChannelInfo(channelId: string): Promise<ChannelInfo>;
|
|
263
|
+
/** WhatsApp conversations are flat, so a channel never contains sub-threads. */
|
|
264
|
+
listThreads(): Promise<ListThreadsResult<Message>>;
|
|
265
|
+
getUser(userId: string): Promise<UserInfo | null>;
|
|
266
|
+
/** A number, or its `@c.us` id, resolves to the chat WhatsApp uses for it — often a LID — so a DM is one thread whoever opened it. */
|
|
267
|
+
openDM(userId: string): Promise<string>;
|
|
268
|
+
markAsRead(threadId: string): Promise<void>;
|
|
269
|
+
startTyping(threadId: string, status?: string): Promise<void>;
|
|
270
|
+
endTyping(threadId: string): Promise<void>;
|
|
271
|
+
renderFormatted(content: FormattedContent): string;
|
|
272
|
+
rehydrateAttachment(attachment: Attachment): Attachment;
|
|
273
|
+
/** Send a map pin. */
|
|
274
|
+
sendLocation(args: WWebJSSendLocationArgs): Promise<RawMessage<Message>>;
|
|
275
|
+
/** Send a native WhatsApp poll. Between 2 and 12 options. */
|
|
276
|
+
sendPoll(args: WWebJSSendPollArgs): Promise<RawMessage<Message>>;
|
|
277
|
+
/** Send a scheduled event card. */
|
|
278
|
+
sendEvent(args: WWebJSSendEventArgs): Promise<RawMessage<Message>>;
|
|
279
|
+
/** Send an image as a sticker. */
|
|
280
|
+
sendSticker(threadId: string, source: Attachment | Parameters<typeof toMedia>[0]): Promise<RawMessage<Message>>;
|
|
281
|
+
/** Forward an existing message into another thread. */
|
|
282
|
+
forwardMessage(messageId: string, targetThreadId: string): Promise<void>;
|
|
283
|
+
/** Pin a message for the given number of seconds. */
|
|
284
|
+
pinMessage(messageId: string, seconds: number): Promise<boolean>;
|
|
285
|
+
/** Unpin a message. */
|
|
286
|
+
unpinMessage(messageId: string): Promise<boolean>;
|
|
287
|
+
/** Star a message. */
|
|
288
|
+
starMessage(messageId: string): Promise<void>;
|
|
289
|
+
/** Unstar a message. */
|
|
290
|
+
unstarMessage(messageId: string): Promise<void>;
|
|
291
|
+
/** Every pinned message in a thread. */
|
|
292
|
+
fetchPinnedMessages(threadId: string): Promise<Message$1<Message>[]>;
|
|
293
|
+
/** Search messages across every chat, or within one thread. */
|
|
294
|
+
searchMessages(query: string, options?: {
|
|
295
|
+
limit?: number;
|
|
296
|
+
page?: number;
|
|
297
|
+
threadId?: string;
|
|
298
|
+
}): Promise<Message$1<Message>[]>;
|
|
299
|
+
/** Participants of a group thread, with their admin status. */
|
|
300
|
+
fetchGroupParticipants(threadId: string): Promise<WWebJSGroupParticipant[]>;
|
|
301
|
+
/** The profile picture of a contact or group, when privacy settings allow it. */
|
|
302
|
+
getProfilePicUrl(userId: string): Promise<string | undefined>;
|
|
303
|
+
/** Show the bot as online or offline. */
|
|
304
|
+
setPresence(presence: "available" | "unavailable"): Promise<void>;
|
|
305
|
+
/** Mark a thread unread. */
|
|
306
|
+
markAsUnread(threadId: string): Promise<void>;
|
|
307
|
+
/** Mute a thread until the given date, or forever when omitted. */
|
|
308
|
+
muteThread(threadId: string, until?: Date): Promise<void>;
|
|
309
|
+
/** Unmute a thread. */
|
|
310
|
+
unmuteThread(threadId: string): Promise<void>;
|
|
311
|
+
/** Archive a thread. */
|
|
312
|
+
archiveThread(threadId: string): Promise<void>;
|
|
313
|
+
/** Move a thread out of the archive. */
|
|
314
|
+
unarchiveThread(threadId: string): Promise<void>;
|
|
315
|
+
/** Pin a thread to the top of the chat list. */
|
|
316
|
+
pinThread(threadId: string): Promise<boolean>;
|
|
317
|
+
/** Unpin a thread. */
|
|
318
|
+
unpinThread(threadId: string): Promise<boolean>;
|
|
319
|
+
/**
|
|
320
|
+
* Subscribe to votes on polls sent from this account, optionally narrowed to
|
|
321
|
+
* specific poll message IDs.
|
|
322
|
+
*/
|
|
323
|
+
onPollVote(handler: WWebJSPollVoteHandler): void;
|
|
324
|
+
onPollVote(pollMessageIds: string | string[], handler: WWebJSPollVoteHandler): void;
|
|
325
|
+
/** Subscribe to incoming calls. Use `call.reject()` to decline. */
|
|
326
|
+
onCall(handler: WWebJSCallHandler): void;
|
|
327
|
+
/** Subscribe to delivery-state changes for messages this account sent. */
|
|
328
|
+
onAck(handler: WWebJSAckHandler): void;
|
|
329
|
+
/** Subscribe to group membership and metadata changes. */
|
|
330
|
+
onGroupEvent(handler: WWebJSGroupEventHandler): void;
|
|
331
|
+
private _clientOptions;
|
|
332
|
+
private _connect;
|
|
333
|
+
private _open;
|
|
334
|
+
private _listen;
|
|
335
|
+
private _onMessage;
|
|
336
|
+
private _onEdit;
|
|
337
|
+
private _onRevoke;
|
|
338
|
+
private _onReaction;
|
|
339
|
+
private _onAck;
|
|
340
|
+
private _onGroup;
|
|
341
|
+
private _onVote;
|
|
342
|
+
private _dispatch;
|
|
343
|
+
private _parse;
|
|
344
|
+
private _author;
|
|
345
|
+
private _indicator;
|
|
346
|
+
/** Groups address the bot by its LID or its phone number, whichever they know it by. */
|
|
347
|
+
private _mentionsBot;
|
|
348
|
+
private _botUsers;
|
|
349
|
+
private _mentioned;
|
|
350
|
+
/** WhatsApp writes a mention as `@` and the number or LID; readers expect the name. */
|
|
351
|
+
private _named;
|
|
352
|
+
private _learnLid;
|
|
353
|
+
/** Listeners run unawaited, so a rejection here would end the process. */
|
|
354
|
+
private _guard;
|
|
355
|
+
private _isOwn;
|
|
356
|
+
private _onDisconnected;
|
|
357
|
+
private _reconnect;
|
|
358
|
+
private _watch;
|
|
359
|
+
/** Revives a session that died without an event, or a first connection that failed. */
|
|
360
|
+
private _check;
|
|
361
|
+
private _render;
|
|
362
|
+
private _send;
|
|
363
|
+
private _sendContent;
|
|
364
|
+
private _raw;
|
|
365
|
+
private _page;
|
|
366
|
+
private _findChat;
|
|
367
|
+
private _requireChat;
|
|
368
|
+
private _requireMessage;
|
|
369
|
+
}
|
|
370
|
+
/** Create a WhatsApp adapter backed by whatsapp-web.js. */
|
|
371
|
+
declare function createWWebJSAdapter(config?: WWebJSAdapterConfig): WWebJSAdapter;
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Converts between WhatsApp's markup and the Chat SDK's mdast AST.
|
|
375
|
+
*
|
|
376
|
+
* WhatsApp understands `*bold*`, `_italic_`, `~strikethrough~`, `` `code` ``,
|
|
377
|
+
* ` ```blocks``` `, `> quotes` and simple lists. It has no link syntax, so
|
|
378
|
+
* links render as `text (url)`, and no tables, so tables render as ASCII
|
|
379
|
+
* inside a code block.
|
|
380
|
+
*/
|
|
381
|
+
declare class WWebJSFormatConverter extends BaseFormatConverter {
|
|
382
|
+
/** Text from anyone: past `MAX_MARKDOWN_LENGTH`, or when the parser gives up, it stays plain rather than stalling or throwing. */
|
|
383
|
+
toAst(platformText: string): Root;
|
|
384
|
+
fromAst(ast: Root): string;
|
|
385
|
+
private toWhatsApp;
|
|
386
|
+
private join;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Narrow an unknown adapter to {@link WWebJSAdapter}. */
|
|
390
|
+
declare function isWWebJSAdapter(value: unknown): value is WWebJSAdapter;
|
|
391
|
+
/**
|
|
392
|
+
* Require that a Chat SDK context belongs to a {@link WWebJSAdapter}.
|
|
393
|
+
*
|
|
394
|
+
* Accepts the adapter itself or anything carrying one, such as a `Thread`,
|
|
395
|
+
* `Channel` or `SentMessage`.
|
|
396
|
+
*/
|
|
397
|
+
declare function requireWWebJSAdapter(value: unknown): WWebJSAdapter;
|
|
398
|
+
|
|
399
|
+
/** True for group chat IDs, e.g. `"1234567890-1234567890@g.us"`. */
|
|
400
|
+
declare function isGroupId(chatId: string): boolean;
|
|
401
|
+
/** True for channel (newsletter) IDs, e.g. `"1234567890@newsletter"`. */
|
|
402
|
+
declare function isNewsletterId(chatId: string): boolean;
|
|
403
|
+
/** True for one-to-one chat IDs, e.g. `"15551234567@c.us"`. */
|
|
404
|
+
declare function isUserId(chatId: string): boolean;
|
|
405
|
+
/** Normalize a bare phone number into a WhatsApp chat ID. */
|
|
406
|
+
declare function toChatId(value: string): string;
|
|
407
|
+
/** The user part of a chat ID, e.g. `"15551234567@c.us"` → `"15551234567"`. */
|
|
408
|
+
declare function toUser(chatId: string): string;
|
|
409
|
+
/**
|
|
410
|
+
* Rewrite Chat SDK mention tokens into WhatsApp's `@number` form and collect
|
|
411
|
+
* the chat IDs WhatsApp needs alongside the body to render them as mentions.
|
|
412
|
+
*/
|
|
413
|
+
declare function extractMentions(text: string): {
|
|
414
|
+
mentions: string[];
|
|
415
|
+
text: string;
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
export { type WWebJSAck, type WWebJSAckHandler, type WWebJSAckStatus, WWebJSAdapter, type WWebJSAdapterConfig, type WWebJSCallHandler, type WWebJSConnection, WWebJSFormatConverter, type WWebJSGroupEvent, type WWebJSGroupEventHandler, type WWebJSGroupParticipant, type WWebJSPollVote, type WWebJSPollVoteHandler, type WWebJSSendEventArgs, type WWebJSSendLocationArgs, type WWebJSSendPollArgs, type WWebJSThreadId, createWWebJSAdapter, download, extractMentions, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser };
|