@hanzofc/baileys
[!IMPORTANT]
This project is a modified fork of WhiskeySockets/Baileys.
The original Baileys project and its upstream contributors are credited below. This fork is independently maintained and published as @hanzofc/baileys.
About
@hanzofc/baileys is a customized fork of Baileys, a TypeScript library for interacting with WhatsApp Web through WebSockets.
This fork is maintained separately from the upstream project and contains additional fixes, modifications, and changes used by the author for WhatsApp automation projects.
Features
- WhatsApp Web socket connection
- Multi-device support
- TypeScript support
- Authentication state management
- Message sending and receiving
- Group management
- Media messages
- Interactive messages (buttons, lists, native flow with the required
biz nodes)
- Presence updates
- Contact and profile information
- Event-based architecture
- Extra message types: product, order, payment request, event, album, poll result, group status, group member label
richMenu and sendHtml helpers
menu / card / shop options for native flow messages (buttons, bottom-sheet list, limited-time offer, Bloks card)
- Full newsletter (channel) API incl. channel status, admin profile events and
newsletterMeta on incoming posts
reportSpam and SPAM_FLOWS for chat-level spam reports, alongside updateBlockStatus / fetchBlocklist
- Rich message helpers:
sendTable, sendList, sendCodeBlock, sendLatex
- WhatsApp username management (
checkUsername, setUsername, findUserByUsername, ...)
- Restored
makeInMemoryStore and optional makeCacheManagerStore
useSqliteAuthState (single-file SQLite auth storage)
- Fine-grained relay options (
isSecret, protected, me)
- Additional fixes and modifications maintained in this fork
Differences from Upstream
This fork is based on WhiskeySockets/Baileys 7.0.0-rc14 (compared against upstream commit 0af2386, "advertise WIN_HYBRID instead of retired WIN32 web sub-platform"). Everything else in the library behaves like upstream.
| Area |
Upstream |
This fork |
| Package name |
baileys |
@hanzofc/baileys |
| Version |
7.0.0-rc14 |
7.1.0 |
| Auth state |
useMultiFileAuthState |
Adds useSqliteAuthState (needs Node 22.5+) |
sendMessage content |
Standard content types |
Adds productMessage, orderMessage, requestPaymentMessage, eventMessage, albumMessage, pollResultMessage, groupStatus, groupLabel |
| Extra socket methods |
- |
richMenu(jid, content), sendHtml(jid, html), sendTable, sendList, sendCodeBlock, sendLatex |
| Username API |
- |
checkUsername, checkUsernameMulti, setUsername, deleteUsername, getMyUsername, getUsernameRecommendations, setUsernamePin, findUserByUsername, fetchContactUsernames |
| Store |
Removed upstream |
makeInMemoryStore and makeCacheManagerStore exported again |
| Utils |
- |
message-composer helpers (tokenizeCode, generateTableContent, generateCodeBlockContent, generateLatexContent, ...) exported from Utils |
| Interactive messages |
Sent as-is |
Adds biz / native_flow / bot nodes automatically for buttons, lists and native flow |
relayMessage options |
participant (retry resend) |
Retry resend renamed to participants; participant now means "recipient only"; adds isSecret, protected, me |
| Client platform |
WEB, or ANDROID if the browser name contains "android" |
Always MACOS |
| On connect |
Nothing extra |
Auto-follows the newsletter JIDs listed in AUTO_FOLLOW_NEWSLETTER_JIDS |
| Protobuf |
Upstream definitions |
Adds BloksWidget to WAProto |
| Build output |
- |
ESM imports use explicit .js extensions |
[!WARNING]
Some of these changes affect behavior or the public API. Read the sections below before upgrading from upstream.
Requirements
- Node.js 20 or newer (enforced by
engine-requirements.js on install)
- Node.js 22.5 or newer only if you use
useSqliteAuthState (it relies on the built-in node:sqlite module)
Breaking / behavior changes
Retry resend option renamed. Upstream passes { participant: { jid, count } } to relayMessage when re-sending after a failed decryption. In this fork that option is participants. participant: { jid } (without count) now targets only that recipient. If you call relayMessage directly with the old shape, update your code.
Client platform is always MACOS. Upstream chooses WEB (or ANDROID when browser[1] contains "android"). This fork always advertises MACOS in the client payload.
Newsletter auto-follow. On the first connection: 'open', the socket calls newsletterFollow for each JID in AUTO_FOLLOW_NEWSLETTER_JIDS (defined in src/Socket/index.ts). Errors are ignored. There is currently no config option for this: to disable it, empty that array in the source and rebuild.
What's New in 7.1.0
Changes compared with 7.0.1 (the previous npm release):
Added
- Rich message helpers (
src/Utils/message-composer.ts, exposed on the socket):
sock.sendTable(jid, title, headers, rows, quoted?, options?)
sock.sendList(jid, title, items, quoted?, options?)
sock.sendCodeBlock(jid, code, quoted?, { language, title, footer }) with built-in syntax tokenizing for JavaScript/TypeScript and Python
sock.sendLatex(jid, quoted?, { text, expressions, headerText, footer })
- Username API (
src/Socket/username.ts), built on a new generic w:mex query helper (src/Socket/mex.ts):
checkUsername, checkUsernameMulti, setUsername, deleteUsername, getMyUsername
getUsernameRecommendations, setUsernamePin, findUserByUsername, fetchContactUsernames
- The
USERNAME_QUERY_IDS, USERNAME_CHECK_RESULT and USERNAME_SOURCE constants are exported.
- Store modules restored:
makeInMemoryStore, makeOrderedDictionary, ObjectRepository, KeyedDB, and the optional makeCacheManagerStore (needs npm install cache-manager).
- New test suites and type declarations for
node:sqlite.
Changed
Utils and Store index files now re-export the new modules (message-composer, store helpers).
- The
lib/ build output was regenerated against the updated src/.
- Dependencies and the
resolutions block were refreshed (security fixes for transitive packages such as tar, minimatch, glob, handlebars, markdown-it, picomatch, socks).
Notes
[!WARNING]
Username operations use WhatsApp w:mex GraphQL query IDs. These IDs are captured from specific WhatsApp client versions and can change without notice, so a call may start failing after a WhatsApp update.
Like richMenu and sendHtml, the rich message helpers depend on undocumented WhatsApp client behavior and may render differently or stop working.
Examples
// Table
await sock.sendTable(jid, 'Prices', ['Item', 'Price'], [
['Coffee', '10.000'],
['Tea', '8.000']
])
// Code block
await sock.sendCodeBlock(jid, 'console.log("hello")', undefined, {
language: 'javascript',
title: 'Example'
})
// Username
const result = await sock.checkUsername('my.username')
if (result.available) await sock.setUsername('my.username')
Installation
Install the package directly from npm:
npm install @hanzofc/baileys
Using yarn:
yarn add @hanzofc/baileys
Using pnpm:
pnpm add @hanzofc/baileys
Existing projects using baileys
If your project already imports the package using:
import makeWASocket from 'baileys'
you can install this fork using an npm alias:
npm install baileys@npm:@hanzofc/baileys
This allows existing imports using baileys to continue working without changing every import in your project.
Usage
import makeWASocket from '@hanzofc/baileys'
const sock = makeWASocket({
// options
})
If you installed the package using the npm alias:
npm install baileys@npm:@hanzofc/baileys
you can continue using:
import makeWASocket from 'baileys'
Authentication
Baileys uses an authentication state to store the credentials required to reconnect to WhatsApp.
A common setup is to use useMultiFileAuthState:
import makeWASocket, {
DisconnectReason,
useMultiFileAuthState
} from '@hanzofc/baileys'
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
const sock = makeWASocket({
auth: state
})
sock.ev.on('creds.update', saveCreds)
The authentication files should generally not be committed to Git.
Add your authentication directory to .gitignore:
auth_info_baileys/
SQLite auth state
As an alternative to many JSON files, the whole auth state can be stored in a single SQLite database:
import makeWASocket, { useSqliteAuthState } from '@hanzofc/baileys'
const { state, saveCreds, close } = await useSqliteAuthState('./auth')
const sock = makeWASocket({ auth: state })
sock.ev.on('creds.update', saveCreds)
Notes:
- Requires Node.js 22.5+ (built-in
node:sqlite). On older versions it throws and you should use useMultiFileAuthState instead.
- The first argument is either a
.db / .sqlite / .sqlite3 file path or a folder. For a folder the file is auth.db unless you set fileName.
- To migrate an existing
useMultiFileAuthState folder, pass migrateFromFolder. It is only used when the database has no credentials yet.
- Call
close() when you shut the socket down.
const { state, saveCreds } = await useSqliteAuthState('./auth', {
fileName: 'auth.db',
migrateFromFolder: './auth_info_baileys'
})
Add the database to .gitignore as well:
auth/
Connection Handling
You can listen for connection updates using connection.update:
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if (connection === 'close') {
console.log('connection closed')
const shouldReconnect =
(lastDisconnect?.error as any)?.output?.statusCode !== DisconnectReason.loggedOut
if (shouldReconnect) {
// reconnect
}
}
if (connection === 'open') {
console.log('connected')
}
})
Sending Messages
Text
await sock.sendMessage(jid, {
text: 'Hello World!'
})
Image
await sock.sendMessage(jid, {
image: { url: './image.jpg' },
caption: 'Hello!'
})
Video
await sock.sendMessage(jid, {
video: { url: './video.mp4' },
caption: 'Hello!'
})
Audio
await sock.sendMessage(jid, {
audio: { url: './audio.mp3' },
mimetype: 'audio/mpeg'
})
Document
await sock.sendMessage(jid, {
document: { url: './document.pdf' },
mimetype: 'application/pdf',
fileName: 'document.pdf'
})
Sticker
await sock.sendMessage(jid, {
sticker: { url: './sticker.webp' }
})
Replying to Messages
Messages can be quoted when sending a response:
await sock.sendMessage(
jid,
{
text: 'This is a reply'
},
{
quoted: message
}
)
Message Events
Incoming messages can be handled through messages.upsert:
sock.ev.on('messages.upsert', async ({ messages }) => {
for (const message of messages) {
console.log(message)
}
})
For example:
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0]
if (!msg.message) return
console.log(msg.message)
})
Groups
Get Group Metadata
const metadata = await sock.groupMetadata(jid)
console.log(metadata)
Create a Group
const group = await sock.groupCreate('My Group', [
'1234567890@s.whatsapp.net'
])
Add Participants
await sock.groupParticipantsUpdate(
jid,
['1234567890@s.whatsapp.net'],
'add'
)
Remove Participants
await sock.groupParticipantsUpdate(
jid,
['1234567890@s.whatsapp.net'],
'remove'
)
Promote Participants
await sock.groupParticipantsUpdate(
jid,
['1234567890@s.whatsapp.net'],
'promote'
)
Demote Participants
await sock.groupParticipantsUpdate(
jid,
['1234567890@s.whatsapp.net'],
'demote'
)
Presence
Presence can be updated using:
await sock.sendPresenceUpdate('available', jid)
Available presence values include:
available
unavailable
composing
recording
paused
For example:
await sock.sendPresenceUpdate('composing', jid)
await new Promise(resolve => setTimeout(resolve, 2000))
await sock.sendPresenceUpdate('paused', jid)
Contacts
You can request information about a WhatsApp user:
const result = await sock.onWhatsApp('1234567890')
console.log(result)
Profile Picture
const profilePicture = await sock.profilePictureUrl(
jid,
'image'
)
console.log(profilePicture)
Depending on the account and privacy settings, the profile picture may not be available.
Presence Updates
You can subscribe to presence updates:
sock.ev.on('presence.update', (update) => {
console.log(update)
})
Typing Indicators
To indicate that the bot is typing:
await sock.sendPresenceUpdate('composing', jid)
Stop typing:
await sock.sendPresenceUpdate('paused', jid)
Read Receipts
Messages can be marked as read:
await sock.readMessages([
message.key
])
Reactions