npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2026 – Pkg Stats / Ryan Hefner

@vanzxysenpai/baileys

v0.0.3

Published

VanzxyenpaiBaileysπŸƒ: an enhanced, ESM-only WhatsApp Web (multi-device) library for Node.js, crafted and maintained by VanzxyπŸƒ. Built on @whiskeysockets/baileys.

Readme



Changelog 0.0.3

  • Chat theme / wallpaper: change the chat theme for everyone with sock.setChatTheme(jid, theme), reset it with sock.clearChatTheme(jid), or send it as a message with sendMessage(jid, { chatTheme }). Supports solid colour (#RGB, #RRGGBB, #AARRGGBB, with separate light/dark values), stock image (with dimLevel), animated, default and already-uploaded custom image wallpapers.
  • Incoming theme changes: emitted as the chat-theme.update event (chatId, wallpaper, cleared).
  • Proto fixes: ChatSolidColorWallpaper colour fields are now fixed32 ARGB (backgroundLightArgb / backgroundDarkArgb), and animatedWallpaper is part of the ChatThemeSetting wallpaper oneof.

See Chat theme for usage examples.


Changelog 0.0.2

  • Voice/video calls (experimental, opt-in): VoipClient, ActiveCall, CallState β€” 1:1 and group calls, video, screen share and playlists; WASM call stack + WebRTC relay ported from ourin-baileys and levvsync-baileys; needs the optional @roamhq/wrtc peer dependency and ffmpeg.
  • Startup banner: VanzxyBanner.js, shown once per process; disable with VANZXY_BANNER=0.
  • Cleanup: repository links now point to github.com/vanzxysenpai/vanzxysenpaibaileys; internal change-log style code comments removed.

Changelog 0.0.1

First release of @vanzxysenpai/baileys, built on top of WhiskeySockets/Baileys 7.0.0-rc14.

  • Core: the rc14 socket, signal, USync and app-state layers, plus the albumParentKey send option (media album association).
  • Message builders: AIRich, Button / ButtonV2 / ButtonV3, Carousel, Poll, Album, Event, A2UI β€” all exported from the package root.
  • Interactive send layer: sendButtons, sendInteractiveMessage, native-flow expansion, group status, newsletter / username / status extras, stickerpacks.
  • Protocol coverage: a merged WAProto that contains every message class and field found in rc14 and several newer community protos (e.g. BotAvatarMetadata, MusicMessage.Lyrics, the newer ExternalAdReplyInfo, EventInviteMessage and SyncActionValue fields), with type declarations.
  • Stability & security: reconnect backoff, Bad MAC handler, connection watchdog, auto-reconnect, encrypted auth state, SQLite / Mongo / MySQL / PostgreSQL / Redis backends, and an anti force-close payload guard (createAnchorGuard).
  • Auth safety: useMultiFileAuthState writes creds.json atomically and keeps a creds.json.bak; a corrupt file is restored from the backup or moved aside instead of silently creating new credentials.
  • Utilities: media helpers (resizeImage, convertToOpusAudio, convertToWhatsAppVideo, getVideoThumbnail, probeMedia), TTLCache, social link-preview helpers, long-text / voice-note / humanized sending, mock socket for offline tests.
  • Packaging: ESM only, Node.js >= 20, pre-built lib/ with a .d.ts next to every file, no install-time scripts, no connect-time account actions and no hidden message attribution.

πŸ‘‘ Maintainer

Vanzxy


πŸƒ Why @vanzxysenpai/baileys?

This fork focuses on:

| | | |---|---| | 🧱 | Built on the current WhiskeySockets/Baileys 7.0.0-rc14 core | | πŸš€ | Better developer experience | | 🎯 | Extended native flow support | | πŸ“’ | Advanced status & broadcast features | | 🧩 | More interactive message types | | ⚑ | Cleaner implementation for bot developers | | πŸ”§ | Extra utilities not available in standard Baileys forks | | πŸ—„οΈ | Multiple auth & store backends out of the box (file, SQLite, MongoDB, MySQL, PostgreSQL, Redis) |


πŸ†š Comparison

How @vanzxysenpai/baileys stacks up against its own lineage and the wider Baileys fork ecosystem:

| Capability | @vanzxysenpai/baileys | @itsliaaa/baileys | WhiskeySockets/Baileys | |---|:---:|:---:|:---:| | Native Flow buttons (V1/V2/V3) | βœ… | βœ… | ⚠️ basic only | | Carousel messages | βœ… | ❌ | ❌ | | Rich response cards (AIRich) | βœ… | ❌ | ❌ | | Commerce flow (catalog/order/payment) | βœ… | ⚠️ partial | ❌ | | Multi-backend store (SQL/Mongo/Redis) | βœ… | ⚠️ file/SQLite only | ⚠️ in-memory only | | Full .d.ts TypeScript definitions | βœ… | ⚠️ partial | ⚠️ partial | | User sync queries (WAUSync) | βœ… | βœ… | βœ… | | Username management (check/set/pin/recommend) | βœ… | ❌ | ❌ | | Bot framework (middleware, session, stats) | βœ… | ❌ | ❌ |

Tabel ini menggambarkan fitur di level package, bukan benchmark performa. PR untuk memperbarui/mengoreksi tabel ini dipersilakan lewat Contributing.


🧰 Built With


πŸ”₯ Features

  • Native Flow
  • Buttons (V1 / V2 / V3)
  • Lists
  • Carousel Messages
  • Poll & Quiz Messages
  • Rich Response Messages (AIRich)
  • CTA / Reply / URL Buttons
  • Call Buttons
  • OTP Buttons
  • Authentication Buttons
  • Catalog Message
  • Order Details
  • Order Status
  • Review & Pay
  • Payment Status
  • Payment Method
  • Track Order
  • Reorder
  • Cancel Order
  • Group Status Support
  • Mention All
  • Lottie Sticker Support
  • Newsletter Support
  • ExternalAdReply Helper
  • View Once Support
  • Rich Formatting
  • Code Highlighting
  • Multi-file auth state
  • Single-file auth state
  • SQLite auth state
  • Cache-manager auth state
  • In-memory store
  • SQLite / MongoDB / MySQL / PostgreSQL / Redis store adapters
  • User sync queries (WAUSync)
  • Presence / status / device lookup
  • Event buffer for high-volume bots
  • Full TypeScript definitions (.d.ts)
  • Anti-delete detection
  • Message search helpers
  • Auto-reply engine
  • Scheduling helpers
  • Message retry manager

✨ Exclusive Vanzxy Enhancements

Audio Group Status Fix

Audio status uses a more compatible implementation to avoid unsupported-version errors on older WhatsApp clients.

AIRich β€” the rich-response message builder

A chainable builder (AIRich, also exported as AIVanzxy / LeafRich / VanzxyAI / VanzxyRich) with 40+ add*()/set*() methods covering headings, formatted text (hyperlinks/citations/LaTeX), code blocks, tables, image/video/product/post cards, task & progress cards, tip banners, and quick-reply suggestions β€” the kind of rich card layout you'd normally only see from an official AI/assistant-style bot. See Usage Examples below.

Native Flow Expansion

Buttons & Actions

  • cta_reminder
  • cta_cancel_reminder
  • otp_button
  • authentication_button
  • call_button
  • url_button
  • reply_button
  • voice_call
  • video_call_button

Commerce Flow

  • catalog_message
  • mpm
  • card_message
  • order_details
  • order_status
  • review_and_pay
  • payment_status
  • payment_method

Navigation & Misc

  • address_message
  • send_location
  • track_order
  • reorder
  • cancel_order
  • clear_chat
  • navigateToScreen
  • flow_action

System Notification Filter

Messages include:

message.isSystemNotification

Useful for filtering:

  • E2E notices
  • Meta service notices
  • Other system-generated messages

πŸ“¦ Installation

npm install @vanzxysenpai/baileys

Directly from GitHub:

npm install github:vanzxysenpai/vanzxysenpaibaileys

Requires Node.js 20+ β€” enforced through the engines field in package.json.

Optional peer dependencies

Everything below is optional β€” the socket works without any of them. Install only what the features you use need; missing ones fail with a clear install hint instead of a silent crash.

| Package | Unlocks | |---|---| | sharp | Fast image resizing/processing (used by the message builders' Toolkit.resize) | | @napi-rs/image | Lighter native alternative to sharp for image ops | | jimp | Pure-JS image fallback when neither of the above is installed | | fluent-ffmpeg | Audio/video conversion for media messages | | link-preview-js | Rich link previews for URLs in outgoing text messages | | better-sqlite3 | SQLite auth state, SQLite store adapter, and the Bot Framework's SQLiteStore/StatsManager | | node-webpmux | Packname/author EXIF metadata on stickers made via MediaManager.convertToSticker() β€” not needed for plain sticker conversion | | mongodb | MongoDB store adapter | | mysql2 | MySQL store adapter | | pg | PostgreSQL store adapter | | ioredis | Redis store adapter |


πŸš€ Quick Start

import { makeWASocket, useMultiFileAuthState } from '@vanzxysenpai/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')

const sock = makeWASocket({
    auth: state
})

// persist credentials whenever Baileys updates them
sock.ev.on('creds.update', saveCreds)

sock.ev.on('connection.update', (update) => {
    const { connection, qr } = update

    // `printQRInTerminal` is deprecated upstream β€” render the QR yourself,
    // e.g. with the `qrcode-terminal` package:
    //   import qrcode from 'qrcode-terminal'
    //   if (qr) qrcode.generate(qr, { small: true })
    if (qr) console.log('Scan this QR:', qr)

    if (connection === 'open') console.log('πŸƒ Connected!')
})

sock.ev.on('messages.upsert', ({ messages }) => {
    const msg = messages[0]
    if (!msg.message || msg.key.fromMe) return
    console.log('New message from', msg.key.remoteJid)
})

πŸ” Authentication

Four auth-state backends ship out of the box. All return the same { state, saveCreds } shape expected by makeWASocket({ auth }), so they're drop-in interchangeable.

| Function | Storage | Best for | |---|---|---| | useMultiFileAuthState(folder) | One JSON file per key, on disk | Default choice β€” simple, debuggable, works everywhere | | useSingleFileAuthState(fileName) | One JSON file, on disk | Small bots where a single file is easier to manage/back up | | useSqliteAuthState(opts) | SQLite (better-sqlite3) | Bots that already use SQLite, or want auth in one embedded DB file | | useCacheManagerAuthState(store, sessionKey) | Any cacheable-compatible store | Multi-session hosting panels, Redis-backed setups |

import { makeWASocket, useMultiFileAuthState } from '@vanzxysenpai/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')
const sock = makeWASocket({ auth: state })
sock.ev.on('creds.update', saveCreds)
// SQLite variant
import { makeWASocket, useSqliteAuthState } from '@vanzxysenpai/baileys'

