libzapitu 1.0.0-alpha.3

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