@gara31/void-baileys 7.0.0-rc.14

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/index.js +117292 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.js +116 -0
  5. package/lib/Signal/Group/ciphertext-message.js +12 -0
  6. package/lib/Signal/Group/group-session-builder.js +42 -0
  7. package/lib/Signal/Group/group_cipher.js +109 -0
  8. package/lib/Signal/Group/index.js +12 -0
  9. package/lib/Signal/Group/keyhelper.js +18 -0
  10. package/lib/Signal/Group/sender-chain-key.js +32 -0
  11. package/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  12. package/lib/Signal/Group/sender-key-message.js +80 -0
  13. package/lib/Signal/Group/sender-key-name.js +50 -0
  14. package/lib/Signal/Group/sender-key-record.js +47 -0
  15. package/lib/Signal/Group/sender-key-state.js +105 -0
  16. package/lib/Signal/Group/sender-message-key.js +30 -0
  17. package/lib/Signal/libsignal.js +416 -0
  18. package/lib/Signal/lid-mapping.js +189 -0
  19. package/lib/Socket/Client/index.js +3 -0
  20. package/lib/Socket/Client/types.js +11 -0
  21. package/lib/Socket/Client/websocket.js +61 -0
  22. package/lib/Socket/business.js +404 -0
  23. package/lib/Socket/chats.js +1146 -0
  24. package/lib/Socket/communities.js +505 -0
  25. package/lib/Socket/groups.js +404 -0
  26. package/lib/Socket/index.js +18 -0
  27. package/lib/Socket/messages-recv.js +1600 -0
  28. package/lib/Socket/messages-send.js +1203 -0
  29. package/lib/Socket/mex.js +56 -0
  30. package/lib/Socket/newsletter.js +240 -0
  31. package/lib/Socket/socket.js +1060 -0
  32. package/lib/Types/Auth.js +2 -0
  33. package/lib/Types/Bussines.js +2 -0
  34. package/lib/Types/Call.js +2 -0
  35. package/lib/Types/Chat.js +8 -0
  36. package/lib/Types/Contact.js +2 -0
  37. package/lib/Types/Events.js +2 -0
  38. package/lib/Types/GroupMetadata.js +2 -0
  39. package/lib/Types/Label.js +25 -0
  40. package/lib/Types/LabelAssociation.js +7 -0
  41. package/lib/Types/Message.js +11 -0
  42. package/lib/Types/Newsletter.js +31 -0
  43. package/lib/Types/Product.js +2 -0
  44. package/lib/Types/Signal.js +2 -0
  45. package/lib/Types/Socket.js +3 -0
  46. package/lib/Types/State.js +13 -0
  47. package/lib/Types/USync.js +2 -0
  48. package/lib/Types/index.js +32 -0
  49. package/lib/Utils/auth-utils.js +276 -0
  50. package/lib/Utils/browser-utils.js +32 -0
  51. package/lib/Utils/business.js +262 -0
  52. package/lib/Utils/chat-utils.js +941 -0
  53. package/lib/Utils/crypto.js +179 -0
  54. package/lib/Utils/decode-wa-message.js +333 -0
  55. package/lib/Utils/event-buffer.js +580 -0
  56. package/lib/Utils/generics.js +436 -0
  57. package/lib/Utils/history.js +103 -0
  58. package/lib/Utils/index.js +19 -0
  59. package/lib/Utils/link-preview.js +99 -0
  60. package/lib/Utils/logger.js +3 -0
  61. package/lib/Utils/lt-hash.js +56 -0
  62. package/lib/Utils/make-mutex.js +38 -0
  63. package/lib/Utils/message-retry-manager.js +181 -0
  64. package/lib/Utils/messages-media.js +727 -0
  65. package/lib/Utils/messages.js +1309 -0
  66. package/lib/Utils/noise-handler.js +162 -0
  67. package/lib/Utils/pre-key-manager.js +125 -0
  68. package/lib/Utils/process-message.js +594 -0
  69. package/lib/Utils/signal.js +194 -0
  70. package/lib/Utils/use-multi-file-auth-state.js +118 -0
  71. package/lib/Utils/validate-connection.js +240 -0
  72. package/lib/WABinary/constants.js +1301 -0
  73. package/lib/WABinary/decode.js +240 -0
  74. package/lib/WABinary/encode.js +216 -0
  75. package/lib/WABinary/generic-utils.js +104 -0
  76. package/lib/WABinary/index.js +6 -0
  77. package/lib/WABinary/jid-utils.js +95 -0
  78. package/lib/WABinary/types.js +2 -0
  79. package/lib/WAM/BinaryInfo.js +10 -0
  80. package/lib/WAM/constants.js +22863 -0
  81. package/lib/WAM/encode.js +152 -0
  82. package/lib/WAM/index.js +4 -0
  83. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  84. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +59 -0
  85. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  86. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +36 -0
  87. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +60 -0
  88. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  89. package/lib/WAUSync/Protocols/index.js +5 -0
  90. package/lib/WAUSync/USyncQuery.js +104 -0
  91. package/lib/WAUSync/USyncUser.js +23 -0
  92. package/lib/WAUSync/index.js +4 -0
  93. package/lib/index.js +11 -0
  94. package/package.json +32 -0
  95. package/readme.md +1452 -0
