whatsapp-js-pure
v1.0.0
Published
A modern, lightweight JavaScript library for WhatsApp Web integration with direct WebSocket connections. Send messages, manage groups, handle media, and automate WhatsApp interactions with a clean, professional API.
Readme
WhatsApp JS Pure
A professional JavaScript library for WhatsApp Web integration that provides direct WebSocket connections without browser dependencies. Built for developers who need reliable WhatsApp automation with a clean, intuitive API.
Why WhatsApp JS Pure?
Traditional WhatsApp automation solutions require heavy browser instances that consume significant resources and complicate deployment. WhatsApp JS Pure eliminates these problems by connecting directly to WhatsApp's Web protocol, offering the same functionality with dramatically reduced overhead.
Key Benefits:
- Direct WebSocket connection saves ~500MB RAM compared to browser-based solutions
- Production-ready error handling and automatic reconnection
- Complete feature parity with WhatsApp Web
- Clean API design that feels natural to JavaScript developers
- Persistent authentication sessions survive application restarts
Installation
npm install whatsapp-js-pureQuick Start
QR Code Authentication
const WhatsAppClient = require('whatsapp-js-pure');
const wa = new WhatsAppClient();
// Listen for QR code
wa.on('qr', (qr) => {
console.log('Scan this QR code with WhatsApp:');
// QR code will be displayed as ASCII art in terminal
});
// Handle successful connection
wa.on('ready', (info) => {
console.log('Connected as:', info.name);
console.log('Phone number:', info.id);
});
// Start connection
wa.connect();Pairing Code Authentication
const WhatsAppClient = require('whatsapp-js-pure');
const wa = new WhatsAppClient();
// Request pairing code
wa.requestPairingCode('+1234567890').then(code => {
console.log('Enter this code in WhatsApp:', code);
});
wa.on('ready', (info) => {
console.log('Connected successfully!');
});Sending Messages
Text Messages
// Simple text message
await wa.sendMessage('+1234567890', 'Hello from WhatsApp JS Pure!');
// Message with mentions
await wa.sendMessage('[email protected]', 'Hello @user!', {
mentions: ['[email protected]']
});Media Messages
// Send image with caption
await wa.sendImage('+1234567890', 'path/to/image.jpg', 'Check this out!');
// Send video
await wa.sendVideo('+1234567890', 'path/to/video.mp4', 'Video caption');
// Send audio file
await wa.sendAudio('+1234567890', 'path/to/audio.mp3');
// Send document
await wa.sendDocument('+1234567890', 'path/to/file.pdf', 'report.pdf', 'Monthly report');
// Send sticker
await wa.sendSticker('+1234567890', 'path/to/sticker.webp');Advanced Messaging
// Reply to a message
wa.on('message', async (message) => {
if (message.text === 'ping') {
await wa.replyToMessage(message, 'pong');
}
});
// React to messages
await wa.reactToMessage(messageObject, '👍');
// Send location
await wa.sendLocation('+1234567890', 40.7128, -74.0060, 'New York', '5th Avenue');Message Handling
// Listen for all messages
wa.on('message', (message) => {
console.log('From:', message.from);
console.log('Text:', message.text);
console.log('Type:', message.type);
console.log('Timestamp:', new Date(message.timestamp * 1000));
});
// Listen for specific message types
wa.on('image_message', (message) => {
console.log('Received image from:', message.from);
console.log('Caption:', message.caption);
});
wa.on('voice_message', (message) => {
console.log('Received voice note from:', message.from);
});Group Management
Creating and Managing Groups
// Create a new group
const group = await wa.createGroup('My Group', ['+1234567890', '+0987654321']);
console.log('Group created:', group.id);
// Add participants
await wa.addParticipant(group.id, '+1111111111');
// Remove participants
await wa.removeParticipant(group.id, '+1234567890');
// Update group settings
await wa.updateGroupSettings(group.id, {
restrict: true, // Only admins can send messages
announce: true // Only admins can edit group info
});
// Promote to admin
await wa.promoteParticipant(group.id, '+1234567890');
// Demote from admin
await wa.demoteParticipant(group.id, '+1234567890');Group Information
// Get group metadata
const groupInfo = await wa.getGroupMetadata(groupId);
console.log('Group name:', groupInfo.subject);
console.log('Participants:', groupInfo.participants.length);
// List all groups
const groups = await wa.getGroups();
groups.forEach(group => {
console.log(`${group.name} (${group.participants.length} members)`);
});Contact Management
// Get contact information
const contact = await wa.getContact('+1234567890');
console.log('Name:', contact.name);
console.log('Status:', contact.status);
// Check if number is registered on WhatsApp
const isRegistered = await wa.isRegisteredUser('+1234567890');
// Get all contacts
const contacts = await wa.getContacts();
// Block/unblock contacts
await wa.blockContact('+1234567890');
await wa.unblockContact('+1234567890');Connection Management
// Connection events
wa.on('connecting', () => {
console.log('Connecting to WhatsApp...');
});
wa.on('ready', (info) => {
console.log('Connection established');
});
wa.on('disconnected', (reason) => {
console.log('Disconnected:', reason);
});
wa.on('reconnecting', () => {
console.log('Attempting to reconnect...');
});
// Manual disconnect
await wa.disconnect();
// Check connection status
if (wa.isConnected()) {
console.log('Currently connected to WhatsApp');
}Error Handling
// Global error handler
wa.on('error', (error) => {
console.error('WhatsApp error:', error.message);
});
// Handle authentication failures
wa.on('auth_failure', (error) => {
console.error('Authentication failed:', error);
// Clear stored credentials and retry
wa.clearAuth();
});
// Try-catch for specific operations
try {
await wa.sendMessage('+1234567890', 'Hello!');
} catch (error) {
console.error('Failed to send message:', error.message);
}Configuration Options
const wa = new WhatsAppClient({
// Custom browser identity
browser: ['My App', 'Chrome', '1.0.0'],
// Authentication directory
authDir: './wa_session',
// Connection timeouts
connectTimeout: 60000,
// Logging level
logger: console, // or null for silent
// Mark as online when connecting
markOnlineOnConnect: false
});Advanced Usage
Custom Event Handling
// Raw Baileys events (for advanced users)
wa.on('raw_message', (baileys_message) => {
// Direct access to Baileys message format
console.log('Raw message:', baileys_message);
});
// Connection state changes
wa.on('connection_update', (update) => {
console.log('Connection update:', update);
});Bulk Operations
// Send message to multiple recipients
const recipients = ['+1234567890', '+0987654321', '+1111111111'];
const promises = recipients.map(number =>
wa.sendMessage(number, 'Bulk message')
);
await Promise.all(promises);Message Filtering
// Filter messages by criteria
wa.on('message', (message) => {
// Only respond to private messages
if (!message.from.includes('@g.us')) {
console.log('Private message from:', message.from);
}
// Only respond to specific contact
if (message.from === '[email protected]') {
wa.sendMessage(message.from, 'Hello back!');
}
});Best Practices
Session Management
Always handle authentication state properly:
wa.on('auth_failure', () => {
// Clear corrupted session and restart
wa.clearAuth();
setTimeout(() => wa.connect(), 5000);
});Rate Limiting
Implement delays between bulk operations:
async function sendBulkMessages(messages) {
for (const msg of messages) {
await wa.sendMessage(msg.to, msg.text);
await new Promise(resolve => setTimeout(resolve, 2000)); // 2 second delay
}
}Error Recovery
let reconnectAttempts = 0;
const maxReconnects = 5;
wa.on('disconnected', (info) => {
if (info.shouldReconnect && reconnectAttempts < maxReconnects) {
reconnectAttempts++;
console.log(`Reconnection attempt ${reconnectAttempts}/${maxReconnects}`);
setTimeout(() => wa.connect(), 5000);
}
});
wa.on('ready', () => {
reconnectAttempts = 0; // Reset counter on successful connection
});Phone Number Format
Always use international format with country code:
// Correct formats
'+1234567890' // US number
'+44123456789' // UK number
'+33123456789' // French number
// The library automatically converts to WhatsApp JID format
// +1234567890 becomes [email protected]Requirements
- Node.js version 17.0.0 or higher
- Active WhatsApp account
- Internet connection
Troubleshooting
Common Issues
Connection timeout:
// Increase timeout for slower connections
const wa = new WhatsAppClient({
connectTimeout: 120000 // 2 minutes
});Authentication failures:
// Clear stored credentials
wa.clearAuth();QR code not appearing: The QR code displays as ASCII art in your terminal. Make sure your terminal supports Unicode characters.
Rate limiting: WhatsApp has built-in rate limits. Add delays between operations:
await new Promise(resolve => setTimeout(resolve, 1000));Support
This library is built on the robust Baileys WhatsApp Web API and provides a simplified interface for common operations. For advanced use cases, you can access the underlying Baileys socket through wa.sock.
License
MIT License - feel free to use in personal and commercial projects.
