@periskope/baileys 6.7.15-alpha.6 → 6.7.16-alpha.1

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