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