@d0v3riz/baileys 6.3.0

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