const { state, saveCreds } = await useSqliteAuthState({ database: './auth.db' })
const sock = makeWASocket({ auth: state })
sock.ev.on('creds.update', saveCreds)

useMultiFileAuthState also exports pruneStaleAuthFiles(folder, options) to clean up old sender-key files on a schedule β€” useful for long-running bots that accumulate thousands of stale key files.


πŸ—„οΈ Store Backends

makeInMemoryStore() from lib/Store gives you the classic in-memory chat/contact/message cache. For anything that needs to survive a restart, makePersistentStore() (from PersistentStore.js) wraps one of five backends behind the same interface:

| Backend | Function | |---|---| | SQLite | createSqliteStoreAdapter(opts) | | MongoDB | createMongoStoreAdapter(opts) | | MySQL | createMysqlStoreAdapter(opts) | | PostgreSQL | createPostgresStoreAdapter(opts) | | Redis | createRedisStoreAdapter(opts) |

import { makeWASocket, makeInMemoryStore } from '@vanzxysenpai/baileys'

const store = makeInMemoryStore({})
store.readFromFile('./baileys_store.json')
setInterval(() => store.writeToFile('./baileys_store.json'), 10_000)

const sock = makeWASocket({ /* ...auth etc */ })
store.bind(sock.ev)

πŸ’‘ Usage Examples

Buttons & Native Flow

import { Button } from '@vanzxysenpai/baileys'

await new Button(sock)
    .setTitle('Promo Spesial')
    .setBody('Diskon 20% cuma hari ini')
    .setFooter('@vanzxysenpai/baileys')
    .addReply('Klaim Sekarang', 'claim_promo')
    .addUrl('Lihat Katalog', 'https://example.com/catalog')
    .addCall('Hubungi Kami', '628123456789')
    .send(jid)

Poll

import { Poll } from '@vanzxysenpai/baileys'

await new Poll(sock)
    .setName('Mau makan apa hari ini?')
    .addOptions(['Nasi Goreng', 'Mie Ayam', 'Bakso'])
    .setSelectable(1)
    .send(jid)

Carousel

Each card must be built with Button(...).toCard() first β€” a carousel card is really just a button card with an image/video header.

import { Button, Carousel } from '@vanzxysenpai/baileys'

const cardA = await new Button(sock)
    .setImage('https://example.com/a.jpg')
    .setTitle('Produk A')
    .addUrl('Lihat', 'https://example.com/a')
    .toCard()

const cardB = await new Button(sock)
    .setImage('https://example.com/b.jpg')
    .setTitle('Produk B')
    .addUrl('Lihat', 'https://example.com/b')
    .toCard()

await new Carousel(sock)
    .setBody('Pilih salah satu produk di bawah ini')
    .addCard([cardA, cardB])
    .send(jid)

AIRich β€” rich response cards

import { AIRich } from '@vanzxysenpai/baileys'

await new AIRich(sock)
    .addHeading('Ringkasan Order')
    .addText('Pesananmu sedang diproses.')
    .addTable([
        ['Item', 'Qty'],
        ['Kopi Susu', '2']
    ])
    .addTip('Pesanan biasanya siap dalam 15 menit')
    .addSuggest('Lacak Order')
    .send(jid)

