@xbibzlibrary/wa-connect
v1.0.0
Published
Advanced WhatsApp Connect Bot with 8-digit Pairing Code System - Powerful & Modern
Downloads
8
Maintainers
Readme
@xbibzlibrary/wa-connect
Advanced WhatsApp Connect Bot with 8-Digit Pairing Code System
Powerful • Modern • Secure • Production-Ready
Installation • Quick Start • Documentation • Examples • API Reference
🌟 Features
Core Capabilities
- ✅ 8-Digit Pairing System - Secure authentication
- ✅ Multi-Session Support - Handle multiple accounts
- ✅ Real-Time Messaging - Instant message monitoring
- ✅ Auto Recovery - Automatic connection restoration
- ✅ Rate Limiting - Built-in request throttling
- ✅ Cross-Platform - Works on Windows, macOS, Linux
Security & Performance
- 🔒 End-to-End Security - Advanced encryption layer
- 🚀 High Performance - Optimized for speed
- 📊 Comprehensive Logging - Detailed activity tracking
- 🛡️ Error Handling - Robust error management
- 🔄 Connection Management - Smart reconnection logic
- ⚡ No Webhooks Required - Direct browser automation
📦 Installation
npm install @xbibzlibrary/wa-connectOr with yarn:
yarn add @xbibzlibrary/wa-connectPrerequisites
- Node.js >= 14.0.0
- Chrome/Chromium browser (automatically handled by Puppeteer)
🚀 Quick Start
Basic Usage
const WhatsAppConnect = require('@xbibzlibrary/wa-connect');
// Initialize the bot
const bot = new WhatsAppConnect({
headless: true,
logLevel: 'info'
});
async function main() {
// 1. Initialize system
await bot.initialize();
// 2. Start pairing process
const pairing = await bot.startPairing('+1234567890');
console.log(`Your Pairing Code: ${pairing.pairingCode}`);
console.log(`Enter this code in WhatsApp mobile app`);
// 3. Wait for user to enter code in WhatsApp
// The verification happens automatically in the browser
// 4. Verify pairing (after user enters code)
await bot.verifyPairing(pairing.sessionId, pairing.pairingCode);
// 5. Start sending messages
await bot.sendMessage('+1234567890', 'Hello from WhatsApp Connect Bot! 🚀');
console.log('Bot is ready!');
}
main().catch(console.error);📖 Documentation
Table of Contents
- Initialization
- Pairing System
- Sending Messages
- Receiving Messages
- Event Handling
- Session Management
- Error Handling
- Advanced Configuration
🔧 Initialization
Constructor Options
const bot = new WhatsAppConnect({
headless: true, // Run browser in headless mode
logLevel: 'info', // Log level: 'error' | 'warn' | 'info' | 'debug' | 'system'
maxRetries: 3, // Maximum retry attempts
pairingTimeout: 300000, // Pairing timeout in ms (5 minutes)
maxInactiveTime: 300000, // Max inactive time before reconnect
maxConnectionAge: 3600000, // Max connection age (1 hour)
debug: false, // Enable debug mode
userDataDir: './sessions' // Session storage directory
});Initialize the Bot
await bot.initialize();This will:
- Launch the browser instance
- Set up security layers
- Initialize event handlers
- Prepare the pairing system
🔐 Pairing System
Start Pairing
const pairingResult = await bot.startPairing('+1234567890');
console.log(pairingResult);
// {
// success: true,
// pairingCode: '12345678',
// sessionId: 'abc123...',
// expiresAt: '2025-10-05T12:30:00.000Z'
// }The 8-Digit Code
The pairing code is an 8-digit number that:
- ✅ Expires after 5 minutes by default
- ✅ Is unique per session
- ✅ Can only be used once
- ✅ Is securely generated using crypto
Verify Pairing
const verified = await bot.verifyPairing(
pairingResult.sessionId,
pairingResult.pairingCode
);
console.log(verified);
// {
// success: true,
// sessionData: { ... },
// message: 'Pairing verified successfully'
// }Complete Example
async function pairDevice() {
const phoneNumber = '+1234567890';
// Step 1: Start pairing
const pairing = await bot.startPairing(phoneNumber);
// Step 2: Display code to user
console.log('═══════════════════════════════════');
console.log(' 📱 PAIRING CODE: ' + pairing.pairingCode);
console.log('═══════════════════════════════════');
console.log(' Enter this code in WhatsApp:');
console.log(' Settings > Linked Devices > Link a Device');
console.log(' Expires: ' + new Date(pairing.expiresAt).toLocaleString());
console.log('═══════════════════════════════════');
// Step 3: Wait for verification (automatic in browser)
await new Promise(resolve => setTimeout(resolve, 30000));
// Step 4: Verify
try {
await bot.verifyPairing(pairing.sessionId, pairing.pairingCode);
console.log('✅ Device paired successfully!');
} catch (error) {
console.error('❌ Pairing failed:', error.message);
}
}💬 Sending Messages
Basic Message
await bot.sendMessage('+1234567890', 'Hello World!');Message with Options
await bot.sendMessage('+1234567890', 'Hello World!', {
delay: 100 // Typing delay in ms
});Send to Multiple Recipients
const recipients = ['+1234567890', '+0987654321'];
for (const recipient of recipients) {
await bot.sendMessage(recipient, 'Bulk message!');
await new Promise(r => setTimeout(r, 2000)); // Wait 2s between messages
}Message Response
const result = await bot.sendMessage('+1234567890', 'Test');
console.log(result);
// {
// to: '+1234567890',
// message: 'Test',
// timestamp: '2025-10-05T12:00:00.000Z',
// status: 'sent',
// messageId: 'msg_1728129600000_abc123'
// }📨 Receiving Messages
Set Up Message Listener
bot.onMessage((message) => {
console.log('Received:', message);
// {
// from: '+1234567890',
// body: 'Hello Bot!',
// timestamp: '2025-10-05T12:00:00.000Z',
// type: 'received'
// }
});Auto-Reply Bot Example
bot.onMessage(async (message) => {
console.log(`Message from ${message.from}: ${message.body}`);
// Auto-reply
if (message.body.toLowerCase().includes('hello')) {
await bot.sendMessage(message.from, 'Hello! How can I help you?');
}
// Command handling
if (message.body === '/help') {
await bot.sendMessage(message.from,
'Available commands:\n/help - Show this message\n/status - Bot status'
);
}
});Advanced Message Handler
bot.onMessage(async (message) => {
try {
// Log incoming message
console.log(`[${message.timestamp}] ${message.from}: ${message.body}`);
// Process commands
if (message.body.startsWith('/')) {
await handleCommand(message);
} else {
await handleRegularMessage(message);
}
} catch (error) {
console.error('Message handling error:', error);
}
});
async function handleCommand(message) {
const [command, ...args] = message.body.split(' ');
switch (command) {
case '/ping':
await bot.sendMessage(message.from, 'Pong! 🏓');
break;
case '/time':
await bot.sendMessage(message.from, `Current time: ${new Date().toLocaleString()}`);
break;
default:
await bot.sendMessage(message.from, 'Unknown command');
}
}🎯 Event Handling
Available Events
| Event | Description | Data |
|-------|-------------|------|
| connection_established | When connection is established | Connection object |
| connection_reestablished | After successful reconnection | Connection object |
| connection_inactive | When connection becomes inactive | Connection object |
| connection_terminated | When connection is terminated | Connection object |
| heartbeat | Periodic heartbeat signal | { sessionId, timestamp } |
| page_loaded | When WhatsApp page loads | None |
| page_error | When page error occurs | Error object |
Register Event Handlers
// Connection established
bot.onEvent('connection_established', (data) => {
console.log('✅ Connected:', data);
});
// Connection lost
bot.onEvent('connection_inactive', (data) => {
console.log('⚠️ Connection inactive:', data);
});
// Heartbeat
bot.onEvent('heartbeat', (data) => {
console.log('💓 Heartbeat:', data.timestamp);
});
// Page loaded
bot.onEvent('page_loaded', () => {
console.log('📄 WhatsApp page loaded');
});📊 Session Management
Get Session Info
const session = bot.getSessionInfo();
console.log(session);
// {
// sessionId: 'abc123...',
// phoneNumber: '+1234567890',
// pairedAt: '2025-10-05T12:00:00.000Z',
// userAgent: 'Mozilla/5.0...',
// metadata: {
// pairingMethod: '8-digit-code',
// securityLevel: 'high'
// }
// }Check Bot Status
const status = bot.getStatus();
console.log(status);
// {
// initialized: true,
// paired: true,
// sessionId: 'abc123...',
// connectionStatus: {
// connected: true,
// browser: true,
// page: true,
// session: true
// }
// }Get Chat List
const chats = await bot.getChatList();
console.log(chats);
// [
// {
// name: 'John Doe',
// lastMessage: 'Hello!',
// timestamp: '10:30 AM',
// unread: true
// },
// ...
// ]❗ Error Handling
Try-Catch Pattern
try {
await bot.sendMessage('+1234567890', 'Hello');
} catch (error) {
console.error('Error:', error.message);
console.error('Context:', error.context);
console.error('Error ID:', error.errorId);
}Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| System not initialized | Called method before initialize() | Call initialize() first |
| Invalid phone number | Phone number format incorrect | Use format: +[country][number] |
| Invalid pairing code | Wrong code format | Must be 8 digits |
| Pairing code expired | Code timeout | Generate new code |
| No active session | Not paired yet | Complete pairing first |
| Contact not found | Recipient doesn't exist | Verify phone number |
Global Error Handler
async function safeExecute(fn, context = 'operation') {
try {
return await fn();
} catch (error) {
console.error(`[${context}] Error:`, error.message);
// Log to file
const fs = require('fs');
fs.appendFileSync('error.log',
`[${new Date().toISOString()}] ${context}: ${error.message}\n`
);
// Attempt recovery
if (error.isRecoverable) {
console.log('Attempting recovery...');
// Recovery logic
}
throw error;
}
}
// Usage
await safeExecute(
() => bot.sendMessage('+1234567890', 'Hello'),
'send_message'
);⚙️ Advanced Configuration
Custom Logger
const bot = new WhatsAppConnect({
logLevel: 'debug' // Show all logs including debug
});
// The logger will output to:
// 1. Console (colored)
// 2. File: whatsapp-connect.logSession Persistence
const bot = new WhatsAppConnect({
userDataDir: './my-sessions' // Custom session directory
});
// Sessions are automatically saved and can be reused
// across restartsHeadless vs Headed Mode
// Headless (production)
const bot = new WhatsAppConnect({
headless: true
});
// Headed (development/debugging)
const bot = new WhatsAppConnect({
headless: false // See the browser
});Custom Timeouts
const bot = new WhatsAppConnect({
pairingTimeout: 600000, // 10 minutes
maxInactiveTime: 600000, // 10 minutes
maxConnectionAge: 7200000 // 2 hours
});📋 Examples
Example 1: Simple Echo Bot
const WhatsAppConnect = require('@xbibzlibrary/wa-connect');
async function echoBot() {
const bot = new WhatsAppConnect({ logLevel: 'info' });
await bot.initialize();
// Pair device
const pairing = await bot.startPairing('+1234567890');
console.log('Pairing Code:', pairing.pairingCode);
await new Promise(r => setTimeout(r, 30000));
await bot.verifyPairing(pairing.sessionId, pairing.pairingCode);
// Echo messages
bot.onMessage(async (message) => {
await bot.sendMessage(message.from, `You said: ${message.body}`);
});
console.log('Echo bot is running...');
}
echoBot().catch(console.error);Example 2: Command Bot
const commands = {
'/ping': 'Pong! 🏓',
'/time': () => new Date().toLocaleString(),
'/help': 'Commands: /ping, /time, /help, /joke',
'/joke': 'Why did the bot cross the road? To get to the other API! 😄'
};
bot.onMessage(async (message) => {
const cmd = message.body.toLowerCase();
if (commands[cmd]) {
const response = typeof commands[cmd] === 'function'
? commands[cmd]()
: commands[cmd];
await bot.sendMessage(message.from, response);
}
});Example 3: Auto-Reply with Keywords
const autoReplies = {
'hello': 'Hi there! How can I help you?',
'help': 'I can assist you with:\n- Product info\n- Support\n- FAQ',
'bye': 'Goodbye! Have a great day! 👋',
'price': 'Please visit our website for pricing information.'
};
bot.onMessage(async (message) => {
const text = message.body.toLowerCase();
for (const [keyword, reply] of Object.entries(autoReplies)) {
if (text.includes(keyword)) {
await bot.sendMessage(message.from, reply);
break;
}
}
});Example 4: Multi-Session Manager
class MultiSessionManager {
constructor() {
this.bots = new Map();
}
async createSession(phoneNumber) {
const bot = new WhatsAppConnect({
userDataDir: `./sessions/${phoneNumber}`
});
await bot.initialize();
const pairing = await bot.startPairing(phoneNumber);
this.bots.set(phoneNumber, bot);
return pairing;
}
getBot(phoneNumber) {
return this.bots.get(phoneNumber);
}
async destroySession(phoneNumber) {
const bot = this.bots.get(phoneNumber);
if (bot) {
await bot.destroy();
this.bots.delete(phoneNumber);
}
}
}
// Usage
const manager = new MultiSessionManager();
await manager.createSession('+1234567890');
await manager.createSession('+0987654321');🔍 API Reference
Class: WhatsAppConnect
Constructor
new WhatsAppConnect(options?: ConnectionOptions)Methods
| Method | Parameters | Returns | Description |
|--------|-----------|---------|-------------|
| initialize() | - | Promise<Object> | Initialize the bot system |
| startPairing(phoneNumber) | string | Promise<PairingResult> | Start pairing process |
| verifyPairing(sessionId, code) | string, string | Promise<VerificationResult> | Verify pairing code |
| sendMessage(to, message, options?) | string, string, Object | Promise<MessageResult> | Send a message |
| onMessage(callback) | Function | Promise<void> | Register message handler |
| onEvent(event, callback) | string, Function | Promise<void> | Register event handler |
| getChatList() | - | Promise<Array> | Get list of chats |
| getStatus() | - | Object | Get bot status |
| getSessionInfo() | - | Object | Get session information |
| destroy() | - | Promise<void> | Cleanup and destroy bot |
Types
interface ConnectionOptions {
headless?: boolean;
logLevel?: 'error' | 'warn' | 'info' | 'debug' | 'system';
maxRetries?: number;
pairingTimeout?: number;
maxInactiveTime?: number;
maxConnectionAge?: number;
debug?: boolean;
userDataDir?: string;
}
interface PairingResult {
success: boolean;
pairingCode: string;
sessionId: string;
expiresAt: string;
}
interface MessageResult {
to: string;
message: string;
timestamp: string;
status: string;
messageId: string;
}🛡️ Security Best Practices
Never commit session data to version control
echo "sessions/" >> .gitignoreUse environment variables for sensitive data
const phoneNumber = process.env.PHONE_NUMBER;Implement rate limiting in your application
const rateLimit = require('express-rate-limit');Validate all inputs before processing
function sanitizeInput(input) { return input.trim().replace(/[<>]/g, ''); }Keep dependencies updated
npm audit npm update
🐛 Troubleshooting
Issue: Browser won't launch
Solution:
# Install required dependencies (Linux)
sudo apt-get install -y \
chromium-browser \
libx11-xcb1 \
libxcomposite1 \
libxdamage1Issue: Pairing code not working
Checks:
- ✅ Code is exactly 8 digits
- ✅ Code hasn't expired (5 minutes)
- ✅ Using correct phone number format
- ✅ WhatsApp mobile app is up to date
Issue: Messages not sending
Debugging:
const bot = new WhatsAppConnect({
logLevel: 'debug', // Enable debug logs
headless: false // See what's happening
});Issue: Session not persisting
Solution:
const bot = new WhatsAppConnect({
userDataDir: path.resolve(__dirname, 'sessions') // Use absolute path
});📝 License
MIT License - see LICENSE file for details
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📞 Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: [email protected]
🙏 Acknowledgments
- Built with Puppeteer
- Inspired by the WhatsApp BOT
- Special thanks to all contributors
Made with ❤️ by Xbibz Official
