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 🙏

© 2025 – Pkg Stats / Ryan Hefner

qudbail

v6.7.246

Published

WhatsApp API

Readme

WhatsApp Baileys

WhatsApp Baileys is a highly modular, open-source Node.js library for building automation, bots, and integrations with WhatsApp using direct WebSocket connections, bypassing the need for a browser. It enables developers to manage messaging, groups, media, and advanced interactive features while maintaining robust stability and security.

The library emphasizes:

  • Reliable pairing & authentication
  • Automatic session management
  • Interactive messaging & dynamic menus
  • Full support for WhatsApp multi-device architecture

Table of Contents

  1. Architecture Overview
  2. Installation
  3. Authentication & Pairing
  4. Session Management
  5. Message Handling
  6. Interactive Messages
  7. Media Handling
  8. Group Management
  9. Event System
  10. Advanced Features
  11. Best Practices
  12. Troubleshooting
  13. Resources

Architecture Overview

Baileys is built with a WebSocket-based event-driven architecture, separating:

  1. Connection Layer – Handles WebSocket communication with WhatsApp servers
  2. Authentication Layer – Manages session credentials, pairing codes, and QR code login
  3. Message Layer – Parses incoming messages, reactions, and status updates
  4. Interactive Layer – Supports buttons, lists, and other rich message types
  5. Persistence Layer – Stores session state and media metadata for reliable reconnections

The modular design allows developers to extend functionality, integrate with databases, or build custom automation pipelines.


Usage / Detailed Examples

WhatsApp Baileys allows developers to quickly setup, authenticate, send messages, manage groups, and handle interactive content in a stable and modular environment. The following example demonstrates a full workflow, including custom pairing code usage.

const { default: makeWASocket, useSingleFileAuthState, makeInMemoryStore } = require("qudbail");
const { Boom } = require("@hapi/boom");

// Authentication state
const { state, saveState } = useSingleFileAuthState("./auth_info.json");

// Initialize WhatsApp connection
const sock = makeWASocket({
    auth: state,
    printQRInTerminal: true, // shows QR code in terminal if no valid session
    connectTimeoutMs: 30_000,
});

// Monitor connection updates
sock.ev.on('connection.update', (update) => {
    console.log('Connection update:', update);

    if (update.connection === 'close') {
        const shouldReconnect = (update.lastDisconnect?.error instanceof Boom) && 
            update.lastDisconnect.error.output.statusCode !== 401;
        if (shouldReconnect) {
            console.log('Reconnecting...');
        } else {
            console.log('Authentication failed, please re-scan QR code or use custom pairing code.');
        }
    }

    if (update.connection === 'open') {
        console.log('Connected successfully!');
    }
});

// Save auth state on exit
process.on('exit', () => saveState());

// ---------------------------
// Custom Pairing / Authentication
// ---------------------------

// If you want a custom pairing code instead of default QR
sock.ev.on('creds.update', saveState);

// Example: listen for QR code updates (ASCII string)
sock.ev.on('connection.update', ({ qr }) => {
    if (qr) {
        console.log('Scan this QR with WhatsApp:', qr);
    }
});

// ---------------------------
// Message Handling
// ---------------------------

// Listen for all incoming messages
sock.ev.on('messages.upsert', async (m) => {
    const msg = m.messages[0];
    console.log('Received message:', msg.message);
});

// Sending text message
await sock.sendMessage('[email protected]', { text: 'Hello! This is a test message.' });

// Sending media
await sock.sendMessage('[email protected]', { image: { url: './image.png' }, caption: 'Sample Image' });
await sock.sendMessage('[email protected]', { video: { url: './video.mp4' }, caption: 'Sample Video' });
await sock.sendMessage('[email protected]', { audio: { url: './audio.mp3' }, mimetype: 'audio/mp3' });
await sock.sendMessage('[email protected]', { document: { url: './document.pdf' }, mimetype: 'application/pdf', fileName: 'example.pdf' });
await sock.sendMessage('[email protected]', { sticker: { url: './sticker.webp' } });

// ---------------------------
// Interactive Messages
// ---------------------------

// Buttons
await sock.sendMessage('[email protected]', {
    text: "Choose an option",
    buttons: [
        { buttonId: 'opt1', buttonText: { displayText: 'Option 1' }, type: 1 },
        { buttonId: 'opt2', buttonText: { displayText: 'Option 2' }, type: 1 }
    ],
    headerType: 1
});

// List message
await sock.sendMessage('[email protected]', {
    text: 'Select from the list below',
    footer: 'Footer text',
    sections: [
        {
            title: 'Menu Section',
            rows: [
                { title: 'Item 1', rowId: 'item1' },
                { title: 'Item 2', rowId: 'item2' }
            ]
        }
    ],
    buttonText: 'Open List'
});

// ---------------------------
// Group Management
// ---------------------------

await sock.groupParticipantsUpdate('[email protected]', ['[email protected]'], 'promote');
await sock.groupParticipantsUpdate('[email protected]', ['[email protected]'], 'demote');
await sock.groupParticipantsUpdate('[email protected]', ['[email protected]'], 'remove');
await sock.groupUpdateSubject('[email protected]', 'New Group Name');
await sock.groupUpdateDescription('[email protected]', 'Updated group description');

// ---------------------------
// Advanced Automation
// ---------------------------

// Relay incoming messages to another chat
sock.ev.on('messages.upsert', async (m) => {
    const msg = m.messages[0];
    if (!msg.key.fromMe) {
        await sock.sendMessage('[email protected]', { text: msg.message.conversation });
    }
});

// Auto-reply system
sock.ev.on('messages.upsert', async (m) => {
    const msg = m.messages[0];
    if (msg.message && !msg.key.fromMe) {
        await sock.sendMessage(msg.key.remoteJid, { text: 'Thanks for your message!' });
    }
});

// ---------------------------
// Connection Handling
// ---------------------------

sock.ev.on('connection.update', (update) => {
    if(update.connection === 'close') {
        const shouldReconnect = (update.lastDisconnect?.error)?.output?.statusCode !== 401;
        if(shouldReconnect) {
            console.log('Reconnecting...');
            // implement reconnection logic
        } else {
            console.log('Authentication failed, please re-scan QR code or provide a new pairing code.');
        }
    }
});
```End Usage

---

## Installation

```bash
npm install qudbail
# or
yarn add qudbail