AIRich supports { id, insertAt } on every add*()/set*() call, so you can insert a block relative to one you added earlier instead of always appending to the end β€” handy for streaming/edit-in-place style responses combined with sendEdit(jid, id).

Other builders worth knowing about: ButtonV2 (simpler quick-reply-only buttons), ButtonV3 (loadFrom(msg) to edit an existing template message in place), and Toolkit (static helpers: Toolkit.resize(), Toolkit.fetchBuffer(), Toolkit.waitAllPromises(), Toolkit.extractIE() for parsing [label](url) links/citations/LaTeX out of plain text).

πŸ“ Builders Folder Map (lib/Builders/)

Every message builder lives in its own file under lib/Builders/, so you can trace exactly where a class comes from instead of digging through one giant MessageBuilder.js. index.js is just the barrel file that re-exports everything below (plus their aliases) for the top-level import { ... } from '@vanzxysenpai/baileys' syntax.

| File | Exports | What it's for | |---|---|---| | shared.js | Toolkit, BaseBuilder, RowBuilder | The shared foundation every other builder is built on. BaseBuilder holds the common chainable send()/context-info plumbing, RowBuilder is the shared row/section helper, and Toolkit is the static-helper grab bag (resize, fetchBuffer, waitAllPromises, extractIE, media-duration/preview helpers). Nothing here is meant to be instantiated directly in bot code β€” it exists so Button, Poll, Carousel, etc. don't each reimplement the same plumbing. | | Button.js | Button, CardBuilder | The main interactive/native-flow button builder β€” headers (image/video/document), CTA helpers (addUrl, addCall, addReply, and the wider native-flow set), and .toCard() to turn a button message into a Carousel card. | | ButtonV2.js | ButtonV2 | A lighter-weight variant limited to simple quick-reply buttons β€” reach for this when you don't need the full native-flow surface of Button. | | ButtonV3.js | ButtonV3 | Built around loadFrom(msg) β€” loads an existing templateMessage (e.g. one you fetched or that was quoted) so you can edit it in place instead of building one from scratch. | | Carousel.js | Carousel | Chains Button(...).toCard() results into a swipeable card carousel. Capped at Carousel.MAX_CARDS (10) since WhatsApp silently truncates anything beyond that. | | Poll.js | Poll | Poll/vote message builder β€” question, options, single/multi-select, hidden-voter mode, correct-answer marking, expiry. | | AIRich.js | AIRich (+ aliases ORich, AIVanzxy, LeafRich, VanzxyAI, VanzxyRich, RichVanzxy) | The rich AI-assistant-style response builder described above β€” headings, formatted text, tables, media/product/post cards, task/progress cards, tip banners, quick-reply suggestions. | | A2UI.js | A2UI, sendA2UIWidget | Lower-level A2UI/Bloks widget builder. Builds the flat components tree (Column/Row β†’ children, Card/Button β†’ child, Modal β†’ trigger/content) that Bloks widgets expect and sends it through the same getBizBinaryNode() path as Button/ButtonV2, so the wire-level node always matches the button names actually sent. | | VanzxyBaileys.js | VanzxyBaileys | A unified builder hub β€” one object that wraps all the builders above behind short method names (.button(), .buttonV2(), .buttonV3(), .carousel(), .poll(), .airich(), .a2ui()), plus PascalCase aliases (.Button(), .Carousel(), .Poll(), .AIRich(), .A2UI()) for developers who prefer that naming style. Nothing new is implemented here β€” it's purely a single entry point over the individual classes. | | index.js | everything above, plus MESSAGE_BUILDER_VERSION | The barrel file β€” re-exports every builder and its aliases so import { Button, Poll, AIRich, VanzxyBaileys } from '@vanzxysenpai/baileys' works without reaching into individual files. MESSAGE_BUILDER_VERSION tracks the builder API surface's own version, independent of the package version. |

Unified hub example β€” useful if you'd rather carry one object around than import each builder individually:

import { VanzxyBaileys } from '@vanzxysenpai/baileys'

const vx = new VanzxyBaileys(sock)

await vx.button()
    .setTitle('Promo Spesial')
    .addReply('Klaim Sekarang', 'claim_promo')
    .send(jid)

await vx.poll()
    .setName('Mau makan apa hari ini?')
    .addOptions(['Nasi Goreng', 'Mie Ayam'])
    .send(jid)

Chat theme / wallpaper (0.0.3)

Full runnable script β€” change, send and clear the chat theme, and listen for theme changes from other people:

import { makeWASocket, useMultiFileAuthState } from '@vanzxysenpai/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')
const sock = makeWASocket({ auth: state })
sock.ev.on('creds.update', saveCreds)

// incoming theme changes (from you on another device, or from the other side)
sock.ev.on('chat-theme.update', (u) => {
    // u = { chatId, author, authorAlt, fromMe, messageTimestamp, timestamp,
    //       cleared, colorSchemeId, wallpaper, setting }
    if (u.cleared) return console.log(`${u.chatId}: theme reset to default`)
    console.log(`${u.chatId}: ${u.author} set`, u.wallpaper)
    // wallpaper examples:
    //   { type: 'solidColor', light: '#FF1B5E20', dark: '#FF1B5E20', doodle: true }
    //   { type: 'stockImage', id: '...', dimLevel: 0.3 }
})

sock.ev.on('connection.update', async ({ connection }) => {
    if (connection !== 'open') return
    const jid = '[email protected]'   // a private chat or a group JID

    // 1) solid colour β€” one colour for light + dark mode
    await sock.setChatTheme(jid, { solidColor: '#1B5E20' })      // #RGB | #RRGGBB | #AARRGGBB | 0xAARRGGBB

    // 2) solid colour β€” separate light / dark, with doodle pattern colours
    await sock.setChatTheme(jid, {
        solidColor: {
            light: '#E8F5E9',
            dark: '#0B2A12',
            doodle: { light: '#C8E6C9', dark: '#1B5E20' }        // or `doodle: true` / `false`
        }
    })

    // 3) stock image (use an id taken from a real incoming `chat-theme.update`) with dimming 0..1
    await sock.setChatTheme(jid, { stockImage: { id: '<stock id>', dimLevel: 0.3 } })

    // 4) animated wallpaper
    await sock.setChatTheme(jid, { animatedWallpaper: { id: '<animated id>', dimLevel: 0.2 } })

    // 5) WhatsApp default wallpaper (optionally with the doodle pattern)
    await sock.setChatTheme(jid, { defaultWallpaper: { doodle: true } })

    // 6) already-uploaded custom image (this package does not upload or decrypt wallpapers)
    await sock.setChatTheme(jid, {
        customImage: { directPath, mediaKey, fileEncSha256, fileSha256, dimLevel: 0.25 }
    })

    // 7) same thing through sendMessage
    await sock.sendMessage(jid, { chatTheme: { solidColor: { light: '#FFFFFF', dark: '#000000' } } })

    // 8) reset to the default theme (all three are equivalent)
    await sock.clearChatTheme(jid)
    await sock.setChatTheme(jid, { clear: true })
    await sock.setChatTheme(jid, null)
})