package/readme.md ADDED
@@ -0,0 +1,1452 @@
1
+ <h1 align='center'><img alt="Baileys logo" src="https://raw.githubusercontent.com/WhiskeySockets/Baileys/refs/heads/master/Media/logo.png" height="75"/></h1>
2
+
3
+ <div align='center'>Baileys is a WebSockets-based TypeScript library for interacting with the WhatsApp Web API.</div>
4
+
5
+ <p align="center">
6
+ <img src="https://img.shields.io/badge/Version-JavaScript--Only-blue?logo=javascript" alt="JavaScript Only Badge"/>
7
+ </p>
8
+
9
+ > [!NOTE]
10
+ > 🧩 **This is a pure JavaScript version (without TypeScript).**
11
+ > This edition is maintained separately to ensure compatibility for environments
12
+ > that use native JS syntax (ESM/CJS) and do not require TypeScript.
13
+
14
+ > [!CAUTION]
15
+ > NOTICE OF BREAKING CHANGE.
16
+ >
17
+ > As of 7.0.0, multiple breaking changes were introduced into the library.
18
+ >
19
+ > Please check out https://whiskey.so/migrate-latest for more information.
20
+
21
+ > [!IMPORTANT]
22
+ > I made a survey for users of the project to ask questions, and provide Baileys valuable insights regarding its users. I will be publishing the results of this form (after filtering) as well so we can study and understand where we need to work.
23
+ >
24
+ > The survey is anonymous and requires no personal info at all. You are required to sign-in with Google to keep responses to one person. You are able to edit your response after you submit. The deadline for this form is September 30, 2025.
25
+ >
26
+ > I encourage you to put the effort, all it takes is 5-10 minutes and you get to ask me any questions you have.
27
+ >
28
+ > \- Rajeh (purpshell)
29
+ >
30
+ > Fill in the survey via the link: https://whiskey.so/survey
31
+
32
+ # Important Note
33
+
34
+ This is a temporary README.md, the new guide is in development and will this file will be replaced with .github/README.md (already a default on GitHub).
35
+
36
+ New guide link: https://baileys.wiki
37
+
38
+ # Sponsor
39
+
40
+ If you'd like to financially support this project, you can do so by supporting the current maintainer [here](https://purpshell.dev/sponsor).
41
+
42
+ # Disclaimer
43
+
44
+ This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or its affiliates.
45
+ The official WhatsApp website can be found at whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
46
+
47
+ The maintainers of Baileys do not in any way condone the use of this application in practices that violate the Terms of Service of WhatsApp. The maintainers of this application call upon the personal responsibility of its users to use this application in a fair way, as it is intended to be used.
48
+ Use at your own discretion. Do not spam people with this. We discourage any stalkerware, bulk or automated messaging usage.
49
+
50
+ ##
51
+
52
+ - Baileys does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a **WebSocket**.
53
+ - Not running Selenium or Chromium saves you like **half a gig** of ram :/
54
+ - Baileys supports interacting with the multi-device & web versions of WhatsApp.
55
+ - Thank you to [@pokearaujo](https://github.com/pokearaujo/multidevice) for writing his observations on the workings of WhatsApp Multi-Device. Also, thank you to [@Sigalor](https://github.com/sigalor/whatsapp-web-reveng) for writing his observations on the workings of WhatsApp Web and thanks to [@Rhymen](https://github.com/Rhymen/go-whatsapp/) for the **go** implementation.
56
+
57
+ > [!IMPORTANT]
58
+ > The original repository had to be removed by the original author - we now continue development in this repository here.
59
+ > This is the only official repository and is maintained by the community.
60
+ > **Join the Discord [here](https://discord.gg/WeJM5FP9GG)**
61
+
62
+ ## Example
63
+
64
+ Do check out & run [example.ts](Example/example.ts) to see an example usage of the library.
65
+ The script covers most common use cases.
66
+ To run the example script, download or clone the repo and then type the following in a terminal:
67
+
68
+ 1. `cd path/to/Baileys`
69
+ 2. `yarn`
70
+ 3. `yarn example`
71
+
72
+ ## Install
73
+
74
+ Use the stable version:
75
+
76
+ ```
77
+ yarn add @whiskeysockets/baileys
78
+ ```
79
+
80
+ Use the edge version (no guarantee of stability, but latest fixes + features)
81
+
82
+ ```
83
+ yarn add github:WhiskeySockets/Baileys
84
+ ```
85
+
86
+ Then import your code using:
87
+
88
+ ```ts
89
+ import makeWASocket from "@whiskeysockets/baileys";
90
+ ```
91
+
92
+ # Links
93
+
94
+ - [Discord](https://discord.gg/WeJM5FP9GG)
95
+ - [Docs](https://guide.whiskeysockets.io/)
96
+
97
+ # Index
98
+
99
+ - [Connecting Account](#connecting-account)
100
+ - [Connect with QR-CODE](#starting-socket-with-qr-code)
101
+ - [Connect with Pairing Code](#starting-socket-with-pairing-code)
102
+ - [Receive Full History](#receive-full-history)
103
+ - [Important Notes About Socket Config](#important-notes-about-socket-config)
104
+ - [Caching Group Metadata (Recommended)](#caching-group-metadata-recommended)
105
+ - [Improve Retry System & Decrypt Poll Votes](#improve-retry-system--decrypt-poll-votes)
106
+ - [Receive Notifications in Whatsapp App](#receive-notifications-in-whatsapp-app)
107
+
108
+ - [Save Auth Info](#saving--restoring-sessions)
109
+ - [Handling Events](#handling-events)
110
+ - [Example to Start](#example-to-start)
111
+ - [Decrypt Poll Votes](#decrypt-poll-votes)
112
+ - [Summary of Events on First Connection](#summary-of-events-on-first-connection)
113
+ - [Implementing a Data Store](#implementing-a-data-store)
114
+ - [Whatsapp IDs Explain](#whatsapp-ids-explain)
115
+ - [Utility Functions](#utility-functions)
116
+ - [Sending Messages](#sending-messages)
117
+ - [Non-Media Messages](#non-media-messages)
118
+ - [Text Message](#text-message)
119
+ - [Quote Message](#quote-message-works-with-all-types)
120
+ - [Mention User](#mention-user-works-with-most-types)
121
+ - [Forward Messages](#forward-messages)
122
+ - [Location Message](#location-message)
123
+ - [Contact Message](#contact-message)
124
+ - [Reaction Message](#reaction-message)
125
+ - [Pin Message](#pin-message)
126
+ - [Poll Message](#poll-message)
127
+ - [Sending with Link Preview](#sending-messages-with-link-previews)
128
+ - [Media Messages](#media-messages)
129
+ - [Gif Message](#gif-message)
130
+ - [Video Message](#video-message)
131
+ - [Audio Message](#audio-message)
132
+ - [Image Message](#image-message)
133
+ - [ViewOnce Message](#view-once-message)
134
+ - [Modify Messages](#modify-messages)
135
+ - [Delete Messages (for everyone)](#deleting-messages-for-everyone)
136
+ - [Edit Messages](#editing-messages)
137
+ - [Manipulating Media Messages](#manipulating-media-messages)
138
+ - [Thumbnail in Media Messages](#thumbnail-in-media-messages)
139
+ - [Downloading Media Messages](#downloading-media-messages)
140
+ - [Re-upload Media Message to Whatsapp](#re-upload-media-message-to-whatsapp)
141
+ - [Reject Call](#reject-call)
142
+ - [Send States in Chat](#send-states-in-chat)
143
+ - [Reading Messages](#reading-messages)
144
+ - [Update Presence](#update-presence)
145
+ - [Modifying Chats](#modifying-chats)
146
+ - [Archive a Chat](#archive-a-chat)
147
+ - [Mute/Unmute a Chat](#muteunmute-a-chat)
148
+ - [Mark a Chat Read/Unread](#mark-a-chat-readunread)
149
+ - [Delete a Message for Me](#delete-a-message-for-me)
150
+ - [Delete a Chat](#delete-a-chat)
151
+ - [Star/Unstar a Message](#starunstar-a-message)
152
+ - [Disappearing Messages](#disappearing-messages)
153
+ - [User Querys](#user-querys)
154
+ - [Check If ID Exists in Whatsapp](#check-if-id-exists-in-whatsapp)
155
+ - [Query Chat History (groups too)](#query-chat-history-groups-too)
156
+ - [Fetch Status](#fetch-status)
157
+ - [Fetch Profile Picture (groups too)](#fetch-profile-picture-groups-too)
158
+ - [Fetch Bussines Profile (such as description or category)](#fetch-bussines-profile-such-as-description-or-category)
159
+ - [Fetch Someone's Presence (if they're typing or online)](#fetch-someones-presence-if-theyre-typing-or-online)
160
+ - [Change Profile](#change-profile)
161
+ - [Change Profile Status](#change-profile-status)
162
+ - [Change Profile Name](#change-profile-name)
163
+ - [Change Display Picture (groups too)](#change-display-picture-groups-too)
164
+ - [Remove display picture (groups too)](#remove-display-picture-groups-too)
165
+ - [Groups](#groups)
166
+ - [Create a Group](#create-a-group)
167
+ - [Add/Remove or Demote/Promote](#addremove-or-demotepromote)
168
+ - [Change Subject (name)](#change-subject-name)
169
+ - [Change Description](#change-description)
170
+ - [Change Settings](#change-settings)
171
+ - [Leave a Group](#leave-a-group)
172
+ - [Get Invite Code](#get-invite-code)
173
+ - [Revoke Invite Code](#revoke-invite-code)
174
+ - [Join Using Invitation Code](#join-using-invitation-code)
175
+ - [Get Group Info by Invite Code](#get-group-info-by-invite-code)
176
+ - [Query Metadata (participants, name, description...)](#query-metadata-participants-name-description)
177
+ - [Join using groupInviteMessage](#join-using-groupinvitemessage)
178
+ - [Get Request Join List](#get-request-join-list)
179
+ - [Approve/Reject Request Join](#approvereject-request-join)
180
+ - [Get All Participating Groups Metadata](#get-all-participating-groups-metadata)
181
+ - [Toggle Ephemeral](#toggle-ephemeral)
182
+ - [Change Add Mode](#change-add-mode)
183
+ - [Privacy](#privacy)
184
+ - [Block/Unblock User](#blockunblock-user)
185
+ - [Get Privacy Settings](#get-privacy-settings)
186
+ - [Get BlockList](#get-blocklist)
187
+ - [Update LastSeen Privacy](#update-lastseen-privacy)
188
+ - [Update Online Privacy](#update-online-privacy)
189
+ - [Update Profile Picture Privacy](#update-profile-picture-privacy)
190
+ - [Update Status Privacy](#update-status-privacy)
191
+ - [Update Read Receipts Privacy](#update-read-receipts-privacy)
192
+ - [Update Groups Add Privacy](#update-groups-add-privacy)
193
+ - [Update Default Disappearing Mode](#update-default-disappearing-mode)
194
+ - [Broadcast Lists & Stories](#broadcast-lists--stories)
195
+ - [Send Broadcast & Stories](#send-broadcast--stories)
196
+ - [Query a Broadcast List's Recipients & Name](#query-a-broadcast-lists-recipients--name)
197
+ - [Writing Custom Functionality](#writing-custom-functionality)
198
+ - [Enabling Debug Level in Baileys Logs](#enabling-debug-level-in-baileys-logs)
199
+ - [How Whatsapp Communicate With Us](#how-whatsapp-communicate-with-us)
200
+ - [Register a Callback for Websocket Events](#register-a-callback-for-websocket-events)
201
+
202
+ ## Connecting Account
203
+
204
+ WhatsApp provides a multi-device API that allows Baileys to be authenticated as a second WhatsApp client by scanning a **QR code** or **Pairing Code** with WhatsApp on your phone.
205
+
206
+ > [!NOTE]
207
+ > **[Here](#example-to-start) is a simple example of event handling**
208
+
209
+ > [!TIP]
210
+ > **You can see all supported socket configs [here](https://baileys.whiskeysockets.io/types/SocketConfig.html) (Recommended)**
211
+
212
+ ### Starting socket with **QR-CODE**
213
+
214
+ > [!TIP]
215
+ > You can customize browser name if you connect with **QR-CODE**, with `Browser` constant, we have some browsers config, **see [here](https://baileys.whiskeysockets.io/types/BrowsersMap.html)**
216
+
217
+ ```ts
218
+ import makeWASocket from "@whiskeysockets/baileys";
219
+
220
+ const sock = makeWASocket({
221
+ // can provide additional config here
222
+ browser: Browsers.ubuntu("My App"),
223
+ printQRInTerminal: true,
224
+ });
225
+ ```
226
+
227
+ If the connection is successful, you will see a QR code printed on your terminal screen, scan it with WhatsApp on your phone and you'll be logged in!
228
+
229
+ ### Starting socket with **Pairing Code**
230
+
231
+ > [!IMPORTANT]
232
+ > Pairing Code isn't Mobile API, it's a method to connect Whatsapp Web without QR-CODE, you can connect only with one device, see [here](https://faq.whatsapp.com/1324084875126592/?cms_platform=web)
233
+
234
+ The phone number can't have `+` or `()` or `-`, only numbers, you must provide country code
235
+
236
+ ```ts
237
+ import makeWASocket from "@whiskeysockets/baileys";
238
+
239
+ const sock = makeWASocket({
240
+ // can provide additional config here
241
+ printQRInTerminal: false, //need to be false
242
+ });
243
+
244
+ if (!sock.authState.creds.registered) {
245
+ const number = "XXXXXXXXXXX";
246
+ const code = await sock.requestPairingCode(number);
247
+ console.log(code);
248
+ }
249
+ ```
250
+
251
+ ### Receive Full History
252
+
253
+ 1. Set `syncFullHistory` as `true`
254
+ 2. Baileys, by default, use chrome browser config
255
+ - If you'd like to emulate a desktop connection (and receive more message history), this browser setting to your Socket config:
256
+
257
+ ```ts
258
+ const sock = makeWASocket({
259
+ ...otherOpts,
260
+ // can use Windows, Ubuntu here too
261
+ browser: Browsers.macOS("Desktop"),
262
+ syncFullHistory: true,
263
+ });
264
+ ```
265
+
266
+ ## Important Notes About Socket Config
267
+
268
+ ### Caching Group Metadata (Recommended)
269
+
270
+ - If you use baileys for groups, we recommend you to set `cachedGroupMetadata` in socket config, you need to implement a cache like this:
271
+
272
+ ```ts
273
+ const groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
274
+
275
+ const sock = makeWASocket({
276
+ cachedGroupMetadata: async (jid) => groupCache.get(jid),
277
+ });
278
+
279
+ sock.ev.on("groups.update", async ([event]) => {
280
+ const metadata = await sock.groupMetadata(event.id);
281
+ groupCache.set(event.id, metadata);
282
+ });
283
+
284
+ sock.ev.on("group-participants.update", async (event) => {
285
+ const metadata = await sock.groupMetadata(event.id);
286
+ groupCache.set(event.id, metadata);
287
+ });
288
+ ```
289
+
290
+ ### Improve Retry System & Decrypt Poll Votes
291
+
292
+ - If you want to improve sending message, retrying when error occurs and decrypt poll votes, you need to have a store and set `getMessage` config in socket like this:
293
+ ```ts
294
+ const sock = makeWASocket({
295
+ getMessage: async (key) => await getMessageFromStore(key),
296
+ });
297
+ ```
298
+
299
+ ### Receive Notifications in Whatsapp App
300
+
301
+ - If you want to receive notifications in whatsapp app, set `markOnlineOnConnect` to `false`
302
+ ```ts
303
+ const sock = makeWASocket({
304
+ markOnlineOnConnect: false,
305
+ });
306
+ ```
307
+
308
+ ## Saving & Restoring Sessions
309
+
310
+ You obviously don't want to keep scanning the QR code every time you want to connect.
311
+
312
+ So, you can load the credentials to log back in:
313
+
314
+ ```ts
315
+ import makeWASocket, { useMultiFileAuthState } from "@whiskeysockets/baileys";
316
+
317
+ const { state, saveCreds } = await useMultiFileAuthState("auth_info_baileys");
318
+
319
+ // will use the given state to connect
320
+ // so if valid credentials are available -- it'll connect without QR
321
+ const sock = makeWASocket({ auth: state });
322
+
323
+ // this will be called as soon as the credentials are updated
324
+ sock.ev.on("creds.update", saveCreds);
325
+ ```
326
+
327
+ > [!IMPORTANT]
328
+ > `useMultiFileAuthState` is a utility function to help save the auth state in a single folder, this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system.
329
+
330
+ > [!NOTE]
331
+ > When a message is received/sent, due to signal sessions needing updating, the auth keys (`authState.keys`) will update. Whenever that happens, you must save the updated keys (`authState.keys.set()` is called). Not doing so will prevent your messages from reaching the recipient & cause other unexpected consequences. The `useMultiFileAuthState` function automatically takes care of that, but for any other serious implementation -- you will need to be very careful with the key state management.
332
+
333
+ ## Handling Events
334
+
335
+ - Baileys uses the EventEmitter syntax for events.
336
+ They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
337
+
338
+ > [!IMPORTANT]
339
+ > **The events are [these](https://baileys.whiskeysockets.io/types/BaileysEventMap.html)**, it's important you see all events
340
+
341
+ You can listen to these events like this:
342
+
343
+ ```ts
344
+ const sock = makeWASocket();
345
+ sock.ev.on("messages.upsert", ({ messages }) => {
346
+ console.log("got messages", messages);
347
+ });
348
+ ```
349
+
350
+ ### Example to Start
351
+
352
+ > [!NOTE]
353
+ > This example includes basic auth storage too
354
+
355
+ > [!NOTE]
356
+ > For reliable serialization of the authentication state, especially when storing as JSON, always use the BufferJSON utility.
357
+
358
+ ```ts
359
+ import makeWASocket, {
360
+ DisconnectReason,
361
+ useMultiFileAuthState,
362
+ } from "@whiskeysockets/baileys";
363
+ import { Boom } from "@hapi/boom";
364
+
365
+ async function connectToWhatsApp() {
366
+ const { state, saveCreds } = await useMultiFileAuthState("auth_info_baileys");
367
+ const sock = makeWASocket({
368
+ // can provide additional config here
369
+ auth: state,
370
+ printQRInTerminal: true,
371
+ });
372
+ sock.ev.on("connection.update", (update) => {
373
+ const { connection, lastDisconnect } = update;
374
+ if (connection === "close") {
375
+ const shouldReconnect =
376
+ (lastDisconnect.error as Boom)?.output?.statusCode !==
377
+ DisconnectReason.loggedOut;
378
+ console.log(
379
+ "connection closed due to ",
380
+ lastDisconnect.error,
381
+ ", reconnecting ",
382
+ shouldReconnect,
383
+ );
384
+ // reconnect if not logged out
385
+ if (shouldReconnect) {
386
+ connectToWhatsApp();
387
+ }
388
+ } else if (connection === "open") {
389
+ console.log("opened connection");
390
+ }
391
+ });
392
+ sock.ev.on("messages.upsert", (event) => {
393
+ for (const m of event.messages) {
394
+ console.log(JSON.stringify(m, undefined, 2));
395
+
396
+ console.log("replying to", m.key.remoteJid);
397
+ await sock.sendMessage(m.key.remoteJid!, { text: "Hello Word" });
398
+ }
399
+ });
400
+
401
+ // to storage creds (session info) when it updates
402
+ sock.ev.on("creds.update", saveCreds);
403
+ }
404
+ // run in main file
405
+ connectToWhatsApp();
406
+ ```
407
+
408
+ > [!IMPORTANT]
409
+ > In `messages.upsert` it's recommended to use a loop like `for (const message of event.messages)` to handle all messages in array
410
+
411
+ ### Decrypt Poll Votes
412
+
413
+ - By default poll votes are encrypted and handled in `messages.update`
414
+ - That's a simple example
415
+
416
+ ```ts
417
+ sock.ev.on("messages.update", (event) => {
418
+ for (const { key, update } of event) {
419
+ if (update.pollUpdates) {
420
+ const pollCreation = await getMessage(key);
421
+ if (pollCreation) {
422
+ console.log(
423
+ "got poll update, aggregation: ",
424
+ getAggregateVotesInPollMessage({
425
+ message: pollCreation,
426
+ pollUpdates: update.pollUpdates,
427
+ }),
428
+ );
429
+ }
430
+ }
431
+ }
432
+ });
433
+ ```
434
+
435
+ - `getMessage` is a [store](#implementing-a-data-store) implementation (in your end)
436
+
437
+ ### Summary of Events on First Connection
438
+
439
+ 1. When you connect first time, `connection.update` will be fired requesting you to restart sock
440
+ 2. Then, history messages will be received in `messaging.history-set`
441
+
442
+ ## Implementing a Data Store
443
+
444
+ - Baileys does not come with a defacto storage for chats, contacts, or messages. However, a simple in-memory implementation has been provided. The store listens for chat updates, new messages, message updates, etc., to always have an up-to-date version of the data.
445
+
446
+ > [!IMPORTANT]
447
+ > I highly recommend building your own data store, as storing someone's entire chat history in memory is a terrible waste of RAM.
448
+
449
+ It can be used as follows:
450
+
451
+ ```ts
452
+ import makeWASocket, { makeInMemoryStore } from "@whiskeysockets/baileys";
453
+ // the store maintains the data of the WA connection in memory
454
+ // can be written out to a file & read from it
455
+ const store = makeInMemoryStore({});
456
+ // can be read from a file
457
+ store.readFromFile("./baileys_store.json");
458
+ // saves the state to a file every 10s
459
+ setInterval(() => {
460
+ store.writeToFile("./baileys_store.json");
461
+ }, 10_000);
462
+
463
+ const sock = makeWASocket({});
464
+ // will listen from this socket
465
+ // the store can listen from a new socket once the current socket outlives its lifetime
466
+ store.bind(sock.ev);
467
+
468
+ sock.ev.on("chats.upsert", () => {
469
+ // can use 'store.chats' however you want, even after the socket dies out
470
+ // 'chats' => a KeyedDB instance
471
+ console.log("got chats", store.chats.all());
472
+ });
473
+
474
+ sock.ev.on("contacts.upsert", () => {
475
+ console.log("got contacts", Object.values(store.contacts));
476
+ });
477
+ ```
478
+
479
+ The store also provides some simple functions such as `loadMessages` that utilize the store to speed up data retrieval.
480
+
481
+ ## Whatsapp IDs Explain
482
+
483
+ - `id` is the WhatsApp ID, called `jid` too, of the person or group you're sending the message to.
484
+ - It must be in the format `[country code][phone number]@s.whatsapp.net`
485
+ - Example for people: `+19999999999@s.whatsapp.net`.
486
+ - For groups, it must be in the format `123456789-123345@g.us`.
487
+ - For broadcast lists, it's `[timestamp of creation]@broadcast`.
488
+ - For stories, the ID is `status@broadcast`.
489
+
490
+ ## Utility Functions
491
+
492
+ - `getContentType`, returns the content type for any message
493
+ - `getDevice`, returns the device from message
494
+ - `makeCacheableSignalKeyStore`, make auth store more fast
495
+ - `downloadContentFromMessage`, download content from any message
496
+
497
+ ## Sending Messages
498
+
499
+ - Send all types of messages with a single function
500
+ - **[Here](https://baileys.whiskeysockets.io/types/AnyMessageContent.html) you can see all message contents supported, like text message**
501
+ - **[Here](https://baileys.whiskeysockets.io/types/MiscMessageGenerationOptions.html) you can see all options supported, like quote message**
502
+
503
+ ```ts
504
+ const jid: string;
505
+ const content: AnyMessageContent;
506
+ const options: MiscMessageGenerationOptions;
507
+
508
+ sock.sendMessage(jid, content, options);
509
+ ```
510
+
511
+ ### Non-Media Messages
512
+
513
+ #### Text Message
514
+
515
+ ```ts
516
+ await sock.sendMessage(jid, { text: "hello word" });
517
+ ```
518
+
519
+ #### Quote Message (works with all types)
520
+
521
+ ```ts
522
+ await sock.sendMessage(jid, { text: "hello word" }, { quoted: message });
523
+ ```
524
+
525
+ #### Mention User (works with most types)
526
+
527
+ - @number is to mention in text, it's optional
528
+
529
+ ```ts
530
+ await sock.sendMessage(jid, {
531
+ text: "@12345678901",
532
+ mentions: ["12345678901@s.whatsapp.net"],
533
+ });
534
+ ```
535
+
536
+ #### Forward Messages
537
+
538
+ - You need to have message object, can be retrieved from [store](#implementing-a-data-store) or use a [message](https://baileys.whiskeysockets.io/types/WAMessage.html) object
539
+
540
+ ```ts
541
+ const msg = getMessageFromStore(); // implement this on your end
542
+ await sock.sendMessage(jid, { forward: msg }); // WA forward the message!
543
+ ```
544
+
545
+ #### Location Message
546
+
547
+ ```ts
548
+ await sock.sendMessage(jid, {
549
+ location: {
550
+ degreesLatitude: 24.121231,
551
+ degreesLongitude: 55.1121221,
552
+ },
553
+ });
554
+ ```
555
+
556
+ #### Contact Message
557
+
558
+ ```ts
559
+ const vcard =
560
+ "BEGIN:VCARD\n" + // metadata of the contact card
561
+ "VERSION:3.0\n" +
562
+ "FN:Jeff Singh\n" + // full name
563
+ "ORG:Ashoka Uni;\n" + // the organization of the contact
564
+ "TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n" + // WhatsApp ID + phone number
565
+ "END:VCARD";
566
+
567
+ await sock.sendMessage(id, {
568
+ contacts: {
569
+ displayName: "Jeff",
570
+ contacts: [{ vcard }],
571
+ },
572
+ });
573
+ ```
574
+
575
+ #### Reaction Message
576
+
577
+ - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](https://baileys.whiskeysockets.io/types/WAMessageKey.html) object
578
+
579
+ ```ts
580
+ await sock.sendMessage(jid, {
581
+ react: {
582
+ text: "💖", // use an empty string to remove the reaction
583
+ key: message.key,
584
+ },
585
+ });
586
+ ```
587
+
588
+ #### Pin Message
589
+
590
+ - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](https://baileys.whiskeysockets.io/types/WAMessageKey.html) object
591
+
592
+ - Time can be:
593
+
594
+ | Time | Seconds |
595
+ | ---- | --------- |
596
+ | 24h | 86.400 |
597
+ | 7d | 604.800 |
598
+ | 30d | 2.592.000 |
599
+
600
+ ```ts
601
+ await sock.sendMessage(
602
+ jid,
603
+ {
604
+ pin: {
605
+ type: 1, // 0 to remove
606
+ time: 86400
607
+ key: message.key
608
+ }
609
+ }
610
+ )
611
+ ```
612
+
613
+ #### Poll Message
614
+
615
+ ```ts
616
+ await sock.sendMessage(
617
+ jid,
618
+ {
619
+ poll: {
620
+ name: 'My Poll',
621
+ values: ['Option 1', 'Option 2', ...],
622
+ selectableCount: 1,
623
+ toAnnouncementGroup: false // or true
624
+ }
625
+ }
626
+ )
627
+ ```
628
+
629
+ ### Sending Messages with Link Previews
630
+
631
+ 1. By default, wa does not have link generation when sent from the web
632
+ 2. Baileys has a function to generate the content for these link previews
633
+ 3. To enable this function's usage, add `link-preview-js` as a dependency to your project with `yarn add link-preview-js`
634
+ 4. Send a link:
635
+
636
+ ```ts
637
+ await sock.sendMessage(jid, {
638
+ text: "Hi, this was sent using https://github.com/whiskeysockets/baileys",
639
+ });
640
+ ```
641
+
642
+ ### Media Messages
643
+
644
+ Sending media (video, stickers, images) is easier & more efficient than ever.
645
+
646
+ > [!NOTE]
647
+ > In media messages, you can pass `{ stream: Stream }` or `{ url: Url }` or `Buffer` directly, you can see more [here](https://baileys.whiskeysockets.io/types/WAMediaUpload.html)
648
+
649
+ - When specifying a media url, Baileys never loads the entire buffer into memory; it even encrypts the media as a readable stream.
650
+
651
+ > [!TIP]
652
+ > It's recommended to use Stream or Url to save memory
653
+
654
+ #### Gif Message
655
+
656
+ - Whatsapp doesn't support `.gif` files, that's why we send gifs as common `.mp4` video with `gifPlayback` flag
657
+
658
+ ```ts
659
+ await sock.sendMessage(jid, {
660
+ video: fs.readFileSync("Media/ma_gif.mp4"),
661
+ caption: "hello word",
662
+ gifPlayback: true,
663
+ });
664
+ ```
665
+
666
+ #### Video Message
667
+
668
+ ```ts
669
+ await sock.sendMessage(id, {
670
+ video: {
671
+ url: "./Media/ma_gif.mp4",
672
+ },
673
+ caption: "hello word",
674
+ ptv: false, // if set to true, will send as a `video note`
675
+ });
676
+ ```
677
+
678
+ #### Audio Message
679
+
680
+ - To audio message work in all devices you need to convert with some tool like `ffmpeg` with this flags:
681
+
682
+ ```bash
683
+ codec: libopus //ogg file
684
+ ac: 1 //one channel
685
+ avoid_negative_ts
686
+ make_zero
687
+ ```
688
+
689
+ - Example:
690
+
691
+ ```bash
692
+ ffmpeg -i input.mp4 -avoid_negative_ts make_zero -ac 1 output.ogg
693
+ ```
694
+
695
+ ```ts
696
+ await sock.sendMessage(jid, {
697
+ audio: {
698
+ url: "./Media/audio.mp3",
699
+ },
700
+ mimetype: "audio/mp4",
701
+ });
702
+ ```
703
+
704
+ #### Image Message
705
+
706
+ ```ts
707
+ await sock.sendMessage(id, {
708
+ image: {
709
+ url: "./Media/ma_img.png",
710
+ },
711
+ caption: "hello word",
712
+ });
713
+ ```
714
+
715
+ #### View Once Message
716
+
717
+ - You can send all messages above as `viewOnce`, you only need to pass `viewOnce: true` in content object
718
+
719
+ ```ts
720
+ await sock.sendMessage(id, {
721
+ image: {
722
+ url: "./Media/ma_img.png",
723
+ },
724
+ viewOnce: true, //works with video, audio too
725
+ caption: "hello word",
726
+ });
727
+ ```
728
+
729
+ ## Modify Messages
730
+
731
+ ### Deleting Messages (for everyone)
732
+
733
+ ```ts
734
+ const msg = await sock.sendMessage(jid, { text: "hello word" });
735
+ await sock.sendMessage(jid, { delete: msg.key });
736
+ ```
737
+
738
+ **Note:** deleting for oneself is supported via `chatModify`, see in [this section](#modifying-chats)
739
+
740
+ ### Editing Messages
741
+
742
+ - You can pass all editable contents here
743
+
744
+ ```ts
745
+ await sock.sendMessage(jid, {
746
+ text: "updated text goes here",
747
+ edit: response.key,
748
+ });
749
+ ```
750
+
751
+ ## Manipulating Media Messages
752
+
753
+ ### Thumbnail in Media Messages
754
+
755
+ - For media messages, the thumbnail can be generated automatically for images & stickers provided you add `jimp` or `sharp` as a dependency in your project using `yarn add jimp` or `yarn add sharp`.
756
+ - Thumbnails for videos can also be generated automatically, though, you need to have `ffmpeg` installed on your system.
757
+
758
+ ### Downloading Media Messages
759
+
760
+ If you want to save the media you received
761
+
762
+ ```ts
763
+ import { createWriteStream } from 'fs'
764
+ import { downloadMediaMessage, getContentType } from '@whiskeysockets/baileys'
765
+
766
+ sock.ev.on('messages.upsert', async ({ [m] }) => {
767
+ if (!m.message) return // if there is no text or media message
768
+ const messageType = getContentType(m) // get what type of message it is (text, image, video...)
769
+
770
+ // if the message is an image
771
+ if (messageType === 'imageMessage') {
772
+ // download the message
773
+ const stream = await downloadMediaMessage(
774
+ m,
775
+ 'stream', // can be 'buffer' too
776
+ { },
777
+ {
778
+ logger,
779
+ // pass this so that baileys can request a reupload of media
780
+ // that has been deleted
781
+ reuploadRequest: sock.updateMediaMessage
782
+ }
783
+ )
784
+ // save to file
785
+ const writeStream = createWriteStream('./my-download.jpeg')
786
+ stream.pipe(writeStream)
787
+ }
788
+ }
789
+ ```
790
+
791
+ ### Re-upload Media Message to Whatsapp
792
+
793
+ - WhatsApp automatically removes old media from their servers. For the device to access said media -- a re-upload is required by another device that has it. This can be accomplished using:
794
+
795
+ ```ts
796
+ await sock.updateMediaMessage(msg);
797
+ ```
798
+
799
+ ## Reject Call
800
+
801
+ - You can obtain `callId` and `callFrom` from `call` event
802
+
803
+ ```ts
804
+ await sock.rejectCall(callId, callFrom);
805
+ ```
806
+
807
+ ## Send States in Chat
808
+
809
+ ### Reading Messages
810
+
811
+ - A set of message [keys](https://baileys.whiskeysockets.io/types/WAMessageKey.html) must be explicitly marked read now.
812
+ - You cannot mark an entire 'chat' read as it were with Baileys Web.
813
+ This means you have to keep track of unread messages.
814
+
815
+ ```ts
816
+ const key: WAMessageKey;
817
+ // can pass multiple keys to read multiple messages as well
818
+ await sock.readMessages([key]);
819
+ ```
820
+
821
+ The message ID is the unique identifier of the message that you are marking as read.
822
+ On a `WAMessage`, the `messageID` can be accessed using `messageID = message.key.id`.
823
+
824
+ ### Update Presence
825
+
826
+ - `presence` can be one of [these](https://baileys.whiskeysockets.io/types/WAPresence.html)
827
+ - The presence expires after about 10 seconds.
828
+ - This lets the person/group with `jid` know whether you're online, offline, typing etc.
829
+
830
+ ```ts
831
+ await sock.sendPresenceUpdate("available", jid);
832
+ ```
833
+
834
+ > [!NOTE]
835
+ > If a desktop client is active, WA doesn't send push notifications to the device. If you would like to receive said notifications -- mark your Baileys client offline using `sock.sendPresenceUpdate('unavailable')`
836
+
837
+ ## Modifying Chats
838
+
839
+ WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
840
+
841
+ > [!IMPORTANT]
842
+ > If you mess up one of your updates, WA can log you out of all your devices and you'll have to log in again.
843
+
844
+ ### Archive a Chat
845
+
846
+ ```ts
847
+ const lastMsgInChat = await getLastMessageInChat(jid); // implement this on your end
848
+ await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, jid);
849
+ ```
850
+
851
+ ### Mute/Unmute a Chat
852
+
853
+ - Supported times:
854
+
855
+ | Time | Miliseconds |
856
+ | ------ | ----------- |
857
+ | Remove | null |
858
+ | 8h | 86.400.000 |
859
+ | 7d | 604.800.000 |
860
+
861
+ ```ts
862
+ // mute for 8 hours
863
+ await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid);
864
+ // unmute
865
+ await sock.chatModify({ mute: null }, jid);
866
+ ```
867
+
868
+ ### Mark a Chat Read/Unread
869
+
870
+ ```ts
871
+ const lastMsgInChat = await getLastMessageInChat(jid); // implement this on your end
872
+ // mark it unread
873
+ await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, jid);
874
+ ```
875
+
876
+ ### Delete a Message for Me
877
+
878
+ ```ts
879
+ await sock.chatModify(
880
+ {
881
+ clear: {
882
+ messages: [
883
+ {
884
+ id: "ATWYHDNNWU81732J",
885
+ fromMe: true,
886
+ timestamp: "1654823909",
887
+ },
888
+ ],
889
+ },
890
+ },
891
+ jid,
892
+ );
893
+ ```
894
+
895
+ ### Delete a Chat
896
+
897
+ ```ts
898
+ const lastMsgInChat = await getLastMessageInChat(jid); // implement this on your end
899
+ await sock.chatModify(
900
+ {
901
+ delete: true,
902
+ lastMessages: [
903
+ {
904
+ key: lastMsgInChat.key,
905
+ messageTimestamp: lastMsgInChat.messageTimestamp,
906
+ },
907
+ ],
908
+ },
909
+ jid,
910
+ );
911
+ ```
912
+
913
+ ### Pin/Unpin a Chat
914
+
915
+ ```ts
916
+ await sock.chatModify(
917
+ {
918
+ pin: true, // or `false` to unpin
919
+ },
920
+ jid,
921
+ );
922
+ ```
923
+
924
+ ### Star/Unstar a Message
925
+
926
+ ```ts
927
+ await sock.chatModify(
928
+ {
929
+ star: {
930
+ messages: [
931
+ {
932
+ id: "messageID",
933
+ fromMe: true, // or `false`
934
+ },
935
+ ],
936
+ star: true, // - true: Star Message; false: Unstar Message
937
+ },
938
+ },
939
+ jid,
940
+ );
941
+ ```
942
+
943
+ ### Disappearing Messages
944
+
945
+ - Ephemeral can be:
946
+
947
+ | Time | Seconds |
948
+ | ------ | --------- |
949
+ | Remove | 0 |
950
+ | 24h | 86.400 |
951
+ | 7d | 604.800 |
952
+ | 90d | 7.776.000 |
953
+
954
+ - You need to pass in **Seconds**, default is 7 days
955
+
956
+ ```ts
957
+ // turn on disappearing messages
958
+ await sock.sendMessage(
959
+ jid,
960
+ // this is 1 week in seconds -- how long you want messages to appear for
961
+ { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL },
962
+ );
963
+
964
+ // will send as a disappearing message
965
+ await sock.sendMessage(
966
+ jid,
967
+ { text: "hello" },
968
+ { ephemeralExpiration: WA_DEFAULT_EPHEMERAL },
969
+ );
970
+
971
+ // turn off disappearing messages
972
+ await sock.sendMessage(jid, { disappearingMessagesInChat: false });
973
+ ```
974
+
975
+ ## User Querys
976
+
977
+ ### Check If ID Exists in Whatsapp
978
+
979
+ ```ts
980
+ const [result] = await sock.onWhatsApp(jid);
981
+ if (result.exists)
982
+ console.log(`${jid} exists on WhatsApp, as jid: ${result.jid}`);
983
+ ```
984
+
985
+ ### Query Chat History (groups too)
986
+
987
+ - You need to have oldest message in chat
988
+
989
+ ```ts
990
+ const msg = await getOldestMessageInChat(jid); // implement this on your end
991
+ await sock.fetchMessageHistory(
992
+ 50, //quantity (max: 50 per query)
993
+ msg.key,
994
+ msg.messageTimestamp,
995
+ );
996
+ ```
997
+
998
+ - Messages will be received in `messaging.history-set` event
999
+
1000
+ ### Fetch Status
1001
+
1002
+ ```ts
1003
+ const status = await sock.fetchStatus(jid);
1004
+ console.log("status: " + status);
1005
+ ```
1006
+
1007
+ ### Fetch Profile Picture (groups too)
1008
+
1009
+ - To get the display picture of some person/group
1010
+
1011
+ ```ts
1012
+ // for low res picture
1013
+ const ppUrl = await sock.profilePictureUrl(jid);
1014
+ console.log(ppUrl);
1015
+
1016
+ // for high res picture
1017
+ const ppUrl = await sock.profilePictureUrl(jid, "image");
1018
+ ```
1019
+
1020
+ ### Fetch Bussines Profile (such as description or category)
1021
+
1022
+ ```ts
1023
+ const profile = await sock.getBusinessProfile(jid);
1024
+ console.log(
1025
+ "business description: " +
1026
+ profile.description +
1027
+ ", category: " +
1028
+ profile.category,
1029
+ );
1030
+ ```
1031
+
1032
+ ### Fetch Someone's Presence (if they're typing or online)
1033
+
1034
+ ```ts
1035
+ // the presence update is fetched and called here
1036
+ sock.ev.on("presence.update", console.log);
1037
+
1038
+ // request updates for a chat
1039
+ await sock.presenceSubscribe(jid);
1040
+ ```
1041
+
1042
+ ## Change Profile
1043
+
1044
+ ### Change Profile Status
1045
+
1046
+ ```ts
1047
+ await sock.updateProfileStatus("Hello World!");
1048
+ ```
1049
+
1050
+ ### Change Profile Name
1051
+
1052
+ ```ts
1053
+ await sock.updateProfileName("My name");
1054
+ ```
1055
+
1056
+ ### Change Display Picture (groups too)
1057
+
1058
+ - To change your display picture or a group's
1059
+
1060
+ > [!NOTE]
1061
+ > Like media messages, you can pass `{ stream: Stream }` or `{ url: Url }` or `Buffer` directly, you can see more [here](https://baileys.whiskeysockets.io/types/WAMediaUpload.html)
1062
+
1063
+ ```ts
1064
+ await sock.updateProfilePicture(jid, { url: "./new-profile-picture.jpeg" });
1065
+ ```
1066
+
1067
+ ### Remove display picture (groups too)
1068
+
1069
+ ```ts
1070
+ await sock.removeProfilePicture(jid);
1071
+ ```
1072
+
1073
+ ## Groups
1074
+
1075
+ - To change group properties you need to be admin
1076
+
1077
+ ### Create a Group
1078
+
1079
+ ```ts
1080
+ // title & participants
1081
+ const group = await sock.groupCreate("My Fab Group", [
1082
+ "1234@s.whatsapp.net",
1083
+ "4564@s.whatsapp.net",
1084
+ ]);
1085
+ console.log("created group with id: " + group.gid);
1086
+ await sock.sendMessage(group.id, { text: "hello there" }); // say hello to everyone on the group
1087
+ ```
1088
+
1089
+ ### Add/Remove or Demote/Promote
1090
+
1091
+ ```ts
1092
+ // id & people to add to the group (will throw error if it fails)
1093
+ await sock.groupParticipantsUpdate(
1094
+ jid,
1095
+ ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"],
1096
+ "add", // replace this parameter with 'remove' or 'demote' or 'promote'
1097
+ );
1098
+ ```
1099
+
1100
+ ### Change Subject (name)
1101
+
1102
+ ```ts
1103
+ await sock.groupUpdateSubject(jid, "New Subject!");
1104
+ ```
1105
+
1106
+ ### Change Description
1107
+
1108
+ ```ts
1109
+ await sock.groupUpdateDescription(jid, "New Description!");
1110
+ ```
1111
+
1112
+ ### Change Settings
1113
+
1114
+ ```ts
1115
+ // only allow admins to send messages
1116
+ await sock.groupSettingUpdate(jid, "announcement");
1117
+ // allow everyone to send messages
1118
+ await sock.groupSettingUpdate(jid, "not_announcement");
1119
+ // allow everyone to modify the group's settings -- like display picture etc.
1120
+ await sock.groupSettingUpdate(jid, "unlocked");
1121
+ // only allow admins to modify the group's settings
1122
+ await sock.groupSettingUpdate(jid, "locked");
1123
+ ```
1124
+
1125
+ ### Leave a Group
1126
+
1127
+ ```ts
1128
+ // will throw error if it fails
1129
+ await sock.groupLeave(jid);
1130
+ ```
1131
+
1132
+ ### Get Invite Code
1133
+
1134
+ - To create link with code use `'https://chat.whatsapp.com/' + code`
1135
+
1136
+ ```ts
1137
+ const code = await sock.groupInviteCode(jid);
1138
+ console.log("group code: " + code);
1139
+ ```
1140
+
1141
+ ### Revoke Invite Code
1142
+
1143
+ ```ts
1144
+ const code = await sock.groupRevokeInvite(jid);
1145
+ console.log("New group code: " + code);
1146
+ ```
1147
+
1148
+ ### Join Using Invitation Code
1149
+
1150
+ - Code can't have `https://chat.whatsapp.com/`, only code
1151
+
1152
+ ```ts
1153
+ const response = await sock.groupAcceptInvite(code);
1154
+ console.log("joined to: " + response);
1155
+ ```
1156
+
1157
+ ### Get Group Info by Invite Code
1158
+
1159
+ ```ts
1160
+ const response = await sock.groupGetInviteInfo(code);
1161
+ console.log("group information: " + response);
1162
+ ```
1163
+
1164
+ ### Query Metadata (participants, name, description...)
1165
+
1166
+ ```ts
1167
+ const metadata = await sock.groupMetadata(jid);
1168
+ console.log(
1169
+ metadata.id +
1170
+ ", title: " +
1171
+ metadata.subject +
1172
+ ", description: " +
1173
+ metadata.desc,
1174
+ );
1175
+ ```
1176
+
1177
+ ### Join using `groupInviteMessage`
1178
+
1179
+ ```ts
1180
+ const response = await sock.groupAcceptInviteV4(jid, groupInviteMessage);
1181
+ console.log("joined to: " + response);
1182
+ ```
1183
+
1184
+ ### Get Request Join List
1185
+
1186
+ ```ts
1187
+ const response = await sock.groupRequestParticipantsList(jid);
1188
+ console.log(response);
1189
+ ```
1190
+
1191
+ ### Approve/Reject Request Join
1192
+
1193
+ ```ts
1194
+ const response = await sock.groupRequestParticipantsUpdate(
1195
+ jid, // group id
1196
+ ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"],
1197
+ "approve", // or 'reject'
1198
+ );
1199
+ console.log(response);
1200
+ ```
1201
+
1202
+ ### Get All Participating Groups Metadata
1203
+
1204
+ ```ts
1205
+ const response = await sock.groupFetchAllParticipating();
1206
+ console.log(response);
1207
+ ```
1208
+
1209
+ ### Toggle Ephemeral
1210
+
1211
+ - Ephemeral can be:
1212
+
1213
+ | Time | Seconds |
1214
+ | ------ | --------- |
1215
+ | Remove | 0 |
1216
+ | 24h | 86.400 |
1217
+ | 7d | 604.800 |
1218
+ | 90d | 7.776.000 |
1219
+
1220
+ ```ts
1221
+ await sock.groupToggleEphemeral(jid, 86400);
1222
+ ```
1223
+
1224
+ ### Change Add Mode
1225
+
1226
+ ```ts
1227
+ await sock.groupMemberAddMode(
1228
+ jid,
1229
+ "all_member_add", // or 'admin_add'
1230
+ );
1231
+ ```
1232
+
1233
+ ## Privacy
1234
+
1235
+ ### Block/Unblock User
1236
+
1237
+ ```ts
1238
+ await sock.updateBlockStatus(jid, "block"); // Block user
1239
+ await sock.updateBlockStatus(jid, "unblock"); // Unblock user
1240
+ ```
1241
+
1242
+ ### Get Privacy Settings
1243
+
1244
+ ```ts
1245
+ const privacySettings = await sock.fetchPrivacySettings(true);
1246
+ console.log("privacy settings: " + privacySettings);
1247
+ ```
1248
+
1249
+ ### Get BlockList
1250
+
1251
+ ```ts
1252
+ const response = await sock.fetchBlocklist();
1253
+ console.log(response);
1254
+ ```
1255
+
1256
+ ### Update LastSeen Privacy
1257
+
1258
+ ```ts
1259
+ const value = "all"; // 'contacts' | 'contact_blacklist' | 'none'
1260
+ await sock.updateLastSeenPrivacy(value);
1261
+ ```
1262
+
1263
+ ### Update Online Privacy
1264
+
1265
+ ```ts
1266
+ const value = "all"; // 'match_last_seen'
1267
+ await sock.updateOnlinePrivacy(value);
1268
+ ```
1269
+
1270
+ ### Update Profile Picture Privacy
1271
+
1272
+ ```ts
1273
+ const value = "all"; // 'contacts' | 'contact_blacklist' | 'none'
1274
+ await sock.updateProfilePicturePrivacy(value);
1275
+ ```
1276
+
1277
+ ### Update Status Privacy
1278
+
1279
+ ```ts
1280
+ const value = "all"; // 'contacts' | 'contact_blacklist' | 'none'
1281
+ await sock.updateStatusPrivacy(value);
1282
+ ```
1283
+
1284
+ ### Update Read Receipts Privacy
1285
+
1286
+ ```ts
1287
+ const value = "all"; // 'none'
1288
+ await sock.updateReadReceiptsPrivacy(value);
1289
+ ```
1290
+
1291
+ ### Update Groups Add Privacy
1292
+
1293
+ ```ts
1294
+ const value = "all"; // 'contacts' | 'contact_blacklist'
1295
+ await sock.updateGroupsAddPrivacy(value);
1296
+ ```
1297
+
1298
+ ### Update Default Disappearing Mode
1299
+
1300
+ - Like [this](#disappearing-messages), ephemeral can be:
1301
+
1302
+ | Time | Seconds |
1303
+ | ------ | --------- |
1304
+ | Remove | 0 |
1305
+ | 24h | 86.400 |
1306
+ | 7d | 604.800 |
1307
+ | 90d | 7.776.000 |
1308
+
1309
+ ```ts
1310
+ const ephemeral = 86400;
1311
+ await sock.updateDefaultDisappearingMode(ephemeral);
1312
+ ```
1313
+
1314
+ ## Broadcast Lists & Stories
1315
+
1316
+ ### Send Broadcast & Stories
1317
+
1318
+ - Messages can be sent to broadcasts & stories. You need to add the following message options in sendMessage, like this:
1319
+
1320
+ ```ts
1321
+ await sock.sendMessage(
1322
+ jid,
1323
+ {
1324
+ image: {
1325
+ url: url,
1326
+ },
1327
+ caption: caption,
1328
+ },
1329
+ {
1330
+ backgroundColor: backgroundColor,
1331
+ font: font,
1332
+ statusJidList: statusJidList,
1333
+ broadcast: true,
1334
+ },
1335
+ );
1336
+ ```
1337
+
1338
+ - Message body can be a `extendedTextMessage` or `imageMessage` or `videoMessage` or `voiceMessage`, see [here](https://baileys.whiskeysockets.io/types/AnyRegularMessageContent.html)
1339
+ - You can add `backgroundColor` and other options in the message options, see [here](https://baileys.whiskeysockets.io/types/MiscMessageGenerationOptions.html)
1340
+ - `broadcast: true` enables broadcast mode
1341
+ - `statusJidList`: a list of people that you can get which you need to provide, which are the people who will get this status message.
1342
+
1343
+ - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
1344
+ - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
1345
+ - Broadcast IDs are in the format `12345678@broadcast`
1346
+
1347
+ ### Query a Broadcast List's Recipients & Name
1348
+
1349
+ ```ts
1350
+ const bList = await sock.getBroadcastListInfo("1234@broadcast");
1351
+ console.log(`list name: ${bList.name}, recps: ${bList.recipients}`);
1352
+ ```
1353
+
1354
+ ## Writing Custom Functionality
1355
+
1356
+ Baileys is written with custom functionality in mind. Instead of forking the project & re-writing the internals, you can simply write your own extensions.
1357
+
1358
+ ### Enabling Debug Level in Baileys Logs
1359
+
1360
+ First, enable the logging of unhandled messages from WhatsApp by setting:
1361
+
1362
+ ```ts
1363
+ const sock = makeWASocket({
1364
+ logger: P({ level: "debug" }),
1365
+ });
1366
+ ```
1367
+
1368
+ This will enable you to see all sorts of messages WhatsApp sends in the console.
1369
+
1370
+ ### How Whatsapp Communicate With Us
1371
+
1372
+ > [!TIP]
1373
+ > If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
1374
+
1375
+ - **Example:** Functionality to track the battery percentage of your phone. You enable logging and you'll see a message about your battery pop up in the console:
1376
+ ```
1377
+ {
1378
+ "level": 10,
1379
+ "fromMe": false,
1380
+ "frame": {
1381
+ "tag": "ib",
1382
+ "attrs": {
1383
+ "from": "@s.whatsapp.net"
1384
+ },
1385
+ "content": [
1386
+ {
1387
+ "tag": "edge_routing",
1388
+ "attrs": {},
1389
+ "content": [
1390
+ {
1391
+ "tag": "routing_info",
1392
+ "attrs": {},
1393
+ "content": {
1394
+ "type": "Buffer",
1395
+ "data": [8,2,8,5]
1396
+ }
1397
+ }
1398
+ ]
1399
+ }
1400
+ ]
1401
+ },
1402
+ "msg":"communication"
1403
+ }
1404
+ ```
1405
+
1406
+ The `'frame'` is what the message received is, it has three components:
1407
+
1408
+ - `tag` -- what this frame is about (eg. message will have 'message')
1409
+ - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
1410
+ - `content` -- the actual data (eg. a message node will have the actual message content in it)
1411
+ - read more about this format [here](/src/WABinary/readme.md)
1412
+
1413
+ ### Register a Callback for Websocket Events
1414
+
1415
+ > [!TIP]
1416
+ > Recommended to see `onMessageReceived` function in `socket.ts` file to understand how websockets events are fired
1417
+
1418
+ ```ts
1419
+ // for any message with tag 'edge_routing'
1420
+ sock.ws.on("CB:edge_routing", (node: BinaryNode) => {});
1421
+
1422
+ // for any message with tag 'edge_routing' and id attribute = abcd
1423
+ sock.ws.on("CB:edge_routing,id:abcd", (node: BinaryNode) => {});
1424
+
1425
+ // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
1426
+ sock.ws.on("CB:edge_routing,id:abcd,routing_info", (node: BinaryNode) => {});
1427
+ ```
1428
+
1429
+ # License
1430
+
1431
+ Copyright (c) 2025 Rajeh Taher/WhiskeySockets
1432
+
1433
+ Licensed under the MIT License:
1434
+ Permission is hereby granted, free of charge, to any person obtaining a copy
1435
+ of this software and associated documentation files (the "Software"), to deal
1436
+ in the Software without restriction, including without limitation the rights
1437
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1438
+ copies of the Software, and to permit persons to whom the Software is
1439
+ furnished to do so, subject to the following conditions:
1440
+
1441
+ The above copyright notice and this permission notice shall be included in all
1442
+ copies or substantial portions of the Software.
1443
+
1444
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1445
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1446
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1447
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1448
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1449
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1450
+ SOFTWARE.
1451
+
1452
+ Thus, the maintainers of the project can't be held liable for any potential misuse of this project.