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

whatsapp-web-automation

v1.0.0

Published

[![npm version](https://badge.fury.io/js/whatsapp-web-automation.svg)](https://www.npmjs.com/package/whatsapp-web-automation) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) [![Node.js Version](https://img.shields.io/badg

Readme

WhatsApp Web.js - WhatsApp Web Automation for Node.js

npm version License Node.js Version

A pure Node.js library for automating WhatsApp Web, similar to whatsapp-web.js. Effectively controls WhatsApp Web in a browser using Puppeteer for authentic interactions like a real user.

⚠️ Important Disclaimer

This library is not officially endorsed by WhatsApp. WhatsApp does not allow bots or unofficial clients on their platform. Using this library may result in your WhatsApp account being banned. Use at your own risk!

✨ Features

  • 🔐 QR Code Authentication - Connect by scanning QR code
  • 💬 Messages - Send and receive text and media messages
  • 👥 Groups - Complete group management (create, participants, admins)
  • 📞 Contacts - Contact management and information
  • 💾 Persistent Sessions - Avoid re-authentication by saving sessions
  • 🎯 Events - Event-driven architecture
  • 🤖 Anti-detection - Simulates human behavior with delays and randomization
  • 📱 Multi-device - Support for WhatsApp's multi-device functionality

Supported Message Types

| Feature | Status | | --- | --- | | Text messages | ✅ | | Media messages (images/audio/documents) | ✅ | | Video messages | ✅ | | Stickers | ✅ | | Location messages | ✅ | | Contact cards | ✅ | | Voice messages | ✅ | | Message replies | ✅ | | Message reactions | ✅ | | Message deletion | ✅ | | Message forwarding | ✅ |

Group Features

| Feature | Status | | --- | --- | | Create groups | ✅ | | Add/remove participants | ✅ | | Promote/demote admins | ✅ | | Group settings (name, description) | ✅ | | Group invite links | ✅ | | Leave groups | ✅ | | Group notifications | ✅ |

📦 Installation

npm install whatsapp-web-automation

🚀 Quick Start

Basic Usage

const { Client } = require('whatsapp-web-automation');

// Create a new client instance
const client = new Client();

// QR Code event - scan with WhatsApp mobile app
client.on('qr', (qr) => {
    console.log('Scan this QR code with WhatsApp mobile app:');
    // The qr variable contains a base64 image data URL
    // Copy and paste it in a browser to see the QR code
    console.log(qr);
});

// Client is ready
client.on('ready', () => {
    console.log('WhatsApp client is ready!');
});

// Listen for new messages
client.on('message', async (message) => {
    console.log(`New message from ${message.from}: ${message.body}`);
    
    // Reply to messages that contain "hello"
    if (message.body.toLowerCase().includes('hello')) {
        await message.reply('Hello! How can I help you?');
    }
});

// Initialize the client
client.initialize();

With Persistent Session (Recommended)

const { Client, LocalAuth } = require('whatsapp-web-automation');

// Use LocalAuth to save session data
const client = new Client({
    authStrategy: new LocalAuth({
        clientId: 'my-bot',
        dataPath: './sessions'
    })
});

client.on('qr', (qr) => {
    console.log('Scan QR code (only needed first time):');
    console.log(qr);
});

client.on('ready', () => {
    console.log('Client is ready!');
});

client.on('message', async (message) => {
    if (message.body === '!ping') {
        await message.reply('pong');
    }
});

client.initialize();

📚 API Documentation

Client Class

The main class for interacting with WhatsApp Web.

Constructor Options

const client = new Client({
    authStrategy: new LocalAuth(), // Authentication strategy
    puppeteer: {
        headless: true,           // Run browser in headless mode
        args: ['--no-sandbox']    // Additional browser arguments
    },
    userAgent: 'Custom User Agent' // Custom user agent
});

Events

| Event | Description | Parameters | |-------|-------------|------------| | qr | QR code received for authentication | qr (string) - Base64 QR code image | | ready | Client is ready to use | None | | message | New message received | message (Message) | | message_create | Message created (sent or received) | message (Message) | | auth_failure | Authentication failed | message (string) | | disconnected | Client disconnected | reason (string) |

Methods

client.sendMessage(chatId, content, options)

Send a message to a chat.

// Send text message
await client.sendMessage('[email protected]', 'Hello World!');

// Send with options
await client.sendMessage('[email protected]', 'Hello!', {
    linkPreview: false
});
client.getChats()

Get all chats.

const chats = await client.getChats();
console.log(`Found ${chats.length} chats`);
client.getContacts()

Get all contacts.

const contacts = await client.getContacts();
console.log(`Found ${contacts.length} contacts`);
client.isRegisteredUser(number)

Check if a number is registered on WhatsApp.

const isRegistered = await client.isRegisteredUser('1234567890');
console.log(`Number is registered: ${isRegistered}`);

Message Class

Represents a WhatsApp message.

Properties

  • id - Message ID
  • from - Sender ID
  • to - Recipient ID
  • body - Message text content
  • type - Message type
  • timestamp - Message timestamp
  • fromMe - Whether message was sent by the client

Methods

message.reply(content, options)

Reply to a message.

client.on('message', async (message) => {
    if (message.body === 'Hi') {
        await message.reply('Hello there!');
    }
});
message.forward(chatId)

Forward a message to another chat.

await message.forward('[email protected]');
message.delete(everyone)

Delete a message.

// Delete for me only
await message.delete();

// Delete for everyone (if sent recently)
await message.delete(true);

MessageMedia Class

Handle media messages (images, videos, documents, audio).

Creating Media

const { MessageMedia } = require('whatsapp-web-automation');

// From file path
const media = await MessageMedia.fromFilePath('./image.jpg');

// From URL (if implemented)
const media = await MessageMedia.fromUrl('https://example.com/image.jpg');

// Send media message
await client.sendMessage('[email protected]', media, {
    caption: 'Check out this image!'
});

🔧 Advanced Usage

Group Management

// Create a group
const group = await client.createGroup('My Group', ['[email protected]', '[email protected]']);

// Get group info
const groupInfo = await group.getInfo();
console.log(groupInfo.name);

// Add participant
await group.addParticipants(['[email protected]']);

// Remove participant
await group.removeParticipants(['[email protected]']);

// Promote to admin
await group.promoteParticipants(['[email protected]']);

Message Filtering

client.on('message', async (message) => {
    // Ignore messages from groups
    if (message.from.endsWith('@g.us')) return;
    
    // Ignore own messages
    if (message.fromMe) return;
    
    // Only respond to specific contacts
    const allowedContacts = ['[email protected]', '[email protected]'];
    if (!allowedContacts.includes(message.from)) return;
    
    // Process the message
    console.log(`Processing message: ${message.body}`);
});

Auto-Reply Bot

const responses = {
    'hello': 'Hi there! How can I help you?',
    'bye': 'Goodbye! Have a great day!',
    'help': 'Available commands:\n- hello\n- bye\n- help'
};

client.on('message', async (message) => {
    if (message.fromMe) return; // Ignore own messages
    
    const text = message.body.toLowerCase();
    
    if (responses[text]) {
        await message.reply(responses[text]);
    }
});

🛠️ Configuration

Browser Configuration

const client = new Client({
    puppeteer: {
        headless: false,          // Show browser window
        devtools: true,           // Open DevTools
        slowMo: 100,             // Slow down actions
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-extensions',
            '--disable-background-timer-throttling'
        ]
    }
});

Session Management

const { LocalAuth } = require('whatsapp-web-automation');

const authStrategy = new LocalAuth({
    clientId: 'unique-client-id',
    dataPath: './my-sessions',     // Custom session directory
    backupSyncIntervalMs: 300000   // Backup every 5 minutes
});

// Check if session exists
const hasAuth = await authStrategy.hasAuthData();
if (hasAuth) {
    console.log('Existing session found');
} else {
    console.log('First time setup - QR code required');
}

📱 QR Code Scanning

When you first run the client, you'll see a base64 data URL in the console:

  1. Method 1: Copy the entire data URL and paste it in a new browser tab to see the QR code
  2. Method 2: Use an online QR decoder like https://webqr.com
  3. Method 3: Use your phone's camera to scan directly from the terminal/browser

On your phone:

  1. Open WhatsApp
  2. Go to Settings → Linked Devices
  3. Tap "Link a Device"
  4. Scan the QR code

⚠️ Important Notes

Rate Limiting

WhatsApp has rate limits. Avoid:

  • Sending too many messages in a short time
  • Adding too many participants to groups quickly
  • Making rapid API calls

Best Practices

// Add delays between actions
await new Promise(resolve => setTimeout(resolve, 1000));

// Handle errors gracefully
client.on('message', async (message) => {
    try {
        await message.reply('Hello!');
    } catch (error) {
        console.error('Failed to send message:', error);
    }
});

// Use session management for production
const client = new Client({
    authStrategy: new LocalAuth({ clientId: 'prod-bot' })
});

Error Handling

client.on('auth_failure', (message) => {
    console.error('Authentication failed:', message);
    process.exit(1);
});

client.on('disconnected', (reason) => {
    console.log('Client disconnected:', reason);
    // Implement reconnection logic if needed
});

// Graceful shutdown
process.on('SIGINT', async () => {
    console.log('Shutting down...');
    await client.destroy();
    process.exit(0);
});

🔍 Troubleshooting

Common Issues

QR Code not appearing: Make sure you're copying the entire data URL starting with data:image/png;base64,

Session not persisting: Ensure the session directory has proper write permissions

Browser crashes: Try running with headless: false to see what's happening

Rate limiting: Add delays between API calls and reduce message frequency

Debug Mode

const client = new Client({
    puppeteer: {
        headless: false,
        devtools: true
    }
});

// Enable verbose logging
client.on('change_state', (state) => {
    console.log('State changed:', state);
});

📄 License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

🤝 Contributing

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

⚡ Support

If you encounter any issues or have questions, please open an issue on the GitHub repository.


Remember: This library is for educational purposes. Always respect WhatsApp's Terms of Service and use responsibly.