Rules: pass exactly one wallpaper kind per call (defaultWallpaper, solidColor, stockImage, animatedWallpaper or customImage) β€” more than one throws a TypeError, as does an invalid colour string. setChatTheme / clearChatTheme resolve to { message, messageId }. The helpers colorToArgb, argbToHex, buildChatThemeSetting, generateChatThemeContent and describeChatThemeSetting live in lib/Utils/chat-theme.js.

Rich message β€” sendMessage(jid, { richMessage }) (0.0.3)

Declarative AI-style rich response. Every field is optional; combine the ones you need:

await sock.sendMessage(jid, {
    richMessage: {
        title: 'Laporan harian',
        text: 'Server **aman**. Dokumentasi: [buka docs](https://example.com/docs) [](https://example.com/sumber)',
        code: { language: 'js', code: "console.log('halo dari Evernight')" },
        table: [
            ['Layanan', 'Status', 'Latency'],        // first row = header
            ['API', 'OK', '42 ms'],
            ['Database', 'OK', '8 ms']
        ],
        image: 'https://example.com/chart.png'
    }
})

Link syntax inside text: [label](url) is a hyperlink, [](url) is a citation, [expr|w|h|font|pad]<imageUrl> is a LaTeX image. Other supported keys: video, tip, footer, suggestions, sources, html, hscroll, hscrollV2, post, reels, productSingle, productMultiple, footerActionV2, response_id, editrich (see lib/Utils/rich-message.d.ts). The same payload can be built without sending via generateRichMessage(rich). How it renders depends on the WhatsApp client version.

Raw message β€” sendMessage(jid, { rawMessage }) (0.0.3)

Send a pre-built proto.Message object as-is (no builder, no conversion) β€” useful for message types that have no helper yet:

// plain text, built by hand
await sock.sendMessage(jid, { rawMessage: { extendedTextMessage: { text: 'Halo dari rawMessage' } } })

// a location
await sock.sendMessage(jid, {
    rawMessage: {
        locationMessage: { degreesLatitude: -6.2, degreesLongitude: 106.816666, name: 'Jakarta' }
    }
})

rawMessage is created with proto.Message.create(...), so field names must match WAProto. productMessage and orderMessage sent this way now get the right biz node automatically.



πŸ“ž Voice Calls (experimental)

Voice/video call support through a WASM call stack + WebRTC relay (ported from ourin-baileys and levvsync-baileys). It is opt-in: nothing starts until you create a VoipClient, and it never opens a session of its own β€” it reuses the socket you already have. Requires the optional @roamhq/wrtc peer dependency, plus ffmpeg for audio/video sources.

import { VoipClient } from '@vanzxysenpai/baileys'

// after connection.update reports 'open'
const voip = new VoipClient({ socket: sock })      // or: new VoipClient(); await voip.connectWithSocket(sock)
await voip.connect()

// 1:1 call (a call that is still active is ended and replaced)
const call = await voip.call('628123456789', { audioSource: './song.mp3', video: false })
call.on('ringing', () => console.log('Ringing...'))
call.on('connected', () => call.enqueue(['./next.mp3']))
call.on('ended', (reason) => console.log('Call ended:', reason))

// group call, and joining one that someone else started
await voip.callGroup('[email protected]', { video: true, videoSource: './clip.mp4' })
sock.ev.on('call', async ([offer]) => {
  if (offer.isGroup && offer.status === 'offer') {
    await voip.joinGroupCall({ callId: offer.id, groupJid: offer.groupJid, callCreatorJid: offer.from })
  }
})

voip.acceptCall()      // answer an incoming 1:1 call
voip.attach(newSock)   // after a reconnect
voip.disconnect()

Full runnable script (1:1 call, group call, incoming-call handling, reconnect):

import { makeWASocket, useMultiFileAuthState, VoipClient } from '@vanzxysenpai/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')
let sock = makeWASocket({ auth: state })
let voip

const wire = (s) => {
    s.ev.on('creds.update', saveCreds)
    s.ev.on('connection.update', async ({ connection }) => {
        if (connection !== 'open') return
        if (!voip) {
            voip = new VoipClient({ socket: s })
            await voip.connect()
        } else {
            voip.attach(s)                       // reconnect: re-bind the new socket
        }

        const call = await voip.call('628123456789', { audioSource: './song.mp3', video: false })
        call.on('ringing', () => console.log('Ringing...'))
        call.on('connected', () => call.enqueue(['./next.mp3']))
        call.on('ended', (reason) => console.log('Call ended:', reason))
    })
    s.ev.on('call', async ([offer]) => {
        if (!voip || offer.status !== 'offer') return
        if (offer.isGroup) {
            await voip.joinGroupCall({ callId: offer.id, groupJid: offer.groupJid, callCreatorJid: offer.from })
        } else {
            voip.acceptCall()                    // answer the incoming 1:1 call
        }
    })
}
wire(sock)

process.on('SIGINT', () => { voip?.disconnect(); process.exit(0) })

ActiveCall also has play / enqueue / skip / queued / nowPlaying, the same with a Video suffix, startScreenShare() / stopScreenShare(), and the events track, trackend, videotrack, videotrackend and idle. Audio sources are anything ffmpeg can read (or 'silence'); video sources can also be 'black' or 'lavfi:<graph>'.

Status: tested against the real WASM engine and ffmpeg, but with a mock socket β€” group, video and screen-share calls have not been verified against live WhatsApp. Check the fields of the incoming call event (id, from, groupJid, isGroup) before wiring joinGroupCall. Use calls responsibly: unsolicited or bulk calling is the fastest way to get a number restricted by WhatsApp.


πŸ”Ž User Sync Queries

WAUSync (USyncQuery / USyncUser + protocols) lets you check things like WhatsApp registration, device lists, status, and username info for a JID before you message it β€” the same mechanism behind sock.onWhatsApp().

import { USyncQuery, USyncUser, USyncContactProtocol } from '@vanzxysenpai/baileys'

const query = new USyncQuery()
    .withContext('interactive')
    .withMode('query')
    .withUser(new USyncUser().withPhone('628123456789'))

query.protocols.push(new USyncContactProtocol())

const result = await sock.executeUSyncQuery(query)

Available protocols: USyncContactProtocol, USyncDeviceProtocol, USyncStatusProtocol, USyncUsernameProtocol, USyncDisappearingModeProtocol, UsyncBotProfileProtocol, UsyncLIDProtocol.

Also available (ported from nexustech): USyncBusinessProtocol, USyncPictureProtocol, USyncTextStatusProtocol, USyncSidelistProtocol, USyncFeatureProtocol, each with a chainable helper on USyncQuery:

const query = new USyncQuery()
    .withContext('interactive')
    .withMode('query')
    .withUser(new USyncUser().withId('[email protected]'))
    .withBusinessProtocol()      // -> { verifiedName, verifiedLevel, profileTag, pnJid }
    .withPictureProtocol()       // -> { id, directPath, hash }
    .withTextStatusProtocol()    // -> { text, emoji, setAt, expiresAt }

const result = await sock.executeUSyncQuery(query)

