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

@xbibzlibrary/wa-connect

v1.0.0

Published

Advanced WhatsApp Connect Bot with 8-digit Pairing Code System - Powerful & Modern

Downloads

8

Readme

@xbibzlibrary/wa-connect

Version License Node WhatsApp

Advanced WhatsApp Connect Bot with 8-Digit Pairing Code System

Powerful • Modern • Secure • Production-Ready

InstallationQuick StartDocumentationExamplesAPI Reference


🌟 Features

Core Capabilities

  • 8-Digit Pairing System - Secure authentication
  • Multi-Session Support - Handle multiple accounts
  • Real-Time Messaging - Instant message monitoring
  • Auto Recovery - Automatic connection restoration
  • Rate Limiting - Built-in request throttling
  • Cross-Platform - Works on Windows, macOS, Linux

Security & Performance

  • 🔒 End-to-End Security - Advanced encryption layer
  • 🚀 High Performance - Optimized for speed
  • 📊 Comprehensive Logging - Detailed activity tracking
  • 🛡️ Error Handling - Robust error management
  • 🔄 Connection Management - Smart reconnection logic
  • No Webhooks Required - Direct browser automation

📦 Installation

npm install @xbibzlibrary/wa-connect

Or with yarn:

yarn add @xbibzlibrary/wa-connect

Prerequisites

  • Node.js >= 14.0.0
  • Chrome/Chromium browser (automatically handled by Puppeteer)

🚀 Quick Start

Basic Usage

const WhatsAppConnect = require('@xbibzlibrary/wa-connect');

// Initialize the bot
const bot = new WhatsAppConnect({
    headless: true,
    logLevel: 'info'
});

async function main() {
    // 1. Initialize system
    await bot.initialize();
    
    // 2. Start pairing process
    const pairing = await bot.startPairing('+1234567890');
    console.log(`Your Pairing Code: ${pairing.pairingCode}`);
    console.log(`Enter this code in WhatsApp mobile app`);
    
    // 3. Wait for user to enter code in WhatsApp
    // The verification happens automatically in the browser
    
    // 4. Verify pairing (after user enters code)
    await bot.verifyPairing(pairing.sessionId, pairing.pairingCode);
    
    // 5. Start sending messages
    await bot.sendMessage('+1234567890', 'Hello from WhatsApp Connect Bot! 🚀');
    
    console.log('Bot is ready!');
}

main().catch(console.error);

📖 Documentation

Table of Contents

  1. Initialization
  2. Pairing System
  3. Sending Messages
  4. Receiving Messages
  5. Event Handling
  6. Session Management
  7. Error Handling
  8. Advanced Configuration

🔧 Initialization

Constructor Options

const bot = new WhatsAppConnect({
    headless: true,              // Run browser in headless mode
    logLevel: 'info',            // Log level: 'error' | 'warn' | 'info' | 'debug' | 'system'
    maxRetries: 3,               // Maximum retry attempts
    pairingTimeout: 300000,      // Pairing timeout in ms (5 minutes)
    maxInactiveTime: 300000,     // Max inactive time before reconnect
    maxConnectionAge: 3600000,   // Max connection age (1 hour)
    debug: false,                // Enable debug mode
    userDataDir: './sessions'    // Session storage directory
});

Initialize the Bot

await bot.initialize();

This will:

  • Launch the browser instance
  • Set up security layers
  • Initialize event handlers
  • Prepare the pairing system

🔐 Pairing System

Start Pairing

const pairingResult = await bot.startPairing('+1234567890');

console.log(pairingResult);
// {
//     success: true,
//     pairingCode: '12345678',
//     sessionId: 'abc123...',
//     expiresAt: '2025-10-05T12:30:00.000Z'
// }

The 8-Digit Code

The pairing code is an 8-digit number that:

  • ✅ Expires after 5 minutes by default
  • ✅ Is unique per session
  • ✅ Can only be used once
  • ✅ Is securely generated using crypto

Verify Pairing

const verified = await bot.verifyPairing(
    pairingResult.sessionId,
    pairingResult.pairingCode
);

console.log(verified);
// {
//     success: true,
//     sessionData: { ... },
//     message: 'Pairing verified successfully'
// }

Complete Example

