@queenanya/baileys 6.5.8

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 +21 -0
  2. package/README.md +960 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +2879 -0
  5. package/WAProto/index.d.ts +32245 -0
  6. package/WAProto/index.js +87831 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/readme.md +6 -0
  16. package/WASignalGroup/sender_chain_key.js +50 -0
  17. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  18. package/WASignalGroup/sender_key_message.js +92 -0
  19. package/WASignalGroup/sender_key_name.js +70 -0
  20. package/WASignalGroup/sender_key_record.js +56 -0
  21. package/WASignalGroup/sender_key_state.js +129 -0
  22. package/WASignalGroup/sender_message_key.js +39 -0
  23. package/lib/Defaults/baileys-version.json +3 -0
  24. package/lib/Defaults/index.d.ts +283 -0
  25. package/lib/Defaults/index.js +115 -0
  26. package/lib/Defaults/phonenumber-mcc.json +223 -0
  27. package/lib/Signal/libsignal.d.ts +3 -0
  28. package/lib/Signal/libsignal.js +152 -0
  29. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  30. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  31. package/lib/Socket/Client/index.d.ts +3 -0
  32. package/lib/Socket/Client/index.js +19 -0
  33. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  34. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  35. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  36. package/lib/Socket/Client/web-socket-client.js +62 -0
  37. package/lib/Socket/business.d.ts +126 -0
  38. package/lib/Socket/business.js +259 -0
  39. package/lib/Socket/chats.d.ts +75 -0
  40. package/lib/Socket/chats.js +842 -0
  41. package/lib/Socket/groups.d.ts +107 -0
  42. package/lib/Socket/groups.js +291 -0
  43. package/lib/Socket/index.d.ts +128 -0
  44. package/lib/Socket/index.js +10 -0
  45. package/lib/Socket/messages-recv.d.ts +115 -0
  46. package/lib/Socket/messages-recv.js +725 -0
  47. package/lib/Socket/messages-send.d.ts +112 -0
  48. package/lib/Socket/messages-send.js +660 -0
  49. package/lib/Socket/registration.d.ts +223 -0
  50. package/lib/Socket/registration.js +166 -0
  51. package/lib/Socket/socket.d.ts +42 -0
  52. package/lib/Socket/socket.js +587 -0
  53. package/lib/Store/index.d.ts +3 -0
  54. package/lib/Store/index.js +10 -0
  55. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  56. package/lib/Store/make-cache-manager-store.js +83 -0
  57. package/lib/Store/make-in-memory-store.d.ts +117 -0
  58. package/lib/Store/make-in-memory-store.js +437 -0
  59. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  60. package/lib/Store/make-ordered-dictionary.js +81 -0
  61. package/lib/Store/object-repository.d.ts +10 -0
  62. package/lib/Store/object-repository.js +27 -0
  63. package/lib/Types/Auth.d.ts +108 -0
  64. package/lib/Types/Auth.js +2 -0
  65. package/lib/Types/Call.d.ts +12 -0
  66. package/lib/Types/Call.js +2 -0
  67. package/lib/Types/Chat.d.ts +102 -0
  68. package/lib/Types/Chat.js +4 -0
  69. package/lib/Types/Contact.d.ts +18 -0
  70. package/lib/Types/Contact.js +2 -0
  71. package/lib/Types/Events.d.ts +152 -0
  72. package/lib/Types/Events.js +2 -0
  73. package/lib/Types/GroupMetadata.d.ts +44 -0
  74. package/lib/Types/GroupMetadata.js +2 -0
  75. package/lib/Types/Label.d.ts +35 -0
  76. package/lib/Types/Label.js +27 -0
  77. package/lib/Types/LabelAssociation.d.ts +29 -0
  78. package/lib/Types/LabelAssociation.js +9 -0
  79. package/lib/Types/Message.d.ts +255 -0
  80. package/lib/Types/Message.js +9 -0
  81. package/lib/Types/Product.d.ts +78 -0
  82. package/lib/Types/Product.js +2 -0
  83. package/lib/Types/Signal.d.ts +57 -0
  84. package/lib/Types/Signal.js +2 -0
  85. package/lib/Types/Socket.d.ts +109 -0
  86. package/lib/Types/Socket.js +2 -0
  87. package/lib/Types/State.d.ts +27 -0
  88. package/lib/Types/State.js +2 -0
  89. package/lib/Types/index.d.ts +54 -0
  90. package/lib/Types/index.js +39 -0
  91. package/lib/Utils/auth-utils.d.ts +18 -0
  92. package/lib/Utils/auth-utils.js +204 -0
  93. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  94. package/lib/Utils/baileys-event-stream.js +63 -0
  95. package/lib/Utils/business.d.ts +22 -0
  96. package/lib/Utils/business.js +234 -0
  97. package/lib/Utils/chat-utils.d.ts +71 -0
  98. package/lib/Utils/chat-utils.js +710 -0
  99. package/lib/Utils/crypto.d.ts +41 -0
  100. package/lib/Utils/crypto.js +151 -0
  101. package/lib/Utils/decode-wa-message.d.ts +19 -0
  102. package/lib/Utils/decode-wa-message.js +160 -0
  103. package/lib/Utils/event-buffer.d.ts +35 -0
  104. package/lib/Utils/event-buffer.js +514 -0
  105. package/lib/Utils/generics.d.ts +93 -0
  106. package/lib/Utils/generics.js +366 -0
  107. package/lib/Utils/history.d.ts +15 -0
  108. package/lib/Utils/history.js +91 -0
  109. package/lib/Utils/index.d.ts +17 -0
  110. package/lib/Utils/index.js +33 -0
  111. package/lib/Utils/link-preview.d.ts +21 -0
  112. package/lib/Utils/link-preview.js +93 -0
  113. package/lib/Utils/logger.d.ts +4 -0
  114. package/lib/Utils/logger.js +7 -0
  115. package/lib/Utils/lt-hash.d.ts +12 -0
  116. package/lib/Utils/lt-hash.js +51 -0
  117. package/lib/Utils/make-mutex.d.ts +7 -0
  118. package/lib/Utils/make-mutex.js +43 -0
  119. package/lib/Utils/messages-media.d.ts +107 -0
  120. package/lib/Utils/messages-media.js +680 -0
  121. package/lib/Utils/messages.d.ts +76 -0
  122. package/lib/Utils/messages.js +762 -0
  123. package/lib/Utils/noise-handler.d.ts +20 -0
  124. package/lib/Utils/noise-handler.js +142 -0
  125. package/lib/Utils/process-message.d.ts +41 -0
  126. package/lib/Utils/process-message.js +297 -0
  127. package/lib/Utils/signal.d.ts +32 -0
  128. package/lib/Utils/signal.js +151 -0
  129. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  130. package/lib/Utils/use-multi-file-auth-state.js +80 -0
  131. package/lib/Utils/validate-connection.d.ts +11 -0
  132. package/lib/Utils/validate-connection.js +187 -0
  133. package/lib/WABinary/constants.d.ts +27 -0
  134. package/lib/WABinary/constants.js +40 -0
  135. package/lib/WABinary/decode.d.ts +7 -0
  136. package/lib/WABinary/decode.js +252 -0
  137. package/lib/WABinary/encode.d.ts +3 -0
  138. package/lib/WABinary/encode.js +228 -0
  139. package/lib/WABinary/generic-utils.d.ts +15 -0
  140. package/lib/WABinary/generic-utils.js +110 -0
  141. package/lib/WABinary/index.d.ts +5 -0
  142. package/lib/WABinary/index.js +21 -0
  143. package/lib/WABinary/jid-utils.d.ts +27 -0
  144. package/lib/WABinary/jid-utils.js +56 -0
  145. package/lib/WABinary/types.d.ts +18 -0
  146. package/lib/WABinary/types.js +2 -0
  147. package/lib/index.d.ts +10 -0
  148. package/lib/index.js +29 -0
  149. package/package.json +113 -0