πŸ‘€ Username Management

High-level wrappers around WhatsApp's username feature (the @username handle you can set instead of exposing your phone number), sitting on top of USyncUsernameProtocol. Query IDs are captured from live WA Web sessions β€” if a call starts throwing unexpected response structure, WA has rotated them and they need re-capturing.

// Check availability + get suggestions if taken
const check = await sock.checkUsername('vanzxy')
// { available: true, username: 'vanzxy' }
// or: { available: false, suggestions: [...], rejectionReasons: [...] }

// Claim a username
await sock.setUsername('vanzxy', { source: sock.USERNAME_SOURCE.USER_INPUT })

// Lock it behind a PIN so it can't be changed without one
await sock.setUsernamePin('123456')

// Read your own username / drop it
const mine = await sock.getMyUsername()
await sock.deleteUsername()

// Resolve a username to a JID (USync-based, like onWhatsApp() but by username)
const user = await sock.findUserByUsername('someone')
// { jid: '[email protected]', contact: false }

// Batch-resolve usernames for a list of known contacts
const usernames = await sock.fetchContactUsernames(jid1, jid2, jid3)

// Get WA's own suggestions (e.g. for onboarding flows)
const recs = await sock.getUsernameRecommendations()

0.0.3 additions β€” complete example:

// Which of these usernames belong to a WhatsApp account? ("name", "@name" or { username, pin })
const found = await sock.onWhatsAppUsername('vanzxy', '@someone', { username: 'private_user', pin: '123456' })
// -> [{ jid: '[email protected]', exists: true }, ...]   (only matches are returned)

// Reverse lookup: JIDs -> usernames (only contacts that actually have a username are returned)
const names = await sock.getUsernames('[email protected]', '[email protected]')
// -> [{ jid: '[email protected]', username: 'vanzxy' }]

// Remove the PIN from your own username β€” resolves `true` on SUCCESS
const removed = await sock.removeUsernamePin()
console.log('PIN removed:', removed)

Requires a Community/Contact-tier account in good standing β€” accounts under WA's usual restrictions for new/unverified numbers may see INVALID or empty suggestions regardless of the username's actual availability.


πŸ€– Bot Framework

An optional, higher-level layer on top of the raw socket: middleware routing, a !command dispatcher, a message queue that survives disconnects, exponential-backoff auto-reconnect, per-JID session storage, group activity stats, and media (sticker/voice-note) conversion helpers β€” so a new bot project doesn't have to hand-roll session/context management every time.

Needs the better-sqlite3 peer dependency (session + stats storage) and fluent-ffmpeg (sticker/voice-note conversion, already listed above) β€” both fail with an install hint rather than crashing if you use a Framework feature that needs them without installing them first.

import { Bot } from '@vanzxysenpai/baileys'

const bot = new Bot({
    socketConfig: { printQRInTerminal: true },
    dbPath: './bot.db',   // sessions + stats, defaults to 'baileys_store.db'
    enableStats: true     // group message/sticker leaderboards + ghost detection
})

bot.command('!ping', async (ctx) => {
    await ctx.reply({ text: 'pong' })
})

bot.command('!sticker', async (ctx) => {
    if (!ctx.quoted?.imageMessage) return ctx.reply({ text: 'Reply to an image with !sticker' })
    // ctx.replySticker() handles the WebP conversion for you
    await ctx.replySticker(imageBuffer, { packname: 'Vanzxy Pack', author: 'you' })
})

bot.onText(async (ctx) => {
    // ctx.session() / ctx.setSession() / ctx.updateSession() / ctx.clearSession()
    // persist small per-chat state (e.g. multi-step flows) to SQLite automatically
    const state = ctx.session()
    if (state?.awaitingReply) {
        ctx.updateSession((s) => ({ ...s, awaitingReply: false }))
    }
})

await bot.start()

Context, SessionManager, StatsManager, MediaManager, and SQLiteStore are also exported individually if you only need one piece rather than the full Bot class.

These files ship as plain .js for now β€” hand-written .d.ts declarations for the Framework module haven't been added yet, unlike the rest of this fork's fully-typed surface.


🧩 Utility Modules

A sample of the utilities exported from lib/Utils beyond the message builders above:

| Module | What it does | |---|---| | anti-delete | Detect and recover messages the sender deleted for everyone | | auto-reply | Simple keyword/pattern-based auto-responder engine | | message-search | Search cached/stored messages, peeling off ephemeral/view-once wrappers first | | message-retry-manager | Handles WhatsApp's retry-receipt protocol for undecryptable messages | | scheduling | Schedule messages/actions for later delivery | | business | Business-profile & catalog helpers | | chat-control | Pin, mute, archive, and mark-read/unread helpers | | chat-history-helpers | Work with synced chat history payloads | | link-preview | Generate link preview metadata for outgoing messages | | stickerpack | Build and send sticker packs (including animated/Lottie) | | templates | Legacy WhatsApp Business template message helpers | | vcard | Build vCard (contact card) payloads | | status | Post and manage WhatsApp Status updates | | event-buffer | Buffers/coalesces high-volume socket events for heavier bots | | reconnect-backoff | computeReconnectDelay() / createReconnectBackoff() β€” full-jitter exponential backoff (2s base, 15 min cap) | | bad-mac-handler | Detect/count "Bad MAC" (out-of-sync Signal session), safe-wrap async fns, optional session-* / sender-key-* cleanup | | connection-watchdog | setupConnectionWatchdog() / opt-in makeWASocket({ connectionWatchdog: true }) liveness probe | | auto-reconnect | autoReconnect(factory, opts) β€” drop-in reconnect manager (never reconnects after loggedOut) | | auth-secure | Encrypted auth state at rest (AES-256-GCM), backup/restore, integrity checks, pairing/QR guards, secret redaction | | humanizer | sendHumanized() β€” typing presence + length-based delay + per-chat send queue | | mock-socket | createMockSocket() β€” offline stand-in for sock, to test bot logic without a WhatsApp account | | meta-ai | askMetaAI() β€” send a prompt to Meta AI and await the reply (experimental) | | meta-ai-msmsg | Experimental, unwired msmsg decrypt helpers (see the note in NOTICE.md / changelog) | | qr-terminal | printQRIfNecessaryListener(ev, logger) β€” opt-in terminal QR printer (lazy qrcode-terminal, returns an unsubscribe fn) | | disconnect-reason | mapDisconnectReason(), isFatalDisconnect(), shouldClearAuth(), shouldReconnect(), getDisconnectInfo() β€” stable names for disconnect codes | | phone-utils | validateE164(), jidToPhone(), phoneToJid() | | text-tools | parseMentions(), extractGroupInviteCode(), joinGroupViaLink() | | pairing-utils | normalizePairingCode(), formatPairingCode(), pairingErrorCode(), isRateLimitError(), isCustomPairingError() | | group-metadata-cache | isUsableGroupMetadata() β€” relay uses it to refetch cached groups that lack a valid addressingMode | | username | validateUsername(), isUsernamePin(), displayUsername() β€” client-side username validation | | jid-tools | getPhoneNumber(), resolveSenderPn(), getLidForPhone() β€” LID <-> phone number via the persistent LID mapping | | tag | tagAll(), hideTag(), buildTagContent() β€” mention every group member | | ffmpeg-path | setFfmpegPath(), resolveFfmpegPath(), requireFfmpegPath() β€” one resolver for the ffmpeg binary (FFMPEG_PATH, ffmpeg-static, system PATH) | | voice-note | sendVoiceNote(), buildVoiceNoteContent() β€” converts to mono 16 kHz Opus/OGG and sends as PTT | | anchor-guard | createAnchorGuard(sock, opts), detectBug(message) β€” detects payloads that crash / force-close WhatsApp clients (invisible-char floods, mention bombs, oversized native-flow, deep or circular structures), optional auto-delete / block | | media-processor | resizeImage, convertToWhatsAppVideo, convertToOpusAudio, getVideoThumbnail, probeMedia, getMp4Duration β€” heavy deps (sharp / ffmpeg) are loaded lazily | | ttl-cache | TTLCache β€” small LRU cache with per-entry TTL | | link-preview-metadata | buildSocialPreview, readSocialPreview, videoEndCard, SocialMediaPostType β€” social-post style link previews | | text-format | splitText(), whatsappify(), sendLongText() β€” chunk long text / convert markdown to WhatsApp formatting | | lock-manager | makeLockManager() β€” deterministic keyed lock manager | | migrate-auth-state | migrateAuthState({ from, to }) β€” copy creds + keys between auth stores (needs keys.list) | | passkey | getPasskeyRequestState(node) β€” passkey companion-linking request parsing |

