@blckrose/baileys 1.2.8 → 2.0.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.
package/README.md CHANGED
@@ -1,2813 +1,647 @@
1
- <h1 align='center'><img alt="Baileys logo" src="https://raw.githubusercontent.com/WhiskeySockets/Baileys/refs/heads/master/Media/logo.png" height="75"/></h1>
1
+ <p align="center">
2
+ <img src="https://files.catbox.moe/f8tj1b.png" alt="Rimuru Bot" width="150"/>
3
+ </p>
4
+
5
+ <h1 align="center">💧 Rimuru Baileys</h1>
6
+ <p align="center">
7
+ <strong>TypeScript-based WhatsApp Multi-Device Library</strong><br/>
8
+ With intelligent @lid/@jid mapping and advanced message handling
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://github.com/ryuhandev/rimuru-baileys/stargazers"><img src="https://img.shields.io/github/stars/ryuhandev/rimuru-baileys?style=flat-square&logo=github" alt="GitHub Stars"/></a>
13
+ <a href="https://github.com/ryuhandev/rimuru-baileys/issues"><img src="https://img.shields.io/github/issues/ryuhandev/rimuru-baileys?style=flat-square&logo=github" alt="GitHub Issues"/></a>
14
+ <a href="https://www.npmjs.com/package/@ryuhan/baileys"><img src="https://img.shields.io/npm/v/@ryuhan/baileys?style=flat-square&logo=npm" alt="npm Version"/></a>
15
+ <a href="https://www.npmjs.com/package/@ryuhan/baileys"><img src="https://img.shields.io/npm/dt/@ryuhan/baileys?style=flat-square&logo=npm" alt="npm Downloads"/></a>
16
+ <img src="https://img.shields.io/badge/License-MIT-green?style=flat-square" alt="License"/>
17
+ </p>
2
18
 