async function pairDevice() {
    const phoneNumber = '+1234567890';
    
    // Step 1: Start pairing
    const pairing = await bot.startPairing(phoneNumber);
    
    // Step 2: Display code to user
    console.log('═══════════════════════════════════');
    console.log('  📱 PAIRING CODE: ' + pairing.pairingCode);
    console.log('═══════════════════════════════════');
    console.log('  Enter this code in WhatsApp:');
    console.log('  Settings > Linked Devices > Link a Device');
    console.log('  Expires: ' + new Date(pairing.expiresAt).toLocaleString());
    console.log('═══════════════════════════════════');
    
    // Step 3: Wait for verification (automatic in browser)
    await new Promise(resolve => setTimeout(resolve, 30000));
    
    // Step 4: Verify
    try {
        await bot.verifyPairing(pairing.sessionId, pairing.pairingCode);
        console.log('✅ Device paired successfully!');
    } catch (error) {
        console.error('❌ Pairing failed:', error.message);
    }
}

💬 Sending Messages

Basic Message

await bot.sendMessage('+1234567890', 'Hello World!');

Message with Options

await bot.sendMessage('+1234567890', 'Hello World!', {
    delay: 100  // Typing delay in ms
});

Send to Multiple Recipients

const recipients = ['+1234567890', '+0987654321'];

for (const recipient of recipients) {
    await bot.sendMessage(recipient, 'Bulk message!');
    await new Promise(r => setTimeout(r, 2000)); // Wait 2s between messages
}

Message Response

const result = await bot.sendMessage('+1234567890', 'Test');

console.log(result);
// {
//     to: '+1234567890',
//     message: 'Test',
//     timestamp: '2025-10-05T12:00:00.000Z',
//     status: 'sent',
//     messageId: 'msg_1728129600000_abc123'
// }

📨 Receiving Messages

Set Up Message Listener

bot.onMessage((message) => {
    console.log('Received:', message);
    // {
    //     from: '+1234567890',
    //     body: 'Hello Bot!',
    //     timestamp: '2025-10-05T12:00:00.000Z',
    //     type: 'received'
    // }
});

Auto-Reply Bot Example

bot.onMessage(async (message) => {
    console.log(`Message from ${message.from}: ${message.body}`);
    
    // Auto-reply
    if (message.body.toLowerCase().includes('hello')) {
        await bot.sendMessage(message.from, 'Hello! How can I help you?');
    }
    
    // Command handling
    if (message.body === '/help') {
        await bot.sendMessage(message.from, 
            'Available commands:\n/help - Show this message\n/status - Bot status'
        );
    }
});

Advanced Message Handler

bot.onMessage(async (message) => {
    try {
        // Log incoming message
        console.log(`[${message.timestamp}] ${message.from}: ${message.body}`);
        
        // Process commands
        if (message.body.startsWith('/')) {
            await handleCommand(message);
        } else {
            await handleRegularMessage(message);
        }
    } catch (error) {
        console.error('Message handling error:', error);
    }
});

async function handleCommand(message) {
    const [command, ...args] = message.body.split(' ');
    
    switch (command) {
        case '/ping':
            await bot.sendMessage(message.from, 'Pong! 🏓');
            break;
        case '/time':
            await bot.sendMessage(message.from, `Current time: ${new Date().toLocaleString()}`);
            break;
        default:
            await bot.sendMessage(message.from, 'Unknown command');
    }
}

🎯 Event Handling

Available Events

| Event | Description | Data | |-------|-------------|------| | connection_established | When connection is established | Connection object | | connection_reestablished | After successful reconnection | Connection object | | connection_inactive | When connection becomes inactive | Connection object | | connection_terminated | When connection is terminated | Connection object | | heartbeat | Periodic heartbeat signal | { sessionId, timestamp } | | page_loaded | When WhatsApp page loads | None | | page_error | When page error occurs | Error object |

Register Event Handlers

// Connection established
bot.onEvent('connection_established', (data) => {
    console.log('✅ Connected:', data);
});

// Connection lost
bot.onEvent('connection_inactive', (data) => {
    console.log('⚠️ Connection inactive:', data);
});

// Heartbeat
bot.onEvent('heartbeat', (data) => {
    console.log('💓 Heartbeat:', data.timestamp);
});

// Page loaded
bot.onEvent('page_loaded', () => {
    console.log('📄 WhatsApp page loaded');
});

📊 Session Management

Get Session Info

const session = bot.getSessionInfo();