Every module above ships a matching .d.ts, so your editor will show full hover-docs regardless of which ones you import.

Stability & security quick start

import makeWASocket, { autoReconnect, useEncryptedFileAuthState, sendHumanized } from '@vanzxysenpai/baileys'

// creds + keys encrypted on disk (legacy plaintext folders are read and migrated on next save)
const { state, saveCreds } = await useEncryptedFileAuthState('./auth', { password: process.env.AUTH_PASSWORD })

const manager = autoReconnect(() => makeWASocket({ auth: state }), {
    onSocket: (sock) => {
        sock.ev.on('creds.update', saveCreds)
        sock.ev.on('messages.upsert', async ({ messages }) => {
            await sendHumanized(sock, messages[0].key.remoteJid, { text: 'pong' })
        })
    },
    onLoggedOut: () => console.log('session logged out β€” wipe ./auth and re-pair'),
})
await manager.start()

Test bot logic offline with createMockSocket():

import { createMockSocket } from '@vanzxysenpai/baileys'

const mock = createMockSocket()
myBotSetup(mock.sock)                              // your real bot code, unchanged
await mock.receiveText('[email protected]', '!ping')
const out = await mock.waitForReply()

πŸ›  Recommended Environment

| Requirement | Version | |---|---| | Node.js | 20+ | | Module system | ESM | | WhatsApp | Latest Multi Device |


πŸ“˜ TypeScript Support

Every file in lib/ ships a matching .d.ts, including all Types/* definitions (Auth, Chat, Contact, Events, GroupMetadata, Message, Product, Signal, USync, and more). No @types/ package needed β€” plain import { ... } from '@vanzxysenpai/baileys' gets full autocomplete in TS or JS-with-checkJS projects.


πŸ“š Fork Lineage

@vanzxysenpai/baileys
└── WhiskeySockets/Baileys (7.0.0-rc14)

Additions ported from other community forks keep their original credit β€” see Credits and NOTICE.md.

Respect to all original maintainers and contributors.


❓ FAQ & Troubleshooting

Cek connection.update untuk field lastDisconnect.error. Kalau status code-nya 401 (loggedOut), sesi memang sudah invalid dan perlu scan ulang QR β€” jangan auto-reconnect di kondisi ini. Untuk status lain (428, 440, dsb.), reconnect dengan backoff biasanya cukup.

printQRInTerminal sudah deprecated di upstream Baileys β€” pastikan kamu render QR sendiri dari event qr (lihat contoh di Quick Start). Kalau QR muncul tapi gagal linking, biasanya karena versi WA Web (version di makeWASocket) sudah kedaluwarsa; fetch versi terbaru lewat fetchLatestBaileysVersion().

Umumnya terjadi kalau folder auth state korup atau sesi dipakai di lebih dari satu proses secara bersamaan. Pastikan hanya satu instance yang menulis ke folder auth state yang sama, dan pertimbangkan pruneStaleAuthFiles() untuk membersihkan sender-key lama secara berkala.

Kalau pakai makeInMemoryStore(), cache chat/message/contact akan terus tumbuh tanpa batas. Untuk bot yang jalan lama, pertimbangkan pindah ke salah satu backend makePersistentStore() (SQLite/Redis/dst) dan pakai event-buffer untuk meredam lonjakan event di trafik tinggi.


🀝 Contributing

Kontribusi dipersilakan, terutama untuk perbaikan bug, dokumentasi, dan enhancement pada MessageBuilder / AIRich.

  1. Fork repo ini, buat branch dari main (feat/nama-fitur atau fix/nama-bug)
  2. Pastikan perubahan tetap ESM-only dan menyertakan/menyesuaikan .d.ts terkait
  3. Uji perubahan pada minimal satu jalur auth state + satu store backend sebelum PR
  4. Buka Pull Request dengan deskripsi singkat: apa yang berubah dan kenapa

Untuk laporan bug, sertakan versi Node.js, cara reproduksi, dan potongan log lastDisconnect.error bila relevan.


πŸ™ Credits

  • Nixel (with contributions from Ahmad tumbuh kembang) β€” base implementation of the MessageBuilder (AIRich / Button / Carousel / Toolkit), originally "NIXCODE β€” Advanced WhatsApp Interactive Message Builder"
  • vinikjkkj (zapo) β€” button/list addon-kind resolution logic
  • QueenAnya (@queenanya/baileys) β€” interactive/native-flow button send layer
  • JAPofc (@japofc/baileys) β€” auto-reconnect manager, encrypted auth state / security pack, humanized sender, offline mock socket, Meta AI helper
  • nexustechpro2 (@nexustechpro/baileys) β€” extra USync protocols (Business, Picture, TextStatus, Sidelist, Feature)
  • lpzeravk / systemzero β€” reconnect backoff, Bad MAC handler, connection watchdog
  • WhiskeySockets/Baileys & @itsliaaa/baileys β€” upstream base

Full details and license terms per component: see NOTICE.md.



⚠️ Disclaimer

This project is an independent fork. Use responsibly and follow WhatsApp Terms of Service.


πŸ“¦ Package Contents

The published package is intentionally limited to the runtime library, generated WhatsApp protocol bindings, installation/runtime helpers, legal files, and documentation. The files field in package.json controls what is included in the published package.

@vanzxysenpai/baileys/
β”œβ”€β”€ lib/                     # Main runtime implementation and TypeScript declarations
β”‚   β”œβ”€β”€ Builders/            # Message and interactive builders
β”‚   β”œβ”€β”€ Defaults/            # Default configuration and constants
β”‚   β”œβ”€β”€ Signal/              # Authentication and Signal-related implementation
β”‚   β”œβ”€β”€ Socket/              # WhatsApp Web socket/runtime layer
β”‚   β”œβ”€β”€ Store/               # Store implementations and helpers
β”‚   β”œβ”€β”€ Types/               # Public and internal type definitions
β”‚   β”œβ”€β”€ Utils/               # Runtime utilities
β”‚   β”œβ”€β”€ WABinary/            # Binary node encoding/decoding helpers
β”‚   β”œβ”€β”€ WAM/                 # WhatsApp Web protocol helpers
β”‚   β”œβ”€β”€ WAUSync/             # USync/query functionality
β”‚   β”œβ”€β”€ index.js             # Main package entrypoint
β”‚   └── index.d.ts           # Main TypeScript entrypoint
β”œβ”€β”€ WAProto/                 # Generated WhatsApp protobuf runtime + declarations
β”œβ”€β”€ NOTICE.md                # Third-party attribution and notices
β”œβ”€β”€ VanzxyBanner.js          # Package/startup banner helper
β”œβ”€β”€ LICENSE                  # MIT license
└── README.md                # Project documentation

The package entry points are defined by package.json:

{
  "type": "module",
  "main": "./lib/index.js",
  "module": "./lib/index.js",
  "types": "./lib/index.d.ts"
}

The package also exposes the generated WAProto surface and selected lib/* paths through the exports map. Consumers should prefer the documented public exports rather than depending on undocumented internal file paths.

Published files

The current files allowlist is:

lib/**/*
WAProto/**/*
NOTICE.md
LICENSE
README.md