3
- <div align='center'>Baileys is a WebSockets-based TypeScript library for interacting with the WhatsApp Web API.</div>
4
-
5
-
6
- > [!CAUTION]
7
- > NOTICE OF BREAKING CHANGE.
8
- >
9
- > As of 1.0.0, multiple breaking changes were introduced into the library.
10
- >
11
- > Please check out https://whiskey.so/migrate-latest for more information.
12
-
13
- # Important Note
14
- This is a temporary README.md, the new guide is in development and will this file will be replaced with .github/README.md (already a default on GitHub).
15
-
16
- New guide link: https://baileys.wiki
17
-
18
- # Get Support
19
-
20
- If you'd like business to enterprise-level support from Rajeh, the current maintainer of Baileys, you can book a video chat. Book a 1 hour time slot by contacting him on Discord or pre-ordering [here](https://purpshell.dev/book). The earlier you pre-order the better, as his time slots usually fill up very quickly. He offers immense value per hour and will answer all your questions before the time runs out.
21
-
22
- If you are a business, we encourage you to contribute back to the high development costs of the project and to feed the maintainers who dump tens of hours a week on this. You can do so by booking meetings or sponsoring below. All support, even in bona fide / contribution hours, is welcome by businesses of all sizes. This is not condoning or endorsing businesses to use the library. See the Disclaimer below.
23
-
24
- # Sponsor
25
- If you'd like to financially support this project, you can do so by supporting the current maintainer [here](https://purpshell.dev/sponsor).
26
-
27
- # Disclaimer
28
- This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or its affiliates.
29
- The official WhatsApp website can be found at whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
30
-
31
- 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.
32
- Use at your own discretion. Do not spam people with this. We discourage any stalkerware, bulk or automated messaging usage.
33
-
34
- ##
35
-
36
- - Baileys does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a **WebSocket**.
37
- - Not running Selenium or Chromium saves you like **half a gig** of ram :/
38
- - Baileys supports interacting with the multi-device & web versions of WhatsApp.
39
- - 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.
40
-
41
- > [!IMPORTANT]
42
- > The original repository had to be removed by the original author - we now continue development in this repository here.
43
- This is the only official repository and is maintained by the community.
44
- > **Join the Discord [here](https://discord.gg/WeJM5FP9GG)**
45
-
46
- ## Example
47
-
48
- Do check out & run [example.ts](Example/example.ts) to see an example usage of the library.
49
- The script covers most common use cases.
50
- To run the example script, download or clone the repo and then type the following in a terminal:
51
- 1. ``` cd path/to/Baileys ```
52
- 2. ``` yarn ```
53
- 3. ``` yarn example ```
54
-
55
- ## Install
56
-
57
- Install dari file `.tgz` lokal (versi modified blckrose):
58
- ```
59
- npm install ./blckrose-baileys-1.1.5-apoc.tgz
60
- ```
61
-
62
- Atau tambahkan ke `package.json`:
63
- ```json
64
- {
65
- "dependencies": {
66
- "@blckrose/baileys": "file:./blckrose-baileys-1.1.5-apoc.tgz"
67
- }
68
- }
69
- ```
70
-
71
- Kemudian jalankan:
72
- ```
73
- npm install
74
- ```
75
-
76
- **ESM:**
77
- ```ts
78
- import makeWASocket from '@blckrose/baileys'
79
- ```
80
-
81
- **CJS (destructure langsung, tanpa top-level await):**
82
- ```js
83
- const { makeWASocket, useMultiFileAuthState, Browsers, DisconnectReason } = require('@blckrose/baileys')
84
- // global apocalypse otomatis tersedia setelah baris di atas
85
- ```
86
-
87
- # Links
88
-
89
- - [Discord](https://discord.gg/WeJM5FP9GG)
90
- - [Docs](https://guide.whiskeysockets.io/)
91
-
92
- # Index
93
-
94
- - [Connecting Account](#connecting-account)
95
- - [Connect with QR-CODE](#starting-socket-with-qr-code)
96
- - [Connect with Pairing Code](#starting-socket-with-pairing-code)
97
- - [Receive Full History](#receive-full-history)
98
- - [Important Notes About Socket Config](#important-notes-about-socket-config)
99
- - [Caching Group Metadata (Recommended)](#caching-group-metadata-recommended)
100
- - [Improve Retry System & Decrypt Poll Votes](#improve-retry-system--decrypt-poll-votes)
101
- - [Receive Notifications in Whatsapp App](#receive-notifications-in-whatsapp-app)
102
-
103
- - [Save Auth Info](#saving--restoring-sessions)
104
- - [Handling Events](#handling-events)
105
- - [Example to Start](#example-to-start)
106
- - [Decrypt Poll Votes](#decrypt-poll-votes)
107
- - [Summary of Events on First Connection](#summary-of-events-on-first-connection)
108
- - [Implementing a Data Store](#implementing-a-data-store)
109
- - [Whatsapp IDs Explain](#whatsapp-ids-explain)
110
- - [Utility Functions](#utility-functions)
111
- - [Apocalypse API](#apocalypse-api)
112
- - [Cara Pakai Tanpa API Key](#cara-pakai-tanpa-api-key)
113
- - [Cara Pakai Dengan API Key](#cara-pakai-dengan-api-key)
114
- - [Contoh Penggunaan](#contoh-penggunaan-apocalypse)
115
- - [Newsletter / Channel](#newsletter--channel)
116
- - [Kirim Media ke Channel](#kirim-media-ke-channel)
117
- - [Button di Channel](#button-di-channel)
118
- - [Edit & Hapus Pesan Channel](#edit--hapus-pesan-channel)
119
- - [Resolve JID (LID → Phone)](#resolve-jid)
120
- - [Sending Messages](#sending-messages)
121
- - [Non-Media Messages](#non-media-messages)
122
- - [Text Message](#text-message)
123
- - [Quote Message](#quote-message-works-with-all-types)
124
- - [Mention User](#mention-user-works-with-most-types)
125
- - [Forward Messages](#forward-messages)
126
- - [Location Message](#location-message)
127
- - [Live Location Message](#live-location-message)
128
- - [Contact Message](#contact-message)
129
- - [Reaction Message](#reaction-message)
130
- - [Pin Message](#pin-message)
131
- - [Keep Message](#keep-message)
132
- - [Poll Message](#poll-message)
133
- - [Poll Result Message](#poll-result-message)
134
- - [Call Message](#call-message)
135
- - [Event Message](#event-message)
136
- - [Order Message](#order-message)
137
- - [Product Message](#product-message)
138
- - [Payment Message](#payment-message)
139
- - [Payment Invite Message](#payment-invite-message)
140
- - [Admin Invite Message](#admin-invite-message)
141
- - [Group Invite Message](#group-invite-message)
142
- - [Sticker Pack Message](#sticker-pack-message)
143
- - [Share Phone Number Message](#share-phone-number-message)
144
- - [Request Phone Number Message](#request-phone-number-message)
145
- - [Buttons Reply Message](#buttons-reply-message)
146
- - [Buttons Message](#buttons-message)
147
- - [Buttons List Message](#buttons-list-message)
148
- - [Buttons Product List Message](#buttons-product-list-message)
149
- - [Buttons Cards Message](#buttons-cards-message)
150
- - [Buttons Template Message](#buttons-template-message)
151
- - [Buttons Interactive Message](#buttons-interactive-message)
152
- - [Buttons Interactive Message PIX](#buttons-interactive-message-pix)
153
- - [Buttons Interactive Message PAY](#buttons-interactive-message-pay)
154
- - [Status Mentions Message](#status-mentions-message)
155
- - [Shop Message](#shop-message)
156
- - [Collection Message](#collection-message)
157
- - [AI Icon Feature](#ai-icon-feature)
158
- - [Sending with Link Preview](#sending-messages-with-link-previews)
159
- - [Media Messages](#media-messages)
160
- - [Gif Message](#gif-message)
161
- - [Video Message](#video-message)
162
- - [Audio Message](#audio-message)
163
- - [Image Message](#image-message)
164
- - [Album Message](#album-message)
165
- - [Ptv Video Message](#ptv-video-message)
166
- - [ViewOnce Message](#view-once-message)
167
- - [Modify Messages](#modify-messages)
168
- - [Delete Messages (for everyone)](#deleting-messages-for-everyone)
169
- - [Edit Messages](#editing-messages)
170
- - [Manipulating Media Messages](#manipulating-media-messages)
171
- - [Thumbnail in Media Messages](#thumbnail-in-media-messages)
172
- - [Downloading Media Messages](#downloading-media-messages)
173
- - [Re-upload Media Message to Whatsapp](#re-upload-media-message-to-whatsapp)
174
- - [Reject Call](#reject-call)
175
- - [Send States in Chat](#send-states-in-chat)
176
- - [Reading Messages](#reading-messages)
177
- - [Update Presence](#update-presence)
178
- - [Modifying Chats](#modifying-chats)
179
- - [Archive a Chat](#archive-a-chat)
180
- - [Mute/Unmute a Chat](#muteunmute-a-chat)
181
- - [Mark a Chat Read/Unread](#mark-a-chat-readunread)
182
- - [Delete a Message for Me](#delete-a-message-for-me)
183
- - [Delete a Chat](#delete-a-chat)
184
- - [Star/Unstar a Message](#starunstar-a-message)
185
- - [Disappearing Messages](#disappearing-messages)
186
- - [Clear Messages](#clear-messages)
187
- - [User Querys](#user-querys)
188
- - [Check If ID Exists in Whatsapp](#check-if-id-exists-in-whatsapp)
189
- - [Query Chat History (groups too)](#query-chat-history-groups-too)
190
- - [Fetch Status](#fetch-status)
191
- - [Fetch Profile Picture (groups too)](#fetch-profile-picture-groups-too)
192
- - [Fetch Bussines Profile (such as description or category)](#fetch-bussines-profile-such-as-description-or-category)
193
- - [Fetch Someone's Presence (if they're typing or online)](#fetch-someones-presence-if-theyre-typing-or-online)
194
- - [Change Profile](#change-profile)
195
- - [Change Profile Status](#change-profile-status)
196
- - [Change Profile Name](#change-profile-name)
197
- - [Change Display Picture (groups too)](#change-display-picture-groups-too)
198
- - [Remove display picture (groups too)](#remove-display-picture-groups-too)
199
- - [Groups](#groups)
200
- - [Create a Group](#create-a-group)
201
- - [Add/Remove or Demote/Promote](#addremove-or-demotepromote)
202
- - [Change Subject (name)](#change-subject-name)
203
- - [Change Description](#change-description)
204
- - [Change Settings](#change-settings)
205
- - [Leave a Group](#leave-a-group)
206
- - [Get Invite Code](#get-invite-code)
207
- - [Revoke Invite Code](#revoke-invite-code)
208
- - [Join Using Invitation Code](#join-using-invitation-code)
209
- - [Get Group Info by Invite Code](#get-group-info-by-invite-code)
210
- - [Query Metadata (participants, name, description...)](#query-metadata-participants-name-description)
211
- - [Join using groupInviteMessage](#join-using-groupinvitemessage)
212
- - [Get Request Join List](#get-request-join-list)
213
- - [Approve/Reject Request Join](#approvereject-request-join)
214
- - [Get All Participating Groups Metadata](#get-all-participating-groups-metadata)
215
- - [Toggle Ephemeral](#toggle-ephemeral)
216
- - [Change Add Mode](#change-add-mode)
217
- - [Privacy](#privacy)
218
- - [Block/Unblock User](#blockunblock-user)
219
- - [Get Privacy Settings](#get-privacy-settings)
220
- - [Get BlockList](#get-blocklist)
221
- - [Update LastSeen Privacy](#update-lastseen-privacy)
222
- - [Update Online Privacy](#update-online-privacy)
223
- - [Update Profile Picture Privacy](#update-profile-picture-privacy)
224
- - [Update Status Privacy](#update-status-privacy)
225
- - [Update Read Receipts Privacy](#update-read-receipts-privacy)
226
- - [Update Groups Add Privacy](#update-groups-add-privacy)
227
- - [Update Default Disappearing Mode](#update-default-disappearing-mode)
228
- - [Broadcast Lists & Stories](#broadcast-lists--stories)
229
- - [Send Broadcast & Stories](#send-broadcast--stories)
230
- - [Query a Broadcast List's Recipients & Name](#query-a-broadcast-lists-recipients--name)
231
- - [Writing Custom Functionality](#writing-custom-functionality)
232
- - [Enabling Debug Level in Baileys Logs](#enabling-debug-level-in-baileys-logs)
233
- - [How Whatsapp Communicate With Us](#how-whatsapp-communicate-with-us)
234
- - [Register a Callback for Websocket Events](#register-a-callback-for-websocket-events)
235
-
236
- ## Connecting Account
237
-
238
- 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.
239
-
240
- > [!NOTE]
241
- > **[Here](#example-to-start) is a simple example of event handling**
242
-
243
- > [!TIP]
244
- > **You can see all supported socket configs [here](https://baileys.whiskeysockets.io/types/SocketConfig.html) (Recommended)**
245
-
246
- ### Starting socket with **QR-CODE**
247
-
248
- > [!TIP]
249
- > You can customize browser name if you connect with **QR-CODE**, with `Browser` constant, we have some browsers config, **see [here](https://baileys.whiskeysockets.io/types/BrowsersMap.html)**
250
-
251
- ```ts
252
- import makeWASocket from '@blckrose/baileys'
253
-
254
- const sock = makeWASocket({
255
- // can provide additional config here
256
- browser: Browsers.ubuntu('My App'),
257
- printQRInTerminal: true
258
- })
259
- ```
260
-
261
- 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!
262
-
263
- ### Starting socket with **Pairing Code**
264
-
265
-
266
- > [!IMPORTANT]
267
- > 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)
268
-
269
- The phone number can't have `+` or `()` or `-`, only numbers, you must provide country code
19
+ ---
270
20
 
271
- ```ts
272
- import makeWASocket from '@blckrose/baileys'
21
+ ## 🌟 Features
22
+
23
+ ### Core Features
24
+ - **💧 Intelligent `@lid` and `@jid` Mapping** - Automatic resolution of LID to phone JID
25
+ - **💧 Multi-Device Support** - Full support for WhatsApp multi-device protocol
26
+ - **💧 End-to-End Encryption** - Complete E2EE support for secure messaging
27
+ - **💧 All Message Types** - Support for text, media, polls, reactions, and more
28
+ - **💧 TypeScript Based** - Type-safe with modern TypeScript
29
+ - **💧 High Performance** - Optimized for speed and efficiency
30
+
31
+ ### Advanced Features
32
+ - **💧 Media Handling** - Send/receive images, videos, audio, stickers, documents
33
+ - **💧 Pairing Code Login** - Easy authentication with custom pairing code "MURUSAMA"
34
+ - **💧 Newsletter/Channel Support** - Full support for WhatsApp channels
35
+ - **💧 Group Management** - Complete group controls and administration
36
+ - **💧 Story/Broadcast** - Send and manage stories and broadcast lists
37
+ - **💧 Business API** - Support for WhatsApp Business features
38
+ - **💧 Poll Messages** - Create and manage poll messages with vote tracking
39
+ - **💧 Reaction Messages** - Send and receive emoji reactions
40
+ - **💧 Pin Messages** - Pin important messages in chats
41
+ - **💧 Disappearing Messages** - Configure ephemeral messages
42
+ - **💧 Contact Messages** - Send vCard contacts
43
+ - **💧 Location Messages** - Share live and static locations
44
+ - **💧 Button Messages** - Interactive button messages (where supported)
45
+ - **💧 List Messages** - Interactive list messages
46
+ - **💧 Template Messages** - Pre-defined message templates
47
+
48
+ ### Developer Friendly
49
+ - **💧 Clean API** - Simple and intuitive API design
50
+ - **💧 Event-Driven** - Comprehensive event system for all actions
51
+ - **💧 Auth Storage** - Multi-file and single-file auth state options
52
+ - **💧 In-Memory Store** - Built-in store for chats, contacts, messages
53
+ - **💧 Customizable** - Easy to extend and customize
54
+ - **💧 Well Documented** - Comprehensive documentation and examples
273
55
 
274
- const sock = makeWASocket({
275
- // can provide additional config here
276
- printQRInTerminal: false //need to be false
277
- })
278
-
279
- if (!sock.authState.creds.registered) {
280
- const number = 'XXXXXXXXXXX'
281
- const code = await sock.requestPairingCode(number)
282
- console.log(code)
283
- }
284
- ```
285
-
286
- ### Receive Full History
56
+ ---
287
57
 
288
- 1. Set `syncFullHistory` as `true`
289
- 2. Baileys, by default, use chrome browser config
290
- - If you'd like to emulate a desktop connection (and receive more message history), this browser setting to your Socket config:
58
+ ## 📦 Installation
291
59
 
292
- ```ts
293
- const sock = makeWASocket({
294
- ...otherOpts,
295
- // can use Windows, Ubuntu here too
296
- browser: Browsers.macOS('Desktop'),
297
- syncFullHistory: true
298
- })
60
+ ### npm
61
+ ```bash
62
+ npm install @ryuhan/baileys
299
63
  ```
300
64
 
301
- ## Important Notes About Socket Config
302
-
303
- ### Caching Group Metadata (Recommended)
304
- - If you use baileys for groups, we recommend you to set `cachedGroupMetadata` in socket config, you need to implement a cache like this:
305
-
306
- ```ts
307
- const groupCache = new NodeCache({stdTTL: 5 * 60, useClones: false})
308
-
309
- const sock = makeWASocket({
310
- cachedGroupMetadata: async (jid) => groupCache.get(jid)
311
- })
312
-
313
- sock.ev.on('groups.update', async ([event]) => {
314
- const metadata = await sock.groupMetadata(event.id)
315
- groupCache.set(event.id, metadata)
316
- })
317
-
318
- sock.ev.on('group-participants.update', async (event) => {
319
- const metadata = await sock.groupMetadata(event.id)
320
- groupCache.set(event.id, metadata)
321
- })
322
- ```
323
-
324
- ### Improve Retry System & Decrypt Poll Votes
325
- - 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:
326
- ```ts
327
- const sock = makeWASocket({
328
- getMessage: async (key) => await getMessageFromStore(key)
329
- })
330
- ```
331
-
332
- ### Receive Notifications in Whatsapp App
333
- - If you want to receive notifications in whatsapp app, set `markOnlineOnConnect` to `false`
334
- ```ts
335
- const sock = makeWASocket({
336
- markOnlineOnConnect: false
337
- })
338
- ```
339
- ## Saving & Restoring Sessions
340
-
341
- You obviously don't want to keep scanning the QR code every time you want to connect.
342
-
343
- So, you can load the credentials to log back in:
344
- ```ts
345
- import makeWASocket, { useMultiFileAuthState } from '@blckrose/baileys'
346
-
347
- const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
348
-
349
- // will use the given state to connect
350
- // so if valid credentials are available -- it'll connect without QR
351
- const sock = makeWASocket({ auth: state })
352
-
353
- // this will be called as soon as the credentials are updated
354
- sock.ev.on('creds.update', saveCreds)
65
+ ### yarn
66
+ ```bash
67
+ yarn add @ryuhan/baileys
355
68
  ```
356
69
 
357
- > [!IMPORTANT]
358
- > `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.
359
-
360
- > [!NOTE]
361
- > 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.
362
-
363
- ## Handling Events
364
-
365
- - Baileys uses the EventEmitter syntax for events.
366
- They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
367
-
368
- > [!IMPORTANT]
369
- > **The events are [these](https://baileys.whiskeysockets.io/types/BaileysEventMap.html)**, it's important you see all events
370
-
371
- You can listen to these events like this:
372
- ```ts
373
- const sock = makeWASocket()
374
- sock.ev.on('messages.upsert', ({ messages }) => {
375
- console.log('got messages', messages)
376
- })
70
+ ### pnpm
71
+ ```bash
72
+ pnpm add @ryuhan/baileys
377
73
  ```
378
74
 
379
- ### Example to Start
380
-
381
- > [!NOTE]
382
- > This example includes basic auth storage too
75
+ ---
383
76
 
384
- > [!NOTE]
385
- > For reliable serialization of the authentication state, especially when storing as JSON, always use the BufferJSON utility.
77
+ ## 🚀 Quick Start
386
78
 
387
- ```ts
388
- import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@blckrose/baileys'
79
+ ### Basic Example
80
+ ```typescript
81
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@ryuhan/baileys'
389
82
  import { Boom } from '@hapi/boom'
390
83
 
391
- async function connectToWhatsApp () {
392
- const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
84
+ async function connectToWhatsApp() {
85
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info')
86
+
393
87
  const sock = makeWASocket({
394
- // can provide additional config here
395
88
  auth: state,
396
89
  printQRInTerminal: true
397
90
  })
91
+
398
92
  sock.ev.on('connection.update', (update) => {
399
93
  const { connection, lastDisconnect } = update
400
- if(connection === 'close') {
401
- const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
402
- console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
403
- // reconnect if not logged out
404
- if(shouldReconnect) {
94
+ if (connection === 'close') {
95
+ const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
96
+ if (shouldReconnect) {
405
97
  connectToWhatsApp()
406
98
  }
407
- } else if(connection === 'open') {
408
- console.log('opened connection')
99
+ } else if (connection === 'open') {
100
+ console.log(' Connected to WhatsApp!')
409
101
  }
410
102
  })
411
- sock.ev.on('messages.upsert', event => {
412
- for (const m of event.messages) {
413
- console.log(JSON.stringify(m, undefined, 2))
414
103
 
415
- console.log('replying to', m.key.remoteJid)
416
- await sock.sendMessage(m.key.remoteJid!, { text: 'Hello Word' })
104
+ sock.ev.on('messages.upsert', async ({ messages }) => {
105
+ for (const m of messages) {
106
+ if (!m.message) continue
107
+ console.log('📱 New message:', m.key.remoteJid)
108
+
109
+ // Reply to message
110
+ await sock.sendMessage(m.key.remoteJid!, {
111
+ text: 'Hello! I am Rimuru Bot 💧'
112
+ })
417
113
  }
418
114
  })
419
115
 
420
- // to storage creds (session info) when it updates
421
116
  sock.ev.on('creds.update', saveCreds)
422
117
  }
423
- // run in main file
424
- connectToWhatsApp()
425
- ```
426
-
427
- ### For example if you use useSingleFileAuthState and useMongoFileAuthState
428
- ```ts
429
- import makeWASocket, { useSingleFileAuthState, useMongoFileAuthState } from '@blckrose/baileys'
430
118
 
431
- // Single Auth
432
- const { state, saveState } = await useSingleFileAuthState('./auth_info_baileys.json')
433
- const sock = makeWASocket({
434
- auth: state,
435
- printQRInTerminal: true
436
- })
437
-
438
- sock.ev.on('creds.update', saveState)
439
-
440
- // Mongo Auth
441
- import { MongoClient } from "mongodb"
442
-
443
- const connectAuth = async() => {
444
- global.client = new MongoClient('mongoURL')
445
- global.client.connect(err => {
446
- if (err) {
447
- console.warn("Warning: MongoDB link is invalid or cannot be connected.")
448
- } else {
449
- console.log('Successfully Connected To MongoDB Server')
450
- }
451
- })
452
- await client.connect()
453
- const collection = client.db("@blckrose").collection("sessions")
454
- return collection
455
- }
456
-
457
- const Authentication = await connectAuth()
458
- const { state, saveCreds } = await useMongoFileAuthState(Authentication)
459
- const sock = makeWASocket({
460
- auth: state,
461
- printQRInTerminal: true
462
- })
463
-
464
- sock.ev.on('creds.update', saveCreds)
465
- ```
466
-
467
- > [!IMPORTANT]
468
- > In `messages.upsert` it's recommended to use a loop like `for (const message of event.messages)` to handle all messages in array
469
-
470
- ### Decrypt Poll Votes
471
-
472
- - By default poll votes are encrypted and handled in `messages.update`
473
- - That's a simple example
474
- ```ts
475
- sock.ev.on('messages.update', event => {
476
- for(const { key, update } of event) {
477
- if(update.pollUpdates) {
478
- const pollCreation = await getMessage(key)
479
- if(pollCreation) {
480
- console.log(
481
- 'got poll update, aggregation: ',
482
- getAggregateVotesInPollMessage({
483
- message: pollCreation,
484
- pollUpdates: update.pollUpdates,
485
- })
486
- )
487
- }
488
- }
489
- }
490
- })
119
+ connectToWhatsApp()
491
120
  ```
492
121
 
493
- - `getMessage` is a [store](#implementing-a-data-store) implementation (in your end)
494
-
495
- ### Summary of Events on First Connection
496
-
497
- 1. When you connect first time, `connection.update` will be fired requesting you to restart sock
498
- 2. Then, history messages will be received in `messaging.history-set`
499
-
500
- ## Implementing a Data Store
501
-
502
- - 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.
503
-
504
- > [!IMPORTANT]
505
- > I highly recommend building your own data store, as storing someone's entire chat history in memory is a terrible waste of RAM.
506
-
507
- It can be used as follows:
508
-
509
- ```ts
510
- import makeWASocket, { makeInMemoryStore } from '@blckrose/baileys'
511
- // the store maintains the data of the WA connection in memory
512
- // can be written out to a file & read from it
513
- const store = makeInMemoryStore({ })
514
- // can be read from a file
515
- store.readFromFile('./baileys_store.json')
516
- // saves the state to a file every 10s
517
- setInterval(() => {
518
- store.writeToFile('./baileys_store.json')
519
- }, 10_000)
122
+ ---
520
123
 
521
- const sock = makeWASocket({ })
522
- // will listen from this socket
523
- // the store can listen from a new socket once the current socket outlives its lifetime
524
- store.bind(sock.ev)
124
+ ## 🔐 Authentication
525
125
 
526
- sock.ev.on('chats.upsert', () => {
527
- // can use 'store.chats' however you want, even after the socket dies out
528
- // 'chats' => a KeyedDB instance
529
- console.log('got chats', store.chats.all())
530
- })
126
+ ### Pairing Code (Recommended)
127
+ ```typescript
128
+ import makeWASocket from '@ryuhan/baileys'
531
129
 
532
- sock.ev.on('contacts.upsert', () => {
533
- console.log('got contacts', Object.values(store.contacts))
130
+ const sock = makeWASocket({
131
+ printQRInTerminal: false
534
132
  })
535
133
 
134
+ // Request pairing code
135
+ if (!sock.authState.creds.registered) {
136
+ const phoneNumber = '6285134816783' // Your phone number with country code
137
+ const code = await sock.requestPairingCode(phoneNumber, "MURUSAMA")
138
+ console.log('💧 Pairing Code:', code)
139
+ }
536
140
  ```
537
141
 
538
- The store also provides some simple functions such as `loadMessages` that utilize the store to speed up data retrieval.
539
-
540
- ## Whatsapp IDs Explain
541
-
542
- - `id` is the WhatsApp ID, called `jid` too, of the person or group you're sending the message to.
543
- - It must be in the format ```[country code][phone number]@s.whatsapp.net```
544
- - Example for people: ```+19999999999@s.whatsapp.net```.
545
- - For groups, it must be in the format ``` 123456789-123345@g.us ```.
546
- - For broadcast lists, it's `[timestamp of creation]@broadcast`.
547
- - For stories, the ID is `status@broadcast`.
548
-
549
- ## Utility Functions
142
+ ### QR Code
143
+ ```typescript
144
+ import makeWASocket, { Browsers } from '@ryuhan/baileys'
550
145
 
551
- ### Resize Image
552
- ```ts
553
- // Resize an image (Buffer, URL, or stream) to given dimensions
554
- const resized = await sock.resize('https://example.com/image.jpg', 320, 320)
555
- // or
556
- const resized = await sock.resize(buffer, 320, 320)
146
+ const sock = makeWASocket({
147
+ browser: Browsers.ubuntu('My Bot'),
148
+ printQRInTerminal: true
149
+ })
557
150
  ```
558
151
 
559
- - `getContentType`, returns the content type for any message
560
- - `getDevice`, returns the device from message
561
- - `makeCacheableSignalKeyStore`, make auth store more fast
562
- - `downloadContentFromMessage`, download content from any message
563
- - `makeNewsletterUtils`, helper lengkap untuk kirim ke newsletter/channel
564
- - `resolveJid`, resolve LID / participant ID ke JID @s.whatsapp.net
565
- - `resolveJids`, resolve banyak JID sekaligus
566
-
567
152
  ---
568
153
 
569
- ## Apocalypse API
570
-
571
- > **Base URL:** `https://api.apocalypse.web.id`
572
- > **Docs:** `https://api.apocalypse.web.id/docs`
573
-
574
- `apocalypse` adalah global HTTP client yang otomatis tersedia setelah `require('@blckrose/baileys')`. Tidak perlu import apapun lagi.
575
-
576
- ### Cara Pakai Tanpa API Key
154
+ ## 📚 Common Use Cases
577
155
 
578
- ```js
579
- // Cukup require baileys seperti biasa, apocalypse langsung ada
580
- const { makeWASocket, useMultiFileAuthState } = require('@blckrose/baileys')
581
-
582
- // Di handler / file manapun — langsung pakai:
583
- const res = await apocalypse.get('/search/spotify?q=swim')
584
- console.log(res.result)
585
-
586
- // Atau gunakan params object (auto-encode):
587
- const res = await apocalypse.get('/search/spotify', { q: 'swim' })
588
-
589
- // Sub-path dengan params:
590
- const res = await apocalypse.get('/manga/jagoanmanga/search', { q: 'killer+peter' })
591
-
592
- // POST:
593
- const res = await apocalypse.post('/ai/chatgpt', { text: 'halo' })
594
- ```
595
-
596
- ### Cara Pakai Dengan API Key
597
-
598
- `createApocalypse` tersedia **global** tanpa import, otomatis setelah `require('@blckrose/baileys')`.
599
-
600
- **Cara 1 — API key langsung di kode:**
601
- ```js
602
- const api = createApocalypse({ apiKey: 'NEMOPHILA' })
603
- await api.get('/search/spotify', { q: 'swim' })
156
+ ### Send Text Message
157
+ ```typescript
158
+ await sock.sendMessage(jid, { text: 'Hello World! 💧' })
604
159
  ```
605
160
 
606
- **Cara 2 — API key dari `config.js` / `setting.js`:**
607
- ```js
608
- // config.js / setting.js
609
- global.apikey = 'NEMOPHILA'
610
-
611
- // handler / file manapun — tidak perlu import apapun
612
- const api = createApocalypse({ apiKey: global.apikey })
613
- await api.get('/search/spotify', { q: 'swim' })
614
- ```
615
-
616
- **Cara 3 — Set ke global `apocalypse` instance (berlaku semua request):**
617
- ```js
618
- // bot.js — set sekali
619
- apocalypse.setKey(global.apikey)
620
-
621
- // handler manapun — langsung pakai, key terbawa otomatis
622
- await apocalypse.get('/premium/endpoint', { q: 'test' })
623
- ```
624
-
625
- **Config lengkap yang tersedia:**
626
- ```js
627
- const api = createApocalypse({
628
- apiKey: 'NEMOPHILA', // API key → dikirim sebagai header x-api-key
629
- timeout: 15000, // timeout ms (default: 30000)
630
- baseUrl: 'https://...', // override base URL (opsional)
631
- headers: { // header tambahan (opsional)
632
- 'x-custom': 'value'
633
- }
161
+ ### Send Image
162
+ ```typescript
163
+ await sock.sendMessage(jid, {
164
+ image: { url: './image.jpg' },
165
+ caption: 'Check this out!'
634
166
  })
635
167
  ```
636
168
 
637
- > [!NOTE]
638
- > `createApocalypse` dan `apocalypse` keduanya tersedia global — tidak perlu tulis `import` atau `require` apapun selain `require('@blckrose/baileys')` yang sudah ada di bot.js.
639
-
640
- ### Contoh Penggunaan Apocalypse
641
-
642
- #### Respon Object
643
-
644
- Setiap response memiliki struktur yang sama:
645
-
646
- | Property | Tipe | Keterangan |
647
- |---|---|---|
648
- | `.result` | `any` | Data utama (`data.result` / `data.data` / root) |
649
- | `.status` | `boolean` | `true` jika API sukses |
650
- | `.message` | `string` | Pesan dari API |
651
- | `.raw` | `object` | Full JSON response mentah |
652
- | `.url` | `string` | URL yang dipanggil |
653
- | `.get(key)` | `any` | Ambil field tertentu dari result |
654
-
655
- #### Search Spotify
656
-
657
- ```js
658
- const res = await apocalypse.get('/search/spotify', { q: 'swim' })
659
- // atau
660
- const res = await apocalypse.get('/search/spotify?q=swim')
661
-
662
- console.log(res.result) // data hasil pencarian
663
- console.log(res.status) // true / false
664
- ```
665
-
666
- #### Search YouTube
667
-
668
- ```js
669
- const res = await apocalypse.get('/search/youtube', { q: 'lagu baru' })
670
- console.log(res.result)
671
- ```
672
-
673
- #### Search dengan URL
674
-
675
- ```js
676
- const res = await apocalypse.get('/search/tiktok', { url: 'https://vm.tiktok.com/xxx' })
677
- console.log(res.result)
678
- ```
679
-
680
- #### Manga Search
681
-
682
- ```js
683
- // Sub-path: /manga/{sumber}/search
684
- const res = await apocalypse.get('/manga/jagoanmanga/search', { q: 'killer+peter' })
685
- console.log(res.result)
686
- ```
687
-
688
- #### AI / Chatbot
689
-
690
- ```js
691
- const res = await apocalypse.post('/ai/chatgpt', { text: 'halo, siapa kamu?' })
692
- console.log(res.result)
693
- ```
694
-
695
- #### Category Helper (shortcut)
696
-
697
- ```js
698
- // Buat caller untuk satu kategori
699
- const search = apocalypse.category('search')
700
- await search.get('spotify', { q: 'swim' })
701
- await search.get('youtube', { q: 'lagu' })
702
- await search.get('tiktok', { q: 'viral' })
703
-
704
- // Sub-path
705
- const manga = apocalypse.category('manga/jagoanmanga')
706
- await manga.get('search', { q: 'naruto' })
707
- await manga.get('chapter', { id: '123' })
169
+ ### Send Video
170
+ ```typescript
171
+ await sock.sendMessage(jid, {
172
+ video: { url: './video.mp4' },
173
+ caption: 'Amazing video!',
174
+ mimetype: 'video/mp4'
175
+ })
708
176
  ```
709
177
 
710
- #### Pakai di Handler Bot
711
-
712
- ```js
713
- // handler/search.js
714
- let handler = async (m, { conn }) => {
715
- const query = m.text.slice(8).trim() // contoh: !search <query>
716
- if (!query) return conn.sendMessage(m.chat, { text: 'Masukkan kata kunci!' }, { quoted: m })
717
-
718
- try {
719
- const res = await apocalypse.get('/search/spotify', { q: query })
720
- if (!res.status) return conn.sendMessage(m.chat, { text: 'Tidak ditemukan.' }, { quoted: m })
721
-
722
- const data = res.result
723
- await conn.sendMessage(m.chat, {
724
- text: `🎵 *${data.title}*\n👤 ${data.artist}\n🔗 ${data.url}`
725
- }, { quoted: m })
726
- } catch (e) {
727
- await conn.sendMessage(m.chat, { text: `Error: ${e.message}` }, { quoted: m })
728
- }
729
- }
730
-
731
- handler.command = /^search$/i
732
- module.exports = handler
178
+ ### Send Audio
179
+ ```typescript
180
+ await sock.sendMessage(jid, {
181
+ audio: { url: './audio.mp3' },
182
+ mimetype: 'audio/mp4'
183
+ })
733
184
  ```
734
185
 
735
- #### Pakai Dengan API Key
736
-
737
- ```js
738
- // Cara 1 langsung di kode
739
- const api = createApocalypse({ apiKey: 'NEMOPHILA' })
740
- await api.get('/search/spotify', { q: 'swim' })
741
-
742
- // Cara 2 — dari config/setting global
743
- const api = createApocalypse({ apiKey: global.apikey })
744
- await api.get('/search/spotify', { q: 'swim' })
745
-
746
- // Cara 3 — set ke global instance (berlaku semua request berikutnya)
747
- apocalypse.setKey(global.apikey)
748
- await apocalypse.get('/premium/endpoint', { q: 'test' })
186
+ ### Send Sticker
187
+ ```typescript
188
+ await sock.sendMessage(jid, {
189
+ sticker: { url: './sticker.webp' }
190
+ })
749
191
  ```
750
192
 
751
- ---
752
-
753
- ## Newsletter / Channel
754
-
755
- > [!NOTE]
756
- > Newsletter menggunakan format JID `@newsletter`, contoh: `120363xxxxxxxxx@newsletter`
757
-
758
- ### Kirim Media ke Channel
759
-
760
- Gunakan helper `makeNewsletterUtils(conn)` yang menggabungkan semua fungsi kirim ke channel:
761
-
762
- ```js
763
- const { makeNewsletterUtils } = require('@blckrose/baileys')
764
- const nl = makeNewsletterUtils(conn)
765
-
766
- const JID = '120363xxxxxxxxx@newsletter'
767
-
768
- // Teks
769
- await nl.sendNewsletterText(JID, 'Halo dari bot!')
770
-
771
- // Gambar
772
- await nl.sendNewsletterImage(JID, { url: 'https://example.com/img.jpg' }, { caption: 'Gambar keren' })
773
-
774
- // Video
775
- await nl.sendNewsletterVideo(JID, { url: 'https://example.com/vid.mp4' }, { caption: 'Video nih' })
776
-
777
- // PTV (video note / lingkaran)
778
- await nl.sendNewsletterPtv(JID, { url: 'https://example.com/vid.mp4' })
779
-
780
- // Audio
781
- await nl.sendNewsletterAudio(JID, { url: 'https://example.com/audio.mp3' })
782
-
783
- // Dokumen
784
- await nl.sendNewsletterDocument(JID, { url: 'https://example.com/file.pdf' }, {
193
+ ### Send Document
194
+ ```typescript
195
+ await sock.sendMessage(jid, {
196
+ document: { url: './document.pdf' },
785
197
  mimetype: 'application/pdf',
786
- fileName: 'dokumen.pdf'
198
+ fileName: 'document.pdf'
787
199
  })
788
-
789
- // Sticker
790
- await nl.sendNewsletterSticker(JID, fs.readFileSync('./sticker.webp'))
791
- ```
792
-
793
- Atau langsung pakai `conn.sendMessage` seperti biasa — semua tipe media sudah support:
794
- ```js
795
- await conn.sendMessage(JID, { image: { url: 'https://...' }, caption: 'test' })
796
- await conn.sendMessage(JID, { video: { url: 'https://...' }, ptv: true })
797
200
  ```
798
201
 
799
- ### Button di Channel
800
-
801
- > [!IMPORTANT]
802
- > Fitur ini **hanya ada di blckrose-baileys 1.1.5-apoc**. Fork lain tidak support button di newsletter.
803
-
804
- ```js
805
- const nl = makeNewsletterUtils(conn)
806
- const JID = '120363xxxxxxxxx@newsletter'
807
-
808
- // Quick Reply Buttons
809
- await nl.sendNewsletterButtons(JID, {
810
- body: 'Pilih salah satu:',
811
- buttons: [
812
- { id: 'btn_yes', text: '✅ Setuju' },
813
- { id: 'btn_no', text: '❌ Tidak' },
814
- { id: 'btn_skip', text: '⏭ Skip' }
815
- ],
816
- footer: 'Powered by bot'
202
+ ### Send Location
203
+ ```typescript
204
+ await sock.sendMessage(jid, {
205
+ location: {
206
+ degreesLatitude: -6.2088,
207
+ degreesLongitude: 106.8456
208
+ }
817
209
  })
210
+ ```
818
211
 
819
- // Single Select List
820
- await nl.sendNewsletterList(JID, {
821
- body: 'Pilih menu yang kamu mau:',
822
- buttonText: 'Buka Menu',
823
- sections: [
824
- {
825
- title: 'Fitur Utama',
826
- rows: [
827
- { id: 'info', title: 'Info Bot', description: 'Lihat info bot' },
828
- { id: 'help', title: 'Bantuan', description: 'Cara pakai bot' },
829
- { id: 'stats', title: 'Statistik', description: 'Lihat statistik' }
830
- ]
831
- },
832
- {
833
- title: 'Lainnya',
834
- rows: [
835
- { id: 'about', title: 'Tentang', description: 'Info developer' }
836
- ]
837
- }
838
- ],
839
- title: 'Menu Bot',
840
- footer: 'Versi 1.0'
841
- })
212
+ ### Send Contact
213
+ ```typescript
214
+ const vcard = `BEGIN:VCARD
215
+ VERSION:3.0
216
+ FN:John Doe
217
+ TEL;type=CELL;type=VOICE;waid=6281234567890:+62 812-3456-7890
218
+ END:VCARD`
842
219
 
843
- // CTA URL Button
844
- await nl.sendNewsletterCtaUrl(JID, {
845
- body: 'Kunjungi website kami untuk info lebih lanjut!',
846
- buttonText: '🌐 Buka Website',
847
- url: 'https://example.com',
848
- title: 'Info Lengkap',
849
- footer: 'Klik tombol di bawah'
220
+ await sock.sendMessage(jid, {
221
+ contacts: {
222
+ displayName: 'John Doe',
223
+ contacts: [{ vcard }]
224
+ }
850
225
  })
851
226
  ```
852
227
 
853
- Atau langsung via `conn.sendMessage` dengan `interactiveMessage`:
854
- ```js
855
- await conn.sendMessage(JID, {
856
- interactiveMessage: {
857
- nativeFlowMessage: {
858
- buttons: [
859
- {
860
- name: 'quick_reply',
861
- buttonParamsJson: JSON.stringify({ display_text: '✅ Ya', id: 'yes' })
862
- },
863
- {
864
- name: 'cta_url',
865
- buttonParamsJson: JSON.stringify({ display_text: 'Buka Link', url: 'https://example.com', merchant_url: 'https://example.com' })
866
- }
867
- ],
868
- messageParamsJson: '',
869
- messageVersion: 1
870
- },
871
- body: { text: 'Pilih aksi:' },
872
- footer: { text: 'Footer text' }
228
+ ### Send Poll
229
+ ```typescript
230
+ await sock.sendMessage(jid, {
231
+ poll: {
232
+ name: 'Favorite Color?',
233
+ values: ['Red', 'Blue', 'Green'],
234
+ selectableCount: 1
873
235
  }
874
236
  })
875
237
  ```
876
238
 
877
- ### Edit & Hapus Pesan Channel
878
-
879
- ```js
880
- const nl = makeNewsletterUtils(conn)
881
- const JID = '120363xxxxxxxxx@newsletter'
882
-
883
- // Edit pesan (gunakan key.id dari pesan yang dikirim)
884
- const sent = await nl.sendNewsletterText(JID, 'Teks lama')
885
- await nl.editNewsletterMessage(JID, sent.key.id, 'Teks baru yang sudah diedit')
886
-
887
- // Hapus pesan
888
- await nl.deleteNewsletterMessage(JID, sent.key.id)
889
-
890
- // React ke pesan channel (gunakan server message ID dari event)
891
- await nl.sendNewsletterReact(JID, serverMessageId, '👍')
892
- // Unreact (kosongkan emoji)
893
- await nl.sendNewsletterReact(JID, serverMessageId, '')
894
- ```
895
-
896
- Atau langsung via `conn.sendMessage`:
897
- ```js
898
- // Edit
899
- await conn.sendMessage(JID, { text: 'Teks baru', edit: { remoteJid: JID, fromMe: true, id: messageId } })
900
-
901
- // Hapus
902
- await conn.sendMessage(JID, { delete: { remoteJid: JID, fromMe: true, id: messageId } })
903
- ```
904
-
905
- ---
906
-
907
- ## Resolve JID
908
-
909
- Berguna untuk mengubah `@lid` format (format baru WA) menjadi JID `@s.whatsapp.net` yang bisa dipakai mengirim pesan.
910
-
911
- ```js
912
- const { resolveJid, resolveJids } = require('@blckrose/baileys')
913
-
914
- // Resolve dari sender pesan (otomatis ambil dari m.sender / m.quoted / m.mentionedJid)
915
- const jid = await resolveJid(conn, m)
916
- if (!jid) return conn.sendMessage(m.chat, { text: 'Tidak bisa resolve JID.' }, { quoted: m })
917
-
918
- console.log(jid) // → '628xxxxxxxxxx@s.whatsapp.net'
919
-
920
- // Resolve target eksplisit (misal dari mention)
921
- const jid = await resolveJid(conn, m, m.mentionedJid?.[0])
922
-
923
- // Resolve banyak JID sekaligus
924
- const jids = await resolveJids(conn, m, m.mentionedJid)
925
- // → ['628xxx@s.whatsapp.net', '628yyy@s.whatsapp.net', null, ...]
926
-
927
- // Contoh pakai di handler
928
- let handler = async (m, { conn }) => {
929
- const target = await resolveJid(conn, m, m.mentionedJid?.[0] || m.quoted?.sender)
930
- if (!target) return conn.sendMessage(m.chat, { text: 'Tag atau reply seseorang.' }, { quoted: m })
931
-
932
- await conn.sendMessage(m.chat, {
933
- text: `JID target: ${target}`
934
- }, { quoted: m })
935
- }
936
- ```
937
-
938
- > [!NOTE]
939
- > `resolveJid` otomatis melakukan lookup ke `groupMetadata` jika JID berbentuk `@lid` di dalam grup. Butuh akses ke `conn` yang terkoneksi.
940
-
941
- ---
942
-
943
-
944
-
945
- - Send all types of messages with a single function
946
- - **[Here](https://baileys.whiskeysockets.io/types/AnyMessageContent.html) you can see all message contents supported, like text message**
947
- - **[Here](https://baileys.whiskeysockets.io/types/MiscMessageGenerationOptions.html) you can see all options supported, like quote message**
948
-
949
- ```ts
950
- const jid: string
951
- const content: AnyMessageContent
952
- const options: MiscMessageGenerationOptions
953
-
954
- sock.sendMessage(jid, content, options)
955
- ```
956
-
957
- ### Non-Media Messages
958
-
959
- #### Text Message
960
- ```ts
961
- await sock.sendMessage(jid, { text: 'hello word' })
962
- ```
963
-
964
- #### Quote Message (works with all types)
965
- ```ts
966
- await sock.sendMessage(jid, { text: 'hello word' }, { quoted: message })
967
- ```
968
-
969
- #### Mention User (works with most types)
970
- - @number is to mention in text, it's optional
971
- ```ts
972
- await sock.sendMessage(
973
- jid,
974
- {
975
- text: '@12345678901',
976
- mentions: ['12345678901@s.whatsapp.net']
239
+ ### Send Reaction
240
+ ```typescript
241
+ await sock.sendMessage(jid, {
242
+ react: {
243
+ text: '💧',
244
+ key: message.key
977
245
  }
978
- )
979
- ```
980
-
981
- #### Forward Messages
982
- - You need to have message object, can be retrieved from [store](#implementing-a-data-store) or use a [message](https://baileys.whiskeysockets.io/types/WAMessage.html) object
983
- ```ts
984
- const msg = getMessageFromStore() // implement this on your end
985
- await sock.sendMessage(jid, { forward: msg }) // WA forward the message!
246
+ })
986
247
  ```
987
248
 
988
- #### Location Message
989
- ```ts
990
- await sock.sendMessage(
991
- jid,
992
- {
993
- location: {
994
- degreesLatitude: 24.121231,
995
- degreesLongitude: 55.1121221
996
- }
997
- }
998
- )
999
- ```
1000
- #### Live Location Message
1001
- ```ts
1002
- await sock.sendMessage(
1003
- jid,
1004
- {
1005
- location: {
1006
- degreesLatitude: 24.121231,
1007
- degreesLongitude: 55.1121221
1008
- },
1009
- live: true
1010
- }
1011
- )
1012
- ```
1013
- #### Contact Message
1014
- ```ts
1015
- const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
1016
- + 'VERSION:3.0\n'
1017
- + 'FN:Jeff Singh\n' // full name
1018
- + 'ORG:Ashoka Uni;\n' // the organization of the contact
1019
- + 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
1020
- + 'END:VCARD'
1021
-
1022
- await sock.sendMessage(
1023
- id,
1024
- {
1025
- contacts: {
1026
- displayName: 'Jeff',
1027
- contacts: [{ vcard }]
1028
- }
1029
- }
1030
- )
249
+ ### Reply/Quote Message
250
+ ```typescript
251
+ await sock.sendMessage(jid, {
252
+ text: 'This is a reply'
253
+ }, {
254
+ quoted: message
255
+ })
1031
256
  ```
1032
257
 
1033
- #### Reaction Message
1034
- - 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
1035
- ```ts
1036
- await sock.sendMessage(
1037
- jid,
1038
- {
1039
- react: {
1040
- text: '💖', // use an empty string to remove the reaction
1041
- key: message.key
1042
- }
1043
- }
1044
- )
258
+ ### Mention Users
259
+ ```typescript
260
+ await sock.sendMessage(jid, {
261
+ text: 'Hello @6281234567890!',
262
+ mentions: ['6281234567890@s.whatsapp.net']
263
+ })
1045
264
  ```
1046
265
 
1047
- #### Pin Message
1048
- - 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
1049
-
1050
- - Time can be:
1051
-
1052
- | Time | Seconds |
1053
- |-------|----------------|
1054
- | 24h | 86.400 |
1055
- | 7d | 604.800 |
1056
- | 30d | 2.592.000 |
1057
-
1058
- ```ts
1059
- await sock.sendMessage(
1060
- jid,
1061
- {
1062
- pin: {
1063
- type: 1, // 0 to remove
1064
- time: 86400
1065
- key: message.key
1066
- }
1067
- }
1068
- )
266
+ ### Forward Message
267
+ ```typescript
268
+ await sock.sendMessage(jid, {
269
+ forward: message
270
+ })
1069
271
  ```
1070
272
 
1071
- ### Keep Message
1072
- ```ts
1073
- await sock.sendMessage(
1074
- jid,
1075
- {
1076
- keep: {
1077
- key: Key,
1078
- type: 1 // or 2
1079
- }
1080
- }
1081
- )
273
+ ### Delete Message (For Everyone)
274
+ ```typescript
275
+ const msg = await sock.sendMessage(jid, { text: 'test' })
276
+ await sock.sendMessage(jid, { delete: msg.key })
1082
277
  ```
1083
278
 
1084
- #### Poll Message
1085
- ```ts
1086
- await sock.sendMessage(
1087
- jid,
1088
- {
1089
- poll: {
1090
- name: 'My Poll',
1091
- values: ['Option 1', 'Option 2', ...],
1092
- selectableCount: 1,
1093
- toAnnouncementGroup: false // or true
1094
- }
1095
- }
1096
- )
279
+ ### Edit Message
280
+ ```typescript
281
+ await sock.sendMessage(jid, {
282
+ text: 'Updated text',
283
+ edit: message.key
284
+ })
1097
285
  ```
1098
286
 
1099
- #### Poll Result Message
1100
- ```ts
1101
- await sock.sendMessage(
1102
- jid,
1103
- {
1104
- pollResult: {
1105
- name: 'Hi',
1106
- values: [
1107
- [
1108
- 'Option 1',
1109
- 1000
1110
- ],
1111
- [
1112
- 'Option 2',
1113
- 2000
1114
- ]
1115
- ]
1116
- }
287
+ ### Pin Message
288
+ ```typescript
289
+ await sock.sendMessage(jid, {
290
+ pin: {
291
+ type: 1, // 1=24h, 2=7d, 3=30d
292
+ time: 86400,
293
+ key: message.key
1117
294
  }
1118
- )
295
+ })
1119
296
  ```
1120
297
 
1121
- ### Call Message
1122
- ```ts
1123
- await sock.sendMessage(
1124
- jid,
1125
- {
1126
- call: {
1127
- name: 'Hay',
1128
- type: 1 // 2 for video
1129
- }
1130
- }
1131
- )
298
+ ### View Once Message
299
+ ```typescript
300
+ await sock.sendMessage(jid, {
301
+ image: { url: './image.jpg' },
302
+ viewOnce: true
303
+ })
1132
304
  ```
1133
305
 
1134
- ### Event Message
1135
- ```ts
1136
- await sock.sendMessage(
1137
- jid,
1138
- {
1139
- event: {
1140
- isCanceled: false, // or true
1141
- name: 'holiday together!',
1142
- description: 'who wants to come along?',
1143
- location: {
1144
- degreesLatitude: 24.121231,
1145
- degreesLongitude: 55.1121221,
1146
- name: 'name'
1147
- },
1148
- call: 'audio', // or 'video'
1149
- startTime: number,
1150
- endTime: number,
1151
- extraGuestsAllowed: true // or false
1152
- }
1153
- }
1154
- )
1155
- ```
306
+ ---
1156
307
 
1157
- ### Order Message
1158
- ```ts
1159
- await sock.sendMessage(
1160
- jid,
1161
- {
1162
- order: {
1163
- orderId: '574xxx',
1164
- thumbnail: 'your_thumbnail',
1165
- itemCount: 'your_count',
1166
- status: 'your_status', // INQUIRY || ACCEPTED || DECLINED
1167
- surface: 'CATALOG',
1168
- message: 'your_caption',
1169
- orderTitle: "your_title",
1170
- sellerJid: 'your_jid',
1171
- token: 'your_token',
1172
- totalAmount1000: 'your_amount',
1173
- totalCurrencyCode: 'IDR'
1174
- }
1175
- }
1176
- )
1177
- ```
308
+ ## 👥 Group Management
1178
309
 
1179
- ### Product Message
1180
- ```ts
1181
- await sock.sendMessage(
1182
- jid,
1183
- {
1184
- product: {
1185
- productImage: { // for using buffer >> productImage: your_buffer
1186
- url: your_url
1187
- },
1188
- productId: 'your_id',
1189
- title: 'your_title',
1190
- description: 'your_description',
1191
- currencyCode: 'IDR',
1192
- priceAmount1000: 'your_amount',
1193
- retailerId: 'your_reid', // optional use if needed
1194
- url: 'your_url', // optional use if needed
1195
- productImageCount: 'your_imageCount',
1196
- firstImageId: 'your_image', // optional use if needed
1197
- salePriceAmount1000: 'your_priceSale',
1198
- signedUrl: 'your_url' // optional use if needed
1199
- },
1200
- businessOwnerJid: 'your_jid'
1201
- }
1202
- )
310
+ ### Create Group
311
+ ```typescript
312
+ const group = await sock.groupCreate('My Group', ['6281234567890@s.whatsapp.net'])
313
+ console.log('Group created:', group.id)
1203
314
  ```
1204
315
 
1205
- ### Payment Message
1206
- ```ts
1207
- await sock.sendMessage(
1208
- jid,
1209
- {
1210
- payment: {
1211
- note: 'Hi!',
1212
- currency: 'IDR', // optional
1213
- offset: 0, // optional
1214
- amount: '10000', // optional
1215
- expiry: 0, // optional
1216
- from: '628xxxx@s.whatsapp.net', // optional
1217
- image: { // optional
1218
- placeholderArgb: "your_background", // optional
1219
- textArgb: "your_text", // optional
1220
- subtextArgb: "your_subtext" // optional
1221
- }
1222
- }
1223
- }
1224
- )
316
+ ### Add Participants
317
+ ```typescript
318
+ await sock.groupParticipantsUpdate(groupId, ['6281234567890@s.whatsapp.net'], 'add')
1225
319
  ```
1226
320
 
1227
- #### Payment Invite Message
1228
- ```ts
1229
- await sock.sendMessage(
1230
- id,
1231
- {
1232
- paymentInvite: {
1233
- type: number, // 1 || 2 || 3
1234
- expiry: 0
1235
- }
1236
- }
1237
- )
321
+ ### Remove Participants
322
+ ```typescript
323
+ await sock.groupParticipantsUpdate(groupId, ['6281234567890@s.whatsapp.net'], 'remove')
1238
324
  ```
1239
325
 
1240
- ### Admin Invite Message
1241
- ```ts
1242
- await sock.sendMessage(
1243
- jid,
1244
- {
1245
- adminInvite: {
1246
- jid: '123xxx@newsletter',
1247
- name: 'newsletter_name',
1248
- caption: 'Please be my channel admin',
1249
- expiration: 86400,
1250
- jpegThumbnail: Buffer // optional
1251
- }
1252
- }
1253
- )
326
+ ### Promote to Admin
327
+ ```typescript
328
+ await sock.groupParticipantsUpdate(groupId, ['6281234567890@s.whatsapp.net'], 'promote')
1254
329
  ```
1255
330
 
1256
- ### Group Invite Message
1257
- ```ts
1258
- await sock.sendMessage(
1259
- jid,
1260
- {
1261
- groupInvite: {
1262
- jid: '123xxx@g.us',
1263
- name: 'group_name',
1264
- caption: 'Please Join My Whatsapp Group',
1265
- code: 'code_invite',
1266
- expiration: 86400,
1267
- jpegThumbnail: Buffer, // optional
1268
- }
1269
- }
1270
- )
331
+ ### Demote Admin
332
+ ```typescript
333
+ await sock.groupParticipantsUpdate(groupId, ['6281234567890@s.whatsapp.net'], 'demote')
1271
334
  ```
1272
335
 
1273
- ### Sticker Pack Message
1274
- ```ts
1275
- // I don't know why the sticker doesn't appear
1276
- await sock.sendMessage(
1277
- jid,
1278
- {
1279
- stickerPack: {
1280
- name: 'Hiii',
1281
- publisher: 'By blckrose',
1282
- description: 'Hello',
1283
- cover: Buffer, // Image buffer
1284
- stickers: [{
1285
- sticker: { url: 'https://example.com/1234kjd.webp' },
1286
- emojis: ['❤'], // optional
1287
- accessibilityLabel: '', // optional
1288
- isLottie: Boolean, // optional
1289
- isAnimated: Boolean // optional
1290
- },
1291
- {
1292
- sticker: Buffer,
1293
- emojis: ['❤'], // optional
1294
- accessibilityLabel: '', // optional
1295
- isLottie: Boolean, // optional
1296
- isAnimated: Boolean // optional
1297
- }]
1298
- }
1299
- }
1300
- )
336
+ ### Update Group Name
337
+ ```typescript
338
+ await sock.groupUpdateSubject(groupId, 'New Group Name')
1301
339
  ```
1302
340
 
1303
- ### Share Phone Number Message
1304
- ```ts
1305
- await sock.sendMessage(
1306
- jid,
1307
- {
1308
- sharePhoneNumber: {
1309
- }
1310
- }
1311
- )
341
+ ### Update Group Description
342
+ ```typescript
343
+ await sock.groupUpdateDescription(groupId, 'New Description')
1312
344
  ```
1313
345
 
1314
- ### Request Phone Number Message
1315
- ```ts
1316
- await sock.sendMessage(
1317
- jid,
1318
- {
1319
- requestPhoneNumber: {
1320
- }
1321
- }
1322
- )
346
+ ### Get Invite Code
347
+ ```typescript
348
+ const code = await sock.groupInviteCode(groupId)
349
+ const inviteLink = 'https://chat.whatsapp.com/' + code
1323
350
  ```
1324
351
 
1325
- ### Buttons Reply Message
1326
- ```ts
1327
- // List
1328
- await sock.sendMessage(
1329
- jid,
1330
- {
1331
- buttonReply: {
1332
- name: 'Hii',
1333
- description: 'description',
1334
- rowId: 'ID'
1335
- },
1336
- type: 'list'
1337
- }
1338
- )
1339
- // Plain
1340
- await sock.sendMessage(
1341
- jid,
1342
- {
1343
- buttonReply: {
1344
- displayText: 'Hii',
1345
- id: 'ID'
1346
- },
1347
- type: 'plain'
1348
- }
1349
- )
1350
-
1351
- // Template
1352
- await sock.sendMessage(
1353
- jid,
1354
- {
1355
- buttonReply: {
1356
- displayText: 'Hii',
1357
- id: 'ID',
1358
- index: 'number'
1359
- },
1360
- type: 'template'
1361
- }
1362
- )
1363
-
1364
- // Interactive
1365
- await sock.sendMessage(
1366
- jid,
1367
- {
1368
- buttonReply: {
1369
- body: 'Hii',
1370
- nativeFlows: {
1371
- name: 'menu_options',
1372
- paramsJson: JSON.stringify({ id: 'ID', description: 'description' })
1373
- version: 1 // 2 | 3
1374
- }
1375
- },
1376
- type: 'interactive'
1377
- }
1378
- )
352
+ ### Join Group
353
+ ```typescript
354
+ await sock.groupAcceptInvite('inviteCode')
1379
355
  ```
1380
356
 
1381
- ### Buttons Message
1382
- ```ts
1383
- await sock.sendMessage(
1384
- jid,
1385
- {
1386
- text: 'This is a button message!', // image: buffer or // image: { url: url } If you want to use images
1387
- caption: 'caption', // Use this if you are using an image or video
1388
- footer: 'Hello World!',
1389
- buttons: [{
1390
- buttonId: 'Id1',
1391
- buttonText: {
1392
- displayText: 'Button 1'
1393
- }
1394
- },
1395
- {
1396
- buttonId: 'Id2',
1397
- buttonText: {
1398
- displayText: 'Button 2'
1399
- }
1400
- },
1401
- {
1402
- buttonId: 'Id3',
1403
- buttonText: {
1404
- displayText: 'Button 3'
1405
- }
1406
- }]
1407
- }
1408
- )
357
+ ### Leave Group
358
+ ```typescript
359
+ await sock.groupLeave(groupId)
1409
360
  ```
1410
361
 
1411
- ### Buttons List Message
1412
- ```ts
1413
- // Just working in a private chat
1414
- await sock.sendMessage(
1415
- jid,
1416
- {
1417
- text: 'This is a list!',
1418
- footer: 'Hello World!',
1419
- title: 'Amazing boldfaced list title',
1420
- buttonText: 'Required, text on the button to view the list',
1421
- sections: [
1422
- {
1423
- title: 'Section 1',
1424
- rows: [{
1425
- title: 'Option 1',
1426
- rowId: 'option1'
1427
- },
1428
- {
1429
- title: 'Option 2',
1430
- rowId: 'option2',
1431
- description: 'This is a description'
1432
- }]
1433
- },
1434
- {
1435
- title: 'Section 2',
1436
- rows: [{
1437
- title: 'Option 3',
1438
- rowId: 'option3'
1439
- },
1440
- {
1441
- title: 'Option 4',
1442
- rowId: 'option4',
1443
- description: 'This is a description V2'
1444
- }]
1445
- }]
1446
- }
1447
- )
1448
- ```
362
+ ---
1449
363
 
1450
- ### Buttons Product List Message
1451
- ```ts
1452
- // Just working in a private chat
1453
- await sock.sendMessage(
1454
- jid,
1455
- {
1456
- text: 'This is a list!',
1457
- footer: 'Hello World!',
1458
- title: 'Amazing boldfaced list title',
1459
- buttonText: 'Required, text on the button to view the list',
1460
- productList: [{
1461
- title: 'This is a title',
1462
- products: [
1463
- {
1464
- productId: '1234'
1465
- },
1466
- {
1467
- productId: '5678'
1468
- }
1469
- ]
1470
- }],
1471
- businessOwnerJid: '628xxx@s.whatsapp.net',
1472
- thumbnail: 'https://example.com/jdbenkksjs.jpg' // or buffer
1473
- }
1474
- )
1475
- ```
364
+ ## 📞 Call Handling
1476
365
 
1477
- ### Buttons Cards Message
1478
- ```ts
1479
- await sock.sendMessage(
1480
- jid,
1481
- {
1482
- text: 'Body Message',
1483
- title: 'Title Message',
1484
- subtile: 'Subtitle Message',
1485
- footer: 'Footer Message',
1486
- cards: [
1487
- {
1488
- image: { url: 'https://example.com/jdbenkksjs.jpg' }, // or buffer
1489
- title: 'Title Cards',
1490
- body: 'Body Cards',
1491
- footer: 'Footer Cards',
1492
- buttons: [
1493
- {
1494
- name: 'quick_reply',
1495
- buttonParamsJson: JSON.stringify({
1496
- display_text: 'Display Button',
1497
- id: 'ID'
1498
- })
1499
- },
1500
- {
1501
- name: 'cta_url',
1502
- buttonParamsJson: JSON.stringify({
1503
- display_text: 'Display Button',
1504
- url: 'https://www.example.com'
1505
- })
1506
- }
1507
- ]
1508
- },
1509
- {
1510
- video: { url: 'https://example.com/jdbenkksjs.mp4' }, // or buffer
1511
- title: 'Title Cards',
1512
- body: 'Body Cards',
1513
- footer: 'Footer Cards',
1514
- buttons: [
1515
- {
1516
- name: 'quick_reply',
1517
- buttonParamsJson: JSON.stringify({
1518
- display_text: 'Display Button',
1519
- id: 'ID'
1520
- })
1521
- },
1522
- {
1523
- name: 'cta_url',
1524
- buttonParamsJson: JSON.stringify({
1525
- display_text: 'Display Button',
1526
- url: 'https://www.example.com'
1527
- })
1528
- }
1529
- ]
1530
- }
1531
- ]
366
+ ### Reject Call
367
+ ```typescript
368
+ sock.ev.on('call', async (calls) => {
369
+ for (const call of calls) {
370
+ await sock.rejectCall(call.id, call.from)
1532
371
  }
1533
- )
372
+ })
1534
373
  ```
1535
374
 
1536
- ### Buttons Template Message
1537
- ```ts
1538
- // This no longer works
1539
- await sock.sendMessage(
1540
- jid,
1541
- {
1542
- text: 'This is a template message!',
1543
- footer: 'Hello World!',
1544
- templateButtons: [{
1545
- index: 1,
1546
- urlButton: {
1547
- displayText: 'Follow Me',
1548
- url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
1549
- },
1550
- },
1551
- {
1552
- index: 2,
1553
- callButton: {
1554
- displayText: 'Call Me!',
1555
- phoneNumber: '628xxx'
1556
- },
1557
- },
1558
- {
1559
- index: 3,
1560
- quickReplyButton: {
1561
- displayText: 'This is a reply, just like normal buttons!',
1562
- id: 'id-like-buttons-message'
1563
- },
1564
- }]
1565
- }
1566
- )
1567
- ```
375
+ ---
1568
376
 
1569
- ### Buttons Interactive Message
1570
- ```ts
1571
- await sock.sendMessage(
1572
- jid,
1573
- {
1574
- text: 'This is an Interactive message!',
1575
- title: 'Hiii',
1576
- subtitle: 'There is a subtitle',
1577
- footer: 'Hello World!',
1578
- interactiveButtons: [
1579
- {
1580
- name: 'quick_reply',
1581
- buttonParamsJson: JSON.stringify({
1582
- display_text: 'Click Me!',
1583
- id: 'your_id'
1584
- })
1585
- },
1586
- {
1587
- name: 'cta_url',
1588
- buttonParamsJson: JSON.stringify({
1589
- display_text: 'Follow Me',
1590
- url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y',
1591
- merchant_url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
1592
- })
1593
- },
1594
- {
1595
- name: 'cta_copy',
1596
- buttonParamsJson: JSON.stringify({
1597
- display_text: 'Click Me!',
1598
- copy_code: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
1599
- })
1600
- },
1601
- {
1602
- name: 'cta_call',
1603
- buttonParamsJson: JSON.stringify({
1604
- display_text: 'Call Me!',
1605
- phone_number: '628xxx'
1606
- })
1607
- },
1608
- {
1609
- name: 'cta_catalog',
1610
- buttonParamsJson: JSON.stringify({
1611
- business_phone_number: '628xxx'
1612
- })
1613
- },
1614
- {
1615
- name: 'cta_reminder',
1616
- buttonParamsJson: JSON.stringify({
1617
- display_text: '...'
1618
- })
1619
- },
1620
- {
1621
- name: 'cta_cancel_reminder',
1622
- buttonParamsJson: JSON.stringify({
1623
- display_text: '...'
1624
- })
1625
- },
1626
- {
1627
- name: 'address_message',
1628
- buttonParamsJson: JSON.stringify({
1629
- display_text: '...'
1630
- })
1631
- },
1632
- {
1633
- name: 'send_location',
1634
- buttonParamsJson: JSON.stringify({
1635
- display_text: '...'
1636
- })
1637
- },
1638
- {
1639
- name: 'open_webview',
1640
- buttonParamsJson: JSON.stringify({
1641
- title: 'Follow Me!',
1642
- link: {
1643
- in_app_webview: true, // or false
1644
- url: 'https://whatsapp.com/channel/0029Vag9VSI2ZjCocqa2lB1y'
1645
- }
1646
- })
1647
- },
1648
- {
1649
- name: 'mpm',
1650
- buttonParamsJson: JSON.stringify({
1651
- product_id: '8816262248471474'
1652
- })
1653
- },
1654
- {
1655
- name: 'wa_payment_transaction_details',
1656
- buttonParamsJson: JSON.stringify({
1657
- transaction_id: '12345848'
1658
- })
1659
- },
1660
- {
1661
- name: 'automated_greeting_message_view_catalog',
1662
- buttonParamsJson: JSON.stringify({
1663
- business_phone_number: '628xxx',
1664
- catalog_product_id: '12345'
1665
- })
1666
- },
1667
- {
1668
- name: 'galaxy_message',
1669
- buttonParamsJson: JSON.stringify({
1670
- mode: 'published',
1671
- flow_message_version: '3',
1672
- flow_token: '1:1307913409923914:293680f87029f5a13d1ec5e35e718af3',
1673
- flow_id: '1307913409923914',
1674
- flow_cta: 'blckrose >',
1675
- flow_action: 'navigate',
1676
- flow_action_payload: {
1677
- screen: 'QUESTION_ONE',
1678
- params: {
1679
- user_id: '123456789',
1680
- referral: 'campaign_xyz'
1681
- }
1682
- },
1683
- flow_metadata: {
1684
- flow_json_version: '201',
1685
- data_api_protocol: 'v2',
1686
- flow_name: 'Lead Qualification [en]',
1687
- data_api_version: 'v2',
1688
- categories: ['Lead Generation', 'Sales']
1689
- }
1690
- })
1691
- },
1692
- {
1693
- name: 'single_select',
1694
- buttonParamsJson: JSON.stringify({
1695
- title: 'Click Me!',
1696
- sections: [
1697
- {
1698
- title: 'Title 1',
1699
- highlight_label: 'Highlight label 1',
1700
- rows: [
1701
- {
1702
- header: 'Header 1',
1703
- title: 'Title 1',
1704
- description: 'Description 1',
1705
- id: 'Id 1'
1706
- },
1707
- {
1708
- header: 'Header 2',
1709
- title: 'Title 2',
1710
- description: 'Description 2',
1711
- id: 'Id 2'
1712
- }
1713
- ]
1714
- }
1715
- ]
1716
- })
1717
- }
1718
- ]
1719
- }
1720
- )
1721
-
1722
- // If you want to use an image
1723
- await sock.sendMessage(
1724
- jid,
1725
- {
1726
- image: {
1727
- url: 'https://example.com/jdbenkksjs.jpg'
1728
- },
1729
- caption: 'Body',
1730
- title: 'Title',
1731
- subtitle: 'Subtitle',
1732
- footer: 'Footer',
1733
- interactiveButtons: [
1734
- {
1735
- name: 'quick_reply',
1736
- buttonParamsJson: JSON.stringify({
1737
- display_text: 'DisplayText',
1738
- id: 'ID1'
1739
- })
1740
- }
1741
- ],
1742
- hasMediaAttachment: false // or true
1743
- }
1744
- )
1745
-
1746
- // If you want to use a video
1747
- await sock.sendMessage(
1748
- jid,
1749
- {
1750
- video: {
1751
- url: 'https://example.com/jdbenkksjs.mp4'
1752
- },
1753
- caption: 'Body',
1754
- title: 'Title',
1755
- subtitle: 'Subtitle',
1756
- footer: 'Footer',
1757
- interactiveButtons: [
1758
- {
1759
- name: 'quick_reply',
1760
- buttonParamsJson: JSON.stringify({
1761
- display_text: 'DisplayText',
1762
- id: 'ID1'
1763
- })
1764
- }
1765
- ],
1766
- hasMediaAttachment: false // or true
1767
- }
1768
- )
1769
-
1770
- // If you want to use a document
1771
- await sock.sendMessage(
1772
- jid,
1773
- {
1774
- document: {
1775
- url: 'https://example.com/jdbenkksjs.jpg'
1776
- },
1777
- mimetype: 'image/jpeg',
1778
- caption: 'Body',
1779
- title: 'Title',
1780
- subtitle: 'Subtitle',
1781
- footer: 'Footer',
1782
- interactiveButtons: [
1783
- {
1784
- name: 'quick_reply',
1785
- buttonParamsJson: JSON.stringify({
1786
- display_text: 'DisplayText',
1787
- id: 'ID1'
1788
- })
1789
- }
1790
- ],
1791
- hasMediaAttachment: false // or true
1792
- }
1793
- )
1794
-
1795
- // If you want to use a location
1796
- await sock.sendMessage(
1797
- jid,
1798
- {
1799
- location: {
1800
- degreesLatitude: -0,
1801
- degreesLongitude: 0,
1802
- name: 'Hi'
1803
- },
1804
- caption: 'Body',
1805
- title: 'Title',
1806
- subtitle: 'Subtitle',
1807
- footer: 'Footer',
1808
- interactiveButtons: [
1809
- {
1810
- name: 'quick_reply',
1811
- buttonParamsJson: JSON.stringify({
1812
- display_text: 'DisplayText',
1813
- id: 'ID1'
1814
- })
1815
- }
1816
- ],
1817
- hasMediaAttachment: false // or true
1818
- }
1819
- )
1820
- ```
377
+ ## 👤 User Operations
1821
378
 
1822
- ### Buttons Interactive Message PIX
1823
- ```ts
1824
- await sock.sendMessage(
1825
- jid,
1826
- {
1827
- text: '', // This string is required. Even it's empty.
1828
- interactiveButtons: [
1829
- {
1830
- name: 'payment_info',
1831
- buttonParamsJson: JSON.stringify({
1832
- payment_settings: [{
1833
- type: "pix_static_code",
1834
- pix_static_code: {
1835
- merchant_name: 'blckrose',
1836
- key: 'example@blckrose.com',
1837
- key_type: 'EMAIL' // PHONE || EMAIL || CPF || EVP
1838
- }
1839
- }]
1840
- })
1841
- }
1842
- ],
1843
- }
1844
- )
1845
- ```
1846
-
1847
- ### Buttons Interactive Message PAY
1848
- ```ts
1849
- await sock.sendMessage(
1850
- jid,
1851
- {
1852
- text: '', // This string is required. Even it's empty.
1853
- interactiveButtons: [
1854
- {
1855
- name: 'review_and_pay',
1856
- buttonParamsJson: JSON.stringify({
1857
- currency: 'IDR',
1858
- payment_configuration: '',
1859
- payment_type: '',
1860
- total_amount: {
1861
- value: '999999999',
1862
- offset: '100'
1863
- },
1864
- reference_id: '45XXXXX',
1865
- type: 'physical-goods',
1866
- payment_method: 'confirm',
1867
- payment_status: 'captured',
1868
- payment_timestamp: Math.floor(Date.now() / 1000),
1869
- order: {
1870
- status: 'completed',
1871
- description: '',
1872
- subtotal: {
1873
- value: '0',
1874
- offset: '100'
1875
- },
1876
- order_type: 'PAYMENT_REQUEST',
1877
- items: [{
1878
- retailer_id: 'your_retailer_id',
1879
- name: 'blckrose',
1880
- amount: {
1881
- value: '999999999',
1882
- offset: '100'
1883
- },
1884
- quantity: '1',
1885
- }]
1886
- },
1887
- additional_note: 'blckrose',
1888
- native_payment_methods: [],
1889
- share_payment_status: false
1890
- })
1891
- }
1892
- ],
1893
- }
1894
- )
1895
- ```
1896
-
1897
- ### Status Mentions Message
1898
- ```ts
1899
- const jidat = [
1900
- '123451679@g.us',
1901
- '124848899@g.us',
1902
- '111384848@g.us',
1903
- '62689xxxx@s.whatsapp.net',
1904
- '62xxxxxxx@s.whatsapp.net'
1905
- ]
1906
- // Text
1907
- await sock.sendStatusMentions(
1908
- {
1909
- text: 'Hello Everyone :3',
1910
- font: 2, // optional
1911
- textColor: 'FF0000', // optional
1912
- backgroundColor: '#000000' // optional
1913
- },
1914
- jids // Limit to 5 mentions per status
1915
- )
1916
-
1917
- // Image
1918
- await sock.sendStatusMentions(
1919
- {
1920
- Image: { url: 'https://example.com/ruriooe.jpg' }, // or image buffer
1921
- caption: 'Hello Everyone :3' // optional
1922
- },
1923
- jids // Limit to 5 mentions per status
1924
- )
1925
-
1926
- // Video
1927
- await sock.sendStatusMentions(
1928
- {
1929
- video: { url: 'https://example.com/ruriooe.mp4' }, // or video buffer
1930
- caption: 'Hello Everyone :3' // optional
1931
- },
1932
- jids // Limit to 5 mentions per status
1933
- )
1934
-
1935
- // Audio
1936
- await sock.sendStatusMentions(
1937
- {
1938
- audio: { url: 'https://example.com/ruriooe.mp3' }, // or audio buffer
1939
- backgroundColor: '#000000', // optional
1940
- mimetype: 'audio/mp4',
1941
- ppt: true
1942
- },
1943
- jids // Limit to 5 mentions per status
1944
- )
379
+ ### Check If Number Exists on WhatsApp
380
+ ```typescript
381
+ const [result] = await sock.onWhatsApp('6281234567890')
382
+ if (result?.exists) {
383
+ console.log('Number exists:', result.jid)
384
+ }
1945
385
  ```
1946
386
 
1947
- ### Shop Message
1948
- ```ts
1949
- await sock.sendMessage(
1950
- jid,
1951
- {
1952
- text: 'Body',
1953
- title: 'Title',
1954
- subtitle: 'Subtitle',
1955
- footer: 'Footer',
1956
- shop: {
1957
- surface: 1, // 2 | 3 | 4
1958
- id: 'https://example.com'
1959
- },
1960
- viewOnce: true
1961
- }
1962
- )
1963
-
1964
- // Image
1965
- await sock.sendMessage(
1966
- jid,
1967
- {
1968
- image: {
1969
- url: 'https://example.com/jdbenkksjs.jpg'
1970
- },
1971
- caption: 'Body',
1972
- title: 'Title',
1973
- subtitle: 'Subtitle',
1974
- footer: 'Footer',
1975
- shop: {
1976
- surface: 1, // 2 | 3 | 4
1977
- id: 'https://example.com'
1978
- },
1979
- hasMediaAttachment: false, // or true
1980
- viewOnce: true
1981
- }
1982
- )
1983
- ```
387
+ ### Get Profile Picture
388
+ ```typescript
389
+ // Low resolution
390
+ const ppUrl = await sock.profilePictureUrl(jid)
1984
391
 
1985
- ### Collection Message
1986
- ```ts
1987
- await sock.sendMessage(
1988
- jid,
1989
- {
1990
- text: 'Body',
1991
- title: 'Title',
1992
- subtitle: 'Subtitle',
1993
- footer: 'Footer',
1994
- collection: {
1995
- bizJid: 'jid',
1996
- id: 'https://example.com',
1997
- version: 1
1998
- },
1999
- viewOnce: true
2000
- }
2001
- )
2002
-
2003
- // Image
2004
- await sock.sendMessage(
2005
- jid,
2006
- {
2007
- image: {
2008
- url: 'https://example.com/jdbenkksjs.jpg'
2009
- },
2010
- caption: 'Body',
2011
- title: 'Title',
2012
- subtitle: 'Subtitle',
2013
- footer: 'Footer',
2014
- collection: {
2015
- bizJid: 'jid',
2016
- id: 'https://example.com',
2017
- version: 1
2018
- },
2019
- hasMediaAttachment: false, // or true
2020
- viewOnce: true
2021
- }
2022
- )
392
+ // High resolution
393
+ const ppUrl = await sock.profilePictureUrl(jid, 'image')
2023
394
  ```
2024
395
 
2025
- ### AI Icon Feature
2026
- ```ts
2027
- await sock.sendMessage(
2028
- jid,
2029
- {
2030
- text: 'Hi'
2031
- }, {
2032
- ai: true // Add ai usage and change it to true
2033
- }
2034
- )
2035
-
2036
- // If using relay
2037
- await sock.relayMessage(
2038
- jid,
2039
- {
2040
- extendedTextMessage: {
2041
- text: 'Hi'
2042
- }
2043
- }, {
2044
- AI: true // Use capital letters
2045
- }
2046
- )
396
+ ### Get Status
397
+ ```typescript
398
+ const status = await sock.fetchStatus(jid)
399
+ console.log('About:', status?.status)
2047
400
  ```
2048
401
 
2049
- ### Sending Messages with Link Previews
2050
-
2051
- 1. By default, wa does not have link generation when sent from the web
2052
- 2. Baileys has a function to generate the content for these link previews
2053
- 3. To enable this function's usage, add `link-preview-js` as a dependency to your project with `yarn add link-preview-js`
2054
- 4. Send a link:
2055
- ```ts
2056
- await sock.sendMessage(
2057
- jid,
2058
- {
2059
- text: 'Hi, this was sent using https://github.com/whiskeysockets/baileys'
2060
- }
2061
- )
402
+ ### Get Business Profile
403
+ ```typescript
404
+ const profile = await sock.getBusinessProfile(jid)
405
+ console.log('Business:', profile)
2062
406
  ```
2063
407
 
2064
- ### Media Messages
2065
-
2066
- Sending media (video, stickers, images) is easier & more efficient than ever.
2067
-
2068
- > [!NOTE]
2069
- > 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)
2070
-
2071
- - When specifying a media url, Baileys never loads the entire buffer into memory; it even encrypts the media as a readable stream.
408
+ ---
2072
409
 
2073
- > [!TIP]
2074
- > It's recommended to use Stream or Url to save memory
410
+ ## 📝 Chat Operations
2075
411
 
2076
- #### Gif Message
2077
- - Whatsapp doesn't support `.gif` files, that's why we send gifs as common `.mp4` video with `gifPlayback` flag
2078
- ```ts
2079
- await sock.sendMessage(
2080
- jid,
2081
- {
2082
- video: fs.readFileSync('Media/ma_gif.mp4'),
2083
- caption: 'hello word',
2084
- gifPlayback: true
2085
- }
2086
- )
412
+ ### Archive Chat
413
+ ```typescript
414
+ const lastMsg = await getLastMessage(jid)
415
+ await sock.chatModify({ archive: true, lastMessages: [lastMsg] }, jid)
2087
416
  ```
2088
417
 
2089
- #### Video Message
2090
- ```ts
2091
- await sock.sendMessage(
2092
- id,
2093
- {
2094
- video: {
2095
- url: './Media/ma_gif.mp4'
2096
- },
2097
- caption: 'hello word',
2098
- ptv: false // if set to true, will send as a `video note`
2099
- }
2100
- )
418
+ ### Mute Chat
419
+ ```typescript
420
+ await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid) // 8 hours
2101
421
  ```
2102
422
 
2103
- #### Audio Message
2104
- - To audio message work in all devices you need to convert with some tool like `ffmpeg` with this flags:
2105
- ```bash
2106
- codec: libopus //ogg file
2107
- ac: 1 //one channel
2108
- avoid_negative_ts
2109
- make_zero
2110
- ```
2111
- - Example:
2112
- ```bash
2113
- ffmpeg -i input.mp4 -avoid_negative_ts make_zero -ac 1 output.ogg
2114
- ```
2115
- ```ts
2116
- await sock.sendMessage(
2117
- jid,
2118
- {
2119
- audio: {
2120
- url: './Media/audio.mp3'
2121
- },
2122
- mimetype: 'audio/mp4'
2123
- }
2124
- )
2125
- ```
2126
-
2127
- #### Image Message
2128
- ```ts
2129
- await sock.sendMessage(
2130
- id,
2131
- {
2132
- image: {
2133
- url: './Media/ma_img.png'
2134
- },
2135
- caption: 'hello word'
2136
- }
2137
- )
423
+ ### Unmute Chat
424
+ ```typescript
425
+ await sock.chatModify({ mute: null }, jid)
2138
426
  ```
2139
427
 
2140
- ### Album Message
2141
- ```ts
2142
- await sock.sendMessage(
2143
- id,
2144
- {
2145
- album: [{
2146
- image: {
2147
- url: 'https://example.com/blckrose.jpg'
2148
- },
2149
- caption: 'Hay'
2150
- }, {
2151
- image: Buffer,
2152
- caption: 'Hay'
2153
- }, {
2154
- video: {
2155
- url: 'https://example.com/blckrose.mp4'
2156
- },
2157
- caption: 'Hay'
2158
- }, {
2159
- video: Buffer,
2160
- caption: 'Hay'
2161
- }]
2162
- }
2163
- )
428
+ ### Mark as Read
429
+ ```typescript
430
+ await sock.readMessages([message.key])
2164
431
  ```
2165
432
 
2166
- #### Ptv Video Message
2167
- ```ts
2168
- await sock.sendMessage(
2169
- id,
2170
- {
2171
- video: {
2172
- url: './Media/ma_gif.mp4'
2173
- },
2174
- ptv: true
2175
- }
2176
- )
433
+ ### Delete Chat
434
+ ```typescript
435
+ await sock.chatModify({ delete: true, lastMessages: [lastMsg] }, jid)
2177
436
  ```
2178
437
 
2179
- #### View Once Message
2180
-
2181
- - You can send all messages above as `viewOnce`, you only need to pass `viewOnce: true` in content object
2182
-
2183
- ```ts
2184
- await sock.sendMessage(
2185
- id,
2186
- {
2187
- image: {
2188
- url: './Media/ma_img.png'
2189
- },
2190
- viewOnce: true, //works with video, audio too
2191
- caption: 'hello word'
438
+ ### Star Message
439
+ ```typescript
440
+ await sock.chatModify({
441
+ star: {
442
+ messages: [{ id: 'messageID', fromMe: true }],
443
+ star: true
2192
444
  }
2193
- )
445
+ }, jid)
2194
446
  ```
2195
447
 
2196
- ## Modify Messages
2197
-
2198
- ### Deleting Messages (for everyone)
2199
-
2200
- ```ts
2201
- const msg = await sock.sendMessage(jid, { text: 'hello word' })
2202
- await sock.sendMessage(jid, { delete: msg.key })
2203
- ```
2204
-
2205
- **Note:** deleting for oneself is supported via `chatModify`, see in [this section](#modifying-chats)
2206
-
2207
- ### Editing Messages
448
+ ### Disappearing Messages
449
+ ```typescript
450
+ // Enable
451
+ await sock.sendMessage(jid, {
452
+ disappearingMessagesInChat: 7 * 24 * 60 * 60 // 7 days
453
+ })
2208
454
 
2209
- - You can pass all editable contents here
2210
- ```ts
455
+ // Disable
2211
456
  await sock.sendMessage(jid, {
2212
- text: 'updated text goes here',
2213
- edit: response.key,
2214
- });
457
+ disappearingMessagesInChat: false
458
+ })
2215
459
  ```
2216
460
 
2217
- ## Manipulating Media Messages
2218
-
2219
- ### Thumbnail in Media Messages
2220
- - 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`.
2221
- - Thumbnails for videos can also be generated automatically, though, you need to have `ffmpeg` installed on your system.
2222
-
2223
- ### Downloading Media Messages
2224
-
2225
- If you want to save the media you received
2226
- ```ts
2227
- import { createWriteStream } from 'fs'
2228
- import { downloadMediaMessage, getContentType } from '@blckrose/baileys'
2229
-
2230
- sock.ev.on('messages.upsert', async ({ [m] }) => {
2231
- if (!m.message) return // if there is no text or media message
2232
- const messageType = getContentType(m) // get what type of message it is (text, image, video...)
2233
-
2234
- // if the message is an image
2235
- if (messageType === 'imageMessage') {
2236
- // download the message
2237
- const stream = await downloadMediaMessage(
2238
- m,
2239
- 'stream', // can be 'buffer' too
2240
- { },
2241
- {
2242
- logger,
2243
- // pass this so that baileys can request a reupload of media
2244
- // that has been deleted
2245
- reuploadRequest: sock.updateMediaMessage
2246
- }
2247
- )
2248
- // save to file
2249
- const writeStream = createWriteStream('./my-download.jpeg')
2250
- stream.pipe(writeStream)
2251
- }
2252
- }
2253
- ```
461
+ ---
2254
462
 
2255
- ### Re-upload Media Message to Whatsapp
463
+ ## 🎨 Profile Management
2256
464
 
2257
- - 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:
2258
- ```ts
2259
- await sock.updateMediaMessage(msg)
465
+ ### Update Profile Name
466
+ ```typescript
467
+ await sock.updateProfileName('New Name')
2260
468
  ```
2261
469
 
2262
- ## Reject Call
2263
-
2264
- - You can obtain `callId` and `callFrom` from `call` event
2265
-
2266
- ```ts
2267
- await sock.rejectCall(callId, callFrom)
470
+ ### Update Profile Status
471
+ ```typescript
472
+ await sock.updateProfileStatus('New Status 💧')
2268
473
  ```
2269
474
 
2270
- ## Send States in Chat
2271
-
2272
- ### Reading Messages
2273
- - A set of message [keys](https://baileys.whiskeysockets.io/types/WAMessageKey.html) must be explicitly marked read now.
2274
- - You cannot mark an entire 'chat' read as it were with Baileys Web.
2275
- This means you have to keep track of unread messages.
2276
-
2277
- ```ts
2278
- const key: WAMessageKey
2279
- // can pass multiple keys to read multiple messages as well
2280
- await sock.readMessages([key])
475
+ ### Update Profile Picture
476
+ ```typescript
477
+ await sock.updateProfilePicture(jid, { url: './new-pp.jpg' })
2281
478
  ```
2282
479
 
2283
- The message ID is the unique identifier of the message that you are marking as read.
2284
- On a `WAMessage`, the `messageID` can be accessed using ```messageID = message.key.id```.
2285
-
2286
- ### Update Presence
2287
-
2288
- - ``` presence ``` can be one of [these](https://baileys.whiskeysockets.io/types/WAPresence.html)
2289
- - The presence expires after about 10 seconds.
2290
- - This lets the person/group with `jid` know whether you're online, offline, typing etc.
2291
-
2292
- ```ts
2293
- await sock.sendPresenceUpdate('available', jid)
480
+ ### Remove Profile Picture
481
+ ```typescript
482
+ await sock.removeProfilePicture(jid)
2294
483
  ```
2295
484
 
2296
- > [!NOTE]
2297
- > 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')`
2298
-
2299
- ## Modifying Chats
2300
-
2301
- WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
485
+ ---
2302
486
 
2303
- > [!IMPORTANT]
2304
- > 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.
487
+ ## 📊 Events
2305
488
 
2306
- ### Archive a Chat
2307
- ```ts
2308
- const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
2309
- await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, jid)
489
+ ### Connection Events
490
+ ```typescript
491
+ sock.ev.on('connection.update', (update) => {
492
+ console.log('Connection:', update)
493
+ })
2310
494
  ```
2311
- ### Mute/Unmute a Chat
2312
495
 
2313
- - Supported times:
496
+ ### Message Events
497
+ ```typescript
498
+ sock.ev.on('messages.upsert', ({ messages }) => {
499
+ console.log('Messages:', messages)
500
+ })
2314
501
 
2315
- | Time | Miliseconds |
2316
- |-------|-----------------|
2317
- | Remove | null |
2318
- | 8h | 86.400.000 |
2319
- | 7d | 604.800.000 |
502
+ sock.ev.on('messages.update', (updates) => {
503
+ console.log('Message updates:', updates)
504
+ })
2320
505
 
2321
- ```ts
2322
- // mute for 8 hours
2323
- await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid)
2324
- // unmute
2325
- await sock.chatModify({ mute: null }, jid)
2326
- ```
2327
- ### Mark a Chat Read/Unread
2328
- ```ts
2329
- const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
2330
- // mark it unread
2331
- await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, jid)
506
+ sock.ev.on('messages.delete', (deletes) => {
507
+ console.log('Messages deleted:', deletes)
508
+ })
2332
509
  ```
2333
510
 
2334
- ### Delete a Message for Me
2335
- ```ts
2336
- await sock.chatModify(
2337
- {
2338
- clear: {
2339
- messages: [
2340
- {
2341
- id: 'ATWYHDNNWU81732J',
2342
- fromMe: true,
2343
- timestamp: '1654823909'
2344
- }
2345
- ]
2346
- }
2347
- },
2348
- jid
2349
- )
511
+ ### Chat Events
512
+ ```typescript
513
+ sock.ev.on('chats.upsert', (chats) => {
514
+ console.log('New chats:', chats)
515
+ })
2350
516
 
517
+ sock.ev.on('chats.update', (updates) => {
518
+ console.log('Chat updates:', updates)
519
+ })
2351
520
  ```
2352
- ### Delete a Chat
2353
- ```ts
2354
- const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
2355
- await sock.chatModify({
2356
- delete: true,
2357
- lastMessages: [
2358
- {
2359
- key: lastMsgInChat.key,
2360
- messageTimestamp: lastMsgInChat.messageTimestamp
2361
- }
2362
- ]
2363
- },
2364
- jid
2365
- )
2366
- ```
2367
- ### Pin/Unpin a Chat
2368
- ```ts
2369
- await sock.chatModify({
2370
- pin: true // or `false` to unpin
2371
- },
2372
- jid
2373
- )
2374
- ```
2375
- ### Star/Unstar a Message
2376
- ```ts
2377
- await sock.chatModify({
2378
- star: {
2379
- messages: [
2380
- {
2381
- id: 'messageID',
2382
- fromMe: true // or `false`
2383
- }
2384
- ],
2385
- star: true // - true: Star Message; false: Unstar Message
2386
- }
2387
- },
2388
- jid
2389
- )
2390
- ```
2391
-
2392
- ### Disappearing Messages
2393
521
 
2394
- - Ephemeral can be:
2395
-
2396
- | Time | Seconds |
2397
- |-------|----------------|
2398
- | Remove | 0 |
2399
- | 24h | 86.400 |
2400
- | 7d | 604.800 |
2401
- | 90d | 7.776.000 |
2402
-
2403
- - You need to pass in **Seconds**, default is 7 days
2404
-
2405
- ```ts
2406
- // turn on disappearing messages
2407
- await sock.sendMessage(
2408
- jid,
2409
- // this is 1 week in seconds -- how long you want messages to appear for
2410
- { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL }
2411
- )
2412
-
2413
- // will send as a disappearing message
2414
- await sock.sendMessage(jid, { text: 'hello' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL })
2415
-
2416
- // turn off disappearing messages
2417
- await sock.sendMessage(
2418
- jid,
2419
- { disappearingMessagesInChat: false }
2420
- )
2421
- ```
522
+ ### Contact Events
523
+ ```typescript
524
+ sock.ev.on('contacts.upsert', (contacts) => {
525
+ console.log('New contacts:', contacts)
526
+ })
2422
527
 
2423
- ### Clear Messages
2424
- ```ts
2425
- await sock.clearMessage(jid, key, timestamps)
528
+ sock.ev.on('contacts.update', (updates) => {
529
+ console.log('Contact updates:', updates)
530
+ })
2426
531
  ```
2427
532
 
2428
- ## User Querys
2429
-
2430
- ### Check If ID Exists in Whatsapp
2431
- ```ts
2432
- const [result] = await sock.onWhatsApp(jid)
2433
- if (result.exists) console.log (`${jid} exists on WhatsApp, as jid: ${result.jid}`)
2434
- ```
533
+ ### Group Events
534
+ ```typescript
535
+ sock.ev.on('groups.upsert', (groups) => {
536
+ console.log('New groups:', groups)
537
+ })
2435
538
 
2436
- ### Query Chat History (groups too)
539
+ sock.ev.on('groups.update', (updates) => {
540
+ console.log('Group updates:', updates)
541
+ })
2437
542
 
2438
- - You need to have oldest message in chat
2439
- ```ts
2440
- const msg = await getOldestMessageInChat(jid) // implement this on your end
2441
- await sock.fetchMessageHistory(
2442
- 50, //quantity (max: 50 per query)
2443
- msg.key,
2444
- msg.messageTimestamp
2445
- )
543
+ sock.ev.on('group-participants.update', (update) => {
544
+ console.log('Participants update:', update)
545
+ })
2446
546
  ```
2447
- - Messages will be received in `messaging.history-set` event
2448
547
 
2449
- ### Fetch Status
2450
- ```ts
2451
- const status = await sock.fetchStatus(jid)
2452
- console.log('status: ' + status)
548
+ ### Presence Events
549
+ ```typescript
550
+ sock.ev.on('presence.update', (presence) => {
551
+ console.log('Presence:', presence)
552
+ })
2453
553
  ```
2454
554
 
2455
- ### Fetch Profile Picture (groups too)
2456
- - To get the display picture of some person/group
2457
- ```ts
2458
- // for low res picture
2459
- const ppUrl = await sock.profilePictureUrl(jid)
2460
- console.log(ppUrl)
555
+ ---
2461
556
 
2462
- // for high res picture
2463
- const ppUrl = await sock.profilePictureUrl(jid, 'image')
2464
- ```
557
+ ## 🗄️ Data Store
2465
558
 
2466
- ### Fetch Bussines Profile (such as description or category)
2467
- ```ts
2468
- const profile = await sock.getBusinessProfile(jid)
2469
- console.log('business description: ' + profile.description + ', category: ' + profile.category)
2470
- ```
559
+ ### In-Memory Store
560
+ ```typescript
561
+ import makeWASocket, { makeInMemoryStore } from '@ryuhan/baileys'
2471
562
 
2472
- ### Fetch Someone's Presence (if they're typing or online)
2473
- ```ts
2474
- // the presence update is fetched and called here
2475
- sock.ev.on('presence.update', console.log)
563
+ const store = makeInMemoryStore()
564
+ store.readFromFile('./baileys_store.json')
2476
565
 
2477
- // request updates for a chat
2478
- await sock.presenceSubscribe(jid)
2479
- ```
566
+ setInterval(() => {
567
+ store.writeToFile('./baileys_store.json')
568
+ }, 10000)
2480
569
 
2481
- ## Change Profile
570
+ const sock = makeWASocket()
571
+ store.bind(sock.ev)
2482
572
 
2483
- ### Change Profile Status
2484
- ```ts
2485
- await sock.updateProfileStatus('Hello World!')
573
+ // Access stored data
574
+ console.log('Chats:', store.chats.all())
575
+ console.log('Contacts:', store.contacts)
576
+ console.log('Messages:', store.messages)
2486
577
  ```
2487
- ### Change Profile Name
2488
- ```ts
2489
- await sock.updateProfileName('My name')
2490
- ```
2491
- ### Change Display Picture (groups too)
2492
- - To change your display picture or a group's
2493
578
 
2494
- > [!NOTE]
2495
- > 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)
579
+ ---
2496
580
 
2497
- ```ts
2498
- await sock.updateProfilePicture(jid, { url: './new-profile-picture.jpeg' })
2499
- ```
2500
- ### Remove display picture (groups too)
2501
- ```ts
2502
- await sock.removeProfilePicture(jid)
2503
- ```
581
+ ## 🔧 Utilities
2504
582
 
2505
- ## Groups
583
+ ### JID Helpers
584
+ ```typescript
585
+ import { jidEncode, jidDecode, isJidGroup, isJidBroadcast } from '@ryuhan/baileys'
2506
586
 
2507
- - To change group properties you need to be admin
587
+ // Encode JID
588
+ const jid = jidEncode('6281234567890', 's.whatsapp.net')
2508
589
 
2509
- ### Create a Group
2510
- ```ts
2511
- // title & participants
2512
- const group = await sock.groupCreate('My Fab Group', ['1234@s.whatsapp.net', '4564@s.whatsapp.net'])
2513
- console.log('created group with id: ' + group.gid)
2514
- await sock.sendMessage(group.id, { text: 'hello there' }) // say hello to everyone on the group
2515
- ```
2516
- ### Add/Remove or Demote/Promote
2517
- ```ts
2518
- // id & people to add to the group (will throw error if it fails)
2519
- await sock.groupParticipantsUpdate(
2520
- jid,
2521
- ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
2522
- 'add' // replace this parameter with 'remove' or 'demote' or 'promote'
2523
- )
2524
- ```
2525
- ### Change Subject (name)
2526
- ```ts
2527
- await sock.groupUpdateSubject(jid, 'New Subject!')
2528
- ```
2529
- ### Change Description
2530
- ```ts
2531
- await sock.groupUpdateDescription(jid, 'New Description!')
2532
- ```
2533
- ### Change Settings
2534
- ```ts
2535
- // only allow admins to send messages
2536
- await sock.groupSettingUpdate(jid, 'announcement')
2537
- // allow everyone to send messages
2538
- await sock.groupSettingUpdate(jid, 'not_announcement')
2539
- // allow everyone to modify the group's settings -- like display picture etc.
2540
- await sock.groupSettingUpdate(jid, 'unlocked')
2541
- // only allow admins to modify the group's settings
2542
- await sock.groupSettingUpdate(jid, 'locked')
2543
- ```
2544
- ### Leave a Group
2545
- ```ts
2546
- // will throw error if it fails
2547
- await sock.groupLeave(jid)
2548
- ```
2549
- ### Get Invite Code
2550
- - To create link with code use `'https://chat.whatsapp.com/' + code`
2551
- ```ts
2552
- const code = await sock.groupInviteCode(jid)
2553
- console.log('group code: ' + code)
2554
- ```
2555
- ### Revoke Invite Code
2556
- ```ts
2557
- const code = await sock.groupRevokeInvite(jid)
2558
- console.log('New group code: ' + code)
2559
- ```
2560
- ### Join Using Invitation Code
2561
- - Code can't have `https://chat.whatsapp.com/`, only code
2562
- ```ts
2563
- const response = await sock.groupAcceptInvite(code)
2564
- console.log('joined to: ' + response)
2565
- ```
2566
- ### Get Group Info by Invite Code
2567
- ```ts
2568
- const response = await sock.groupGetInviteInfo(code)
2569
- console.log('group information: ' + response)
2570
- ```
2571
- ### Query Metadata (participants, name, description...)
2572
- ```ts
2573
- const metadata = await sock.groupMetadata(jid)
2574
- console.log(metadata.id + ', title: ' + metadata.subject + ', description: ' + metadata.desc)
2575
- ```
2576
- ### Join using `groupInviteMessage`
2577
- ```ts
2578
- const response = await sock.groupAcceptInviteV4(jid, groupInviteMessage)
2579
- console.log('joined to: ' + response)
2580
- ```
2581
- ### Get Request Join List
2582
- ```ts
2583
- const response = await sock.groupRequestParticipantsList(jid)
2584
- console.log(response)
2585
- ```
2586
- ### Approve/Reject Request Join
2587
- ```ts
2588
- const response = await sock.groupRequestParticipantsUpdate(
2589
- jid, // group id
2590
- ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
2591
- 'approve' // or 'reject'
2592
- )
2593
- console.log(response)
2594
- ```
2595
- ### Get All Participating Groups Metadata
2596
- ```ts
2597
- const response = await sock.groupFetchAllParticipating()
2598
- console.log(response)
590
+ // Decode JID
591
+ const decoded = jidDecode(jid)
592
+
593
+ // Check JID type
594
+ const isGroup = isJidGroup(jid)
595
+ const isBroadcast = isJidBroadcast(jid)
2599
596
  ```
2600
- ### Toggle Ephemeral
2601
597
 
2602
- - Ephemeral can be:
598
+ ### Message Helpers
599
+ ```typescript
600
+ import { getContentType, getDevice, downloadMediaMessage } from '@ryuhan/baileys'
2603
601
 
2604
- | Time | Seconds |
2605
- |-------|----------------|
2606
- | Remove | 0 |
2607
- | 24h | 86.400 |
2608
- | 7d | 604.800 |
2609
- | 90d | 7.776.000 |
602
+ // Get content type
603
+ const type = getContentType(message)
2610
604
 
2611
- ```ts
2612
- await sock.groupToggleEphemeral(jid, 86400)
2613
- ```
605
+ // Get device
606
+ const device = getDevice(message)
2614
607
 
2615
- ### Change Add Mode
2616
- ```ts
2617
- await sock.groupMemberAddMode(
2618
- jid,
2619
- 'all_member_add' // or 'admin_add'
2620
- )
608
+ // Download media
609
+ const buffer = await downloadMediaMessage(message, 'buffer')
2621
610
  ```
2622
611
 
2623
- ## Privacy
612
+ ---
2624
613
 
2625
- ### Block/Unblock User
2626
- ```ts
2627
- await sock.updateBlockStatus(jid, 'block') // Block user
2628
- await sock.updateBlockStatus(jid, 'unblock') // Unblock user
2629
- ```
2630
- ### Get Privacy Settings
2631
- ```ts
2632
- const privacySettings = await sock.fetchPrivacySettings(true)
2633
- console.log('privacy settings: ' + privacySettings)
2634
- ```
2635
- ### Get BlockList
2636
- ```ts
2637
- const response = await sock.fetchBlocklist()
2638
- console.log(response)
2639
- ```
2640
- ### Update LastSeen Privacy
2641
- ```ts
2642
- const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
2643
- await sock.updateLastSeenPrivacy(value)
2644
- ```
2645
- ### Update Online Privacy
2646
- ```ts
2647
- const value = 'all' // 'match_last_seen'
2648
- await sock.updateOnlinePrivacy(value)
2649
- ```
2650
- ### Update Profile Picture Privacy
2651
- ```ts
2652
- const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
2653
- await sock.updateProfilePicturePrivacy(value)
2654
- ```
2655
- ### Update Status Privacy
2656
- ```ts
2657
- const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
2658
- await sock.updateStatusPrivacy(value)
2659
- ```
2660
- ### Update Read Receipts Privacy
2661
- ```ts
2662
- const value = 'all' // 'none'
2663
- await sock.updateReadReceiptsPrivacy(value)
2664
- ```
2665
- ### Update Groups Add Privacy
2666
- ```ts
2667
- const value = 'all' // 'contacts' | 'contact_blacklist'
2668
- await sock.updateGroupsAddPrivacy(value)
2669
- ```
2670
- ### Update Default Disappearing Mode
614
+ ## 💝 Credits & Inspiration
2671
615
 
2672
- - Like [this](#disappearing-messages), ephemeral can be:
616
+ This project is built upon the amazing work of:
2673
617
 
2674
- | Time | Seconds |
2675
- |-------|----------------|
2676
- | Remove | 0 |
2677
- | 24h | 86.400 |
2678
- | 7d | 604.800 |
2679
- | 90d | 7.776.000 |
618
+ - **[@blck-baileys](https://github.com/blckrose)** - Original modified Baileys fork with advanced features
619
+ - **[@WhiskeySockets](https://github.com/WhiskeySockets/Baileys)** - Base Baileys library
620
+ - **[@itsukichan](https://github.com/itsukichan/baileys)** - Additional features and improvements
2680
621
 
2681
- ```ts
2682
- const ephemeral = 86400
2683
- await sock.updateDefaultDisappearingMode(ephemeral)
2684
- ```
622
+ Special thanks to all contributors and the WhatsApp community!
2685
623
 
2686
- ## Broadcast Lists & Stories
2687
-
2688
- ### Send Broadcast & Stories
2689
- - Messages can be sent to broadcasts & stories. You need to add the following message options in sendMessage, like this:
2690
- ```ts
2691
- await sock.sendMessage(
2692
- jid,
2693
- {
2694
- image: {
2695
- url: url
2696
- },
2697
- caption: caption
2698
- },
2699
- {
2700
- backgroundColor: backgroundColor,
2701
- font: font,
2702
- statusJidList: statusJidList,
2703
- broadcast: true
2704
- }
2705
- )
2706
- ```
2707
- - Message body can be a `extendedTextMessage` or `imageMessage` or `videoMessage` or `voiceMessage`, see [here](https://baileys.whiskeysockets.io/types/AnyRegularMessageContent.html)
2708
- - You can add `backgroundColor` and other options in the message options, see [here](https://baileys.whiskeysockets.io/types/MiscMessageGenerationOptions.html)
2709
- - `broadcast: true` enables broadcast mode
2710
- - `statusJidList`: a list of people that you can get which you need to provide, which are the people who will get this status message.
2711
-
2712
- - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
2713
- - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
2714
- - Broadcast IDs are in the format `12345678@broadcast`
2715
- ### Query a Broadcast List's Recipients & Name
2716
- ```ts
2717
- const bList = await sock.getBroadcastListInfo('1234@broadcast')
2718
- console.log (`list name: ${bList.name}, recps: ${bList.recipients}`)
2719
- ```
624
+ ---
2720
625
 
2721
- ## Writing Custom Functionality
2722
- Baileys is written with custom functionality in mind. Instead of forking the project & re-writing the internals, you can simply write your own extensions.
626
+ ## ⚠️ Disclaimer
2723
627
 
2724
- ### Enabling Debug Level in Baileys Logs
2725
- First, enable the logging of unhandled messages from WhatsApp by setting:
2726
- ```ts
2727
- const sock = makeWASocket({
2728
- logger: P({ level: 'debug' }),
2729
- })
2730
- ```
2731
- This will enable you to see all sorts of messages WhatsApp sends in the console.
2732
-
2733
- ### How Whatsapp Communicate With Us
2734
-
2735
- > [!TIP]
2736
- > If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
2737
-
2738
- - **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:
2739
- ```
2740
- {
2741
- "level": 10,
2742
- "fromMe": false,
2743
- "frame": {
2744
- "tag": "ib",
2745
- "attrs": {
2746
- "from": "@s.whatsapp.net"
2747
- },
2748
- "content": [
2749
- {
2750
- "tag": "edge_routing",
2751
- "attrs": {},
2752
- "content": [
2753
- {
2754
- "tag": "routing_info",
2755
- "attrs": {},
2756
- "content": {
2757
- "type": "Buffer",
2758
- "data": [8,2,8,5]
2759
- }
2760
- }
2761
- ]
2762
- }
2763
- ]
2764
- },
2765
- "msg":"communication"
2766
- }
2767
- ```
628
+ This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries. The official WhatsApp website can be found at [whatsapp.com](https://whatsapp.com).
2768
629
 
2769
- The `'frame'` is what the message received is, it has three components:
2770
- - `tag` -- what this frame is about (eg. message will have 'message')
2771
- - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
2772
- - `content` -- the actual data (eg. a message node will have the actual message content in it)
2773
- - read more about this format [here](/src/WABinary/readme.md)
630
+ The maintainers of Rimuru Baileys do not endorse the use of this application for violating WhatsApp's Terms of Service. We emphasize the personal responsibility of users to use it fairly and responsibly.
2774
631
 
2775
- ### Register a Callback for Websocket Events
632
+ **Use wisely. Avoid spam. Do not use excessive automation.**
2776
633
 
2777
- > [!TIP]
2778
- > Recommended to see `onMessageReceived` function in `socket.ts` file to understand how websockets events are fired
634
+ ---
2779
635
 
2780
- ```ts
2781
- // for any message with tag 'edge_routing'
2782
- sock.ws.on('CB:edge_routing', (node: BinaryNode) => { })
636
+ ## 📄 License
2783
637
 
2784
- // for any message with tag 'edge_routing' and id attribute = abcd
2785
- sock.ws.on('CB:edge_routing,id:abcd', (node: BinaryNode) => { })
638
+ MIT License - see [LICENSE](LICENSE) for details.
2786
639
 
2787
- // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
2788
- sock.ws.on('CB:edge_routing,id:abcd,routing_info', (node: BinaryNode) => { })
2789
- ```
640
+ ---
2790
641
 
2791
- # License
2792
- Copyright (c) 2025 Rajeh Taher/WhiskeySockets
2793
-
2794
- Licensed under the MIT License:
2795
- Permission is hereby granted, free of charge, to any person obtaining a copy
2796
- of this software and associated documentation files (the "Software"), to deal
2797
- in the Software without restriction, including without limitation the rights
2798
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2799
- copies of the Software, and to permit persons to whom the Software is
2800
- furnished to do so, subject to the following conditions:
2801
-
2802
- The above copyright notice and this permission notice shall be included in all
2803
- copies or substantial portions of the Software.
2804
-
2805
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2806
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2807
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2808
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2809
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2810
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2811
- SOFTWARE.
2812
-
2813
- Thus, the maintainers of the project can't be held liable for any potential misuse of this project.
642
+ <p align="center">Made with 💧 by <a href="https://github.com/ryuhandev">@ryuhandev</a></p>
643
+ <p align="center">
644
+ <a href="https://github.com/ryuhandev/rimuru-baileys">GitHub</a> •
645
+ <a href="https://www.npmjs.com/package/@ryuhan/baileys">npm</a>
646
+ <a href="https://github.com/ryuhandev/rimuru-baileys/issues">Issues</a>
647
+ </p>