lordceaser-baileys 2.0.49 → 2.0.51

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +899 -0
  3. package/index.js +5 -6
  4. package/package.json +16 -17
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 WhiskeySockets
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,899 @@
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.upsert', () => {
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.upsert', () => {
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
+ ptv: false // if set to true, will send as a `video note`
427
+ }
428
+ )
429
+
430
+ // send an audio file
431
+ await sock.sendMessage(
432
+ id,
433
+ { audio: { url: "./Media/audio.mp3" }, mimetype: 'audio/mp4' }
434
+ { url: "Media/audio.mp3" }, // can send mp3, mp4, & ogg
435
+ )
436
+ ```
437
+
438
+ ### Notes
439
+
440
+ - `id` is the WhatsApp ID of the person or group you're sending the message to.
441
+ - It must be in the format ```[country code][phone number]@s.whatsapp.net```
442
+ - Example for people: ```+19999999999@s.whatsapp.net```.
443
+ - For groups, it must be in the format ``` 123456789-123345@g.us ```.
444
+ - For broadcast lists, it's `[timestamp of creation]@broadcast`.
445
+ - For stories, the ID is `status@broadcast`.
446
+ - 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.
447
+ - **MiscGenerationOptions**: some extra info about the message. It can have the following __optional__ values:
448
+ ``` ts
449
+ const info: MessageOptions = {
450
+ quoted: quotedMessage, // the message you want to quote
451
+ contextInfo: { forwardingScore: 2, isForwarded: true }, // some random context info (can show a forwarded message with this too)
452
+ timestamp: Date(), // optional, if you want to manually set the timestamp of the message
453
+ caption: "hello there!", // (for media messages) the caption to send with the media (cannot be sent with stickers though)
454
+ jpegThumbnail: "23GD#4/==", /* (for location & media messages) has to be a base 64 encoded JPEG if you want to send a custom thumb,
455
+ or set to null if you don't want to send a thumbnail.
456
+ Do not enter this field if you want to automatically generate a thumb
457
+ */
458
+ mimetype: Mimetype.pdf, /* (for media messages) specify the type of media (optional for all media types except documents),
459
+ import {Mimetype} from '@whiskeysockets/baileys'
460
+ */
461
+ fileName: 'somefile.pdf', // (for media messages) file name for the media
462
+ /* will send audio messages as voice notes, if set to true */
463
+ ptt: true,
464
+ /** Should it send as a disappearing messages.
465
+ * By default 'chat' -- which follows the setting of the chat */
466
+ ephemeralExpiration: WA_DEFAULT_EPHEMERAL
467
+ }
468
+ ```
469
+ ## Forwarding Messages
470
+
471
+ ``` ts
472
+ const msg = getMessageFromStore('455@s.whatsapp.net', 'HSJHJWH7323HSJSJ') // implement this on your end
473
+ await sock.sendMessage('1234@s.whatsapp.net', { forward: msg }) // WA forward the message!
474
+ ```
475
+
476
+ ## Reading Messages
477
+
478
+ A set of message keys must be explicitly marked read now.
479
+ In multi-device, you cannot mark an entire "chat" read as it were with Baileys Web.
480
+ This means you have to keep track of unread messages.
481
+
482
+ ``` ts
483
+ const key = {
484
+ remoteJid: '1234-123@g.us',
485
+ id: 'AHASHH123123AHGA', // id of the message you want to read
486
+ participant: '912121232@s.whatsapp.net' // the ID of the user that sent the message (undefined for individual chats)
487
+ }
488
+ // pass to readMessages function
489
+ // can pass multiple keys to read multiple messages as well
490
+ await sock.readMessages([key])
491
+ ```
492
+
493
+ The message ID is the unique identifier of the message that you are marking as read.
494
+ On a `WAMessage`, the `messageID` can be accessed using ```messageID = message.key.id```.
495
+
496
+ ## Update Presence
497
+
498
+ ``` ts
499
+ await sock.sendPresenceUpdate('available', id)
500
+
501
+ ```
502
+ This lets the person/group with ``` id ``` know whether you're online, offline, typing etc.
503
+
504
+ ``` presence ``` can be one of the following:
505
+ ``` ts
506
+ type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused'
507
+ ```
508
+
509
+ The presence expires after about 10 seconds.
510
+
511
+ **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')`
512
+
513
+ ## Downloading Media Messages
514
+
515
+ If you want to save the media you received
516
+ ``` ts
517
+ import { writeFile } from 'fs/promises'
518
+ import { downloadMediaMessage } from '@whiskeysockets/baileys'
519
+
520
+ sock.ev.on('messages.upsert', async ({ messages }) => {
521
+ const m = messages[0]
522
+
523
+ if (!m.message) return // if there is no text or media message
524
+ const messageType = Object.keys (m.message)[0]// get what type of message it is -- text, image, video
525
+ // if the message is an image
526
+ if (messageType === 'imageMessage') {
527
+ // download the message
528
+ const buffer = await downloadMediaMessage(
529
+ m,
530
+ 'buffer',
531
+ { },
532
+ {
533
+ logger,
534
+ // pass this so that baileys can request a reupload of media
535
+ // that has been deleted
536
+ reuploadRequest: sock.updateMediaMessage
537
+ }
538
+ )
539
+ // save to file
540
+ await writeFile('./my-download.jpeg', buffer)
541
+ }
542
+ }
543
+ ```
544
+
545
+ **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:
546
+ ``` ts
547
+ const updatedMediaMsg = await sock.updateMediaMessage(msg)
548
+ ```
549
+
550
+ ## Deleting Messages
551
+
552
+ ``` ts
553
+ const jid = '1234@s.whatsapp.net' // can also be a group
554
+ const response = await sock.sendMessage(jid, { text: 'hello!' }) // send a message
555
+ // sends a message to delete the given message
556
+ // this deletes the message for everyone
557
+ await sock.sendMessage(jid, { delete: response.key })
558
+ ```
559
+
560
+ **Note:** deleting for oneself is supported via `chatModify` (next section)
561
+
562
+ ## Updating Messages
563
+
564
+ ``` ts
565
+ const jid = '1234@s.whatsapp.net'
566
+
567
+ await sock.sendMessage(jid, {
568
+ text: 'updated text goes here',
569
+ edit: response.key,
570
+ });
571
+ ```
572
+
573
+ ## Modifying Chats
574
+
575
+ WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
576
+
577
+ - Archive a chat
578
+ ``` ts
579
+ const lastMsgInChat = await getLastMessageInChat('123456@s.whatsapp.net') // implement this on your end
580
+ await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, '123456@s.whatsapp.net')
581
+ ```
582
+ - Mute/unmute a chat
583
+ ``` ts
584
+ // mute for 8 hours
585
+ await sock.chatModify({ mute: 8*60*60*1000 }, '123456@s.whatsapp.net', [])
586
+ // unmute
587
+ await sock.chatModify({ mute: null }, '123456@s.whatsapp.net', [])
588
+ ```
589
+ - Mark a chat read/unread
590
+ ``` ts
591
+ const lastMsgInChat = await getLastMessageInChat('123456@s.whatsapp.net') // implement this on your end
592
+ // mark it unread
593
+ await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, '123456@s.whatsapp.net')
594
+ ```
595
+
596
+ - Delete a message for me
597
+ ``` ts
598
+ await sock.chatModify(
599
+ { clear: { messages: [{ id: 'ATWYHDNNWU81732J', fromMe: true, timestamp: "1654823909" }] } },
600
+ '123456@s.whatsapp.net',
601
+ []
602
+ )
603
+
604
+ ```
605
+
606
+ - Delete a chat
607
+ ``` ts
608
+ const lastMsgInChat = await getLastMessageInChat('123456@s.whatsapp.net') // implement this on your end
609
+ await sock.chatModify({
610
+ delete: true,
611
+ lastMessages: [{ key: lastMsgInChat.key, messageTimestamp: lastMsgInChat.messageTimestamp }]
612
+ },
613
+ '123456@s.whatsapp.net')
614
+ ```
615
+
616
+ - Pin/unpin a chat
617
+ ``` ts
618
+ await sock.chatModify({
619
+ pin: true // or `false` to unpin
620
+ },
621
+ '123456@s.whatsapp.net')
622
+ ```
623
+
624
+ - Star/unstar a message
625
+ ``` ts
626
+ await sock.chatModify({
627
+ star: {
628
+ messages: [{ id: 'messageID', fromMe: true // or `false` }],
629
+ star: true // - true: Star Message; false: Unstar Message
630
+ }},'123456@s.whatsapp.net');
631
+ ```
632
+
633
+ **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.
634
+
635
+ ## Disappearing Messages
636
+
637
+ ``` ts
638
+ const jid = '1234@s.whatsapp.net' // can also be a group
639
+ // turn on disappearing messages
640
+ await sock.sendMessage(
641
+ jid,
642
+ // this is 1 week in seconds -- how long you want messages to appear for
643
+ { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL }
644
+ )
645
+ // will send as a disappearing message
646
+ await sock.sendMessage(jid, { text: 'hello' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL })
647
+ // turn off disappearing messages
648
+ await sock.sendMessage(
649
+ jid,
650
+ { disappearingMessagesInChat: false }
651
+ )
652
+
653
+ ```
654
+
655
+ ## Misc
656
+
657
+ - To check if a given ID is on WhatsApp
658
+ ``` ts
659
+ const id = '123456'
660
+ const [result] = await sock.onWhatsApp(id)
661
+ if (result.exists) console.log (`${id} exists on WhatsApp, as jid: ${result.jid}`)
662
+ ```
663
+ - To query chat history on a group or with someone
664
+ TODO, if possible
665
+ - To get the status of some person
666
+ ``` ts
667
+ const status = await sock.fetchStatus("xyz@s.whatsapp.net")
668
+ console.log("status: " + status)
669
+ ```
670
+ - To change your profile status
671
+ ``` ts
672
+ const status = 'Hello World!'
673
+ await sock.updateProfileStatus(status)
674
+ ```
675
+ - To change your profile name
676
+ ``` ts
677
+ const name = 'My name'
678
+ await sock.updateProfileName(name)
679
+ ```
680
+ - To get the display picture of some person/group
681
+ ``` ts
682
+ // for low res picture
683
+ const ppUrl = await sock.profilePictureUrl("xyz@g.us")
684
+ console.log("download profile picture from: " + ppUrl)
685
+ // for high res picture
686
+ const ppUrl = await sock.profilePictureUrl("xyz@g.us", 'image')
687
+ ```
688
+ - To change your display picture or a group's
689
+ ``` ts
690
+ const jid = '111234567890-1594482450@g.us' // can be your own too
691
+ await sock.updateProfilePicture(jid, { url: './new-profile-picture.jpeg' })
692
+ ```
693
+ - To remove your display picture or a group's
694
+ ``` ts
695
+ const jid = '111234567890-1594482450@g.us' // can be your own too
696
+ await sock.removeProfilePicture(jid)
697
+ ```
698
+ - To get someone's presence (if they're typing or online)
699
+ ``` ts
700
+ // the presence update is fetched and called here
701
+ sock.ev.on('presence.update', json => console.log(json))
702
+ // request updates for a chat
703
+ await sock.presenceSubscribe("xyz@s.whatsapp.net")
704
+ ```
705
+ - To block or unblock user
706
+ ``` ts
707
+ await sock.updateBlockStatus("xyz@s.whatsapp.net", "block") // Block user
708
+ await sock.updateBlockStatus("xyz@s.whatsapp.net", "unblock") // Unblock user
709
+ ```
710
+ - To get a business profile, such as description or category
711
+ ```ts
712
+ const profile = await sock.getBusinessProfile("xyz@s.whatsapp.net")
713
+ console.log("business description: " + profile.description + ", category: " + profile.category)
714
+ ```
715
+ Of course, replace ``` xyz ``` with an actual ID.
716
+
717
+ ## Groups
718
+ - To create a group
719
+ ``` ts
720
+ // title & participants
721
+ const group = await sock.groupCreate("My Fab Group", ["1234@s.whatsapp.net", "4564@s.whatsapp.net"])
722
+ console.log ("created group with id: " + group.gid)
723
+ sock.sendMessage(group.id, { text: 'hello there' }) // say hello to everyone on the group
724
+ ```
725
+ - To add/remove people to a group or demote/promote people
726
+ ``` ts
727
+ // id & people to add to the group (will throw error if it fails)
728
+ const response = await sock.groupParticipantsUpdate(
729
+ "abcd-xyz@g.us",
730
+ ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"],
731
+ "add" // replace this parameter with "remove", "demote" or "promote"
732
+ )
733
+ ```
734
+ - To change the group's subject
735
+ ``` ts
736
+ await sock.groupUpdateSubject("abcd-xyz@g.us", "New Subject!")
737
+ ```
738
+ - To change the group's description
739
+ ``` ts
740
+ await sock.groupUpdateDescription("abcd-xyz@g.us", "New Description!")
741
+ ```
742
+ - To change group settings
743
+ ``` ts
744
+ // only allow admins to send messages
745
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'announcement')
746
+ // allow everyone to send messages
747
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'not_announcement')
748
+ // allow everyone to modify the group's settings -- like display picture etc.
749
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'unlocked')
750
+ // only allow admins to modify the group's settings
751
+ await sock.groupSettingUpdate("abcd-xyz@g.us", 'locked')
752
+ ```
753
+ - To leave a group
754
+ ``` ts
755
+ await sock.groupLeave("abcd-xyz@g.us") // (will throw error if it fails)
756
+ ```
757
+ - To get the invite code for a group
758
+ ``` ts
759
+ const code = await sock.groupInviteCode("abcd-xyz@g.us")
760
+ console.log("group code: " + code)
761
+ ```
762
+ - To revoke the invite code in a group
763
+ ```ts
764
+ const code = await sock.groupRevokeInvite("abcd-xyz@g.us")
765
+ console.log("New group code: " + code)
766
+ ```
767
+ - To query the metadata of a group
768
+ ``` ts
769
+ const metadata = await sock.groupMetadata("abcd-xyz@g.us")
770
+ console.log(metadata.id + ", title: " + metadata.subject + ", description: " + metadata.desc)
771
+ ```
772
+ - To join the group using the invitation code
773
+ ``` ts
774
+ const response = await sock.groupAcceptInvite("xxx")
775
+ console.log("joined to: " + response)
776
+ ```
777
+ Of course, replace ``` xxx ``` with invitation code.
778
+ - To get group info by invite code
779
+ ```ts
780
+ const response = await sock.groupGetInviteInfo("xxx")
781
+ console.log("group information: " + response)
782
+ ```
783
+ - To join the group using groupInviteMessage
784
+ ``` ts
785
+ const response = await sock.groupAcceptInviteV4("abcd@s.whatsapp.net", groupInviteMessage)
786
+ console.log("joined to: " + response)
787
+ ```
788
+ Of course, replace ``` xxx ``` with invitation code.
789
+
790
+ - To get list request join
791
+ ``` ts
792
+ const response = await sock.groupRequestParticipantsList("abcd-xyz@g.us")
793
+ console.log(response)
794
+ ```
795
+ - To approve/reject request join
796
+ ``` ts
797
+ const response = await sock.groupRequestParticipantsUpdate(
798
+ "abcd-xyz@g.us", // id group,
799
+ ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"],
800
+ "approve" // replace this parameter with "reject"
801
+ )
802
+ console.log(response)
803
+ ```
804
+
805
+ ## Privacy
806
+ - To get the privacy settings
807
+ ``` ts
808
+ const privacySettings = await sock.fetchPrivacySettings(true)
809
+ console.log("privacy settings: " + privacySettings)
810
+ ```
811
+ - To update the LastSeen privacy
812
+ ``` ts
813
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
814
+ await sock.updateLastSeenPrivacy(value)
815
+ ```
816
+ - To update the Online privacy
817
+ ``` ts
818
+ const value = 'all' // 'match_last_seen'
819
+ await sock.updateOnlinePrivacy(value)
820
+ ```
821
+ - To update the Profile Picture privacy
822
+ ``` ts
823
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
824
+ await sock.updateProfilePicturePrivacy(value)
825
+ ```
826
+ - To update the Status privacy
827
+ ``` ts
828
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
829
+ await sock.updateStatusPrivacy(value)
830
+ ```
831
+ - To update the Read Receipts privacy
832
+ ``` ts
833
+ const value = 'all' // 'none'
834
+ await sock.updateReadReceiptsPrivacy(value)
835
+ ```
836
+ - To update the Groups Add privacy
837
+ ``` ts
838
+ const value = 'all' // 'contacts' | 'contact_blacklist'
839
+ await sock.updateGroupsAddPrivacy(value)
840
+ ```
841
+ - To update the Default Disappearing Mode
842
+ ``` ts
843
+ const duration = 86400 // 604800 | 7776000 | 0
844
+ await sock.updateDefaultDisappearingMode(duration)
845
+ ```
846
+ ## Broadcast Lists & Stories
847
+
848
+ Messages can be sent to broadcasts & stories.
849
+ you need to add the following message options in sendMessage, like this:
850
+ ```ts
851
+ sock.sendMessage(jid, {image: {url: url}, caption: caption}, {backgroundColor : backgroundColor, font : font, statusJidList: statusJidList, broadcast : true})
852
+ ```
853
+ - the message body can be a extendedTextMessage or imageMessage or videoMessage or voiceMessage
854
+ - You can add backgroundColor and other options in the message options
855
+ - broadcast: true enables broadcast mode
856
+ - statusJidList: a list of people that you can get which you need to provide, which are the people who will get this status message.
857
+
858
+ - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
859
+ - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
860
+ - Broadcast IDs are in the format `12345678@broadcast`
861
+ - To query a broadcast list's recipients & name:
862
+ ``` ts
863
+ const bList = await sock.getBroadcastListInfo("1234@broadcast")
864
+ console.log (`list name: ${bList.name}, recps: ${bList.recipients}`)
865
+ ```
866
+
867
+ ## Writing Custom Functionality
868
+ Baileys is written with custom functionality in mind. Instead of forking the project & re-writing the internals, you can simply write your own extensions.
869
+
870
+ First, enable the logging of unhandled messages from WhatsApp by setting:
871
+ ``` ts
872
+ const sock = makeWASocket({
873
+ logger: P({ level: 'debug' }),
874
+ })
875
+ ```
876
+ This will enable you to see all sorts of messages WhatsApp sends in the console.
877
+
878
+ Some examples:
879
+
880
+ 1. Functionality to track the battery percentage of your phone.
881
+ You enable logging and you'll see a message about your battery pop up in the console:
882
+ ```{"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"} ```
883
+
884
+ The "frame" is what the message received is, it has three components:
885
+ - `tag` -- what this frame is about (eg. message will have "message")
886
+ - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
887
+ - `content` -- the actual data (eg. a message node will have the actual message content in it)
888
+ - read more about this format [here](/src/WABinary/readme.md)
889
+
890
+ You can register a callback for an event using the following:
891
+ ``` ts
892
+ // for any message with tag 'edge_routing'
893
+ sock.ws.on(`CB:edge_routing`, (node: BinaryNode) => { })
894
+ // for any message with tag 'edge_routing' and id attribute = abcd
895
+ sock.ws.on(`CB:edge_routing,id:abcd`, (node: BinaryNode) => { })
896
+ // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
897
+ sock.ws.on(`CB:edge_routing,id:abcd,routing_info`, (node: BinaryNode) => { })
898
+ ```
899
+ Also, this repo is now licenced under GPL 3 since it uses [libsignal-node](https://git.questbook.io/backend/service-coderunner/-/merge_requests/1)
package/index.js CHANGED
@@ -1,7 +1,6 @@
1
- console.log('\x1b[36m ⚡ CEASER v2.0.49 FINAL - ALL DEPS FIXED ⚡\x1b[0m');
2
- let lib=require('./lib'); console.log('\x1b[32m✅ lib loaded\x1b[0m');
1
+ console.log('⚡ CEASER v2.0.51 FINAL - WAProto fixed ⚡');
2
+ let lib=require('./lib');
3
3
  const orig=lib.default||lib.makeWASocket||lib;
4
- function patch(s){ if(!s||s._p) return s; const o=s.sendMessage.bind(s); s.sendMessage=async(j,c,op)=>o(j,c,op); s._p=true; return s; }
5
- function makeFixed(...a){ return patch(orig(...a)) }
6
- if(lib.default) lib.default=makeFixed; if(lib.makeWASocket) lib.makeWASocket=makeFixed;
7
- module.exports={...lib, makeWASocket: makeFixed, default: makeFixed, version:'2.0.49'};
4
+ function makeFixed(...a){ const s=orig(...a); return s; }
5
+ module.exports={...lib, makeWASocket: makeFixed, default: makeFixed, version:'2.0.51'};
6
+ console.log('✅ v2.0.51 loaded');
package/package.json CHANGED
@@ -1,33 +1,32 @@
1
1
  {
2
2
  "name": "lordceaser-baileys",
3
- "version": "2.0.49",
4
- "description": "CEASER v2.0.49 FINAL - Pterodactyl fixed - 6.7.8 CJS - ALL deps",
3
+ "version": "2.0.51",
5
4
  "main": "index.js",
6
- "type": "commonjs",
7
- "files": ["lib/","WAProto/","WASignalGroup/","WABinary/","WAM/","index.js"],
5
+ "files": ["lib/","WAProto/","WASignalGroup/","WABinary/","index.js"],
8
6
  "dependencies": {
9
7
  "@adiwajshing/keyed-db": "^0.2.4",
10
- "@cacheable/node-cache": "^1.1.4",
11
8
  "@hapi/boom": "^9.1.4",
9
+ "async-lock": "^1.4.1",
12
10
  "async-mutex": "^0.4.0",
13
11
  "axios": "^1.6.0",
14
- "cache-manager": "^3.6.3",
15
- "fflate": "^0.8.2",
12
+ "ws": "^8.14.2",
13
+ "pino": "^8.17.2",
14
+ "protobufjs": "^7.2.5",
15
+ "qrcode-terminal": "^0.12.0",
16
+ "libsignal": "^2.0.1",
16
17
  "futoin-hkdf": "^1.5.1",
17
18
  "jimp": "^0.22.10",
18
- "libsignal": "^2.0.1",
19
- "long": "^5.2.3",
20
19
  "lru-cache": "^7.18.3",
21
- "music-metadata": "^7.14.0",
20
+ "file-type": "^16.5.4",
21
+ "node-cache": "^5.1.2",
22
+ "uuid": "^11.0.0",
23
+ "long": "^5.2.3",
22
24
  "p-queue": "^6.6.2",
23
- "pino": "^8.17.2",
24
- "protobufjs": "^7.2.5",
25
- "ws": "^8.14.2",
26
- "qrcode-terminal": "^0.12.0",
25
+ "music-metadata": "^7.14.0",
27
26
  "lodash": "^4.17.21",
28
27
  "mysql2": "^3.9.7",
29
- "node-cache": "^5.1.2",
30
- "file-type": "^16.5.4",
31
- "uuid": "^9.0.0"
28
+ "fflate": "^0.8.2",
29
+ "cache-manager": "^3.6.3",
30
+ "@cacheable/node-cache": "^1.1.4"
32
31
  }
33
32
  }