@skyzopedia/baileys-pro 8.0.2 → 8.0.3

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.
package/README.md DELETED
@@ -1,1116 +0,0 @@
1
- # <div align='center'>Baileys - Typescript/Javascript WhatsApp Web API</div>
2
- Then import the default function in your code:
3
- ```ts
4
- import makeWASocket from 'baileys'
5
- ```
6
-
7
- ## Links
8
-
9
- - [WhatsApp Channel](https://whatsapp.com/channel/0029VbBcgCK1SWstUXZnLh1o)
10
- - [Contact Developer](https://t.me/Skyzopedia)
11
-
12
- ## Connecting Account
13
-
14
- WhatsApp provides a multi-device API that allows Baileys to be authenticated as a second WhatsApp client by scanning a **QR code** or **Pairing Code** with WhatsApp on your phone.
15
-
16
- ```ts
17
- import makeWASocket from 'baileys'
18
-
19
- const sock = makeWASocket({
20
- // can provide additional config here
21
- browser: Browsers.ubuntu('My App'),
22
- printQRInTerminal: true
23
- })
24
- ```
25
-
26
- 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!
27
-
28
- ### Starting socket with **Pairing Code**
29
-
30
-
31
- > [!IMPORTANT]
32
- > Pairing Code isn't Mobile API, it's a method to connect Whatsapp Web without QR-CODE, you can connect only with one device, see [here](https://faq.whatsapp.com/1324084875126592/?cms_platform=web)
33
-
34
- The phone number can't have `+` or `()` or `-`, only numbers, you must provide country code
35
-
36
- ```ts
37
- import makeWASocket from 'baileys'
38
-
39
- const sock = makeWASocket({
40
- // can provide additional config here
41
- printQRInTerminal: false //need to be false
42
- })
43
- // NOTE: WAIT TILL QR EVENT BEFORE REQUESTING THE PAIRING CODE
44
- if (!sock.authState.creds.registered) {
45
- const number = 'XXXXXXXXXXX'
46
- const code = await sock.requestPairingCode(number)
47
- console.log(code)
48
- }
49
- ```
50
-
51
- ### Receive Full History
52
-
53
- 1. Set `syncFullHistory` as `true`
54
- 2. Baileys, by default, use chrome browser config
55
- - If you'd like to emulate a desktop connection (and receive more message history), this browser setting to your Socket config:
56
-
57
- ```ts
58
- const sock = makeWASocket({
59
- ...otherOpts,
60
- // can use Windows, Ubuntu here too
61
- browser: Browsers.macOS('Desktop'),
62
- syncFullHistory: true
63
- })
64
- ```
65
-
66
- ## Important Notes About Socket Config
67
-
68
- ### Caching Group Metadata (Recommended)
69
- - If you use baileys for groups, we recommend you to set `cachedGroupMetadata` in socket config, you need to implement a cache like this:
70
-
71
- ```ts
72
- const groupCache = new NodeCache({stdTTL: 5 * 60, useClones: false})
73
-
74
- const sock = makeWASocket({
75
- cachedGroupMetadata: async (jid) => groupCache.get(jid)
76
- })
77
-
78
- sock.ev.on('groups.update', async ([event]) => {
79
- const metadata = await sock.groupMetadata(event.id)
80
- groupCache.set(event.id, metadata)
81
- })
82
-
83
- sock.ev.on('group-participants.update', async (event) => {
84
- const metadata = await sock.groupMetadata(event.id)
85
- groupCache.set(event.id, metadata)
86
- })
87
- ```
88
-
89
- ### Improve Retry System & Decrypt Poll Votes
90
- - If you want to improve sending message, retrying when error occurs and decrypt poll votes, you need to have a store and set `getMessage` config in socket like this:
91
- ```ts
92
- const sock = makeWASocket({
93
- getMessage: async (key) => await getMessageFromStore(key)
94
- })
95
- ```
96
-
97
- ### Receive Notifications in Whatsapp App
98
- - If you want to receive notifications in whatsapp app, set `markOnlineOnConnect` to `false`
99
- ```ts
100
- const sock = makeWASocket({
101
- markOnlineOnConnect: false
102
- })
103
- ```
104
- ## Saving & Restoring Sessions
105
-
106
- You obviously don't want to keep scanning the QR code every time you want to connect.
107
-
108
- So, you can load the credentials to log back in:
109
- ```ts
110
- import makeWASocket, { useMultiFileAuthState } from 'baileys'
111
-
112
- const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
113
-
114
- // will use the given state to connect
115
- // so if valid credentials are available -- it'll connect without QR
116
- const sock = makeWASocket({ auth: state })
117
-
118
- // this will be called as soon as the credentials are updated
119
- sock.ev.on('creds.update', saveCreds)
120
- ```
121
-
122
- > [!IMPORTANT]
123
- > `useMultiFileAuthState` is a utility function to help save the auth state in a single folder, 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.
124
-
125
- > [!NOTE]
126
- > 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.
127
-
128
- ## Handling Events
129
-
130
- - Baileys uses the EventEmitter syntax for events.
131
- They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
132
-
133
- You can listen to these events like this:
134
- ```ts
135
- const sock = makeWASocket()
136
- sock.ev.on('messages.upsert', ({ messages }) => {
137
- console.log('got messages', messages)
138
- })
139
- ```
140
-
141
- ### Example to Start
142
-
143
- > [!NOTE]
144
- > This example includes basic auth storage too
145
-
146
- ```ts
147
- import makeWASocket, { DisconnectReason, useMultiFileAuthState } from 'baileys'
148
- import { Boom } from '@hapi/boom'
149
-
150
- async function connectToWhatsApp () {
151
- const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
152
- const sock = makeWASocket({
153
- // can provide additional config here
154
- auth: state,
155
- printQRInTerminal: true
156
- })
157
- sock.ev.on('connection.update', (update) => {
158
- const { connection, lastDisconnect } = update
159
- if(connection === 'close') {
160
- const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
161
- console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
162
- // reconnect if not logged out
163
- if(shouldReconnect) {
164
- connectToWhatsApp()
165
- }
166
- } else if(connection === 'open') {
167
- console.log('opened connection')
168
- }
169
- })
170
- sock.ev.on('messages.upsert', event => {
171
- for (const m of event.messages) {
172
- console.log(JSON.stringify(m, undefined, 2))
173
-
174
- console.log('replying to', m.key.remoteJid)
175
- await sock.sendMessage(m.key.remoteJid!, { text: 'Hello Word' })
176
- }
177
- })
178
-
179
- // to storage creds (session info) when it updates
180
- sock.ev.on('creds.update', saveCreds)
181
- }
182
- // run in main file
183
- connectToWhatsApp()
184
- ```
185
-
186
- > [!IMPORTANT]
187
- > In `messages.upsert` it's recommended to use a loop like `for (const message of event.messages)` to handle all messages in array
188
-
189
- ### Decrypt Poll Votes
190
-
191
- - By default poll votes are encrypted and handled in `messages.update`
192
- - That's a simple example
193
- ```ts
194
- sock.ev.on('messages.update', event => {
195
- for(const { key, update } of event) {
196
- if(update.pollUpdates) {
197
- const pollCreation = await getMessage(key)
198
- if(pollCreation) {
199
- console.log(
200
- 'got poll update, aggregation: ',
201
- getAggregateVotesInPollMessage({
202
- message: pollCreation,
203
- pollUpdates: update.pollUpdates,
204
- })
205
- )
206
- }
207
- }
208
- }
209
- })
210
- ```
211
-
212
- - `getMessage` is a [store](#implementing-a-data-store) implementation (in your end)
213
-
214
- ### Summary of Events on First Connection
215
-
216
- 1. When you connect first time, `connection.update` will be fired requesting you to restart sock
217
- 2. Then, history messages will be received in `messaging-history.set`
218
-
219
- ## Implementing a Data Store
220
-
221
- - 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.
222
-
223
- > [!IMPORTANT]
224
- > I highly recommend building your own data store, as storing someone's entire chat history in memory is a terrible waste of RAM.
225
-
226
- It can be used as follows:
227
-
228
- ```ts
229
- import makeWASocket, { makeInMemoryStore } from 'baileys'
230
- // the store maintains the data of the WA connection in memory
231
- // can be written out to a file & read from it
232
- const store = makeInMemoryStore({ })
233
- // can be read from a file
234
- store.readFromFile('./baileys_store.json')
235
- // saves the state to a file every 10s
236
- setInterval(() => {
237
- store.writeToFile('./baileys_store.json')
238
- }, 10_000)
239
-
240
- const sock = makeWASocket({ })
241
- // will listen from this socket
242
- // the store can listen from a new socket once the current socket outlives its lifetime
243
- store.bind(sock.ev)
244
-
245
- sock.ev.on('chats.upsert', () => {
246
- // can use 'store.chats' however you want, even after the socket dies out
247
- // 'chats' => a KeyedDB instance
248
- console.log('got chats', store.chats.all())
249
- })
250
-
251
- sock.ev.on('contacts.upsert', () => {
252
- console.log('got contacts', Object.values(store.contacts))
253
- })
254
-
255
- ```
256
-
257
- The store also provides some simple functions such as `loadMessages` that utilize the store to speed up data retrieval.
258
-
259
- ## Whatsapp IDs Explain
260
-
261
- - `id` is the WhatsApp ID, called `jid` too, of the person or group you're sending the message to.
262
- - It must be in the format ```[country code][phone number]@s.whatsapp.net```
263
- - Example for people: ```+19999999999@s.whatsapp.net```.
264
- - For groups, it must be in the format ``` 123456789-123345@g.us ```.
265
- - For broadcast lists, it's `[timestamp of creation]@broadcast`.
266
- - For stories, the ID is `status@broadcast`.
267
-
268
- ## Utility Functions
269
-
270
- - `getContentType`, returns the content type for any message
271
- - `getDevice`, returns the device from message
272
- - `makeCacheableSignalKeyStore`, make auth store more fast
273
- - `downloadContentFromMessage`, download content from any message
274
-
275
- ## JID Conversion Utilities
276
-
277
- Baileys provides helper methods to convert between standard JIDs (@s.whatsapp.net) and LID (Local ID) format (@lid). These are useful when working with different WhatsApp ID formats.
278
-
279
- #### Convert to LID (@lid)
280
-
281
- ```ts
282
- const standardJid = '1234567890@s.whatsapp.net'
283
- const lidJid = sock.toLid(standardJid)
284
- // Result: '1234567890@lid'
285
- ```
286
-
287
- #### Convert from LID to Standard (@s.whatsapp.net)
288
-
289
- ```ts
290
- const lidJid = '1234567890@lid'
291
- const standardJid = sock.toPn(lidJid)
292
- // Result: '1234567890@s.whatsapp.net'
293
- ```
294
-
295
- ## Sending Messages
296
-
297
- ```ts
298
- const jid: string
299
- const content: AnyMessageContent
300
- const options: MiscMessageGenerationOptions
301
-
302
- sock.sendMessage(jid, content, options)
303
- ```
304
-
305
- ### Non-Media Messages
306
-
307
- #### Text Message
308
- ```ts
309
- await sock.sendMessage(jid, { text: 'hello word' })
310
- ```
311
-
312
- #### Quote Message (works with all types)
313
- ```ts
314
- await sock.sendMessage(jid, { text: 'hello word' }, { quoted: message })
315
- ```
316
-
317
- #### Mention User (works with most types)
318
- - @number is to mention in text, it's optional
319
- ```ts
320
- await sock.sendMessage(
321
- jid,
322
- {
323
- text: '@12345678901',
324
- mentions: ['12345678901@s.whatsapp.net']
325
- }
326
- )
327
- ```
328
-
329
- ```ts
330
- const msg = getMessageFromStore() // implement this on your end
331
- await sock.sendMessage(jid, { forward: msg }) // WA forward the message!
332
- ```
333
-
334
- #### Location Message
335
- ```ts
336
- await sock.sendMessage(
337
- jid,
338
- {
339
- location: {
340
- degreesLatitude: 24.121231,
341
- degreesLongitude: 55.1121221
342
- }
343
- }
344
- )
345
- ```
346
- #### Contact Message
347
- ```ts
348
- const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
349
- + 'VERSION:3.0\n'
350
- + 'FN:Jeff Singh\n' // full name
351
- + 'ORG:Ashoka Uni;\n' // the organization of the contact
352
- + 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
353
- + 'END:VCARD'
354
-
355
- await sock.sendMessage(
356
- id,
357
- {
358
- contacts: {
359
- displayName: 'Jeff',
360
- contacts: [{ vcard }]
361
- }
362
- }
363
- )
364
- ```
365
-
366
- ```ts
367
- await sock.sendMessage(
368
- jid,
369
- {
370
- react: {
371
- text: '💖', // use an empty string to remove the reaction
372
- key: message.key
373
- }
374
- }
375
- )
376
- ```
377
-
378
- #### Pin Message
379
- - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](https://baileys.whiskeysockets.io/types/WAMessageKey.html) object
380
-
381
- - Time can be:
382
-
383
- | Time | Seconds |
384
- |-------|----------------|
385
- | 24h | 86.400 |
386
- | 7d | 604.800 |
387
- | 30d | 2.592.000 |
388
-
389
- ```ts
390
- await sock.sendMessage(
391
- jid,
392
- {
393
- pin: {
394
- type: 1, // 0 to remove
395
- time: 86400
396
- key: message.key
397
- }
398
- }
399
- )
400
- ```
401
-
402
- #### Poll Message
403
- ```ts
404
- await sock.sendMessage(
405
- jid,
406
- {
407
- poll: {
408
- name: 'My Poll',
409
- values: ['Option 1', 'Option 2', ...],
410
- selectableCount: 1,
411
- toAnnouncementGroup: false // or true
412
- }
413
- }
414
- )
415
- ```
416
-
417
- ### Sending Messages with Link Previews
418
-
419
- 1. By default, wa does not have link generation when sent from the web
420
- 2. Baileys has a function to generate the content for these link previews
421
- 3. To enable this function's usage, add `link-preview-js` as a dependency to your project with `yarn add link-preview-js`
422
- 4. Send a link:
423
- ```ts
424
- await sock.sendMessage(
425
- jid,
426
- {
427
- text: 'Hi, this was sent using https://github.com/whiskeysockets/baileys'
428
- }
429
- )
430
- ```
431
-
432
- ### Media Messages
433
-
434
- Sending media (video, stickers, images) is easier & more efficient than ever.
435
-
436
- > [!NOTE]
437
- > In media messages, you can pass `{ stream: Stream }` or `{ url: Url }` or `Buffer` directly, you can see more [here](https://baileys.whiskeysockets.io/types/WAMediaUpload.html)
438
-
439
- - When specifying a media url, Baileys never loads the entire buffer into memory; it even encrypts the media as a readable stream.
440
-
441
- > [!TIP]
442
- > It's recommended to use Stream or Url to save memory
443
-
444
- #### Gif Message
445
- - Whatsapp doesn't support `.gif` files, that's why we send gifs as common `.mp4` video with `gifPlayback` flag
446
- ```ts
447
- await sock.sendMessage(
448
- jid,
449
- {
450
- video: fs.readFileSync('Media/ma_gif.mp4'),
451
- caption: 'hello word',
452
- gifPlayback: true
453
- }
454
- )
455
- ```
456
-
457
- #### Video Message
458
- ```ts
459
- await sock.sendMessage(
460
- id,
461
- {
462
- video: {
463
- url: './Media/ma_gif.mp4'
464
- },
465
- caption: 'hello word',
466
- ptv: false // if set to true, will send as a `video note`
467
- }
468
- )
469
- ```
470
-
471
- #### Audio Message
472
- - To audio message work in all devices you need to convert with some tool like `ffmpeg` with this flags:
473
- ```bash
474
- codec: libopus //ogg file
475
- ac: 1 //one channel
476
- avoid_negative_ts
477
- make_zero
478
- ```
479
- - Example:
480
- ```bash
481
- ffmpeg -i input.mp4 -avoid_negative_ts make_zero -ac 1 output.ogg
482
- ```
483
- ```ts
484
- await sock.sendMessage(
485
- jid,
486
- {
487
- audio: {
488
- url: './Media/audio.mp3'
489
- },
490
- mimetype: 'audio/mp4'
491
- }
492
- )
493
- ```
494
-
495
- #### Image Message
496
- ```ts
497
- await sock.sendMessage(
498
- id,
499
- {
500
- image: {
501
- url: './Media/ma_img.png'
502
- },
503
- caption: 'hello word'
504
- }
505
- )
506
- ```
507
-
508
- #### View Once Message
509
-
510
- - You can send all messages above as `viewOnce`, you only need to pass `viewOnce: true` in content object
511
-
512
- ```ts
513
- await sock.sendMessage(
514
- id,
515
- {
516
- image: {
517
- url: './Media/ma_img.png'
518
- },
519
- viewOnce: true, //works with video, audio too
520
- caption: 'hello word'
521
- }
522
- )
523
- ```
524
-
525
- ## Modify Messages
526
-
527
- ### Deleting Messages (for everyone)
528
-
529
- ```ts
530
- const msg = await sock.sendMessage(jid, { text: 'hello word' })
531
- await sock.sendMessage(jid, { delete: msg.key })
532
- ```
533
-
534
- **Note:** deleting for oneself is supported via `chatModify`, see in [this section](#modifying-chats)
535
-
536
- ### Editing Messages
537
-
538
- - You can pass all editable contents here
539
- ```ts
540
- await sock.sendMessage(jid, {
541
- text: 'updated text goes here',
542
- edit: response.key,
543
- });
544
- ```
545
-
546
- ## Manipulating Media Messages
547
-
548
- ### Thumbnail in Media Messages
549
- - 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`.
550
- - Thumbnails for videos can also be generated automatically, though, you need to have `ffmpeg` installed on your system.
551
-
552
- ### Downloading Media Messages
553
-
554
- If you want to save the media you received
555
- ```ts
556
- import { createWriteStream } from 'fs'
557
- import { downloadMediaMessage, getContentType } from 'baileys'
558
-
559
- sock.ev.on('messages.upsert', async ({ [m] }) => {
560
- if (!m.message) return // if there is no text or media message
561
- const messageType = getContentType(m) // get what type of message it is (text, image, video...)
562
-
563
- // if the message is an image
564
- if (messageType === 'imageMessage') {
565
- // download the message
566
- const stream = await downloadMediaMessage(
567
- m,
568
- 'stream', // can be 'buffer' too
569
- { },
570
- {
571
- logger,
572
- // pass this so that baileys can request a reupload of media
573
- // that has been deleted
574
- reuploadRequest: sock.updateMediaMessage
575
- }
576
- )
577
- // save to file
578
- const writeStream = createWriteStream('./my-download.jpeg')
579
- stream.pipe(writeStream)
580
- }
581
- }
582
- ```
583
-
584
- ### Re-upload Media Message to Whatsapp
585
-
586
- - 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:
587
- ```ts
588
- await sock.updateMediaMessage(msg)
589
- ```
590
-
591
- ## Reject Call
592
-
593
- - You can obtain `callId` and `callFrom` from `call` event
594
-
595
- ```ts
596
- await sock.rejectCall(callId, callFrom)
597
- ```
598
-
599
- ## Send States in Chat
600
-
601
- ### Reading Messages
602
- - A set of message [keys](https://baileys.whiskeysockets.io/types/WAMessageKey.html) must be explicitly marked read now.
603
- - You cannot mark an entire 'chat' read as it were with Baileys Web.
604
- This means you have to keep track of unread messages.
605
-
606
- ```ts
607
- const key: WAMessageKey
608
- // can pass multiple keys to read multiple messages as well
609
- await sock.readMessages([key])
610
- ```
611
-
612
- The message ID is the unique identifier of the message that you are marking as read.
613
- On a `WAMessage`, the `messageID` can be accessed using ```messageID = message.key.id```.
614
-
615
- ### Update Presence
616
-
617
- - ``` presence ``` can be one of [these](https://baileys.whiskeysockets.io/types/WAPresence.html)
618
- - The presence expires after about 10 seconds.
619
- - This lets the person/group with `jid` know whether you're online, offline, typing etc.
620
-
621
- ```ts
622
- await sock.sendPresenceUpdate('available', jid)
623
- ```
624
-
625
- > [!NOTE]
626
- > 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')`
627
-
628
- ## Modifying Chats
629
-
630
- WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
631
-
632
- > [!IMPORTANT]
633
- > 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
- ### Archive a Chat
636
- ```ts
637
- const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
638
- await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, jid)
639
- ```
640
- ### Mute/Unmute a Chat
641
-
642
- - Supported times:
643
-
644
- | Time | Miliseconds |
645
- |-------|-----------------|
646
- | Remove | null |
647
- | 8h | 86.400.000 |
648
- | 7d | 604.800.000 |
649
-
650
- ```ts
651
- // mute for 8 hours
652
- await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid)
653
- // unmute
654
- await sock.chatModify({ mute: null }, jid)
655
- ```
656
- ### Mark a Chat Read/Unread
657
- ```ts
658
- const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
659
- // mark it unread
660
- await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, jid)
661
- ```
662
-
663
- ### Delete a Message for Me
664
- ```ts
665
- await sock.chatModify(
666
- {
667
- clear: {
668
- messages: [
669
- {
670
- id: 'ATWYHDNNWU81732J',
671
- fromMe: true,
672
- timestamp: '1654823909'
673
- }
674
- ]
675
- }
676
- },
677
- jid
678
- )
679
-
680
- ```
681
- ### Delete a Chat
682
- ```ts
683
- const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
684
- await sock.chatModify({
685
- delete: true,
686
- lastMessages: [
687
- {
688
- key: lastMsgInChat.key,
689
- messageTimestamp: lastMsgInChat.messageTimestamp
690
- }
691
- ]
692
- },
693
- jid
694
- )
695
- ```
696
- ### Pin/Unpin a Chat
697
- ```ts
698
- await sock.chatModify({
699
- pin: true // or `false` to unpin
700
- },
701
- jid
702
- )
703
- ```
704
- ### Star/Unstar a Message
705
- ```ts
706
- await sock.chatModify({
707
- star: {
708
- messages: [
709
- {
710
- id: 'messageID',
711
- fromMe: true // or `false`
712
- }
713
- ],
714
- star: true // - true: Star Message; false: Unstar Message
715
- }
716
- },
717
- jid
718
- )
719
- ```
720
-
721
- ### Disappearing Messages
722
-
723
- - Ephemeral can be:
724
-
725
- | Time | Seconds |
726
- |-------|----------------|
727
- | Remove | 0 |
728
- | 24h | 86.400 |
729
- | 7d | 604.800 |
730
- | 90d | 7.776.000 |
731
-
732
- - You need to pass in **Seconds**, default is 7 days
733
-
734
- ```ts
735
- // turn on disappearing messages
736
- await sock.sendMessage(
737
- jid,
738
- // this is 1 week in seconds -- how long you want messages to appear for
739
- { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL }
740
- )
741
-
742
- // will send as a disappearing message
743
- await sock.sendMessage(jid, { text: 'hello' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL })
744
-
745
- // turn off disappearing messages
746
- await sock.sendMessage(
747
- jid,
748
- { disappearingMessagesInChat: false }
749
- )
750
- ```
751
-
752
- ## User Querys
753
-
754
- ### Check If ID Exists in Whatsapp
755
- ```ts
756
- const [result] = await sock.onWhatsApp(jid)
757
- if (result.exists) console.log (`${jid} exists on WhatsApp, as jid: ${result.jid}`)
758
- ```
759
-
760
- ### Query Chat History (groups too)
761
-
762
- - You need to have oldest message in chat
763
- ```ts
764
- const msg = await getOldestMessageInChat(jid)
765
- await sock.fetchMessageHistory(
766
- 50, //quantity (max: 50 per query)
767
- msg.key,
768
- msg.messageTimestamp
769
- )
770
- ```
771
- - Messages will be received in `messaging-history.set` event
772
-
773
- ### Fetch Status
774
- ```ts
775
- const status = await sock.fetchStatus(jid)
776
- console.log('status: ' + status)
777
- ```
778
-
779
- ### Fetch Profile Picture (groups too)
780
- - To get the display picture of some person/group
781
- ```ts
782
- // for low res picture
783
- const ppUrl = await sock.profilePictureUrl(jid)
784
- console.log(ppUrl)
785
-
786
- // for high res picture
787
- const ppUrl = await sock.profilePictureUrl(jid, 'image')
788
- ```
789
-
790
- ### Fetch Bussines Profile (such as description or category)
791
- ```ts
792
- const profile = await sock.getBusinessProfile(jid)
793
- console.log('business description: ' + profile.description + ', category: ' + profile.category)
794
- ```
795
-
796
- ### Fetch Someone's Presence (if they're typing or online)
797
- ```ts
798
- // the presence update is fetched and called here
799
- sock.ev.on('presence.update', console.log)
800
-
801
- // request updates for a chat
802
- await sock.presenceSubscribe(jid)
803
- ```
804
-
805
- ## Change Profile
806
-
807
- ### Change Profile Status
808
- ```ts
809
- await sock.updateProfileStatus('Hello World!')
810
- ```
811
- ### Change Profile Name
812
- ```ts
813
- await sock.updateProfileName('My name')
814
- ```
815
- ### Change Display Picture (groups too)
816
- - To change your display picture or a group's
817
-
818
- > [!NOTE]
819
- > Like media messages, you can pass `{ stream: Stream }` or `{ url: Url }` or `Buffer` directly, you can see more [here](https://baileys.whiskeysockets.io/types/WAMediaUpload.html)
820
-
821
- ```ts
822
- await sock.updateProfilePicture(jid, { url: './new-profile-picture.jpeg' })
823
- ```
824
- ### Remove display picture (groups too)
825
- ```ts
826
- await sock.removeProfilePicture(jid)
827
- ```
828
-
829
- ## Groups
830
-
831
- - To change group properties you need to be admin
832
-
833
- ### Create a Group
834
- ```ts
835
- // title & participants
836
- const group = await sock.groupCreate('My Fab Group', ['1234@s.whatsapp.net', '4564@s.whatsapp.net'])
837
- console.log('created group with id: ' + group.gid)
838
- await sock.sendMessage(group.id, { text: 'hello there' }) // say hello to everyone on the group
839
- ```
840
- ### Add/Remove or Demote/Promote
841
- ```ts
842
- // id & people to add to the group (will throw error if it fails)
843
- await sock.groupParticipantsUpdate(
844
- jid,
845
- ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
846
- 'add' // replace this parameter with 'remove' or 'demote' or 'promote'
847
- )
848
- ```
849
- ### Change Subject (name)
850
- ```ts
851
- await sock.groupUpdateSubject(jid, 'New Subject!')
852
- ```
853
- ### Change Description
854
- ```ts
855
- await sock.groupUpdateDescription(jid, 'New Description!')
856
- ```
857
- ### Change Settings
858
- ```ts
859
- // only allow admins to send messages
860
- await sock.groupSettingUpdate(jid, 'announcement')
861
- // allow everyone to send messages
862
- await sock.groupSettingUpdate(jid, 'not_announcement')
863
- // allow everyone to modify the group's settings -- like display picture etc.
864
- await sock.groupSettingUpdate(jid, 'unlocked')
865
- // only allow admins to modify the group's settings
866
- await sock.groupSettingUpdate(jid, 'locked')
867
- ```
868
- ### Leave a Group
869
- ```ts
870
- // will throw error if it fails
871
- await sock.groupLeave(jid)
872
- ```
873
- ### Get Invite Code
874
- - To create link with code use `'https://chat.whatsapp.com/' + code`
875
- ```ts
876
- const code = await sock.groupInviteCode(jid)
877
- console.log('group code: ' + code)
878
- ```
879
- ### Revoke Invite Code
880
- ```ts
881
- const code = await sock.groupRevokeInvite(jid)
882
- console.log('New group code: ' + code)
883
- ```
884
- ### Join Using Invitation Code
885
- - Code can't have `https://chat.whatsapp.com/`, only code
886
- ```ts
887
- const response = await sock.groupAcceptInvite(code)
888
- console.log('joined to: ' + response)
889
- ```
890
- ### Get Group Info by Invite Code
891
- ```ts
892
- const response = await sock.groupGetInviteInfo(code)
893
- console.log('group information: ' + response)
894
- ```
895
- ### Query Metadata (participants, name, description...)
896
- ```ts
897
- const metadata = await sock.groupMetadata(jid)
898
- console.log(metadata.id + ', title: ' + metadata.subject + ', description: ' + metadata.desc)
899
- ```
900
- ### Join using `groupInviteMessage`
901
- ```ts
902
- const response = await sock.groupAcceptInviteV4(jid, groupInviteMessage)
903
- console.log('joined to: ' + response)
904
- ```
905
- ### Get Request Join List
906
- ```ts
907
- const response = await sock.groupRequestParticipantsList(jid)
908
- console.log(response)
909
- ```
910
- ### Approve/Reject Request Join
911
- ```ts
912
- const response = await sock.groupRequestParticipantsUpdate(
913
- jid, // group id
914
- ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
915
- 'approve' // or 'reject'
916
- )
917
- console.log(response)
918
- ```
919
- ### Get All Participating Groups Metadata
920
- ```ts
921
- const response = await sock.groupFetchAllParticipating()
922
- console.log(response)
923
- ```
924
- ### Toggle Ephemeral
925
-
926
- - Ephemeral can be:
927
-
928
- | Time | Seconds |
929
- |-------|----------------|
930
- | Remove | 0 |
931
- | 24h | 86.400 |
932
- | 7d | 604.800 |
933
- | 90d | 7.776.000 |
934
-
935
- ```ts
936
- await sock.groupToggleEphemeral(jid, 86400)
937
- ```
938
-
939
- ### Change Add Mode
940
- ```ts
941
- await sock.groupMemberAddMode(
942
- jid,
943
- 'all_member_add' // or 'admin_add'
944
- )
945
- ```
946
-
947
- ## Privacy
948
-
949
- ### Block/Unblock User
950
- ```ts
951
- await sock.updateBlockStatus(jid, 'block') // Block user
952
- await sock.updateBlockStatus(jid, 'unblock') // Unblock user
953
- ```
954
- ### Get Privacy Settings
955
- ```ts
956
- const privacySettings = await sock.fetchPrivacySettings(true)
957
- console.log('privacy settings: ' + privacySettings)
958
- ```
959
- ### Get BlockList
960
- ```ts
961
- const response = await sock.fetchBlocklist()
962
- console.log(response)
963
- ```
964
- ### Update LastSeen Privacy
965
- ```ts
966
- const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
967
- await sock.updateLastSeenPrivacy(value)
968
- ```
969
- ### Update Online Privacy
970
- ```ts
971
- const value = 'all' // 'match_last_seen'
972
- await sock.updateOnlinePrivacy(value)
973
- ```
974
- ### Update Profile Picture Privacy
975
- ```ts
976
- const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
977
- await sock.updateProfilePicturePrivacy(value)
978
- ```
979
- ### Update Status Privacy
980
- ```ts
981
- const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
982
- await sock.updateStatusPrivacy(value)
983
- ```
984
- ### Update Read Receipts Privacy
985
- ```ts
986
- const value = 'all' // 'none'
987
- await sock.updateReadReceiptsPrivacy(value)
988
- ```
989
- ### Update Groups Add Privacy
990
- ```ts
991
- const value = 'all' // 'contacts' | 'contact_blacklist'
992
- await sock.updateGroupsAddPrivacy(value)
993
- ```
994
- ### Update Default Disappearing Mode
995
-
996
- - Like [this](#disappearing-messages), ephemeral can be:
997
-
998
- | Time | Seconds |
999
- |-------|----------------|
1000
- | Remove | 0 |
1001
- | 24h | 86.400 |
1002
- | 7d | 604.800 |
1003
- | 90d | 7.776.000 |
1004
-
1005
- ```ts
1006
- const ephemeral = 86400
1007
- await sock.updateDefaultDisappearingMode(ephemeral)
1008
- ```
1009
-
1010
- ## Broadcast Lists & Stories
1011
-
1012
- ### Send Broadcast & Stories
1013
- - Messages can be sent to broadcasts & stories. You need to add the following message options in sendMessage, like this:
1014
- ```ts
1015
- await sock.sendMessage(
1016
- jid,
1017
- {
1018
- image: {
1019
- url: url
1020
- },
1021
- caption: caption
1022
- },
1023
- {
1024
- backgroundColor: backgroundColor,
1025
- font: font,
1026
- statusJidList: statusJidList,
1027
- broadcast: true
1028
- }
1029
- )
1030
- ```
1031
- - Message body can be a `extendedTextMessage` or `imageMessage` or `videoMessage` or `voiceMessage`, see [here](https://baileys.whiskeysockets.io/types/AnyRegularMessageContent.html)
1032
- - You can add `backgroundColor` and other options in the message options, see [here](https://baileys.whiskeysockets.io/types/MiscMessageGenerationOptions.html)
1033
- - `broadcast: true` enables broadcast mode
1034
- - `statusJidList`: a list of people that you can get which you need to provide, which are the people who will get this status message.
1035
-
1036
- - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
1037
- - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
1038
- - Broadcast IDs are in the format `12345678@broadcast`
1039
- ### Query a Broadcast List's Recipients & Name
1040
- ```ts
1041
- const bList = await sock.getBroadcastListInfo('1234@broadcast')
1042
- console.log (`list name: ${bList.name}, recps: ${bList.recipients}`)
1043
- ```
1044
-
1045
- ## Writing Custom Functionality
1046
- Baileys is written with custom functionality in mind. Instead of forking the project & re-writing the internals, you can simply write your own extensions.
1047
-
1048
- ### Enabling Debug Level in Baileys Logs
1049
- First, enable the logging of unhandled messages from WhatsApp by setting:
1050
- ```ts
1051
- const sock = makeWASocket({
1052
- logger: P({ level: 'debug' }),
1053
- })
1054
- ```
1055
- This will enable you to see all sorts of messages WhatsApp sends in the console.
1056
-
1057
- ### How Whatsapp Communicate With Us
1058
-
1059
- > [!TIP]
1060
- > If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
1061
-
1062
- - **Example:** Functionality to track the battery percentage of your phone. You enable logging and you'll see a message about your battery pop up in the console:
1063
- ```
1064
- {
1065
- "level": 10,
1066
- "fromMe": false,
1067
- "frame": {
1068
- "tag": "ib",
1069
- "attrs": {
1070
- "from": "@s.whatsapp.net"
1071
- },
1072
- "content": [
1073
- {
1074
- "tag": "edge_routing",
1075
- "attrs": {},
1076
- "content": [
1077
- {
1078
- "tag": "routing_info",
1079
- "attrs": {},
1080
- "content": {
1081
- "type": "Buffer",
1082
- "data": [8,2,8,5]
1083
- }
1084
- }
1085
- ]
1086
- }
1087
- ]
1088
- },
1089
- "msg":"communication"
1090
- }
1091
- ```
1092
-
1093
- The `'frame'` is what the message received is, it has three components:
1094
- - `tag` -- what this frame is about (eg. message will have 'message')
1095
- - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
1096
- - `content` -- the actual data (eg. a message node will have the actual message content in it)
1097
- - read more about this format [here](/src/WABinary/readme.md)
1098
-
1099
- ### Register a Callback for Websocket Events
1100
-
1101
- > [!TIP]
1102
- > Recommended to see `onMessageReceived` function in `socket.ts` file to understand how websockets events are fired
1103
-
1104
- ```ts
1105
- // for any message with tag 'edge_routing'
1106
- sock.ws.on('CB:edge_routing', (node: BinaryNode) => { })
1107
-
1108
- // for any message with tag 'edge_routing' and id attribute = abcd
1109
- sock.ws.on('CB:edge_routing,id:abcd', (node: BinaryNode) => { })
1110
-
1111
- // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
1112
- sock.ws.on('CB:edge_routing,id:abcd,routing_info', (node: BinaryNode) => { })
1113
- ```
1114
-
1115
- > [!NOTE]
1116
- > Also, this repo is now licenced under GPL 3 since it uses [libsignal-node](https://git.questbook.io/backend/service-coderunner/-/merge_requests/1)