This means documentation changes do not modify the runtime implementation. Editing README.md alone does not alter lib/, WAProto/, authentication behavior, socket behavior, or builders.


πŸ—οΈ Architecture Overview

@vanzxysenpai/baileys is organized in layers. Keeping these layers separate makes it easier to extend a builder or protocol surface without unnecessarily changing the transport layer.

Runtime flow

Application / Bot
       β”‚
       β–Ό
Public exports (`lib/index.js`)
       β”‚
       β”œβ”€β”€ Builders ───────────────► Message construction
       β”‚                              AIRich / A2UI / Button / Carousel / Toolkit
       β”‚
       β”œβ”€β”€ Socket ─────────────────► Connection + send/receive lifecycle
       β”‚                              auth state / reconnect / message send
       β”‚
       β”œβ”€β”€ Signal ─────────────────► Session + cryptographic state
       β”‚
       β”œβ”€β”€ Store ──────────────────► Message / auth / metadata persistence
       β”‚
       β”œβ”€β”€ WABinary / WAM ─────────► WhatsApp node and protocol helpers
       β”‚
       └── WAUSync ────────────────► User/business/query synchronization
       β”‚
       β–Ό
WAProto
       β”‚
       β–Ό
WhatsApp Web protocol messages

lib/Builders/

This layer contains the higher-level message construction APIs. It is where the fork's interactive and rich-message work is concentrated. Builders are designed to turn JavaScript objects and fluent method calls into WhatsApp message structures before the socket layer transmits them.

Important builder families documented by this package include AIRich, A2UI, button builders, carousel support, and the shared toolkit/helpers used by those builders.

lib/Socket/

The socket layer is responsible for the connection-facing side of the library: establishing and maintaining the WhatsApp Web session, receiving nodes/events, sending messages, and coordinating runtime state.

Application code should normally interact with this layer through the public socket factory and exported helpers instead of reaching into socket implementation files directly.

lib/Signal/

Signal-related modules handle the cryptographic/session state required for multi-device communication. Changes here should be treated as high-impact changes: a seemingly small alteration can affect authentication, session establishment, message decryption, or group sender-key behavior.

lib/Store/

Store modules provide persistence abstractions and helpers used by the runtime. The exact backend can vary depending on the application and the optional dependencies installed alongside the package.

lib/WABinary/, lib/WAM/, and lib/WAUSync/

These lower-level modules provide protocol-facing utilities. They are useful when implementing advanced functionality, but application code should use higher-level public helpers where possible.

WAProto/

WAProto contains the generated protocol definitions used to construct and parse WhatsApp message structures. It is part of the published package and is exposed separately through the package exports.


🧭 Public Entry Points & Module Map

The main declaration entry point re-exports the principal package surfaces so TypeScript consumers can resolve the same API family as JavaScript consumers.

lib/index.d.ts
β”œβ”€β”€ WAProto
β”œβ”€β”€ Utils
β”œβ”€β”€ Builders
β”œβ”€β”€ Types
β”œβ”€β”€ Store
β”œβ”€β”€ Defaults
β”œβ”€β”€ WABinary
β”œβ”€β”€ WAM
β”œβ”€β”€ WAUSync
β”œβ”€β”€ Dugong
β”œβ”€β”€ makeWASocket
└── exports-extra

The package also defines these export paths in package.json:

