
Product
Introducing Webhook Events for Alert Changes
Add real-time Socket webhook events to your workflows to automatically receive software supply chain alert changes in real time.
whatsapp-web-automation
Advanced tools
[](https://www.npmjs.com/package/whatsapp-web-automation) [](LICENSE) [ | ✅ |
| Video messages | ✅ |
| Stickers | ✅ |
| Location messages | ✅ |
| Contact cards | ✅ |
| Voice messages | ✅ |
| Message replies | ✅ |
| Message reactions | ✅ |
| Message deletion | ✅ |
| Message forwarding | ✅ |
| Feature | Status |
|---|---|
| Create groups | ✅ |
| Add/remove participants | ✅ |
| Promote/demote admins | ✅ |
| Group settings (name, description) | ✅ |
| Group invite links | ✅ |
| Leave groups | ✅ |
| Group notifications | ✅ |
npm install whatsapp-web-automation
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();
The main class for interacting with WhatsApp Web.
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
});
| 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) |
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}`);
Represents a WhatsApp message.
id - Message IDfrom - Sender IDto - Recipient IDbody - Message text contenttype - Message typetimestamp - Message timestampfromMe - Whether message was sent by the clientmessage.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);
Handle media messages (images, videos, documents, audio).
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!'
});
// 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']);
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}`);
});
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]);
}
});
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'
]
}
});
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');
}
When you first run the client, you'll see a base64 data URL in the console:
On your phone:
WhatsApp has rate limits. Avoid:
// 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' })
});
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);
});
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
const client = new Client({
puppeteer: {
headless: false,
devtools: true
}
});
// Enable verbose logging
client.on('change_state', (state) => {
console.log('State changed:', state);
});
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
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
[](https://www.npmjs.com/package/whatsapp-web-automation) [](LICENSE) [
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.

Product
Add real-time Socket webhook events to your workflows to automatically receive software supply chain alert changes in real time.

Security News
ENISA has become a CVE Program Root, giving the EU a central authority for coordinating vulnerability reporting, disclosure, and cross-border response.

Product
Socket now scans OpenVSX extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.