package/README.md ADDED
@@ -0,0 +1,960 @@
1
+ # Baileys - Typescript/Javascript WhatsApp Web API
2
+
3
+ ### Important Note
4
+
5
+ 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.
6
+
7
+ #### Liability and License Notice
8
+ 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).
9
+ 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.
10
+ ##
11
+
12
+ Baileys does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a **WebSocket**.
13
+ Not running Selenium or Chromimum saves you like **half a gig** of ram :/
14
+ Baileys supports interacting with the multi-device & web versions of WhatsApp.
15
+ 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.
16
+
17
+ ## Please Read
18
+
19
+ The original repository had to be removed by the original author - we now continue development in this repository here.
20
+ This is the only official repository and is maintained by the community.
21
+ **Join the Discord [here](https://discord.gg/WeJM5FP9GG)**
22
+
23
+ ## Example
24
+
25
+ Do check out & run [example.ts](Example/example.ts) to see an example usage of the library.
26
+ The script covers most common use cases.
27
+ To run the example script, download or clone the repo and then type the following in a terminal:
28
+ 1. ``` cd path/to/Baileys ```
29
+ 2. ``` yarn ```
30
+ 3. ``` yarn example ```
31
+
32
+ ## Install
33
+
34
+ Use the stable version:
35
+ ```
36
+ yarn add @whiskeysockets/baileys
37
+ ```
38
+
39
+ Use the edge version (no guarantee of stability, but latest fixes + features)
40
+ ```
41
+ yarn add github:WhiskeySockets/Baileys
42
+ ```
43
+
44
+ Then import your code using:
45
+ ``` ts
46
+ import makeWASocket from '@whiskeysockets/baileys'
47
+ ```
48
+
49
+ ## Unit Tests
50
+
51
+ TODO
52
+
53
+ ## Connecting multi device (recommended)
54
+
55
+ WhatsApp provides a multi-device API that allows Baileys to be authenticated as a second WhatsApp client by scanning a QR code with WhatsApp on your phone.
56
+
57
+ ``` ts
58
+ import makeWASocket, { DisconnectReason } from '@whiskeysockets/baileys'
59
+ import { Boom } from '@hapi/boom'
60
+
61
+ async function connectToWhatsApp () {
62
+ const sock = makeWASocket({
63
+ // can provide additional config here
64
+ printQRInTerminal: true
65
+ })
66
+ sock.ev.on('connection.update', (update) => {
67
+ const { connection, lastDisconnect } = update
68
+ if(connection === 'close') {
69
+ const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
70
+ console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
71
+ // reconnect if not logged out
72
+ if(shouldReconnect) {
73
+ connectToWhatsApp()
74
+ }
75
+ } else if(connection === 'open') {
76
+ console.log('opened connection')
77
+ }
78
+ })
79
+ sock.ev.on('messages.upsert', m => {
80
+ console.log(JSON.stringify(m, undefined, 2))
81
+
82
+ console.log('replying to', m.messages[0].key.remoteJid)
83
+ await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
84
+ })
85
+ }
86
+ // run in main file
87
+ connectToWhatsApp()
88
+ ```
89
+
90
+ 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!
91
+
92
+ **Note:** install `qrcode-terminal` using `yarn add qrcode-terminal` to auto-print the QR to the terminal.
93
+
94
+ **Note:** the code to support the legacy version of WA Web (pre multi-device) has been removed in v5. Only the standard multi-device connection is now supported. This is done as WA seems to have completely dropped support for the legacy version.
95
+
96
+ ## Connecting native mobile api
97
+
98
+ Baileys also supports the native mobile API, which allows users to authenticate as a standalone WhatsApp client using their phone number.
99
+
100
+ Run the [example](Example/example.ts) file with ``--mobile`` cli flag to use the native mobile API.
101
+
102
+ ## Configuring the Connection
103
+
104
+ You can configure the connection by passing a `SocketConfig` object.
105
+
106
+ The entire `SocketConfig` structure is mentioned here with default values:
107
+ ``` ts
108
+ type SocketConfig = {
109
+ /** the WS url to connect to WA */
110
+ waWebSocketUrl: string | URL
111
+ /** Fails the connection if the socket times out in this interval */
112
+ connectTimeoutMs: number
113
+ /** Default timeout for queries, undefined for no timeout */
114
+ defaultQueryTimeoutMs: number | undefined
115
+ /** ping-pong interval for WS connection */
116
+ keepAliveIntervalMs: number
117
+ /** proxy agent */
118
+ agent?: Agent
119
+ /** pino logger */
120
+ logger: Logger
121
+ /** version to connect with */
122
+ version: WAVersion
123
+ /** override browser config */
124
+ browser: WABrowserDescription
125
+ /** agent used for fetch requests -- uploading/downloading media */
126
+ fetchAgent?: Agent
127
+ /** should the QR be printed in the terminal */
128
+ printQRInTerminal: boolean
129
+ /** should events be emitted for actions done by this socket connection */
130
+ emitOwnEvents: boolean
131
+ /** provide a cache to store media, so does not have to be re-uploaded */
132
+ mediaCache?: NodeCache
133
+ /** custom upload hosts to upload media to */
134
+ customUploadHosts: MediaConnInfo['hosts']
135
+ /** time to wait between sending new retry requests */
136
+ retryRequestDelayMs: number
137
+ /** time to wait for the generation of the next QR in ms */
138
+ qrTimeout?: number;
139
+ /** provide an auth state object to maintain the auth state */
140
+ auth: AuthenticationState
141
+ /** manage history processing with this control; by default will sync up everything */
142
+ shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean
143
+ /** transaction capability options for SignalKeyStore */
144
+ transactionOpts: TransactionCapabilityOptions
145
+ /** provide a cache to store a user's device list */
146
+ userDevicesCache?: NodeCache
147
+ /** marks the client as online whenever the socket successfully connects */
148
+ markOnlineOnConnect: boolean
149
+ /**
150
+ * map to store the retry counts for failed messages;
151
+ * used to determine whether to retry a message or not */
152
+ msgRetryCounterMap?: MessageRetryMap
153
+ /** width for link preview images */
154
+ linkPreviewImageThumbnailWidth: number
155
+ /** Should Baileys ask the phone for full history, will be received async */
156
+ syncFullHistory: boolean
157
+ /** Should baileys fire init queries automatically, default true */
158
+ fireInitQueries: boolean
159
+ /**
160
+ * generate a high quality link preview,
161
+ * entails uploading the jpegThumbnail to WA
162
+ * */
163
+ generateHighQualityLinkPreview: boolean
164
+
165
+ /** options for axios */
166
+ options: AxiosRequestConfig<any>
167
+ /**
168
+ * fetch a message from your store
169
+ * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
170
+ * */
171
+ getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
172
+ }
173
+ ```
174
+
175
+ ### Emulating the Desktop app instead of the web
176
+
177
+ 1. Baileys, by default, emulates a chrome web session
178
+ 2. If you'd like to emulate a desktop connection (and receive more message history), add this to your Socket config:
179
+ ``` ts
180
+ const conn = makeWASocket({
181
+ ...otherOpts,
182
+ // can use Windows, Ubuntu here too
183
+ browser: Browsers.macOS('Desktop'),
184
+ syncFullHistory: true
185
+ })
186
+ ```
187
+
188
+ ## Saving & Restoring Sessions
189
+
190
+ You obviously don't want to keep scanning the QR code every time you want to connect.
191
+
192
+ So, you can load the credentials to log back in:
193
+ ``` ts
194
+ import makeWASocket, { BufferJSON, useMultiFileAuthState } from '@whiskeysockets/baileys'
195
+ import * as fs from 'fs'
196
+
197
+ // utility function to help save the auth state in a single folder
198
+ // 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
199
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
200
+ // will use the given state to connect
201
+ // so if valid credentials are available -- it'll connect without QR
202
+ const conn = makeWASocket({ auth: state })
203
+ // this will be called as soon as the credentials are updated
204
+ conn.ev.on ('creds.update', saveCreds)
205
+ ```
206
+
207
+ **Note:** 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.
208
+
209
+ ## Listening to Connection Updates
210
+
211
+ Baileys now fires the `connection.update` event to let you know something has updated in the connection. This data has the following structure:
212
+ ``` ts
213
+ type ConnectionState = {
214
+ /** connection is now open, connecting or closed */
215
+ connection: WAConnectionState
216
+ /** the error that caused the connection to close */
217
+ lastDisconnect?: {
218
+ error: Error
219
+ date: Date
220
+ }
221
+ /** is this a new login */
222
+ isNewLogin?: boolean
223
+ /** the current QR code */
224
+ qr?: string
225
+ /** has the device received all pending notifications while it was offline */
226
+ receivedPendingNotifications?: boolean
227
+ }
228
+ ```
229
+
230
+ **Note:** this also offers any updates to the QR
231
+
232
+ ## Handling Events
233
+
234
+ Baileys uses the EventEmitter syntax for events.
235
+ They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
236
+
237
+ The events are typed as mentioned here:
238
+
239
+ ``` ts
240
+
241
+ export type BaileysEventMap = {
242
+ /** connection state has been updated -- WS closed, opened, connecting etc. */
243
+ 'connection.update': Partial<ConnectionState>
244
+ /** credentials updated -- some metadata, keys or something */
245
+ 'creds.update': Partial<AuthenticationCreds>
246
+ /** history sync, everything is reverse chronologically sorted */
247
+ 'messaging-history.set': {
248
+ chats: Chat[]
249
+ contacts: Contact[]
250
+ messages: WAMessage[]
251
+ isLatest: boolean
252
+ }
253
+ /** upsert chats */
254
+ 'chats.upsert': Chat[]
255
+ /** update the given chats */
256
+ 'chats.update': Partial<Chat>[]
257
+ /** delete chats with given ID */
258
+ 'chats.delete': string[]
259
+ 'labels.association': LabelAssociation
260
+ 'labels.edit': Label
261
+ /** presence of contact in a chat updated */
262
+ 'presence.update': { id: string, presences: { [participant: string]: PresenceData } }
263
+
264
+ 'contacts.upsert': Contact[]
265
+ 'contacts.update': Partial<Contact>[]
266
+
267
+ 'messages.delete': { keys: WAMessageKey[] } | { jid: string, all: true }
268
+ 'messages.update': WAMessageUpdate[]
269
+ 'messages.media-update': { key: WAMessageKey, media?: { ciphertext: Uint8Array, iv: Uint8Array }, error?: Boom }[]
270
+ /**
271
+ * add/update the given messages. If they were received while the connection was online,
272
+ * the update will have type: "notify"
273
+ * */
274
+ 'messages.upsert': { messages: WAMessage[], type: MessageUpsertType }
275
+ /** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
276
+ 'messages.reaction': { key: WAMessageKey, reaction: proto.IReaction }[]
277
+
278
+ 'message-receipt.update': MessageUserReceiptUpdate[]
279
+
280
+ 'groups.upsert': GroupMetadata[]
281
+ 'groups.update': Partial<GroupMetadata>[]
282
+ /** apply an action to participants in a group */
283
+ 'group-participants.update': { id: string, participants: string[], action: ParticipantAction }
284
+
285
+ 'blocklist.set': { blocklist: string[] }
286
+ 'blocklist.update': { blocklist: string[], type: 'add' | 'remove' }
287
+ /** Receive an update on a call, including when the call was received, rejected, accepted */
288
+ 'call': WACallEvent[]
289
+ }
290
+ ```
291
+
292
+ You can listen to these events like this:
293
+ ``` ts
294
+
295
+ const sock = makeWASocket()
296
+ sock.ev.on('messages.upsert', ({ messages }) => {
297
+ console.log('got messages', messages)
298
+ })
299
+
300
+ ```
301
+
302
+ ## Implementing a Data Store
303
+
304
+ 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.
305
+
306
+ It can be used as follows:
307
+
308
+ ``` ts
309
+ import makeWASocket, { makeInMemoryStore } from '@whiskeysockets/baileys'
310
+ // the store maintains the data of the WA connection in memory
311
+ // can be written out to a file & read from it
312
+ const store = makeInMemoryStore({ })
313
+ // can be read from a file
314
+ store.readFromFile('./baileys_store.json')
315
+ // saves the state to a file every 10s
316
+ setInterval(() => {
317
+ store.writeToFile('./baileys_store.json')
318
+ }, 10_000)
319
+
320
+ const sock = makeWASocket({ })
321
+ // will listen from this socket
322
+ // the store can listen from a new socket once the current socket outlives its lifetime
323
+ store.bind(sock.ev)
324
+
325
+ sock.ev.on('chats.set', () => {
326
+ // can use "store.chats" however you want, even after the socket dies out
327
+ // "chats" => a KeyedDB instance
328
+ console.log('got chats', store.chats.all())
329
+ })
330
+
331
+ sock.ev.on('contacts.set', () => {
332
+ console.log('got contacts', Object.values(store.contacts))
333
+ })
334
+
335
+ ```
336
+
337
+ The store also provides some simple functions such as `loadMessages` that utilize the store to speed up data retrieval.
338
+
339
+ **Note:** I highly recommend building your own data store especially for MD connections, as storing someone's entire chat history in memory is a terrible waste of RAM.
340
+
341
+ ## Sending Messages
342
+
343
+ **Send all types of messages with a single function:**
344
+
345
+ ### Non-Media Messages
346
+
347
+ ``` ts
348
+ import { MessageType, MessageOptions, Mimetype } from '@whiskeysockets/baileys'
349
+
350
+ const id = 'abcd@s.whatsapp.net' // the WhatsApp ID
351
+ // send a simple text!
352
+ const sentMsg = await sock.sendMessage(id, { text: 'oh hello there' })
353
+ // send a reply messagge
354
+ const sentMsg = await sock.sendMessage(id, { text: 'oh hello there' }, { quoted: message })
355
+ // send a mentions message
356
+ const sentMsg = await sock.sendMessage(id, { text: '@12345678901', mentions: ['12345678901@s.whatsapp.net'] })
357
+ // send a location!
358
+ const sentMsg = await sock.sendMessage(
359
+ id,
360
+ { location: { degreesLatitude: 24.121231, degreesLongitude: 55.1121221 } }
361
+ )
362
+ // send a contact!
363
+ const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
364
+ + 'VERSION:3.0\n'
365
+ + 'FN:Jeff Singh\n' // full name
366
+ + 'ORG:Ashoka Uni;\n' // the organization of the contact
367
+ + 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
368
+ + 'END:VCARD'
369
+ const sentMsg = await sock.sendMessage(
370
+ id,
371
+ {
372
+ contacts: {
373
+ displayName: 'Jeff',
374
+ contacts: [{ vcard }]
375
+ }
376
+ }
377
+ )
378
+
379
+ // send a buttons message!
380
+ const buttons = [
381
+ {buttonId: 'id1', buttonText: {displayText: 'Button 1'}, type: 1},
382
+ {buttonId: 'id2', buttonText: {displayText: 'Button 2'}, type: 1},
383
+ {buttonId: 'id3', buttonText: {displayText: 'Button 3'}, type: 1}
384
+ ]
385
+
386
+ const buttonMessage = {
387
+ text: "Hi it's button message",
388
+ footer: 'Hello World',
389
+ buttons: buttons,
390
+ headerType: 1
391
+ }
392
+
393
+ const sendMsg = await sock.sendMessage(id, buttonMessage)
394
+
395
+ //send a template message!
396
+ const templateButtons = [
397
+ {index: 1, urlButton: {displayText: '⭐ Star Baileys on GitHub!', url: 'https://github.com/adiwajshing/Baileys'}},
398
+ {index: 2, callButton: {displayText: 'Call me!', phoneNumber: '+1 (234) 5678-901'}},
399
+ {index: 3, quickReplyButton: {displayText: 'This is a reply, just like normal buttons!', id: 'id-like-buttons-message'}},
400
+ ]
401
+
402
+ const templateMessage = {
403
+ text: "Hi it's a template message",
404
+ footer: 'Hello World',
405
+ templateButtons: templateButtons
406
+ }
407
+
408
+ const sendMsg = await sock.sendMessage(id, templateMessage)
409
+
410
+ // send a list message!
411
+ const sections = [
412
+ {
413
+ title: "Section 1",
414
+ rows: [
415
+ {title: "Option 1", rowId: "option1"},
416
+ {title: "Option 2", rowId: "option2", description: "This is a description"}
417
+ ]
418
+ },
419
+ {
420
+ title: "Section 2",
421
+ rows: [
422
+ {title: "Option 3", rowId: "option3"},
423
+ {title: "Option 4", rowId: "option4", description: "This is a description V2"}
424
+ ]
425
+ },
426
+ ]
427
+
428
+ const listMessage = {
429
+ text: "This is a list",
430
+ footer: "nice footer, link: https://google.com",
431
+ title: "Amazing boldfaced list title",
432
+ buttonText: "Required, text on the button to view the list",
433
+ sections
434
+ }
435
+
436
+ const sendMsg = await sock.sendMessage(id, listMessage)
437
+
438
+ const reactionMessage = {
439
+ react: {
440
+ text: "💖", // use an empty string to remove the reaction
441
+ key: message.key
442
+ }
443
+ }
444
+
445
+ const sendMsg = await sock.sendMessage(id, reactionMessage)
446
+ ```
447
+
448
+ ### Sending messages with link previews
449
+
450
+ 1. By default, WA MD does not have link generation when sent from the web
451
+ 2. Baileys has a function to generate the content for these link previews
452
+ 3. To enable this function's usage, add `link-preview-js` as a dependency to your project with `yarn add link-preview-js`
453
+ 4. Send a link:
454
+ ``` ts
455
+ // send a link
456
+ const sentMsg = await sock.sendMessage(id, { text: 'Hi, this was sent using https://github.com/adiwajshing/baileys' })
457
+ ```
458
+
459
+ ### Media Messages
460
+
461
+ Sending media (video, stickers, images) is easier & more efficient than ever.
462
+ - You can specify a buffer, a local url or even a remote url.
463
+ - When specifying a media url, Baileys never loads the entire buffer into memory; it even encrypts the media as a readable stream.
464
+
465
+ ``` ts
466
+ import { MessageType, MessageOptions, Mimetype } from '@whiskeysockets/baileys'
467
+ // Sending gifs
468
+ await sock.sendMessage(
469
+ id,
470
+ {
471
+ video: fs.readFileSync("Media/ma_gif.mp4"),
472
+ caption: "hello!",
473
+ gifPlayback: true
474
+ }
475
+ )
476
+
477
+ await sock.sendMessage(
478
+ id,
479
+ {
480
+ video: "./Media/ma_gif.mp4",
481
+ caption: "hello!",
482
+ gifPlayback: true
483
+ }
484
+ )
485
+
486
+ // send an audio file
487
+ await sock.sendMessage(
488
+ id,
489
+ { audio: { url: "./Media/audio.mp3" }, mimetype: 'audio/mp4' }
490
+ { url: "Media/audio.mp3" }, // can send mp3, mp4, & ogg
491
+ )
492
+
493
+ // send a buttons message with image header!
494
+ const buttons = [
495
+ {buttonId: 'id1', buttonText: {displayText: 'Button 1'}, type: 1},
496
+ {buttonId: 'id2', buttonText: {displayText: 'Button 2'}, type: 1},
497
+ {buttonId: 'id3', buttonText: {displayText: 'Button 3'}, type: 1}
498
+ ]
499
+
500
+ const buttonMessage = {
501
+ image: {url: 'https://example.com/image.jpeg'},
502
+ caption: "Hi it's button message",
503
+ footer: 'Hello World',
504
+ buttons: buttons,
505
+ headerType: 4
506
+ }
507
+
508
+ const sendMsg = await sock.sendMessage(id, buttonMessage)
509
+
510
+ //send a template message with an image **attached**!
511
+ const templateButtons = [
512
+ {index: 1, urlButton: {displayText: '⭐ Star Baileys on GitHub!', url: 'https://github.com/adiwajshing/Baileys'}},
513
+ {index: 2, callButton: {displayText: 'Call me!', phoneNumber: '+1 (234) 5678-901'}},
514
+ {index: 3, quickReplyButton: {displayText: 'This is a reply, just like normal buttons!', id: 'id-like-buttons-message'}},
515
+ ]
516
+
517
+ const buttonMessage = {
518
+ text: "Hi it's a template message",
519
+ footer: 'Hello World',
520
+ templateButtons: templateButtons,
521
+ image: {url: 'https://example.com/image.jpeg'}
522
+ }
523
+
524
+ const sendMsg = await sock.sendMessage(id, templateMessage)
525
+ ```
526
+
527
+ ### Notes
528
+
529
+ - `id` is the WhatsApp ID of the person or group you're sending the message to.
530
+ - It must be in the format ```[country code][phone number]@s.whatsapp.net```
531
+ - Example for people: ```+19999999999@s.whatsapp.net```.
532
+ - For groups, it must be in the format ``` 123456789-123345@g.us ```.
533
+ - For broadcast lists, it's `[timestamp of creation]@broadcast`.
534
+ - For stories, the ID is `status@broadcast`.
535
+ - 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`. Thumbnails for videos can also be generated automatically, though, you need to have `ffmpeg` installed on your system.
536
+ - **MiscGenerationOptions**: some extra info about the message. It can have the following __optional__ values:
537
+ ``` ts
538
+ const info: MessageOptions = {
539
+ quoted: quotedMessage, // the message you want to quote
540
+ contextInfo: { forwardingScore: 2, isForwarded: true }, // some random context info (can show a forwarded message with this too)
541
+ timestamp: Date(), // optional, if you want to manually set the timestamp of the message
542
+ caption: "hello there!", // (for media messages) the caption to send with the media (cannot be sent with stickers though)
543
+ jpegThumbnail: "23GD#4/==", /* (for location & media messages) has to be a base 64 encoded JPEG if you want to send a custom thumb,
544
+ or set to null if you don't want to send a thumbnail.
545
+ Do not enter this field if you want to automatically generate a thumb
546
+ */
547
+ mimetype: Mimetype.pdf, /* (for media messages) specify the type of media (optional for all media types except documents),
548
+ import {Mimetype} from '@whiskeysockets/baileys'
549
+ */
550
+ fileName: 'somefile.pdf', // (for media messages) file name for the media
551
+ /* will send audio messages as voice notes, if set to true */
552
+ ptt: true,
553
+ /** Should it send as a disappearing messages.
554
+ * By default 'chat' -- which follows the setting of the chat */
555
+ ephemeralExpiration: WA_DEFAULT_EPHEMERAL
556
+ }
557
+ ```
558
+ ## Forwarding Messages
559
+
560
+ ``` ts
561
+ const msg = getMessageFromStore('455@s.whatsapp.net', 'HSJHJWH7323HSJSJ') // implement this on your end
562
+ await sock.sendMessage('1234@s.whatsapp.net', { forward: msg }) // WA forward the message!
563
+ ```
564
+
565
+ ## Reading Messages
566
+
567
+ A set of message keys must be explicitly marked read now.
568
+ In multi-device, you cannot mark an entire "chat" read as it were with Baileys Web.
569
+ This means you have to keep track of unread messages.
570
+
571
+ ``` ts
572
+ const key = {
573
+ remoteJid: '1234-123@g.us',
574
+ id: 'AHASHH123123AHGA', // id of the message you want to read
575
+ participant: '912121232@s.whatsapp.net' // the ID of the user that sent the message (undefined for individual chats)
576
+ }
577
+ // pass to readMessages function
578
+ // can pass multiple keys to read multiple messages as well
579
+ await sock.readMessages([key])
580
+ ```
581
+
582
+ The message ID is the unique identifier of the message that you are marking as read.
583
+ On a `WAMessage`, the `messageID` can be accessed using ```messageID = message.key.id```.
584
+
585
+ ## Update Presence
586
+
587
+ ``` ts
588
+ await sock.sendPresenceUpdate('available', id)
589
+
590
+ ```
591
+ This lets the person/group with ``` id ``` know whether you're online, offline, typing etc.
592
+
593
+ ``` presence ``` can be one of the following:
594
+ ``` ts
595
+ type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused'
596
+ ```
597
+
598
+ The presence expires after about 10 seconds.
599
+
600
+ **Note:** In the multi-device version of WhatsApp -- 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')`
601
+
602
+ ## Downloading Media Messages
603
+
604
+ If you want to save the media you received
605
+ ``` ts
606
+ import { writeFile } from 'fs/promises'
607
+ import { downloadMediaMessage } from '@whiskeysockets/baileys'
608
+
609
+ sock.ev.on('messages.upsert', async ({ messages }) => {
610
+ const m = messages[0]
611
+
612
+ if (!m.message) return // if there is no text or media message
613
+ const messageType = Object.keys (m.message)[0]// get what type of message it is -- text, image, video
614
+ // if the message is an image
615
+ if (messageType === 'imageMessage') {
616
+ // download the message
617
+ const buffer = await downloadMediaMessage(
618
+ m,
619
+ 'buffer',
620
+ { },
621
+ {
622
+ logger,
623
+ // pass this so that baileys can request a reupload of media
624
+ // that has been deleted
625
+ reuploadRequest: sock.updateMediaMessage
626
+ }
627
+ )
628
+ // save to file
629
+ await writeFile('./my-download.jpeg', buffer)
630
+ }
631
+ }
632
+ ```
633
+
634
+ **Note:** 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:
635
+ ``` ts
636
+ const updatedMediaMsg = await sock.updateMediaMessage(msg)
637
+ ```
638
+
639
+ ## Deleting Messages
640
+
641
+ ``` ts
642
+ const jid = '1234@s.whatsapp.net' // can also be a group
643
+ const response = await sock.sendMessage(jid, { text: 'hello!' }) // send a message
644
+ // sends a message to delete the given message
645
+ // this deletes the message for everyone
646
+ await sock.sendMessage(jid, { delete: response.key })
647
+ ```
648
+
649
+ **Note:** deleting for oneself is supported via `chatModify` (next section)
650
+
651
+ ## Modifying Chats
652
+
653
+ WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
654
+
655
+ - Archive a chat
656
+ ``` ts
657
+ const lastMsgInChat = await getLastMessageInChat('123456@s.whatsapp.net') // implement this on your end
658
+ await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, '123456@s.whatsapp.net')
659
+ ```
660
+ - Mute/unmute a chat
661
+ ``` ts
662
+ // mute for 8 hours
663
+ await sock.chatModify({ mute: 8*60*60*1000 }, '123456@s.whatsapp.net', [])
664
+ // unmute
665
+ await sock.chatModify({ mute: null }, '123456@s.whatsapp.net', [])
666
+ ```
667
+ - Mark a chat read/unread
668
+ ``` ts
669
+ const lastMsgInChat = await getLastMessageInChat('123456@s.whatsapp.net') // implement this on your end
670
+ // mark it unread
671
+ await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, '123456@s.whatsapp.net')
672
+ ```
673
+
674
+ - Delete a message for me
675
+ ``` ts
676
+ await sock.chatModify(
677
+ { clear: { messages: [{ id: 'ATWYHDNNWU81732J', fromMe: true, timestamp: "1654823909" }] } },
678
+ '123456@s.whatsapp.net',
679
+ []
680
+ )
681
+
682
+ ```
683
+
684
+ - Delete a chat
685
+ ``` ts
686
+ const lastMsgInChat = await getLastMessageInChat('123456@s.whatsapp.net') // implement this on your end
687
+ await sock.chatModify({
688
+ delete: true,
689
+ lastMessages: [{ key: lastMsgInChat.key, messageTimestamp: lastMsgInChat.messageTimestamp }]
690
+ },
691
+ '123456@s.whatsapp.net')
692
+ ```
693
+
694
+ - Pin/unpin a chat
695
+ ``` ts
696
+ await sock.chatModify({
697
+ pin: true // or `false` to unpin
698
+ },
699
+ '123456@s.whatsapp.net')
700
+ ```
701
+
702
+ **Note:** 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.
703
+
704
+ ## Disappearing Messages
705
+
706
+ ``` ts
707
+ const jid = '1234@s.whatsapp.net' // can also be a group
708
+ // turn on disappearing messages
709
+ await sock.sendMessage(
710
+ jid,
711
+ // this is 1 week in seconds -- how long you want messages to appear for
712
+ { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL }
713
+ )
714
+ // will send as a disappearing message
715
+ await sock.sendMessage(jid, { text: 'hello' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL })
716
+ // turn off disappearing messages
717
+ await sock.sendMessage(
718
+ jid,
719
+ { disappearingMessagesInChat: false }
720
+ )
721
+
722
+ ```
723
+
724
+ ## Misc
725
+
726
+ - To check if a given ID is on WhatsApp
727
+ ``` ts
728
+ const id = '123456'
729
+ const [result] = await sock.onWhatsApp(id)
730
+ if (result.exists) console.log (`${id} exists on WhatsApp, as jid: ${result.jid}`)
731
+ ```
732
+ - To query chat history on a group or with someone
733
+ TODO, if possible
734
+ - To get the status of some person
735
+ ``` ts
736
+ const status = await sock.fetchStatus("xyz@s.whatsapp.net")
737
+ console.log("status: " + status)
738
+ ```
739
+ - To change your profile status
740
+ ``` ts
741
+ const status = 'Hello World!'
742
+ await sock.updateProfileStatus(status)
743
+ ```
744
+ - To change your profile name
745
+ ``` ts
746
+ const name = 'My name'
747
+ await sock.updateProfileName(name)
748
+ ```
749
+ - To get the display picture of some person/group
750
+ ``` ts
751
+ // for low res picture
752
+ const ppUrl = await sock.profilePictureUrl("xyz@g.us")
753
+ console.log("download profile picture from: " + ppUrl)
754
+ // for high res picture
755
+ const ppUrl = await sock.profilePictureUrl("xyz@g.us", 'image')
756
+ ```
757
+ - To change your display picture or a group's
758
+ ``` ts
759
+ const jid = '111234567890-1594482450@g.us' // can be your own too
760
+ await sock.updateProfilePicture(jid, { url: './new-profile-picture.jpeg' })
761
+ ```
762
+ - To remove your display picture or a group's
763
+ ``` ts
764
+ const jid = '111234567890-1594482450@g.us' // can be your own too
765
+ await sock.removeProfilePicture(jid)
766
+ ```
767
+ - To get someone's presence (if they're typing or online)
768
+ ``` ts
769
+ // the presence update is fetched and called here
770
+ sock.ev.on('presence.update', json => console.log(json))
771
+ // request updates for a chat
772
+ await sock.presenceSubscribe("xyz@s.whatsapp.net")
773
+ ```
774
+ - To block or unblock user
775
+ ``` ts
776
+ await sock.updateBlockStatus("xyz@s.whatsapp.net", "block") // Block user
777
+ await sock.updateBlockStatus("xyz@s.whatsapp.net", "unblock") // Unblock user
778
+ ```
779
+ - To get a business profile, such as description or category
780
+ ```ts
781
+ const profile = await sock.getBusinessProfile("xyz@s.whatsapp.net")
782
+ console.log("business description: " + profile.description + ", category: " + profile.category)
783
+ ```
784
+ Of course, replace ``` xyz ``` with an actual ID.
785
+
786
+ ## Groups
787
+ - To create a group
788
+ ``` ts
789
+ // title & participants
790
+ const group = await sock.groupCreate("My Fab Group", ["1234@s.whatsapp.net", "4564@s.whatsapp.net"])
791
+ console.log ("created group with id: " + group.gid)
792
+ sock.sendMessage(group.id, { text: 'hello there' }) // say hello to everyone on the group
793
+ ```
794
+ - To add/remove people to a group or demote/promote people
795
+ ``` ts
796
+ // id & people to add to the group (will throw error if it fails)
797
+ const response = await sock.groupParticipantsUpdate(
798
+ "abcd-xyz@g.us",
799
+ ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"],
800
+ "add" // replace this parameter with "remove", "demote" or "promote"
801
+ )
802
+ ```
803
+ - To change the group's subject
804
+ ``` ts
805
+ await sock.groupUpdateSubject("abcd-xyz@g.us", "New Subject!")
806
+ ```
807
+ - To change the group's description
808
+ ``` ts
809
+ await sock.groupUpdateDescription("abcd-xyz@g.us", "New Description!")
810
+ ```
811
+ - To change group settings
812
+ ``` ts
813
+ // only allow admins to send messages
814
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'announcement')
815
+ // allow everyone to send messages
816
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'not_announcement')
817
+ // allow everyone to modify the group's settings -- like display picture etc.
818
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'unlocked')
819
+ // only allow admins to modify the group's settings
820
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'locked')
821
+ ```
822
+ - To leave a group
823
+ ``` ts
824
+ await sock.groupLeave("abcd-xyz@g.us") // (will throw error if it fails)
825
+ ```
826
+ - To get the invite code for a group
827
+ ``` ts
828
+ const code = await sock.groupInviteCode("abcd-xyz@g.us")
829
+ console.log("group code: " + code)
830
+ ```
831
+ - To revoke the invite code in a group
832
+ ```ts
833
+ const code = await sock.groupRevokeInvite("abcd-xyz@g.us")
834
+ console.log("New group code: " + code)
835
+ ```
836
+ - To query the metadata of a group
837
+ ``` ts
838
+ const metadata = await sock.groupMetadata("abcd-xyz@g.us")
839
+ console.log(metadata.id + ", title: " + metadata.subject + ", description: " + metadata.desc)
840
+ ```
841
+ - To join the group using the invitation code
842
+ ``` ts
843
+ const response = await sock.groupAcceptInvite("xxx")
844
+ console.log("joined to: " + response)
845
+ ```
846
+ Of course, replace ``` xxx ``` with invitation code.
847
+ - To get group info by invite code
848
+ ```ts
849
+ const response = await sock.groupGetInviteInfo("xxx")
850
+ console.log("group information: " + response)
851
+ ```
852
+ - To join the group using groupInviteMessage
853
+ ``` ts
854
+ const response = await sock.groupAcceptInviteV4("abcd@s.whatsapp.net", groupInviteMessage)
855
+ console.log("joined to: " + response)
856
+ ```
857
+ Of course, replace ``` xxx ``` with invitation code.
858
+
859
+ - To get list request join
860
+ ``` ts
861
+ const response = await sock.groupRequestParticipantsList("abcd-xyz@g.us")
862
+ console.log(response)
863
+ ```
864
+ - To approve/reject request join
865
+ ``` ts
866
+ const response = await sock.groupRequestParticipantsUpdate(
867
+ "abcd-xyz@g.us", // id group,
868
+ ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"],
869
+ "approve" // replace this parameter with "reject"
870
+ )
871
+ console.log(response)
872
+ ```
873
+
874
+ ## Privacy
875
+ - To get the privacy settings
876
+ ``` ts
877
+ const privacySettings = await sock.fetchPrivacySettings(true)
878
+ console.log("privacy settings: " + privacySettings)
879
+ ```
880
+ - To update the LastSeen privacy
881
+ ``` ts
882
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
883
+ await sock.updateLastSeenPrivacy(value)
884
+ ```
885
+ - To update the Online privacy
886
+ ``` ts
887
+ const value = 'all' // 'match_last_seen'
888
+ await sock.updateOnlinePrivacy(value)
889
+ ```
890
+ - To update the Profile Picture privacy
891
+ ``` ts
892
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
893
+ await sock.updateProfilePicturePrivacy(value)
894
+ ```
895
+ - To update the Status privacy
896
+ ``` ts
897
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
898
+ await sock.updateStatusPrivacy(value)
899
+ ```
900
+ - To update the Read Receipts privacy
901
+ ``` ts
902
+ const value = 'all' // 'none'
903
+ await sock.updateReadReceiptsPrivacy(value)
904
+ ```
905
+ - To update the Groups Add privacy
906
+ ``` ts
907
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
908
+ await sock.updateGroupsAddPrivacy(value)
909
+ ```
910
+ - To update the Default Disappearing Mode
911
+ ``` ts
912
+ const duration = 86400 // 604800 | 7776000 | 0
913
+ await sock.updateDefaultDisappearingMode(duration)
914
+ ```
915
+ ## Broadcast Lists & Stories
916
+
917
+ **Note:** messages currently cannot be sent to broadcast lists from the MD version.
918
+
919
+ - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
920
+ - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
921
+ - Broadcast IDs are in the format `12345678@broadcast`
922
+ - To query a broadcast list's recipients & name:
923
+ ``` ts
924
+ const bList = await sock.getBroadcastListInfo("1234@broadcast")
925
+ console.log (`list name: ${bList.name}, recps: ${bList.recipients}`)
926
+ ```
927
+
928
+ ## Writing Custom Functionality
929
+ Baileys is written with custom functionality in mind. Instead of forking the project & re-writing the internals, you can simply write your own extensions.
930
+
931
+ First, enable the logging of unhandled messages from WhatsApp by setting:
932
+ ``` ts
933
+ const sock = makeWASocket({
934
+ logger: P({ level: 'debug' }),
935
+ })
936
+ ```
937
+ This will enable you to see all sorts of messages WhatsApp sends in the console.
938
+
939
+ Some examples:
940
+
941
+ 1. Functionality to track the battery percentage of your phone.
942
+ You enable logging and you'll see a message about your battery pop up in the console:
943
+ ```{"level":10,"fromMe":false,"frame":{"tag":"ib","attrs":{"from":"@s.whatsapp.net"},"content":[{"tag":"edge_routing","attrs":{},"content":[{"tag":"routing_info","attrs":{},"content":{"type":"Buffer","data":[8,2,8,5]}}]}]},"msg":"communication"} ```
944
+
945
+ The "frame" is what the message received is, it has three components:
946
+ - `tag` -- what this frame is about (eg. message will have "message")
947
+ - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
948
+ - `content` -- the actual data (eg. a message node will have the actual message content in it)
949
+ - read more about this format [here](/src/WABinary/readme.md)
950
+
951
+ You can register a callback for an event using the following:
952
+ ``` ts
953
+ // for any message with tag 'edge_routing'
954
+ sock.ws.on(`CB:edge_routing`, (node: BinaryNode) => { })
955
+ // for any message with tag 'edge_routing' and id attribute = abcd
956
+ sock.ws.on(`CB:edge_routing,id:abcd`, (node: BinaryNode) => { })
957
+ // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
958
+ sock.ws.on(`CB:edge_routing,id:abcd,routing_info`, (node: BinaryNode) => { })
959
+ ```
960
+ Also, this repo is now licenced under GPL 3 since it uses [libsignal-node](https://git.questbook.io/backend/service-coderunner/-/merge_requests/1)