whatsapp-web-automation
v1.0.0
Published
[](https://www.npmjs.com/package/whatsapp-web-automation) [](LICENSE) [
- 📞 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 IDfrom- Sender IDto- Recipient IDbody- Message text contenttype- Message typetimestamp- Message timestampfromMe- 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:
- 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.