console.log(session);
// {
//     sessionId: 'abc123...',
//     phoneNumber: '+1234567890',
//     pairedAt: '2025-10-05T12:00:00.000Z',
//     userAgent: 'Mozilla/5.0...',
//     metadata: {
//         pairingMethod: '8-digit-code',
//         securityLevel: 'high'
//     }
// }

Check Bot Status

const status = bot.getStatus();

console.log(status);
// {
//     initialized: true,
//     paired: true,
//     sessionId: 'abc123...',
//     connectionStatus: {
//         connected: true,
//         browser: true,
//         page: true,
//         session: true
//     }
// }

Get Chat List

const chats = await bot.getChatList();

console.log(chats);
// [
//     {
//         name: 'John Doe',
//         lastMessage: 'Hello!',
//         timestamp: '10:30 AM',
//         unread: true
//     },
//     ...
// ]

❗ Error Handling

Try-Catch Pattern

try {
    await bot.sendMessage('+1234567890', 'Hello');
} catch (error) {
    console.error('Error:', error.message);
    console.error('Context:', error.context);
    console.error('Error ID:', error.errorId);
}

Common Errors

| Error | Cause | Solution | |-------|-------|----------| | System not initialized | Called method before initialize() | Call initialize() first | | Invalid phone number | Phone number format incorrect | Use format: +[country][number] | | Invalid pairing code | Wrong code format | Must be 8 digits | | Pairing code expired | Code timeout | Generate new code | | No active session | Not paired yet | Complete pairing first | | Contact not found | Recipient doesn't exist | Verify phone number |

Global Error Handler

async function safeExecute(fn, context = 'operation') {
    try {
        return await fn();
    } catch (error) {
        console.error(`[${context}] Error:`, error.message);
        
        // Log to file
        const fs = require('fs');
        fs.appendFileSync('error.log', 
            `[${new Date().toISOString()}] ${context}: ${error.message}\n`
        );
        
        // Attempt recovery
        if (error.isRecoverable) {
            console.log('Attempting recovery...');
            // Recovery logic
        }
        
        throw error;
    }
}

// Usage
await safeExecute(
    () => bot.sendMessage('+1234567890', 'Hello'),
    'send_message'
);

⚙️ Advanced Configuration

Custom Logger

const bot = new WhatsAppConnect({
    logLevel: 'debug'  // Show all logs including debug
});

// The logger will output to:
// 1. Console (colored)
// 2. File: whatsapp-connect.log

Session Persistence

const bot = new WhatsAppConnect({
    userDataDir: './my-sessions'  // Custom session directory
});

// Sessions are automatically saved and can be reused
// across restarts

Headless vs Headed Mode

// Headless (production)
const bot = new WhatsAppConnect({
    headless: true
});

// Headed (development/debugging)
const bot = new WhatsAppConnect({
    headless: false  // See the browser
});

Custom Timeouts

const bot = new WhatsAppConnect({
    pairingTimeout: 600000,      // 10 minutes
    maxInactiveTime: 600000,     // 10 minutes
    maxConnectionAge: 7200000    // 2 hours
});

📋 Examples

Example 1: Simple Echo Bot

const WhatsAppConnect = require('@xbibzlibrary/wa-connect');

async function echoBot() {
    const bot = new WhatsAppConnect({ logLevel: 'info' });
    
    await bot.initialize();
    
    // Pair device
    const pairing = await bot.startPairing('+1234567890');
    console.log('Pairing Code:', pairing.pairingCode);
    
    await new Promise(r => setTimeout(r, 30000));
    await bot.verifyPairing(pairing.sessionId, pairing.pairingCode);
    
    // Echo messages
    bot.onMessage(async (message) => {
        await bot.sendMessage(message.from, `You said: ${message.body}`);
    });
    
    console.log('Echo bot is running...');
}

echoBot().catch(console.error);

Example 2: Command Bot

const commands = {
    '/ping': 'Pong! 🏓',
    '/time': () => new Date().toLocaleString(),
    '/help': 'Commands: /ping, /time, /help, /joke',
    '/joke': 'Why did the bot cross the road? To get to the other API! 😄'
};

bot.onMessage(async (message) => {
    const cmd = message.body.toLowerCase();
    
    if (commands[cmd]) {
        const response = typeof commands[cmd] === 'function' 
            ? commands[cmd]() 
            : commands[cmd];
        await bot.sendMessage(message.from, response);
    }
});

Example 3: Auto-Reply with Keywords

