@itznomo/baileys 0.0.0-stage โ†’ 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,1152 @@
1
+ # @nomo/ballieys feature guide
2
+
3
+ > This guide is the feature documentation of @dnuzi/baileys 0.1.4 (MIT, by DanuZz), kept because @nomo/ballieys is built on that runtime. Examples that use `footer: 'DanuZz'` are just sample text, use your own. Button helpers from nomo 1.x are documented in `BUTTONS.md`.
4
+
5
+ ## โœจ Highlights
6
+
7
+
8
+ | | |
9
+ |---|---|
10
+ | ๐Ÿ†” **Identity** | LID, phone number and username support |
11
+ | โšก **Performance** | Built for many sessions at once, low CPU and memory use |
12
+ | ๐Ÿ“ฆ **Dependencies** | Zero runtime dependencies, no native or WebRTC builds |
13
+ | ๐Ÿ“ž **Calls** | Audio and video calls, playlists, multi-call |
14
+ | ๐Ÿงฉ **Messages** | Buttons, carousels, widgets, polls, events, payments, AI rich |
15
+ | ๐Ÿ—„๏ธ **Sessions** | Multi-file, single-file, SQLite or MongoDB auth storage |
16
+
17
+ > DanuZz 2.0.0 runtime notes: release introducing official WhatsApp Chat Theme Settings (preset themes & custom ARGB backgrounds with doodle toggles), precision stealth device targeting (participant for recipient-only delivery, isSecret for primary mobile device only, and protected to exclude companion web/desktop sessions), zero-overhead fanout controls, and full CommonJS & ESM compatibility.
18
+
19
+
20
+ ## ๐Ÿ“ฅ Install
21
+
22
+ Requires **Node.js 18+** and **FFmpeg**. Calls also need `ffprobe` available in `PATH`.
23
+
24
+ ```bash
25
+ npm install @nomo/ballieys
26
+ ```
27
+
28
+ ```json
29
+ {
30
+ "dependencies": {
31
+ "@nomo/ballieys": "^1.0.0"
32
+ }
33
+ }
34
+ ```
35
+
36
+
37
+ ## ๐Ÿš€ Quick Start
38
+
39
+ A complete bot that links by QR or pairing code and answers `!ping`.
40
+
41
+ ```javascript
42
+ import makeWASocket, {
43
+ useMultiFileAuthState,
44
+ DisconnectReason,
45
+ extractMessageContent
46
+ } from '@nomo/ballieys'
47
+
48
+ const PHONE_NUMBER = '' // e.g. '948123456789' to use a pairing code
49
+ const PAIR_CODE = '' // optional custom 8-character code
50
+
51
+ const start = async () => {
52
+ const { state, saveCreds } = await useMultiFileAuthState('./session')
53
+
54
+ const sock = makeWASocket({
55
+ auth: state,
56
+ printQRInTerminal: !PHONE_NUMBER,
57
+ syncFullHistory: false
58
+ })
59
+
60
+ sock.ev.on('creds.update', saveCreds)
61
+
62
+ let pairingRequested = false
63
+ sock.ev.on('connection.update', async ({ connection, lastDisconnect, qr }) => {
64
+ if (qr && PHONE_NUMBER && !pairingRequested) {
65
+ pairingRequested = true
66
+ try {
67
+ console.log('Pairing code:', await sock.requestPairingCode(PHONE_NUMBER, PAIR_CODE || undefined))
68
+ } catch (err) {
69
+ console.error('Could not request a pairing code:', err.message)
70
+ }
71
+ }
72
+
73
+ if (connection === 'open') console.log('Connected as', sock.user?.id)
74
+
75
+ if (connection === 'close') {
76
+ const code = lastDisconnect?.error?.output?.statusCode
77
+ if (code === DisconnectReason.loggedOut) {
78
+ return console.log('Logged out. Delete ./session and run again to link a new device.')
79
+ }
80
+ if (code === DisconnectReason.connectionReplaced) {
81
+ return console.log('This session was opened somewhere else. Not reconnecting.')
82
+ }
83
+ console.log(`Connection closed (${code}), reconnecting...`)
84
+ setTimeout(start, 1000)
85
+ }
86
+ })
87
+
88
+ sock.ev.on('messages.upsert', async ({ messages, type }) => {
89
+ if (type !== 'notify') return
90
+ for (const m of messages) {
91
+ if (m.key.fromMe || !m.message) continue
92
+ const content = extractMessageContent(m.message)
93
+ const text = content?.conversation || content?.extendedTextMessage?.text
94
+ if (text === '!ping') {
95
+ await sock.sendMessage(m.key.remoteJid, { text: 'pong' }, { quoted: m }).catch(console.error)
96
+ }
97
+ }
98
+ })
99
+ }
100
+
101
+ start()
102
+ ```
103
+
104
+ **How to link**
105
+
106
+ | Method | Steps |
107
+ |---|---|
108
+ | QR code | Leave `PHONE_NUMBER` empty, then scan from *Linked devices โ†’ Link a device* |
109
+ | Pairing code | Set `PHONE_NUMBER`, choose *Link with phone number instead*, enter the code |
110
+ | Custom code | Set `PAIR_CODE` to any 8 characters (empty = random) |
111
+
112
+ > Your login is stored in `./session`. Keep it private and out of git.
113
+
114
+ ### โš™๏ธ Socket options
115
+
116
+ | Option | Default | What it does |
117
+ |---|---|---|
118
+ | `auth` | โ€“ | **Required.** The `state` from an auth helper |
119
+ | `performanceMode` | `'balanced'` | Performance preset: `'balanced'` (safe defaults), `'high'` (aggressive caching & lowest latency), or `'low-memory'` (RAM-constrained environments) |
120
+ | `dedupTTL` | `30000` (ms) | Deduplication window for incoming message stanzas |
121
+ | `dedupMax` | `2000` | Maximum messages tracked in deduplication buffer |
122
+ | `groupMetadataCacheTTL` | `300000` (ms) | In-memory group metadata cache TTL |
123
+ | `browser` | `Browsers.macOS('Chrome')` | Device name in *Linked devices* (also `.ubuntu()`, `.windows()`, `.appropriate()`) |
124
+ | `printQRInTerminal` | `false` | Print each QR in the terminal (`qr` is always emitted on `connection.update`) |
125
+ | `qrTimeout` | `60000`, then `20000` | How long each QR stays valid |
126
+ | `syncFullHistory` | `true` | Set `false` for lighter bots |
127
+ | `markOnlineOnConnect` | `true` | Set `false` to keep notifications on your phone |
128
+ | `connectTimeoutMs` | `20000` | Opening handshake timeout |
129
+ | `keepAliveIntervalMs` | `30000` | Ping interval |
130
+ | `defaultQueryTimeoutMs` | `60000` | Server request timeout |
131
+ | `getMessage` | `undefined` | Return a stored message by key so retries and poll votes can be decrypted |
132
+ | `disableStickyRouting` | `false` | `true` stops sending `ED` in the URL and the `sticky_routing` cookie |
133
+ | `waWebSocketUrl` | `wss://web.whatsapp.com/ws/chat` | Custom endpoint only |
134
+ | `logger` | built-in | Any pino-style logger |
135
+
136
+
137
+ ## โšก Performance Optimization & Latency Tuning
138
+
139
+ `@nomo/ballieys` includes an internal performance engine engineered to minimize bot response latency and eliminate redundant network operations without breaking any existing Baileys APIs.
140
+
141
+ ### ๐Ÿš€ Performance Modes
142
+
143
+ You can select a performance mode when initializing your socket:
144
+
145
+ ```javascript
146
+ const sock = makeWASocket({
147
+ auth: state,
148
+ performanceMode: 'high' // 'balanced' | 'high' | 'low-memory'
149
+ })
150
+ ```
151
+
152
+ | Mode | Target | Description |
153
+ |---|---|---|
154
+ | `'balanced'` *(default)* | General Bots | Safe, backward-compatible defaults. In-memory group metadata caching (5 min), message deduplication (30s window), request coalescing, and safe event isolation. |
155
+ | `'high'` | Ultra-fast Response Bots | Maximum throughput and lowest latency. Extended caching (15 min group cache, 60s dedup), aggressive request coalescing, enlarged signal cache, and zero-overhead lazy logging. |
156
+ | `'low-memory'` | VPS / Embedded (โ‰ค512MB RAM) | Compact cache bounds (100 groups, 500 messages, 2 min TTL) with aggressive garbage collection. |
157
+
158
+ ### ๐Ÿ› ๏ธ Core Optimization Architecture
159
+
160
+ 1. **Fast Message Pipeline & Deduplication**
161
+ - Incoming message stanzas are checked against a high-speed, bounded circular cache (`MessageDeduplicator`) before expensive cryptographic decryption.
162
+ - Duplicate message delivery stanzas are acknowledged and dropped instantly (~116,000+ msgs/sec throughput).
163
+ - If decryption fails (e.g. key missing/resend needed), the entry is automatically forgotten so retries can proceed seamlessly.
164
+
165
+ 2. **Intelligent Request Coalescing**
166
+ - Prevents duplicate concurrent lookups (e.g. 50 incoming messages requesting group metadata at the same millisecond).
167
+ - Reuses the in-flight Promise so **50 concurrent requests trigger exactly 1 network query**, reducing server round-trips by up to 98%.
168
+
169
+ 3. **In-Memory Group Metadata & LID Caching**
170
+ - `sock.groupMetadata(jid)` caches results with automatic invalidation on group changes (subject, description, participants, settings).
171
+ - Pre-populates the cache during initial sync (`groupFetchAllParticipating`) so your bot answers commands without cold-start delay.
172
+ - Access the cache directly via `sock.groupMetadataCache`.
173
+
174
+ 4. **Event Emitter Fault Isolation**
175
+ - Broken or crashing listener functions registered on `sock.ev.on('messages.upsert', ...)` are safely isolated.
176
+ - One plugin/handler error will **never crash other listeners or break the WhatsApp connection pipeline**.
177
+
178
+ 5. **Optimized Serialization & Sender Keys**
179
+ - In-memory sender key record caching avoids constant JSON serialization and file/database re-reading during rapid group chat traffic.
180
+
181
+ 6. **Zero-Overhead Lazy Logging**
182
+ - Uses `logger.isLevelEnabled(level)` and lazy argument evaluation so debug information is never formatted when running in production.
183
+
184
+ ### ๐Ÿ“Š Real-World Benchmarks
185
+
186
+ Run the benchmark suite on your own machine:
187
+
188
+ ```bash
189
+ npm run benchmark
190
+ ```
191
+
192
+ Results on standard hardware (Node.js 20+):
193
+ - **Message Deduplicator:** 115,000+ msgs/sec throughput
194
+ - **Request Coalescer:** 50 concurrent callers โ†’ 1 network operation (100% deduplicated in 27ms)
195
+ - **Isolated Event Dispatch:** 19,000+ events/sec with 100% fault-isolation
196
+ - **LRU-TTL Cache:** 165,000+ operations/sec
197
+
198
+ ### ๐Ÿ—„๏ธ Session storage
199
+
200
+ All helpers return `{ state, saveCreds }`, so you can swap them freely.
201
+
202
+ ```javascript
203
+ import {
204
+ useMultiFileAuthState,
205
+ useSingleFileAuthState,
206
+ useSqliteAuthState,
207
+ useMongoDBAuthState
208
+ } from '@nomo/ballieys'
209
+
210
+ const multi = await useMultiFileAuthState('./session') // one file per key
211
+ const single = await useSingleFileAuthState('./session.json') // one file, flushed in batches
212
+ const sqlite = await useSqliteAuthState({ dbPath: './session.db' }) // SQLite (file-based, zero setup)
213
+ const mongo = await useMongoDBAuthState({ url: 'mongodb://localhost:27017' }) // MongoDB (cloud & Docker)
214
+ ```
215
+
216
+ #### SQLite Auth Storage
217
+
218
+ Stores session credentials and Signal cryptographic keys in an SQLite database file. Built-in WAL (Write-Ahead Logging) mode ensures safe concurrent transactions with ultra-low memory overhead.
219
+
220
+ > [!TIP]
221
+ > **Zero extra dependencies required!** Baileys includes a built-in lightweight pure-JS SQLite engine, or you can plug in [`better-sqlite3`](https://www.npmjs.com/package/better-sqlite3) for native C++ performance.
222
+
223
+ **1. Basic setup (Built-in engine)**
224
+
225
+ ```javascript
226
+ import makeWASocket, { useSqliteAuthState } from '@nomo/ballieys'
227
+
228
+ const { state, saveCreds } = await useSqliteAuthState({
229
+ dbPath: './session.db'
230
+ })
231
+
232
+ const sock = makeWASocket({
233
+ auth: state,
234
+ printQRInTerminal: true
235
+ })
236
+
237
+ sock.ev.on('creds.update', saveCreds)
238
+ ```
239
+
240
+ **2. Using with `better-sqlite3` (Optional native driver)**
241
+
242
+ ```javascript
243
+ import Database from 'better-sqlite3'
244
+ import makeWASocket, { useSqliteAuthState } from '@nomo/ballieys'
245
+
246
+ const db = new Database('./session.db')
247
+
248
+ const { state, saveCreds } = await useSqliteAuthState({
249
+ database: db
250
+ })
251
+
252
+ const sock = makeWASocket({
253
+ auth: state
254
+ })
255
+
256
+ sock.ev.on('creds.update', saveCreds)
257
+ ```
258
+
259
+ **Options for `useSqliteAuthState`**
260
+
261
+ | Option | Type | Description |
262
+ |---|---|---|
263
+ | `dbPath` | `string` | File path to the SQLite database (e.g. `'./session.db'`). Uses the built-in pure-JS database engine |
264
+ | `database` | `object` | An existing database instance (e.g. from `better-sqlite3` or `sqlite3`) |
265
+
266
+
267
+ #### MongoDB Auth Storage
268
+
269
+ Store session credentials and encryption keys directly in MongoDB (local or MongoDB Atlas). Ideal for cloud deployments (Railway, Render, Heroku, AWS, Docker) where local files are ephemeral, or for managing multiple accounts in a single database.
270
+
271
+ > [!NOTE]
272
+ > When connecting via MongoDB URI (`url` / `uri`), ensure the `mongodb` package is installed in your project:
273
+ > ```bash
274
+ > npm install mongodb
275
+ > ```
276
+
277
+ **1. Connect via MongoDB URI**
278
+
279
+ ```javascript
280
+ import makeWASocket, { useMongoDBAuthState } from '@nomo/ballieys'
281
+
282
+ const { state, saveCreds } = await useMongoDBAuthState({
283
+ url: 'mongodb+srv://user:password@cluster.mongodb.net/?retryWrites=true&w=majority',
284
+ dbName: 'whatsapp_bot', // optional (default: 'baileys')
285
+ collectionName: 'sessions', // optional (default: 'auth_state')
286
+ sessionId: 'bot-1' // optional: isolate multiple accounts in one collection
287
+ })
288
+
289
+ const sock = makeWASocket({
290
+ auth: state,
291
+ printQRInTerminal: true
292
+ })
293
+
294
+ sock.ev.on('creds.update', saveCreds)
295
+ ```
296
+
297
+ **2. Use an existing MongoDB collection or client**
298
+
299
+ If your app already connects to MongoDB, pass the collection directly โ€” no extra driver connection needed:
300
+
301
+ ```javascript
302
+ import { MongoClient } from 'mongodb'
303
+ import { useMongoDBAuthState } from '@nomo/ballieys'
304
+
305
+ const client = new MongoClient('mongodb://localhost:27017')
306
+ await client.connect()
307
+
308
+ const collection = client.db('whatsapp_bot').collection('sessions')
309
+
310
+ // Pass collection directly (with optional sessionId as 2nd argument)
311
+ const { state, saveCreds } = await useMongoDBAuthState(collection, 'main-session')
312
+ ```
313
+
314
+ **3. Use with Mongoose**
315
+
316
+ ```javascript
317
+ import mongoose from 'mongoose'
318
+ import { useMongoDBAuthState } from '@nomo/ballieys'
319
+
320
+ await mongoose.connect('mongodb://localhost:27017/whatsapp_bot')
321
+
322
+ const collection = mongoose.connection.collection('sessions')
323
+ const { state, saveCreds } = await useMongoDBAuthState(collection)
324
+ ```
325
+
326
+ **Options for `useMongoDBAuthState`**
327
+
328
+ | Option | Type | Description |
329
+ |---|---|---|
330
+ | `url` / `uri` | `string` | MongoDB connection string (e.g. `mongodb://localhost:27017` or Atlas URI) |
331
+ | `collection` | `Collection` | Existing MongoDB collection or Mongoose model |
332
+ | `db` / `database` | `Db` | Existing MongoDB database instance (`client.db(...)`) |
333
+ | `client` | `MongoClient` | Existing `MongoClient` instance |
334
+ | `dbName` | `string` | Database name (default: `'baileys'` or DB from connection string) |
335
+ | `collectionName` | `string` | Collection name (default: `'auth_state'`) |
336
+ | `sessionId` | `string` | Session ID to namespace credentials and keys in a shared collection |
337
+ | `mongoOptions` | `object` | Connection options passed directly to `MongoClient` |
338
+
339
+ #### Per-Type Routing (Keyv Auth Storage)
340
+
341
+ Route different authentication key types to separate backends (e.g. `creds` to Postgres, `pre-key` to Redis, `session` to memory):
342
+
343
+ ```javascript
344
+ import makeWASocket, { useKeyvAuthState } from '@nomo/ballieys'
345
+
346
+ // Multi-backend per-type routing
347
+ const { state, saveCreds } = await useKeyvAuthState('my-session', {
348
+ creds: 'postgresql://user:pass@localhost:5432/whatsapp',
349
+ 'pre-key': 'redis://localhost:6379/1',
350
+ session: 'redis://localhost:6379/2',
351
+ default: 'redis://localhost:6379/0'
352
+ })
353
+
354
+ const sock = makeWASocket({ auth: state })
355
+ sock.ev.on('creds.update', saveCreds)
356
+ ```
357
+
358
+
359
+ ### ๐Ÿ”Œ Disconnect reasons
360
+
361
+ `lastDisconnect.error.output.statusCode` maps to `DisconnectReason`:
362
+
363
+ | Code | Reason | Do this |
364
+ |---|---|---|
365
+ | `401` | `loggedOut` | Delete the session and link again |
366
+ | `440` | `connectionReplaced` | Do **not** reconnect |
367
+ | `515` | `restartRequired` | Normal after pairing, reconnect |
368
+ | `428` / `408` | `connectionClosed` / `connectionLost` / `timedOut` | Network drop, reconnect |
369
+ | `500` | `badSession` | Reconnect |
370
+
371
+ When the server closes the socket, `lastDisconnect.error.data` includes `wsCode` and `wsReason`.
372
+
373
+
374
+ ## ๐Ÿ’ฌ Messages
375
+
376
+ ### Text, mentions, reactions, contacts
377
+
378
+ ```javascript
379
+ await sock.sendMessage(jid, { text: 'Hello there!' })
380
+
381
+ await sock.sendMessage(jid, {
382
+ text: 'Hi @948123456789',
383
+ mentions: ['948123456789@s.whatsapp.net']
384
+ }, { quoted: m, ephemeralExpiration: 86400 })
385
+
386
+ await sock.sendMessage(jid, { react: { text: '๐Ÿ‘', key: m.key } })
387
+
388
+ await sock.sendMessage(jid, {
389
+ contacts: {
390
+ contacts: [{
391
+ displayName: 'DanuZz',
392
+ vcard: 'BEGIN:VCARD\nVERSION:3.0\nFN:DanuZz\nTEL;type=CELL:+948123456789\nEND:VCARD'
393
+ }]
394
+ }
395
+ })
396
+ ```
397
+
398
+ ### Media
399
+
400
+ ```javascript
401
+ await sock.sendMessage(jid, { image: { url: './photo.jpg' }, caption: 'Nice view' })
402
+ await sock.sendMessage(jid, { video: { url: './clip.mp4' }, caption: 'Clip', gifPlayback: false })
403
+ await sock.sendMessage(jid, { audio: { url: './voice.ogg' }, ptt: true })
404
+ await sock.sendMessage(jid, { document: { url: './file.pdf' }, mimetype: 'application/pdf', fileName: 'file.pdf' })
405
+ await sock.sendMessage(jid, { sticker: { url: './sticker.webp' } })
406
+ ```
407
+
408
+ **Wrappers and albums**
409
+
410
+ ```javascript
411
+ await sock.sendMessage(jid, { image: { url: './photo.jpg' }, viewOnce: true }) // view once
412
+ await sock.sendMessage(jid, { video: { url: './clip.mp4' }, ptv: true }) // video note
413
+ await sock.sendMessage(jid, { image: { url: './surprise.jpg' }, caption: 'Peekaboo', spoiler: true }) // spoiler
414
+
415
+ await sock.sendMessage(jid, {
416
+ album: [
417
+ { image: { url: './1.jpg' } },
418
+ { image: { url: './2.jpg' } },
419
+ { video: { url: './clip.mp4' } }
420
+ ]
421
+ })
422
+ ```
423
+
424
+ ### Stickers & sticker packs
425
+
426
+ **Single sticker**
427
+
428
+ ```javascript
429
+ await sock.sendMessage(jid, { sticker: { url: './sticker.webp' } })
430
+ ```
431
+
432
+ #### ๐Ÿ“ฆ Sticker Pack
433
+
434
+ > [!IMPORTANT]
435
+ > If `sharp` or `@napi-rs/image` is not installed, the `cover` and `stickers` must already be in WebP format.
436
+
437
+ ```javascript
438
+ await sock.sendMessage(jid, {
439
+ cover: {
440
+ url: './path/to/image.webp'
441
+ },
442
+ stickers: [
443
+ {
444
+ data: {
445
+ url: './path/to/image.webp'
446
+ }
447
+ },
448
+ {
449
+ data: {
450
+ url: './path/to/image.webp'
451
+ }
452
+ },
453
+ {
454
+ data: {
455
+ url: './path/to/image.webp'
456
+ }
457
+ }
458
+ ],
459
+ name: '๐Ÿ“ฆ My Sticker Pack',
460
+ publisher: 'DanuZz',
461
+ description: 'Optional pack description'
462
+ })
463
+ ```
464
+
465
+ **Sticker pack options**
466
+
467
+ | Property | Type | Description |
468
+ |---|---|---|
469
+ | `cover` | `{ url: string }` \| `Buffer` | **Required.** The pack tray icon / cover image |
470
+ | `stickers` | `Array<{ data: { url } \| Buffer, emojis?: string[] }>` | **Required.** List of stickers (up to 60 stickers) |
471
+ | `name` | `string` | Name of the sticker pack (e.g. `'๐Ÿ“ฆ My Sticker Pack'`) |
472
+ | `publisher` | `string` | Author / publisher name (e.g. `'DanuZz'`) |
473
+ | `description` | `string` | Optional description of the pack |
474
+
475
+
476
+ ### Location & events
477
+
478
+ ```javascript
479
+ await sock.sendMessage(jid, {
480
+ location: { degreesLatitude: -6.2088, degreesLongitude: 106.8456, name: 'Monas' }
481
+ })
482
+
483
+ await sock.sendMessage(jid, {
484
+ event: {
485
+ name: 'Team Sync',
486
+ description: 'Discuss the Q1 roadmap',
487
+ startDate: new Date(Date.now() + 3600_000)
488
+ }
489
+ })
490
+ ```
491
+
492
+ ### Polls
493
+
494
+ ```javascript
495
+ // Fluent Poll builder
496
+ await sock.poll()
497
+ .name('Favorite language?')
498
+ .options(['JavaScript', 'Python', 'Rust'])
499
+ .multiSelect(1)
500
+ .send(jid)
501
+
502
+ // Quiz polls: newsletters or channels, require correctAnswer
503
+ await sock.sendMessage(newsletterJid, {
504
+ poll: { name: 'Capital of Japan?', values: ['Tokyo', 'Osaka'], pollType: 1, correctAnswer: 'Tokyo' }
505
+ })
506
+
507
+ // Add an option to an existing poll
508
+ await sock.sendMessage(jid, {
509
+ pollAddOption: {
510
+ pollMessageKey: pollKey,
511
+ optionName: 'Go'
512
+ }
513
+ })
514
+
515
+ // Poll result snapshot
516
+ await sock.sendMessage(jid, {
517
+ pollResultMessage: {
518
+ name: 'Favorite language?',
519
+ pollVotes: [{ optionName: 'JavaScript', optionVoteCount: 12 }, { optionName: 'Python', optionVoteCount: 9 }]
520
+ }
521
+ })
522
+ ```
523
+
524
+ ### Comments
525
+
526
+ Target newsletter messages or status updates:
527
+
528
+ ```javascript
529
+ await sock.sendMessage(newsletterJid, {
530
+ comment: 'Great news!',
531
+ parentMessageKey: targetMessageKey
532
+ })
533
+ ```
534
+
535
+ ### Fake Quoted Messages & Mimic
536
+
537
+ Create realistic fake quoted previews or relay messages as another participant:
538
+
539
+ ```javascript
540
+ import { createFakeQuoted } from '@nomo/ballieys'
541
+
542
+ // Create a fake quoted message structure
543
+ const fakeQuoted = createFakeQuoted('Hey there, this was quoted!', {
544
+ participant: '1234567890@s.whatsapp.net',
545
+ pushName: 'Alice'
546
+ })
547
+
548
+ await sock.sendMessage(jid, { text: 'Reply to quote' }, { quoted: fakeQuoted })
549
+
550
+ // sendAsMimic (admin mode)
551
+ await sock.sendAsMimic(jid, { text: 'Simulated admin announcement' }, '1234567890@s.whatsapp.net', { admin: true })
552
+ ```
553
+
554
+ ### Status & Stories
555
+
556
+ ```javascript
557
+ // Send status update with specific audience
558
+ await sock.sendStatus({ text: 'Hello Status!' }, {
559
+ statusJidList: [contactJid1, contactJid2]
560
+ })
561
+
562
+ // Send status mention to a user in a chat
563
+ await sock.sendStatusMentions(chatJid, {
564
+ image: { url: 'https://example.com/story.jpg' },
565
+ mentions: targetUserJid
566
+ })
567
+ ```
568
+
569
+ ### Chat Theme Setting
570
+
571
+ Set preset chat themes or custom solid background/bubble colors for chats and groups:
572
+
573
+ ```javascript
574
+ import { CHAT_THEMES } from '@nomo/ballieys'
575
+
576
+ // Set a preset theme using the helper
577
+ await sock.setChatTheme(jid, 'Default-Blue@Minimal')
578
+
579
+ // Available preset theme IDs:
580
+ // 'Default-Blue@Minimal'
581
+ // 'Default-Blue@Tonal@Minimal'
582
+ // 'Emerald@Minimal'
583
+ // 'Emerald@Tonal@Minimal'
584
+ // 'Pink@Minimal'
585
+ // 'Red@Minimal'
586
+ // 'Royal-Blue@Minimal'
587
+ // 'Tyrian-Purple@Minimal'
588
+ // 'WhatsApp-Green@Minimal'
589
+
590
+ // Or set custom solid color background & doodle for groups/chats
591
+ await sock.setChatThemeColor(jid, {
592
+ backgroundLightArgb: 0xFFFF0000,
593
+ backgroundDarkArgb: 0xFFFF0000,
594
+ isDoodleEnabled: false
595
+ })
596
+
597
+ // Or relay directly via protocolMessage:
598
+ await sock.relayMessage(jid, {
599
+ protocolMessage: {
600
+ type: 34,
601
+ chatThemeSetting: {
602
+ settingTimestampMs: Date.now(),
603
+ colorSchemeId: 'Default-Blue@Minimal'
604
+ }
605
+ }
606
+ }, {
607
+ additionalAttributes: {
608
+ type: 'media'
609
+ }
610
+ })
611
+ ```
612
+
613
+ ### Device Targeting & Stealth Delivery
614
+
615
+ Control exact device fanout and recipient delivery:
616
+
617
+ ```javascript
618
+ const message = { conversation: 'hey' }
619
+
620
+ // 1. participant โ€” Send ONLY to the target's devices, skipping your own (recipient-only, no "waiting" on your side):
621
+ await sock.relayMessage(jid, message, { participant: { jid } })
622
+
623
+ // 2. isSecret โ€” Send ONLY to the target's primary (main) phone device:
624
+ await sock.relayMessage(jid, message, { isSecret: true })
625
+
626
+ // 3. protected โ€” Send to everything EXCEPT the target's linked (secondary/web) devices:
627
+ await sock.relayMessage(jid, message, { protected: true })
628
+ ```
629
+
630
+
631
+ ## ๐ŸŽ›๏ธ Interactive Messages
632
+
633
+ ### Native flow buttons
634
+
635
+ ```javascript
636
+ await sock.sendMessage(jid, {
637
+ text: 'Choose one:',
638
+ footer: 'DanuZz',
639
+ nativeFlow: [
640
+ { text: '๐Ÿ‘‹๐Ÿป Yes', id: 'yes_1' },
641
+ { text: '๐Ÿ“ž Call', call: '948123456789' },
642
+ { text: '๐Ÿ“‹ Copy', copy: 'PROMO123' },
643
+ { text: '๐ŸŒ Source', url: 'https://example.com' },
644
+ {
645
+ text: '๐Ÿ“‹ Select',
646
+ sections: [{ title: 'โœจ Section 1', rows: [{ title: '๐Ÿท๏ธ Coupon', id: 'coupon_code' }] }]
647
+ }
648
+ ]
649
+ })
650
+ ```
651
+
652
+ With a media header, use `caption` instead of `text` (works with image, video, document, location, product):
653
+
654
+ ```javascript
655
+ await sock.sendMessage(jid, {
656
+ image: { url: './promo.jpg' },
657
+ title: 'Flash Sale',
658
+ caption: 'Up to 50% off today only',
659
+ footer: 'DanuZz',
660
+ nativeFlow: [
661
+ { text: 'Shop Now', url: 'https://shop.example.com' },
662
+ { text: 'Copy Code', copy: 'SALE50' }
663
+ ]
664
+ })
665
+ ```
666
+
667
+ ### Carousel
668
+
669
+ Card headers can be an image, a video or a product.
670
+
671
+ ```javascript
672
+ await sock.sendMessage(jid, {
673
+ text: 'Check out our new arrivals:',
674
+ footer: 'DanuZz',
675
+ cards: [
676
+ { image: { url: './item-a.jpg' }, title: 'Item A', caption: 'New in stock', nativeFlow: [{ text: 'View', id: 'view_a' }] },
677
+ { video: { url: './item-b.mp4' }, title: 'Item B', caption: 'Limited edition', nativeFlow: [{ text: 'View', id: 'view_b' }] },
678
+ {
679
+ businessOwnerJid: '1234567890@s.whatsapp.net',
680
+ product: { title: 'Wireless Mouse', productImage: { url: './mouse.png' } },
681
+ title: 'Wireless Mouse',
682
+ caption: '$19.99',
683
+ nativeFlow: [{ text: 'Buy Now', id: 'buy_mouse' }]
684
+ }
685
+ ]
686
+ })
687
+ ```
688
+
689
+ ### Widgets (A2UI)
690
+
691
+ Combine with buttons, or pass `nativeFlow: []` for none.
692
+
693
+ ```javascript
694
+ await sock.sendMessage(jid, {
695
+ text: 'Widget demo',
696
+ footer: 'A2UI Showcase',
697
+ nativeFlow: [{ text: '๐ŸŒ Source', url: 'https://example.com' }],
698
+ widget: {
699
+ align: 'center',
700
+ fallback: 'Widget cannot be loaded on this device', // optional
701
+ items: [
702
+ { text: 'Welcome to the Widget Demo', variant: 'title' }, // title | body | caption
703
+ { text: 'This is a longer description.', variant: 'body' },
704
+
705
+ { icon: 'info' },
706
+ { icon: 'warning', style: 'symbol' },
707
+ { icon: 'favorite', native: true },
708
+
709
+ { image: 'https://example.com/banner.jpg', variant: 'header', fit: 'cover', description: 'Promo banner' },
710
+ { video: 'https://example.com/preview.mp4' },
711
+ { audio: 'https://example.com/audio.mp3', description: 'Listen to this audio' },
712
+
713
+ { divider: 'horizontal' }, // or 'vertical'
714
+ { button: 'Open Website', url: 'https://example.com', variant: 'primary' },
715
+
716
+ { input: 'name', label: 'Enter your name', value: '', variant: 'shortText' }, // or 'longText'
717
+ { input: 'email', label: 'Email', validationRegexp: '^[^@]+@[^@]+\\.[^@]+$' },
718
+ { checkbox: 'I agree to the terms & conditions', value: false },
719
+ { choice: ['Red', 'Green', 'Blue'], label: 'Favorite color', variant: 'mutuallyExclusive', displayStyle: 'chips', filterable: true },
720
+ { choice: [{ label: 'Option A', value: 'a' }, { label: 'Option B', value: 'b' }], label: 'Multi-select', variant: 'multipleSelection', value: ['a'] },
721
+ { slider: 100, min: 0, value: 50, label: 'Volume' }, // slider = max value
722
+ { datetime: true, label: 'Pick a date', enableDate: true, enableTime: false },
723
+
724
+ { row: [{ text: 'Left' }, { text: 'Center' }, { text: 'Right' }], justify: 'space-between', align: 'center' },
725
+ { column: [{ text: 'Row 1' }, { text: 'Row 2' }], justify: 'start', align: 'stretch' },
726
+ { list: [{ text: 'โ€ข First item' }, { text: 'โ€ข Second item' }], direction: 'vertical' }
727
+ ]
728
+ }
729
+ })
730
+ ```
731
+
732
+ ### Legacy template buttons
733
+
734
+ Old format. Prefer `nativeFlow`.
735
+
736
+ ```javascript
737
+ await sock.sendMessage(jid, {
738
+ text: 'Choose one:',
739
+ footer: 'DanuZz',
740
+ templateButtons: [
741
+ { text: 'Reply', id: 'r1' },
742
+ { text: 'Visit', url: 'https://example.com' },
743
+ { text: 'Call', call: '+948123456789' }
744
+ ]
745
+ })
746
+ ```
747
+
748
+ ### Simulated replies
749
+
750
+ Send a reply as if a user tapped a button or list row.
751
+
752
+ ```javascript
753
+ await sock.sendMessage(jid, { buttonReply: { id: 'yes_1', displayText: 'Yes' }, type: 'plain' })
754
+ await sock.sendMessage(jid, { listReply: { id: 'row1', title: 'Row 1', description: 'desc' } })
755
+ await sock.sendMessage(jid, { flowReply: { name: 'single_select', paramsJson: JSON.stringify({ id: 'row1' }) } })
756
+ ```
757
+
758
+
759
+ ## ๐Ÿค– AI Rich Messages
760
+
761
+ Build structured rich responses with a chainable builder.
762
+
763
+ ```javascript
764
+ await sock.aiRich()
765
+ .setTitle('Ai Rich Message')
766
+ .addText('[HyperLink](https://example.com)\nCitation [](https://example.com)')
767
+ .addImage('https://example.com/image.png')
768
+ .addCode('javascript', `console.log('Hello World')`)
769
+ .addHtml(['<html>Hello world</html>', 'Tab 1'], ['<html>Hi twin</html>', 'Tab 2'])
770
+ .addTable([
771
+ ['Name', 'DanuZz'],
772
+ ['Bio', 'Im developer'],
773
+ ['Age', '67']
774
+ ])
775
+ .addSource([['https://example.com/favicon.ico', 'https://example.com', 'Source']])
776
+ .addTip('Tip Text')
777
+ .addSuggest(['Continue', 'Cancel'])
778
+ .send(jid, { quoted: m })
779
+ ```
780
+
781
+ ```javascript
782
+ // Animated progress indicator
783
+ await sock.aiRich().addProcess('Loading...').send(jid)
784
+
785
+ // Shorthand without the builder
786
+ await sock.sendMessage(jid, {
787
+ aiRich: { title: 'Assistant', text: 'Here is what I found:', table: [['Name', 'Score'], ['Alice', '90']] }
788
+ })
789
+ ```
790
+
791
+ > **Bypass download** is on by default for both `send()` and `sendMessage(jid, { aiRich })`. The message edits itself right after sending so the client renders it without downloading first. Pass `bypassDownload: false` to turn it off. If the edit fails, the thrown error has `error.relayedKey` set to the key of the message that was already sent.
792
+
793
+ <details>
794
+ <summary><b>Builder method reference</b></summary>
795
+
796
+ | Method | Purpose |
797
+ |---|---|
798
+ | `setTitle(title)` | Disclaimer label shown on the message |
799
+ | `setFooter(footer)` | Trailing metadata text block |
800
+ | `setContextInfo(obj)` | Merge extra fields into `contextInfo` |
801
+ | `addText(text, opts?)` | Markdown text. Extracts `[text](url)` links, `[](url)` citations, `[text\|w\|h](<url>)` LaTeX |
802
+ | `addCode(language, code)` | Syntax-highlighted code block |
803
+ | `addTable(rows, opts?)` | `[[header...], [row...], ...]` array of strings |
804
+ | `addImage(image)` | `string \| Buffer \| array`, shown as a grid |
805
+ | `addVideo(video)` | `string \| Buffer \| { url, mimeType?, duration? } \| array` |
806
+ | `addSource(sources)` | `[icon, url, text][]` source cards |
807
+ | `addProduct(data)` | Product card, or an array for a carousel |
808
+ | `addPost(data)` | Social-post card, or an array for a carousel |
809
+ | `addReels(data)` | Reel card, or an array |
810
+ | `addTip(text)` | Small tip line |
811
+ | `addSuggest(suggestion, opts?)` | Follow-up suggestion pill |
812
+ | `addProcess(title)` | In-progress status indicator |
813
+ | `addHtml(...)` | One inline HTML block, or `[html, title]` tab pairs |
814
+ | `build(opts?)` | Build the raw content without sending |
815
+ | `buildEdit(jid, key, message)` | Build the edit payload used by bypass download |
816
+ | `send(jid, opts?)` | Send it. `opts.bypassDownload` (default `true`) sends the follow-up edit, other options go to `sendMessage` |
817
+
818
+ </details>
819
+
820
+
821
+ ## ๐Ÿ›๏ธ Commerce & Payments
822
+
823
+ ```javascript
824
+ // Product message
825
+ await sock.sendMessage(jid, {
826
+ businessOwnerJid: '1234567890@s.whatsapp.net',
827
+ image: { url: './mouse.png' },
828
+ product: {
829
+ title: 'Wireless Mouse',
830
+ description: 'Ergonomic, 2.4GHz',
831
+ currencyCode: 'USD',
832
+ priceAmount1000: 19990, // $19.99
833
+ retailerId: 'sku-001'
834
+ }
835
+ })
836
+
837
+ // Payments
838
+ await sock.sendMessage(jid, { requestPaymentFrom: recipientJid, text: 'Payment for order #123' })
839
+ await sock.sendMessage(jid, { paymentInviteServiceType: 1 })
840
+ await sock.sendMessage(jid, { orderText: 'Your order summary', thumbnail: fs.readFileSync('./order-thumb.jpg') })
841
+ await sock.sendMessage(jid, { document: { url: './invoice.pdf' }, mimetype: 'application/pdf', invoiceNote: 'Invoice #1024' })
842
+ ```
843
+
844
+ ### Extras
845
+
846
+ ```javascript
847
+ // Sponsored ad card on any message
848
+ await sock.sendMessage(jid, {
849
+ text: 'Check this deal!',
850
+ externalAdReply: {
851
+ title: 'Big Sale',
852
+ body: '50% off',
853
+ thumbnail: fs.readFileSync('./thumb.jpg'),
854
+ mediaType: 1,
855
+ url: 'https://example.com'
856
+ }
857
+ })
858
+
859
+ // Phone number requests
860
+ await sock.sendMessage(jid, { requestPhoneNumber: true })
861
+ await sock.sendMessage(jid, { sharePhoneNumber: true })
862
+
863
+ // Group invite card
864
+ await sock.sendMessage(jid, {
865
+ groupInvite: { jid: groupJid, inviteCode: code, inviteExpiration: Date.now() + 3600_000, subject: 'My Group', text: 'Join us!' }
866
+ })
867
+
868
+ // Disable forwarding
869
+ await sock.sendMessage(jid, { limitSharing: true })
870
+ ```
871
+
872
+
873
+ ## ๐Ÿ” Check Number Status
874
+
875
+ Check whether a phone number is registered on WhatsApp, if it is banned, requires the official WhatsApp client, or get ban appeal status:
876
+
877
+ ```javascript
878
+ import { checkStatusWA } from '@nomo/ballieys'
879
+
880
+ // Standalone check (no socket connection required)
881
+ const result = await checkStatusWA('+1234567890')
882
+ console.log(result)
883
+ // {
884
+ // number: '+1234567890',
885
+ // status: 'banned',
886
+ // isBanned: true,
887
+ // isNeedOfficialWa: false,
888
+ // banInfo: {
889
+ // banType: 'PERMANENT',
890
+ // violationType: 'SPAM',
891
+ // canAppeal: true,
892
+ // appealToken: '...'
893
+ // }
894
+ // }
895
+
896
+ // Or call directly from the socket instance
897
+ const info = await sock.checkStatusWA('+1234567890')
898
+ ```
899
+
900
+
901
+ ## ๐Ÿ”’ Privacy Controls & Spam Reporting
902
+
903
+ Comprehensive privacy settings management and native spam reporting:
904
+
905
+ ```javascript
906
+ // Privacy settings
907
+ await sock.updateLastSeenPrivacy('all') // 'all' | 'contacts' | 'contact_blacklist' | 'none'
908
+ await sock.updateOnlinePrivacy('all') // 'all' | 'match_last_seen'
909
+ await sock.updateProfilePicturePrivacy('all')
910
+ await sock.updateStatusPrivacy('all')
911
+ await sock.updateReadReceiptsPrivacy('all') // 'all' | 'none'
912
+ await sock.updateGroupsAddPrivacy('all') // 'all' | 'contacts' | 'contact_blacklist'
913
+ await sock.updateDefaultDisappearingMode(86400) // 24h (or 604800 for 7d, 7776000 for 90d, 0 for off)
914
+
915
+ // Spam reporting with optional block & delete
916
+ await sock.reportSpam(spammerJid, {
917
+ reason: 'spam', // 'spam' | 'inappropriate' | 'offensive'
918
+ block: true,
919
+ deleteChat: true
920
+ })
921
+ ```
922
+
923
+
924
+ ## ๐Ÿ“ข Newsletter / Channels
925
+
926
+ Full CRUD, admin management, status publishing, discovery, and reactions:
927
+
928
+ ```javascript
929
+ // Create a channel
930
+ const channel = await sock.newsletterCreate('My Channel', 'Official Channel description')
931
+
932
+ // Channel metadata & settings
933
+ const meta = await sock.newsletterMetadata('jid', channel.id)
934
+ await sock.newsletterUpdateName(channel.id, 'New Channel Name')
935
+ await sock.newsletterUpdateDescription(channel.id, 'Updated description')
936
+ await sock.newsletterUpdateReactions(channel.id, 'ALL') // 'ALL' | 'BASIC' | 'NONE'
937
+
938
+ // Admin invites & roles
939
+ await sock.newsletterCreateAdminInvite(channel.id, userJid)
940
+ await sock.newsletterAdminPromote(channel.id, userJid)
941
+ await sock.newsletterDemote(channel.id, userJid)
942
+
943
+ // Reactions & poll votes
944
+ await sock.newsletterReactMessage(channel.id, serverId, '๐Ÿ”ฅ')
945
+ await sock.newsletterBulkReactions(channel.id, serverId, ['โค๏ธ', '๐Ÿ”ฅ', '๐Ÿ‘'], 10)
946
+ await sock.newsletterSendPollVote(channel.id, serverId, 'Option A')
947
+
948
+ // Publish channel status & stories
949
+ await sock.newsletterSendStatus(channel.id, { text: 'Channel announcement!' })
950
+
951
+ // Directory search & discovery
952
+ const list = await sock.newsletterDirectoryList({ limit: 20 })
953
+ const search = await sock.newsletterDirectorySearch('tech', { limit: 10 })
954
+ ```
955
+
956
+
957
+ ## ๐Ÿ—๏ธ Fluent Message Builders
958
+
959
+ Build complex WhatsApp message payloads cleanly with fluent builders:
960
+
961
+ ```javascript
962
+ import { Button, Interactive, Carousel, Album, Poll, Event, A2UI } from '@nomo/ballieys'
963
+
964
+ // Button builder
965
+ new Button(sock)
966
+ .setBody('Choose an option')
967
+ .reply('Option 1', 'opt_1')
968
+ .url('Visit Website', 'https://example.com')
969
+ .call('Call Us', '+1234567890')
970
+ .send(jid)
971
+
972
+ // Album builder (multi-media grouping)
973
+ await sock.album()
974
+ .image('https://example.com/img1.jpg', 'Photo 1')
975
+ .image('https://example.com/img2.jpg', 'Photo 2')
976
+ .video('https://example.com/video.mp4', 'Clip')
977
+ .send(jid)
978
+
979
+ // Event builder
980
+ await sock.event()
981
+ .setName('Community Meetup')
982
+ .setDescription('Annual developer meetup')
983
+ .setStartTime(new Date(Date.now() + 86400000))
984
+ .setLocation({ name: 'Tech Hub', degreesLatitude: 40.7128, degreesLongitude: -74.0060 })
985
+ .send(jid)
986
+ ```
987
+
988
+
989
+ ## ๐Ÿ“ž Calls
990
+
991
+ Calls need `ffmpeg` and `ffprobe` in `PATH`. Create **one `Voip` per socket** after it opens. After a reconnect you get a new socket, so create a new `Voip`.
992
+
993
+ ### Start a call
994
+
995
+ ```javascript
996
+ import Voip from '@nomo/ballieys/voip'
997
+
998
+ const voip = new Voip(sock, {
999
+ ffprobePath: 'ffprobe',
1000
+ voipLogLevel: 'warn', // trace | debug | info | warn | error
1001
+ tmpDir: './tmp', // temp folder for downloads
1002
+ maxConcurrentCalls: 1
1003
+ })
1004
+
1005
+ const call = await voip.call('948123456789', './song.mp3')
1006
+ await call.hangup() // or call.end()
1007
+
1008
+ await voip.call('948123456789') // ring only, no media
1009
+ ```
1010
+
1011
+ ### Media, video & playlists
1012
+
1013
+ ```javascript
1014
+ await voip.call(jid, './song.mp3') // local file
1015
+ await voip.call(jid, 'https://example.com/song.mp3') // URL, downloaded first
1016
+ await voip.call(jid, { audio: './voice.ogg' })
1017
+ await voip.call(jid, './clip.mp4', '720p') // video call
1018
+
1019
+ await voip.call(
1020
+ jid,
1021
+ ['./intro.mp3', './clip.mp4', 'https://example.com/outro.mp3'],
1022
+ '480p',
1023
+ {
1024
+ loop: false, // repeat the playlist
1025
+ autoEndCall: true, // hang up when the playlist ends
1026
+ autoDowngrade: true // drop to audio when the peer turns every camera off
1027
+ }
1028
+ )
1029
+ ```
1030
+
1031
+ | Item | Supported |
1032
+ |---|---|
1033
+ | Audio formats | `mp3` `ogg` `opus` `wav` `m4a` `aac` `flac` `weba` |
1034
+ | Video formats | `mp4` `mov` `webm` `mkv` `avi` `m4v` `3gp` |
1035
+ | Download limits | Audio 20 MB, video 50 MB |
1036
+ | Resolution | `'240p'` `'360p'` `'480p'` `'720p'` `'1080p'` or `{ width, height, frameRate }` (default 480p, portrait is rotated automatically) |
1037
+ | `jid` | A number or a JID, non-digits are stripped |
1038
+
1039
+ ### In-call controls
1040
+
1041
+ ```javascript
1042
+ await call.silent(true) // silence audio (false = resume, no arg = toggle)
1043
+ console.log(call.isSilenced)
1044
+
1045
+ call.mute(true) // mic only
1046
+ call.raiseHand(true)
1047
+ call.react('๐Ÿ‘') // returns false if not connected yet
1048
+ await call.shareScreen(true) // needs video, 1:1 only
1049
+ await call.shareScreen(false)
1050
+
1051
+ const result = await call.upgradeToVideo()
1052
+ // 'accepted' | 'rejected' | 'rejected_by_timeout' | 'error' | 'timeout' | 'cancelled'
1053
+ ```
1054
+
1055
+ > `shareScreen` only tells the peer a screen is being shared. The picture is whatever you feed to `voip.coordinator.feedLiveVideo()`.
1056
+
1057
+ ### Call events
1058
+
1059
+ ```javascript
1060
+ call.on('ringing', () => {})
1061
+ call.on('connected', () => {})
1062
+ call.on('ended', reason => {}) // 'connection_closed' if the socket drops
1063
+ call.on('error', err => {})
1064
+
1065
+ call.on('item', ({ index, kind, source }) => {})
1066
+ call.on('playlist_looped', () => {})
1067
+ call.on('playlist_ended', () => {})
1068
+ call.on('downgraded', () => {}) // video dropped to audio
1069
+ call.on('silent', state => {})
1070
+
1071
+ call.on('peer_mute', muted => {})
1072
+ call.on('hand_raise', ({ jid, raised }) => {})
1073
+ call.on('reaction', reaction => {})
1074
+ call.on('screen_share', share => {})
1075
+ call.on('peer_video', change => {})
1076
+ call.on('inbound_audio', pcm => {}) // Float32Array, 16 kHz mono, 60 ms
1077
+ call.on('inbound_video', frame => {}) // decoded H.264 frame
1078
+ call.on('audio_finished', () => {}) // current audio item reached its end
1079
+ ```
1080
+
1081
+ ### Incoming calls
1082
+
1083
+ ```javascript
1084
+ await voip.listen() // register call handlers, safe to call twice
1085
+
1086
+ voip.on('call_incoming', async call => {
1087
+ console.log('incoming from', call.peerJid, call.callId)
1088
+ await voip.acceptCall(call.callId)
1089
+ })
1090
+
1091
+ voip.on('call_inbound_audio', ({ call, pcm }) => {})
1092
+ voip.on('call_ended', call => console.log('ended', call.callId))
1093
+
1094
+ await voip.rejectCall(callId)
1095
+ await voip.hangup(callId)
1096
+ ```
1097
+
1098
+ Available `voip` events: `call_incoming`, `call_state`, `call_ended`, `call_peer_mute`, `call_inbound_audio`, `call_inbound_video`, `call_hand_raise`, `call_reaction`, `call_screen_share`, `call_peer_video_state`, `call_outbound_audio_finished`, `call_error`.
1099
+
1100
+ `voip.coordinator` is the raw engine (`feedLiveAudio`, `feedLiveVideo`, `setExternalAudioMode`, ...).
1101
+
1102
+ ### Multi-call
1103
+
1104
+ ```javascript
1105
+ const voip = new Voip(sock, { maxConcurrentCalls: 3 })
1106
+
1107
+ const a = await voip.call('948111111111', './song.mp3')
1108
+ const b = await voip.call('948222222222', './song.mp3')
1109
+
1110
+ // Many numbers at once
1111
+ const results = await voip.callMany(
1112
+ ['948111111111', '948222222222', '948333333333'],
1113
+ './song.mp3'
1114
+ )
1115
+
1116
+ for (const { jid, call, error } of results) {
1117
+ if (error) { console.log(jid, 'failed:', error.message); continue }
1118
+ call.on('ended', reason => console.log(jid, 'ended:', reason))
1119
+ call.on('error', err => console.error(jid, err))
1120
+ }
1121
+
1122
+ voip.calls // active calls
1123
+ voip.calls[0].callId
1124
+ voip.calls[0].target // dialed number
1125
+ await voip.hangup(callId) // end one call
1126
+ await voip.end() // end all calls
1127
+ await voip.end(true) // only release the slots
1128
+ ```
1129
+
1130
+ - `maxConcurrentCalls` defaults to `1`. Each call gets its own relay, codec and audio.
1131
+ - Incoming calls count toward the limit.
1132
+ - Going over the limit throws `Maximum concurrent calls reached`. In `callMany()` it is returned as `error` for that number and the rest still go through.
1133
+ - `callMany()` accepts the same media and options as `call()` and dials duplicate numbers once.
1134
+ - A safety timeout emits `error` if a call never ends (starts at 105 s).
1135
+
1136
+
1137
+ ## ๐Ÿ™ Credits
1138
+
1139
+ This library is built on the original **[Baileys](https://github.com/WhiskeySockets/Baileys)** by **[@WhiskeySockets](https://github.com/WhiskeySockets)**.
1140
+
1141
+ Thanks to the Baileys maintainers and contributors:
1142
+ [purpshell](https://github.com/purpshell) ยท [jlucaso1](https://github.com/jlucaso1) ยท [adiwajshing](https://github.com/adiwajshing)
1143
+
1144
+ Protocol Buffer definitions come from [`wa-proto`](https://github.com/wppconnect-team/wa-proto) by [WPP Connect](https://github.com/wppconnect-team).
1145
+
1146
+ Runtime, calls, AI rich, widgets, payments and storage code by [DanuZz](https://danuzz.movanest.xyz) (@dnuzi/baileys, MIT). Button helpers, command router, call auto answer and packaging by Anuhas Bandara. See `NOTICE.md`.
1147
+
1148
+
1149
+ ## ๐Ÿ“„ License
1150
+
1151
+ MIT. Copyright notices of every author are in the `LICENSE` file.
1152
+