
Company News
Socket Named Top Sales Organization by RepVue
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.
@xbibzlibrary/wa-connect
Advanced tools
Advanced WhatsApp Connect Bot with 8-digit Pairing Code System - Powerful & Modern
Advanced WhatsApp Connect Bot with 8-Digit Pairing Code System
Powerful • Modern • Secure • Production-Ready
Installation • Quick Start • Documentation • Examples • API Reference
Core Capabilities
|
Security & Performance
|
npm install @xbibzlibrary/wa-connect
Or with yarn:
yarn add @xbibzlibrary/wa-connect
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);
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
});
await bot.initialize();
This will:
const pairingResult = await bot.startPairing('+1234567890');
console.log(pairingResult);
// {
// success: true,
// pairingCode: '12345678',
// sessionId: 'abc123...',
// expiresAt: '2025-10-05T12:30:00.000Z'
// }
The pairing code is an 8-digit number that:
const verified = await bot.verifyPairing(
pairingResult.sessionId,
pairingResult.pairingCode
);
console.log(verified);
// {
// success: true,
// sessionData: { ... },
// message: 'Pairing verified successfully'
// }
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);
}
}
await bot.sendMessage('+1234567890', 'Hello World!');
await bot.sendMessage('+1234567890', 'Hello World!', {
delay: 100 // Typing delay in ms
});
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
}
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'
// }
bot.onMessage((message) => {
console.log('Received:', message);
// {
// from: '+1234567890',
// body: 'Hello Bot!',
// timestamp: '2025-10-05T12:00:00.000Z',
// type: 'received'
// }
});
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'
);
}
});
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 | 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 |
// 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');
});
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'
// }
// }
const status = bot.getStatus();
console.log(status);
// {
// initialized: true,
// paired: true,
// sessionId: 'abc123...',
// connectionStatus: {
// connected: true,
// browser: true,
// page: true,
// session: true
// }
// }
const chats = await bot.getChatList();
console.log(chats);
// [
// {
// name: 'John Doe',
// lastMessage: 'Hello!',
// timestamp: '10:30 AM',
// unread: true
// },
// ...
// ]
try {
await bot.sendMessage('+1234567890', 'Hello');
} catch (error) {
console.error('Error:', error.message);
console.error('Context:', error.context);
console.error('Error ID:', error.errorId);
}
| 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 |
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'
);
const bot = new WhatsAppConnect({
logLevel: 'debug' // Show all logs including debug
});
// The logger will output to:
// 1. Console (colored)
// 2. File: whatsapp-connect.log
const bot = new WhatsAppConnect({
userDataDir: './my-sessions' // Custom session directory
});
// Sessions are automatically saved and can be reused
// across restarts
// Headless (production)
const bot = new WhatsAppConnect({
headless: true
});
// Headed (development/debugging)
const bot = new WhatsAppConnect({
headless: false // See the browser
});
const bot = new WhatsAppConnect({
pairingTimeout: 600000, // 10 minutes
maxInactiveTime: 600000, // 10 minutes
maxConnectionAge: 7200000 // 2 hours
});
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);
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);
}
});
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;
}
}
});
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');
new WhatsAppConnect(options?: ConnectionOptions)
| 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 |
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;
}
Never commit session data to version control
echo "sessions/" >> .gitignore
Use 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
Solution:
# Install required dependencies (Linux)
sudo apt-get install -y \
chromium-browser \
libx11-xcb1 \
libxcomposite1 \
libxdamage1
Checks:
Debugging:
const bot = new WhatsAppConnect({
logLevel: 'debug', // Enable debug logs
headless: false // See what's happening
});
Solution:
const bot = new WhatsAppConnect({
userDataDir: path.resolve(__dirname, 'sessions') // Use absolute path
});
MIT License - see LICENSE file for details
Contributions are welcome! Please feel free to submit a Pull Request.
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)Made with ❤️ by Xbibz Official
FAQs
Advanced WhatsApp Connect Bot with 8-digit Pairing Code System - Powerful & Modern
We found that @xbibzlibrary/wa-connect demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Company News
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.

Security News
NIST will stop enriching most CVEs under a new risk-based model, narrowing the NVD's scope as vulnerability submissions continue to surge.

Company News
/Security News
Socket is an initial recipient of OpenAI's Cybersecurity Grant Program, which commits $10M in API credits to defenders securing open source software.