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