| Export | Purpose | |---|---| | @vanzxysenpai/baileys | Main public API and socket factory | | @vanzxysenpai/baileys/WAProto | Generated protocol API | | @vanzxysenpai/baileys/WAProto/* | Individual generated protocol modules | | @vanzxysenpai/baileys/lib/* | Published library modules with declarations | | @vanzxysenpai/baileys/package.json | Package metadata |

For normal application development, the root import is the safest starting point:

import makeWASocket, { AIRich, DisconnectReason } from '@vanzxysenpai/baileys'

If a specialized module is required, use an export path explicitly documented by the package rather than importing a source file that is not part of the export map.


🧩 Feature Surface Matrix

The following matrix describes the documented surface of this fork without treating every feature as equally stable or equally supported by every WhatsApp client version.

| Area | Surface | Notes | |---|---|---| | Connection | Multi-device socket | Main runtime surface | | Authentication | Auth state / Signal | Session state is security-sensitive | | Messages | Standard message generation | Core Baileys-style flow | | Media | Image/audio/video/document helpers | Optional codecs/tools may be required | | Interactive | Buttons / native-flow related builders | Client rendering can vary | | Rich messages | AIRich | Extended builder surface | | UI | A2UI | Advanced interactive/UI structures | | Carousel | Carousel builder/support | Client capability dependent | | Polls | Poll construction | Rendering/support depends on message type and client | | USync | User/business/query helpers | Protocol-facing API | | LID | LID-aware participant handling | Important for modern WhatsApp addressing | | TypeScript | .d.ts declarations | Included in the package | | Protocol | WAProto | Generated protobuf surface | | Stores | Store helpers/backends | Some backends use optional dependencies | | Calls | Voice/video call helpers | Runtime/client capability dependent |

Compatibility note: a function being present in the JavaScript or TypeScript API does not guarantee that every WhatsApp client version will render or accept every advanced message structure. For experimental/native structures, verify behavior against the client versions you actually target.


πŸ”„ Migration Notes

When moving an application to @vanzxysenpai/baileys, check the following areas first:

  1. Runtime: use Node.js >=20.0.0.
  2. Module system: the package is ESM-only ("type": "module"). Use import/export rather than CommonJS require() for package modules.
  3. Entry point: the package resolves the main runtime through ./lib/index.js and TypeScript declarations through ./lib/index.d.ts.
  4. Protocol imports: WAProto is available through the package export map; avoid assuming an unrelated generated-proto path from another Baileys fork.
  5. Builders: advanced builder APIs such as AIRich and A2UI should be tested against the actual WhatsApp client/device combination used by the application.
  6. LID-aware code: applications that manually construct quoted messages, participants, or group/status payloads should verify that their code does not blindly assume PN-only addressing.
  7. Optional dependencies: media, database, WebRTC, preview, and other optional capabilities may require their corresponding peer dependency to be installed.

Common ESM migration mistakes

// ❌ CommonJS in an ESM-only application
const baileys = require('@vanzxysenpai/baileys')

// βœ… ESM
import makeWASocket from '@vanzxysenpai/baileys'

For dynamic loading, use import():

const module = await import('@vanzxysenpai/baileys')

πŸ§ͺ Verification & Test Strategy

Advanced changes should be tested at the layer they modify rather than relying on one end-to-end send test to prove everything works.

Recommended verification order

1. Static/import check
        ↓
2. Type/declaration check
        ↓
3. Builder construction test
        ↓
4. Serialization/protobuf test
        ↓
5. Relay/send test
        ↓
6. Real-client rendering test

For example, an AIRich change should first prove that the builder produces the expected structure before diagnosing a client-rendering issue as a builder bug. Likewise, a protocol change should be checked at the protobuf/node level before adding retries or transport workarounds.

What a useful bug report contains

Package version: @vanzxysenpai/baileys x.y.z
Node.js version: v20+ / exact version
Environment: Linux / Pterodactyl / Termux / VPS / other
Feature: AIRich / A2UI / media / socket / auth / etc.
Expected: ...
Actual: ...
Reproduction: minimal code or command
Stack trace: ...
WhatsApp client/device: ...

For authentication or connection failures, include the relevant disconnect reason and a sanitized log. Never publish credentials, session files, private keys, or authentication state in an issue.


πŸ› οΈ Troubleshooting Guide

require() cannot be used on an ESM graph

The package is ESM-only. Replace CommonJS require() usage with static import or dynamic import() as appropriate.

ERR_MODULE_NOT_FOUND

Check all of the following:

  • The dependency is installed in the same runtime where the bot is running.
  • The import path includes the correct extension when importing local ESM files where required.
  • The package version installed is the version your application expects.
  • The file is actually included by the package files allowlist when testing a packed/published tarball.

Cannot find module for an optional capability

Some functionality is represented by optional peer dependencies. Install only the dependency required by the feature you use, then restart the application so Node resolves the newly installed module.

The message is sent but the client displays it differently

Advanced WhatsApp message structures are client-capability dependent. Compare the serialized structure produced by the builder with the structure expected by the target client before changing transport code.

LID/PN-related participant problems

Do not assume that every chat can use the same participant JID representation. Modern WhatsApp conversations can be LID-addressed. If your application manually builds message content or quote context, use the package's LID-aware helpers and pass the correct identity information rather than deriving everything from a PN-only JID.

πŸ” Security & Operational Checklist

Before deploying a bot based on this package:

  • Keep authentication state outside Git repositories and public uploads.
  • Never paste private credentials or session keys into issue reports.
  • Restrict filesystem permissions for auth/session directories.
  • Use a process manager or container restart policy appropriate for your deployment.
  • Keep Node.js and dependencies updated within versions compatible with the package.
  • Treat protocol/builder changes as potentially breaking until verified against a real client.
  • Sanitize logs before sharing them publicly.
  • Review third-party notices in NOTICE.md when redistributing the package.

The package's MIT license does not remove the need to comply with WhatsApp's own terms, applicable laws, or the licenses/notices of bundled or derived components.


🧰 Optional Dependencies at a Glance

The package declares several optional peer dependencies because not every application needs every capability. The exact dependency set should be checked against package.json for the installed version.

| Dependency family | Typical purpose | |---|---| | sharp, @napi-rs/image | Image processing | | fluent-ffmpeg | Media/FFmpeg workflows | | audio-decode | Audio decoding | | node-webpmux | WebP-related processing | | better-sqlite3 | SQLite-backed application storage | | mongodb | MongoDB-backed storage | | mysql2 | MySQL-backed storage | | pg | PostgreSQL-backed storage | | ioredis | Redis-backed storage | | link-preview-js | Link preview functionality | | axios | HTTP/client integrations |

Optional does not mean universally unnecessary: if an application calls a feature that depends on one of these packages, install the corresponding dependency and verify the feature independently.


🧭 Developer Guide

Task-oriented recipes that sit on top of the reference sections above. Every API used here is documented elsewhere in this README or in the Complete API Reference; nothing below relies on features that are not in the shipped source. Remember the project-status note: wire formats for the more exotic message types are not confirmed against a live WhatsApp client β€” test on a throw-away account first.

Which API do I use? (quick lookup)

| I want to… | Use | Section | |---|---|---| | Send plain text / media / reaction / edit / delete | sock.sendMessage(jid, content, options) | Messaging | | Send a message built by hand | generateWAMessageFromContent() + sock.relayMessage() | Generating vs. relaying | | Quick-reply / URL / call buttons | Button (or ButtonV2 for reply-only) | Builders Reference | | Edit an existing template message | ButtonV3.loadFrom(msg) | Builders Reference | | Swipeable cards | Button(...).toCard() β†’ Carousel | Carousel | | Poll or quiz | Poll (setQuiz() for quiz mode) | Poll | | Album of 2–10 images/videos | Album or sock.sendAlbumMessage() | Media | | AI-assistant-style rich card | AIRich | AIRich Reference | | Auto-delete a message after N seconds | Expiring | Builders Reference | | Persist auth between restarts | useMultiFileAuthState / useSqliteAuthState / useEncryptedFileAuthState | Authentication | | Survive disconnects | autoReconnect() or the Bot framework | Utility Modules | | Persist chats/messages | makePersistentStore() + a store adapter | Store Backends | | Map LID ↔ phone number | sock.signalRepository.lidMapping, resolveSenderPn() | LID / PN Addressing | | Check whether a number is on WhatsApp | sock.onWhatsApp(...numbers) | User Sync Queries | | Mention everyone in a group | sock.sendMentionAll() / tagAll() / hideTag() | recipe below | | Test bot logic without WhatsApp | createMockSocket() | recipe below |

Recipe 1 β€” A production-minded bot skeleton

This combines the pieces the defaults table calls out as important: a fresh WA Web version, a getMessage that can resend, a cachedGroupMetadata lookup, creds.update persistence, and a reconnect policy that never reconnects after a logout.

import makeWASocket, {
    autoReconnect,
    useMultiFileAuthState,
    fetchLatestBaileysVersion,
    Browsers
} from '@vanzxysenpai/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')
const { version } = await fetchLatestBaileysVersion()

// Your own caches. Any Map-like store works; this is the mini