🚀 DAY 5 OF LAUNCH WEEK:Introducing Webhook Events for Alert Changes.Learn more
Socket
Book a DemoInstallSign in
Socket

whatsapp-web-automation

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

whatsapp-web-automation

[![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

latest
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

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

FeatureStatus
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

FeatureStatus
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();
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

EventDescriptionParameters
qrQR code received for authenticationqr (string) - Base64 QR code image
readyClient is ready to useNone
messageNew message receivedmessage (Message)
message_createMessage created (sent or received)message (Message)
auth_failureAuthentication failedmessage (string)
disconnectedClient disconnectedreason (string)

Methods

client.sendMessage(chatId, content, options)

Send a message to a chat.

// Send text message
await client.sendMessage('1234567890@c.us', 'Hello World!');

// Send with options
await client.sendMessage('1234567890@c.us', '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('1234567890@c.us');
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('1234567890@c.us', media, {
    caption: 'Check out this image!'
});

🔧 Advanced Usage

Group Management

// Create a group
const group = await client.createGroup('My Group', ['1234567890@c.us', '0987654321@c.us']);

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

// Add participant
await group.addParticipants(['1111111111@c.us']);

// Remove participant
await group.removeParticipants(['1111111111@c.us']);

// Promote to admin
await group.promoteParticipants(['1234567890@c.us']);

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 = ['1234567890@c.us', '0987654321@c.us'];
    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:

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

On your phone:

  • Open WhatsApp
  • Go to Settings → Linked Devices
  • Tap "Link a Device"
  • 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.

FAQs

Package last updated on 09 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts