π Table of Contents
β¨ Features
Core Features
- π₯ Multi-Device Support - Connect without phone always online
- β‘ WebSocket Based - Fast and efficient communication
- πΎ Session Management - Save and restore authentication
- π― Event-Driven - Reactive message handling
- π¦ TypeScript Ready - Full type definitions included
- π Built on WhiskeySockets - Latest Baileys implementation
|
Extended Features
- π¨ Universal Button System - Auto-converts any button format
- πΈ Media Handling - Images, videos, audio, documents
- π€ Poll Support - Create and manage polls
- π Location Sharing - Share locations with metadata
- π Newsletter Support - Manage WhatsApp channels
- πͺ Carousel Messages - Multi-card interactive displays
|
π¦ Installation
NPM
npm install supun-baileyz
Yarn
yarn add supun-baileyz
Using Different Package Name
Add to your package.json:
{
"dependencies": {
"@whiskeysockets/baileys": "npm:supun-baileyz"
}
}
Import
import makeWASocket from 'supun-baileyz'
const { default: makeWASocket } = require('supun-baileyz')
π Quick Start
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from 'supun-baileyz'
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState('auth_session')
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
browser: ['SupunMd', 'Chrome', '1.0.0']
})
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if(connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut
if(shouldReconnect) {
connectToWhatsApp()
}
} else if(connection === 'open') {
console.log('β
Connected to WhatsApp!')
}
})
sock.ev.on('messages.upsert', async ({ messages }) => {
for(const msg of messages) {
if(!msg.key.fromMe && msg.message) {
await sock.sendMessage(msg.key.remoteJid, {
text: 'Hello from SupunMd Baileys!'
})
}
}
})
sock.ev.on('creds.update', saveCreds)
}
connectToWhatsApp()
π Authentication
QR Code Authentication
import makeWASocket from 'supun-baileyz'
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
browser: ['SupunMd', 'Chrome', '1.0.0']
})
Pairing Code Authentication
const sock = makeWASocket({
auth: state,
printQRInTerminal: false
})
if(!sock.authState.creds.registered) {
const phoneNumber = '1234567890'
const code = await sock.requestPairingCode(phoneNumber)
console.log(`Pairing code: ${code}`)
}
Custom Pairing Code
const phoneNumber = "947XXXXX"
const code = await sock.requestPairingCode(phoneNumber.trim(), "ABCDE01")
console.log("Your pairing code: " + code)
π‘ Socket Configuration
Cache Group Metadata (Recommended)
const groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false })
const sock = makeWASocket({
cachedGroupMetadata: async (jid) => groupCache.get(jid)
})
sock.ev.on('groups.update', async ([event]) => {
const metadata = await sock.groupMetadata(event.id)
groupCache.set(event.id, metadata)
})
Improve Retry & Poll Decryption
const sock = makeWASocket({
getMessage: async (key) => await getMessageFromStore(key)
})
Receive Notifications in WhatsApp App
const sock = makeWASocket({
markOnlineOnConnect: false
})
πΎ Session Management
Avoid scanning QR every time:
import makeWASocket, { useMultiFileAuthState } from 'supun-baileyz'
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
const sock = makeWASocket({ auth: state })
sock.ev.on('creds.update', saveCreds)
π‘ Tip: For production, store auth in a database instead of files.
π‘ Event Handling
Connection Updates
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if(connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut
console.log('Connection closed, reconnecting:', shouldReconnect)
if(shouldReconnect) connectToWhatsApp()
} else if(connection === 'open') {
console.log('Connection opened')
}
})
New Messages
sock.ev.on('messages.upsert', async ({ messages }) => {
for(const msg of messages) {
console.log('New message:', msg)
}
})
Message Updates
sock.ev.on('messages.update', async (updates) => {
for(const update of updates) {
console.log('Message updated:', update)
}
})
Decrypt Poll Votes
sock.ev.on('messages.update', async (event) => {
for(const { key, update } of event) {
if(update.pollUpdates) {
const pollCreation = await getMessage(key)
if(pollCreation) {
console.log('Poll update:', getAggregateVotesInPollMessage({
message: pollCreation,
pollUpdates: update.pollUpdates,
}))
}
}
}
})
π οΈ Data Store
import makeWASocket, { makeInMemoryStore } from 'supun-baileyz'
const store = makeInMemoryStore({})
store.readFromFile('./baileys_store.json')
setInterval(() => {
store.writeToFile('./baileys_store.json')
}, 10_000)
const sock = makeWASocket({})
store.bind(sock.ev)
sock.ev.on('chats.upsert', () => {
console.log('Got chats:', store.chats.all())
})
sock.ev.on('contacts.upsert', () => {
console.log('Got contacts:', Object.values(store.contacts))
})
β οΈ Important: Build your own data store for production. In-memory storage wastes RAM.
π WhatsApp IDs
- Personal Chats:
[country code][phone number]@s.whatsapp.net
- Example:
1234567890@s.whatsapp.net
- Groups:
[group id]@g.us
- Example:
123456789-987654321@g.us
- Broadcast Lists:
[timestamp]@broadcast
- Status:
status@broadcast
π¬ Sending Messages
Text & Special Messages
Text Message
await sock.sendMessage(jid, { text: 'Hello World!' })
Quote Message (works with all types)
await sock.sendMessage(jid, { text: 'This is a reply' }, { quoted: message })
Mention User (works with most types)
await sock.sendMessage(jid, {
text: '@12345678901',
mentions: ['12345678901@s.whatsapp.net']
})
Mention Status
await sock.sendStatusMentions(
{
text: "Hello",
},
[
"123456789123456789@g.us",
"123456789@s.whatsapp.net",
]
)
Result Poll From Newsletter
await sock.sendMessage(jid, {
pollResult: {
name: "Text poll",
votes: [["Options 1", 10], ["Options 2", 10]],
}
}, { quoted: message })
Send Album Message
await sock.sendAlbumMessage(
jid,
[
{
image: { url: "https://example.jpg" },
caption: "Hello World",
},
{
video: { url: "https://example.mp4" },
caption: "Hello World",
},
],
{
quoted: message,
delay: 2000
}
)
Request Payment
await sock.sendMessage(jid, {
requestPayment: {
currency: "IDR",
amount: "10000000",
from: "123456@s.whatsapp.net",
note: "Payment Request",
background: { }
}
}, { quoted: message })
await sock.sendMessage(jid, {
requestPayment: {
currency: "IDR",
amount: "10000000",
from: "123456@s.whatsapp.net",
sticker: buffer,
background: { }
}
}, { quoted: message })
await sock.sendMessage(jid, {
requestPayment: {
currency: "IDR",
amount: "10000000",
from: "123456@s.whatsapp.net",
sticker: { url: "https://example.com/sticker.webp" },
background: { }
}
}, { quoted: message })
Event Message
await sock.sendMessage(jid, {
event: {
isCanceled: false,
name: "Event Name",
description: "Event Description",
location: {
degreesLatitude: -0,
degreesLongitude: -0
},
link: "https://call-link.example.com",
startTime: m.messageTimestamp.low,
endTime: m.messageTimestamp.low + 86400,
extraGuestsAllowed: true
}
}, { quoted: message })
Product Message
await sock.sendMessage(jid, {
productMessage: {
title: "Product Title",
description: "Product Description",
thumbnail: "https://example.png",
productId: "123456789",
retailerId: "STORE",
url: "https://example.png",
body: "Product Body",
footer: "Product Footer",
buttons: [
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "Visit Site",
url: "https://example.com"
})
}
]
}
}, { quoted: message })
Carousel Message
await sock.sendMessage(jid, {
carouselMessage: {
caption: "Click URL",
footer: "Powered By SupunFernando",
cards: [
{
headerTitle: "`</> Owner Bot </>`",
imageUrl: "https://example.com/image.jpg",
productTitle: "Premium Bot",
productDescription: "Get premium access",
bodyText: "[SupunFernando]\n- Important chat only\n- Don't call owner",
buttons: [
{
name: "cta_call",
params: {
display_text: "Contact Owner",
phone_number: "+1234567890"
}
}
]
},
{
headerTitle: "`</> Bot Assistant </>`",
imageUrl: "https://example.com/image2.jpg",
bodyText: "[AI Assistant]\n- Don't spam bot\n- Don't call bot",
buttons: [
{
name: "cta_url",
params: {
display_text: "Chat Bot",
url: "https://wa.me/1234567890",
merchant_url: "https://wa.me/1234567890"
}
}
]
}
]
}
}, { quoted: message })
Forward Messages
const msg = getMessageFromStore()
await sock.sendMessage(jid, { forward: msg })
Location Message
await sock.sendMessage(jid, {
location: {
degreesLatitude: 24.121231,
degreesLongitude: 55.1121221,
name: "Location Name",
address: "Location Address"
}
})
Contact Message
const vcard = 'BEGIN:VCARD\n'
+ 'VERSION:3.0\n'
+ 'FN:John Doe\n'
+ 'ORG:SupunFernando;\n'
+ 'TEL;type=CELL;type=VOICE;waid=1234567890:+1 234 567 890\n'
+ 'END:VCARD'
await sock.sendMessage(jid, {
contacts: {
displayName: 'John Doe',
contacts: [{ vcard }]
}
})
Reaction Message
await sock.sendMessage(jid, {
react: {
text: 'π',
key: message.key
}
})
Pin Message
await sock.sendMessage(jid, {
pin: {
type: 1,
time: 86400,
key: message.key
}
})
Pin Time Options:
| 24h | 86,400 |
| 7d | 604,800 |
| 30d | 2,592,000 |
Keep Message
await sock.sendMessage(jid, {
keep: message.key,
type: 1,
time: 86400
})
Keep Time Options:
| 24h | 86,400 |
| 7d | 604,800 |
| 30d | 2,592,000 |
Poll Message
await sock.sendMessage(jid, {
poll: {
name: 'Favorite Color?',
values: ['Red', 'Blue', 'Green', 'Yellow'],
selectableCount: 1,
toAnnouncementGroup: false
}
})
Link Preview
await sock.sendMessage(jid, {
text: 'Check out https://www.npmjs.com/package/mr-supun-fernando/baileyz'
})
Media Messages
π Note: You can pass { stream: Stream }, { url: Url }, or Buffer directly
Image Message
await sock.sendMessage(jid, {
image: { url: 'https://example.com/image.jpg' },
caption: 'Beautiful image!'
})
await sock.sendMessage(jid, {
image: buffer,
caption: 'Image from buffer'
})
await sock.sendMessage(jid, {
image: fs.readFileSync('./image.jpg'),
caption: 'Local image'
})
Video Message
await sock.sendMessage(jid, {
video: { url: './video.mp4' },
caption: 'Check this out!',
gifPlayback: false,
ptv: false
})
GIF Message
await sock.sendMessage(jid, {
video: fs.readFileSync('Media/gif.mp4'),
caption: 'Funny GIF',
gifPlayback: true
})
Audio Message
await sock.sendMessage(jid, {
audio: { url: './audio.mp3' },
mimetype: 'audio/mp4',
ptt: true
})
π‘ Audio Conversion Tip:
ffmpeg -i input.mp4 -avoid_negative_ts make_zero -ac 1 output.ogg
Document
await sock.sendMessage(jid, {
document: { url: './document.pdf' },
fileName: 'document.pdf',
mimetype: 'application/pdf'
})
Sticker
await sock.sendMessage(jid, {
sticker: { url: './sticker.webp' }
})
Sticker Pack
Method 1: Direct Socket Method (Recommended)
await sock.stickerPackMessage(jid, {
name: 'My Stickers',
publisher: 'Your Bot',
description: 'Collection of stickers',
stickers: [
{ data: buffer, emojis: ['π'] },
{ data: './sticker.png', emojis: ['π'] },
{ data: './sticker.webp', emojis: ['π'] },
{ data: 'https://example.com/sticker.jpg', emojis: ['β€οΈ'] }
],
cover: buffer
}, { quoted: message });
Method 2: Via sendMessage
await sock.sendMessage(jid, {
stickerPack: {
name: 'My Stickers',
publisher: 'Your Bot',
description: 'Collection of stickers',
stickers: [
{ data: buffer, emojis: ['π'] },
{ data: './sticker.png', emojis: ['π'] },
{ data: './sticker.webp', emojis: ['π'] },
{ data: 'https://example.com/sticker.jpg', emojis: ['β€οΈ'] }
],
cover: buffer
}
}, { quoted: message });
Supported Image Formats
| WebP | β
Full | Used as-is, no conversion needed |
| PNG | β
Full | Auto-converts to WebP |
| JPG/JPEG | β
Full | Auto-converts to WebP |
| GIF | β
Limited | Converts to static WebP |
| BMP | β
Full | Auto-converts to WebP |
| Video | β Not supported | Only static images |
Key Features
β
Automatic batching - Splits packs >60 stickers
β
Compression - Auto-compresses stickers >1MB
β
Auto-conversion - Converts PNG, JPG, GIF, BMP to WebP
β
Multiple formats - Supports buffers, file paths, URLs
β
Rate limiting - 2-second delays between batches
β
Error handling - Gracefully skips invalid stickers
View Once Message
await sock.sendMessage(jid, {
image: { url: './secret.jpg' },
viewOnce: true,
caption: 'View once only!'
})
Buttons & Interactive Messages
Simple Text with Buttons
await sock.sendMessage(jid, {
text: "Choose an option",
footer: "Β© SupunFernando",
buttons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Option 1",
id: "opt1"
})
},
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "Visit Website",
url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07",
merchant_url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07"
})
}
]
})
Image with Buttons
await sock.sendMessage(jid, {
image: { url: "https://example.com/image.jpg" },
caption: "Description",
footer: "Β© SupunFernando",
buttons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Reply",
id: "btn1"
})
}
]
})
Video with Buttons
await sock.sendMessage(jid, {
video: { url: "https://example.com/video.mp4" },
caption: "Watch this",
footer: "Β© SupunFernando",
buttons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Like",
id: "like"
})
}
]
})
Document with Buttons
await sock.sendMessage(jid, {
document: { url: "./file.pdf" },
fileName: "Document.pdf",
mimetype: "application/pdf",
caption: "Read this",
footer: "Β© SupunFernando",
buttons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Download",
id: "download"
})
}
]
})
All Button Types
1. Quick Reply
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Quick Reply",
id: "button_id"
})
}
2. URL Button
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "Visit Website",
url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07",
merchant_url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07"
})
}
3. Call Button
{
name: "cta_call",
buttonParamsJson: JSON.stringify({
display_text: "Call Us",
phone_number: "+1234567890"
})
}
4. Copy Button
{
name: "cta_copy",
buttonParamsJson: JSON.stringify({
display_text: "Copy Code",
id: "copy_id",
copy_code: "PROMO2025"
})
}
5. List/Single Select
{
name: "single_select",
buttonParamsJson: JSON.stringify({
title: "Select Option",
sections: [{
title: "Section 1",
highlight_label: "Popular",
rows: [
{ title: "Option 1", description: "Desc 1", id: "opt1" },
{ title: "Option 2", description: "Desc 2", id: "opt2" }
]
}]
})
}
6. Call Permission Request
{
name: "call_permission_request",
buttonParamsJson: JSON.stringify({
has_multiple_buttons: true
})
}
Classic Buttons (Old Style)
For compatibility with older WhatsApp versions:
await sock.sendMessage(jid, {
text: "Message with classic buttons",
footer: "Footer text",
buttons: [
{
buttonId: "btn1",
buttonText: { displayText: "Button 1" },
type: 1
},
{
buttonId: "btn2",
buttonText: { displayText: "Button 2" },
type: 1
}
],
headerType: 1
})
0 | EMPTY | No header |
1 | TEXT | Text header (use title field) |
2 | DOCUMENT | Document header |
3 | IMAGE | Image header |
4 | VIDEO | Video header |
5 | LOCATION | Location header |
Button Types (Classic Buttons)
1 | RESPONSE | Standard clickable button |
2 | NATIVE_FLOW | Native flow button |
Example with Image Header:
await sock.sendMessage(jid, {
image: { url: "https://example.com/image.jpg" },
caption: "Body text",
footer: "Footer",
buttons: [
{ buttonId: "btn1", buttonText: { displayText: "Button 1" }, type: 1 }
],
headerType: 3
})
Advanced: Native Flow Messages
Complete example with all features:
await sock.sendMessage(jid, {
interactiveMessage: {
title: "Interactive Message",
footer: "Β© SupunFernando",
image: { url: "https://example.com/image.jpg" },
nativeFlowMessage: {
messageParamsJson: JSON.stringify({
limited_time_offer: {
text: "Limited offer!",
url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07",
copy_code: "SUPUNMD OFC",
expiration_time: Date.now() + (24 * 60 * 60 * 1000)
},
bottom_sheet: {
in_thread_buttons_limit: 2,
divider_indices: [0, 1, 2],
list_title: "Select Option",
button_title: "Click Here"
},
tap_target_configuration: {
title: "Tap Target",
description: "Description",
canonical_url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07",
domain: "supunmd.vercel.app/",
button_index: 0
}
}),
buttons: [
{
name: "single_select",
buttonParamsJson: JSON.stringify({
title: "Select",
sections: [{
title: "Options",
rows: [
{ title: "Option 1", description: "Desc 1", id: "opt1" }
]
}]
})
},
{
name: "cta_copy",
buttonParamsJson: JSON.stringify({
display_text: "Copy Code",
copy_code: "SUPUNM2026"
})
}
]
}
}
})
Interactive Buttons (Alternative Format)
await sock.sendMessage(jid, {
text: "Description of Message",
title: "Title of Message",
subtitle: "Subtitle Message",
footer: "Footer Message",
interactiveButtons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Quick Reply",
id: "button_1"
})
},
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "Visit Channel",
url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07"
})
}
]
}, { quoted: message })
await sock.sendMessage(jid, {
image: { url: "https://example.jpg" },
caption: "Description of Message",
title: "Title of Message",
subtitle: "Subtitle Message",
footer: "Footer Message",
media: true,
interactiveButtons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Quick Reply",
id: "button_1"
})
},
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "Visit Channel",
url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07"
})
}
]
}, { quoted: message })
await sock.sendMessage(jid, {
product: {
productImage: { url: "https://example.jpg" },
productImageCount: 1,
title: "Product Title",
description: "Product Description",
priceAmount1000: 20000 * 1000,
currencyCode: "USD",
retailerId: "Retail",
url: "https://example.com",
},
businessOwnerJid: "1234@s.whatsapp.net",
caption: "Description of Message",
title: "Title of Message",
footer: "Footer Message",
media: true,
interactiveButtons: [
{
name: "quick_reply",
buttonParamsJson: JSON.stringify({
display_text: "Quick Reply",
id: "button_1"
})
},
{
name: "cta_url",
buttonParamsJson: JSON.stringify({
display_text: "Visit Channel",
url: "https://whatsapp.com/channel/0029Vb55cv41nozBTTIw1y07"
})
}
]
}, { quoted: message })
βοΈ Message Modifications
Delete Message (for everyone)
const msg = await sock.sendMessage(jid, { text: 'hello' })
await sock.sendMessage(jid, { delete: msg.key })
Edit Message
await sock.sendMessage(jid, {
text: 'Updated message text',
edit: originalMessage.key
})
π₯ Media Operations
Download Media
import { downloadMediaMessage, getContentType } from 'supun-baileyz'
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0]
if(!msg.message) return
const messageType = getContentType(msg.message)
if(messageType === 'imageMessage') {
const buffer = await downloadMediaMessage(
msg,
'buffer',
{},
{
logger: console,
reuploadRequest: sock.updateMediaMessage
}
)
fs.writeFileSync('./download.jpeg', buffer)
}
})
Re-upload Media
await sock.updateMediaMessage(msg)
π₯ Group Management
Create Group
const group = await sock.groupCreate('Group Name', [
'1234567890@s.whatsapp.net',
'0987654321@s.whatsapp.net'
])
console.log('Group created:', group.id)
Add/Remove Participants
await sock.groupParticipantsUpdate(groupJid, ['1234567890@s.whatsapp.net'], 'add')
await sock.groupParticipantsUpdate(groupJid, ['1234567890@s.whatsapp.net'], 'remove')
await sock.groupParticipantsUpdate(groupJid, ['1234567890@s.whatsapp.net'], 'promote')
await sock.groupParticipantsUpdate(groupJid, ['1234567890@s.whatsapp.net'], 'demote')
Update Group Subject
await sock.groupUpdateSubject(groupJid, 'New Group Name')
Update Group Description
await sock.groupUpdateDescription(groupJid, 'New group description')
Group Settings
await sock.groupSettingUpdate(groupJid, 'announcement')
await sock.groupSettingUpdate(groupJid, 'not_announcement')
await sock.groupSettingUpdate(groupJid, 'locked')
await sock.groupSettingUpdate(groupJid, 'unlocked')
Get Group Metadata
const metadata = await sock.groupMetadata(groupJid)
console.log('Group:', metadata.subject)
console.log('Participants:', metadata.participants.length)
Get Invite Code
const code = await sock.groupInviteCode(groupJid)
console.log('Invite link:', `https://chat.whatsapp.com/${code}`)
Revoke Invite Code
const newCode = await sock.groupRevokeInvite(groupJid)
console.log('New invite code:', newCode)
Join Group via Invite Code
await sock.groupAcceptInvite('INVITE_CODE_HERE')
Leave Group
await sock.groupLeave(groupJid)
Get Group Invite Info
const info = await sock.groupGetInviteInfo('INVITE_CODE')
console.log('Group info:', info)
π± User Operations
Check if Number Exists
const [result] = await sock.onWhatsApp('1234567890')
if(result?.exists) {
console.log('Number exists:', result.jid)
}
Get Profile Picture
const ppUrl = await sock.profilePictureUrl(jid)
const ppUrlHD = await sock.profilePictureUrl(jid, 'image')
Update Profile Picture
await sock.updateProfilePicture(jid, {
url: './profile.jpg'
})
Remove Profile Picture
await sock.removeProfilePicture(jid)
Get Status
const status = await sock.fetchStatus(jid)
console.log('Status:', status)
Update Profile Status
await sock.updateProfileStatus('Available 24/7')
Update Profile Name
await sock.updateProfileName('Supun Wa Bot')
Get Business Profile
const profile = await sock.getBusinessProfile(jid)
console.log('Business:', profile.description)
Presence Updates
await sock.presenceSubscribe(jid)
await sock.sendPresenceUpdate('available', jid)
Read Messages
await sock.readMessages([message.key])
π Privacy Controls
Block/Unblock User
await sock.updateBlockStatus(jid, 'block')
await sock.updateBlockStatus(jid, 'unblock')
Get Privacy Settings
const settings = await sock.fetchPrivacySettings()
console.log(settings)
Update Privacy Settings
await sock.updateLastSeenPrivacy('contacts')
await sock.updateOnlinePrivacy('all')
await sock.updateProfilePicturePrivacy('contacts')
await sock.updateStatusPrivacy('contacts')
await sock.updateReadReceiptsPrivacy('all')
await sock.updateGroupsAddPrivacy('contacts')
Get Block List
const blocklist = await sock.fetchBlocklist()
console.log('Blocked users:', blocklist)
π¬ Chat Operations
Archive/Unarchive Chat
const lastMsg = await getLastMessageInChat(jid)
await sock.chatModify({
archive: true,
lastMessages: [lastMsg]
}, jid)
Mute/Unmute Chat
await sock.chatModify({
mute: 8 * 60 * 60 * 1000
}, jid)
await sock.chatModify({
mute: null
}, jid)
Pin/Unpin Chat
await sock.chatModify({ pin: true }, jid)
await sock.chatModify({ pin: false }, jid)
Delete Chat
const lastMsg = await getLastMessageInChat(jid)
await sock.chatModify({
delete: true,
lastMessages: [{
key: lastMsg.key,
messageTimestamp: lastMsg.messageTimestamp
}]
}, jid)
Mark Chat as Read/Unread
await sock.chatModify({ markRead: true }, jid)
await sock.chatModify({ markRead: false }, jid)
π’ Broadcast & Stories
Send Broadcast Message
await sock.sendMessage(jid, {
text: 'Broadcast message',
statusJidList: [
'1234567890@s.whatsapp.net',
'0987654321@s.whatsapp.net'
],
broadcast: true
})
Send Story/Status
await sock.sendMessage('status@broadcast', {
image: { url: './story.jpg' },
caption: 'My story update!'
})
Newsletter/Channel Management
await sock.newsletterCreate('Newsletter Name', {
description: 'Newsletter description',
picture: buffer
})
await sock.newsletterUpdateMetadata(newsletterJid, {
name: 'New Name',
description: 'New description'
})
await sock.newsletterUpdatePicture(newsletterJid, buffer)
await sock.newsletterReactMessage(newsletterJid, messageId, 'π')
await sock.newsletterFollow(newsletterJid)
await sock.newsletterUnfollow(newsletterJid)
await sock.newsletterMute(newsletterJid)
await sock.newsletterUnmute(newsletterJid)
π§© Advanced Features
Disappearing Messages
await sock.sendMessage(jid, {
disappearingMessagesInChat: 86400
})
await sock.sendMessage(jid, {
disappearingMessagesInChat: false
})
Query Message
const msg = await sock.loadMessage(jid, messageId)
console.log('Message:', msg)
Get Message Info
const info = await sock.messageInfo(jid, messageId)
console.log('Read by:', info.readBy.length)
console.log('Played by:', info.playedBy.length)
App State Sync
await sock.appPatch(['regular', 'critical_block', 'critical_unblock_low'])
WABrowserId
const browserId = sock.generateBrowserId()
console.log('Browser ID:', browserId)
π― Best Practices
1. Session Management
import { useMultiFileAuthState } from '@mr-supun-fernando/baileyz'
const { state, saveCreds } = await useMultiFileAuthState('auth_folder')
const sock = makeWASocket({ auth: state })
sock.ev.on('creds.update', saveCreds)
2. Store Implementation
import { makeInMemoryStore } from '@mr-supun-fernando/baileyz'
const store = makeInMemoryStore({})
store.readFromFile('./store.json')
setInterval(() => {
store.writeToFile('./store.json')
}, 10_000)
store.bind(sock.ev)
3. Error Handling
try {
await sock.sendMessage(jid, { text: 'Hello' })
} catch(error) {
if(error.output?.statusCode === 401) {
console.log('Not authorized')
} else {
console.error('Send failed:', error)
}
}
4. Reconnection Logic
sock.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect } = update
if(connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut
if(shouldReconnect) {
console.log('Reconnecting...')
await connectToWhatsApp()
} else {
console.log('Logged out')
}
}
})
5. Rate Limiting
const queue = []
const sending = false
async function queueMessage(jid, message) {
queue.push({ jid, message })
if(!sending) processQueue()
}
async function processQueue() {
sending = true
while(queue.length > 0) {
const { jid, message } = queue.shift()
await sock.sendMessage(jid, message)
await delay(1000)
}
sending = false
}
π License
This project is licensed under the MIT License - see the LICENSE file for details.
β οΈ Disclaimer
This project is NOT officially affiliated with WhatsApp or Meta. This is an independent project and should be used responsibly. The authors and maintainers are not responsible for any misuse of this library.
Important:
- Follow WhatsApp's Terms of Service
- Don't spam or send unsolicited messages
- Respect user privacy
- Use for legitimate purposes only
- Be aware of WhatsApp's rate limits
π Acknowledgments
Special thanks to:
- WhiskeySockets for the original Baileys library
- All contributors who have helped improve this project
- The open-source community for their continuous support
π Support