const autoReplies = {
    'hello': 'Hi there! How can I help you?',
    'help': 'I can assist you with:\n- Product info\n- Support\n- FAQ',
    'bye': 'Goodbye! Have a great day! 👋',
    'price': 'Please visit our website for pricing information.'
};

bot.onMessage(async (message) => {
    const text = message.body.toLowerCase();
    
    for (const [keyword, reply] of Object.entries(autoReplies)) {
        if (text.includes(keyword)) {
            await bot.sendMessage(message.from, reply);
            break;
        }
    }
});

Example 4: Multi-Session Manager

class MultiSessionManager {
    constructor() {
        this.bots = new Map();
    }
    
    async createSession(phoneNumber) {
        const bot = new WhatsAppConnect({
            userDataDir: `./sessions/${phoneNumber}`
        });
        
        await bot.initialize();
        const pairing = await bot.startPairing(phoneNumber);
        
        this.bots.set(phoneNumber, bot);
        
        return pairing;
    }
    
    getBot(phoneNumber) {
        return this.bots.get(phoneNumber);
    }
    
    async destroySession(phoneNumber) {
        const bot = this.bots.get(phoneNumber);
        if (bot) {
            await bot.destroy();
            this.bots.delete(phoneNumber);
        }
    }
}

// Usage
const manager = new MultiSessionManager();
await manager.createSession('+1234567890');
await manager.createSession('+0987654321');

🔍 API Reference

Class: WhatsAppConnect

Constructor

new WhatsAppConnect(options?: ConnectionOptions)

Methods

| Method | Parameters | Returns | Description | |--------|-----------|---------|-------------| | initialize() | - | Promise<Object> | Initialize the bot system | | startPairing(phoneNumber) | string | Promise<PairingResult> | Start pairing process | | verifyPairing(sessionId, code) | string, string | Promise<VerificationResult> | Verify pairing code | | sendMessage(to, message, options?) | string, string, Object | Promise<MessageResult> | Send a message | | onMessage(callback) | Function | Promise<void> | Register message handler | | onEvent(event, callback) | string, Function | Promise<void> | Register event handler | | getChatList() | - | Promise<Array> | Get list of chats | | getStatus() | - | Object | Get bot status | | getSessionInfo() | - | Object | Get session information | | destroy() | - | Promise<void> | Cleanup and destroy bot |

Types

interface ConnectionOptions {
    headless?: boolean;
    logLevel?: 'error' | 'warn' | 'info' | 'debug' | 'system';
    maxRetries?: number;
    pairingTimeout?: number;
    maxInactiveTime?: number;
    maxConnectionAge?: number;
    debug?: boolean;
    userDataDir?: string;
}

interface PairingResult {
    success: boolean;
    pairingCode: string;
    sessionId: string;
    expiresAt: string;
}

interface MessageResult {
    to: string;
    message: string;
    timestamp: string;
    status: string;
    messageId: string;
}

🛡️ Security Best Practices

  1. Never commit session data to version control

    echo "sessions/" >> .gitignore
  2. Use environment variables for sensitive data

    const phoneNumber = process.env.PHONE_NUMBER;
  3. Implement rate limiting in your application

    const rateLimit = require('express-rate-limit');
  4. Validate all inputs before processing

    function sanitizeInput(input) {
        return input.trim().replace(/[<>]/g, '');
    }
  5. Keep dependencies updated

    npm audit
    npm update

🐛 Troubleshooting

Issue: Browser won't launch

Solution:

# Install required dependencies (Linux)
sudo apt-get install -y \
    chromium-browser \
    libx11-xcb1 \
    libxcomposite1 \
    libxdamage1

Issue: Pairing code not working

Checks:

  • ✅ Code is exactly 8 digits
  • ✅ Code hasn't expired (5 minutes)
  • ✅ Using correct phone number format
  • ✅ WhatsApp mobile app is up to date

Issue: Messages not sending

Debugging:

const bot = new WhatsAppConnect({
    logLevel: 'debug',  // Enable debug logs
    headless: false     // See what's happening
});

Issue: Session not persisting

Solution:

const bot = new WhatsAppConnect({
    userDataDir: path.resolve(__dirname, 'sessions')  // Use absolute path
});

📝 License

MIT License - see LICENSE file for details


🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📞 Support


🙏 Acknowledgments

  • Built with Puppeteer
  • Inspired by the WhatsApp BOT
  • Special thanks to all contributors

Made with ❤️ by Xbibz Official

⬆ Back to Top