@akson/chatsuite-sdk
Version:
Production-ready TypeScript SDK for ChatSuite - WhatsApp automation with built-in session management, message queuing, webhook server, and database sync
199 lines (165 loc) ⢠6.97 kB
text/typescript
/**
* Enhanced WhatsApp Client Example
*
* This example demonstrates the new v2.0 enhanced features:
* - Session management with MongoDB persistence
* - Message queuing with rate limiting
* - Webhook server with event handling
* - Database synchronization
*
* Run: npx ts-node examples/enhanced-client.ts
*/
import { createEnhancedClient } from '../src/index';
async function main() {
console.log('š ChatSuite SDK v2.0 Enhanced Client Example');
// Create enhanced client with all features enabled
const client = createEnhancedClient({
apiToken: process.env.WHATSAPP_API_TOKEN || 'wa_your_token_here',
baseUrl: process.env.WHATSAPP_API_URL || 'https://api.chatsuite.com',
// MongoDB for session persistence and data sync
mongoUri: process.env.MONGODB_URI || 'mongodb://localhost:27017/whatsapp',
// Built-in webhook server
webhookPort: 3001,
// Enable all enhanced features
sessionStorage: 'mongodb', // or 'memory' for development
enableQueue: true,
enableWebhook: true
});
// Initialize all components
console.log('Initializing enhanced client...');
await client.initialize();
console.log('ā
Enhanced client initialized successfully!');
// Set up webhook handlers for real-time events
client.addWebhookHandler('messages.upsert', async (data) => {
console.log('šØ New messages received:', data.messages?.length || 0);
for (const message of data.messages || []) {
const text = message.message?.conversation;
const from = message.key.remoteJid;
if (text && from) {
console.log(`š¬ Message from ${from}: ${text}`);
// Auto-reply with queue (rate limited)
if (text.toLowerCase().includes('hello')) {
await client.sendMessage(from, {
text: `Hello! I received your message: "${text}"`
});
}
}
}
});
client.addWebhookHandler('connection.update', async (data) => {
console.log('š Connection update:', data);
if (data.connection === 'open') {
console.log('ā
WhatsApp connected successfully!');
} else if (data.connection === 'close') {
console.log('ā WhatsApp connection closed');
}
});
// Create and manage sessions with automatic persistence
const phoneNumber = '+1234567890'; // Replace with your phone number
try {
console.log(`\nš± Creating session for ${phoneNumber}...`);
const session = await client.createSession(phoneNumber, 'Enhanced Bot');
console.log('ā
Session created:', session.sessionId);
// Get all sessions (automatically retrieved from MongoDB)
const allSessions = await client.getAllSessions();
console.log(`š Total sessions: ${allSessions.length}`);
// Send a single message through the queue
console.log('\nš¤ Sending message through queue...');
const messageId = await client.sendMessage(
phoneNumber + '@c.us',
{ text: 'Hello from Enhanced SDK v2.0! š' },
5 // High priority
);
console.log('ā
Message queued:', messageId);
// Send bulk messages with automatic scheduling
console.log('\nš¬ Sending bulk messages...');
const recipients = [
phoneNumber + '@c.us',
// Add more recipients as needed
];
const bulkIds = await client.sendBulkMessages({
recipients,
message: { text: 'This is a bulk message from Enhanced SDK!' },
delay: 2000, // 2 seconds between messages
priority: 3,
metadata: { campaign: 'sdk-demo' }
});
console.log(`ā
Bulk messages queued: ${bulkIds.length}`);
// Monitor queue statistics
setInterval(() => {
const queueStats = client.getQueueStats();
if (queueStats) {
console.log('\nš Queue Statistics:');
console.log(` Pending: ${queueStats.pending}`);
console.log(` Processing: ${queueStats.processing}`);
console.log(` Completed: ${queueStats.completed}`);
console.log(` Failed: ${queueStats.failed}`);
console.log(` Throughput: ${queueStats.throughput.toFixed(2)} msgs/sec`);
}
const webhookStats = client.getWebhookStats();
if (webhookStats) {
console.log('\nš Webhook Statistics:');
console.log(` Total Requests: ${webhookStats.totalRequests}`);
console.log(` Success Rate: ${(webhookStats.successfulRequests / webhookStats.totalRequests * 100).toFixed(1)}%`);
console.log(` Avg Response Time: ${webhookStats.averageResponseTime.toFixed(0)}ms`);
console.log(` Uptime: ${(webhookStats.uptime / 60).toFixed(1)} minutes`);
}
}, 10000); // Every 10 seconds
// Query database directly (messages automatically synced)
console.log('\nš¾ Querying database...');
try {
const messages = await client.queryDatabase('messages', {
'key.remoteJid': phoneNumber + '@c.us'
}, {
sort: { messageTimestamp: -1 },
limit: 5
});
console.log(`š Found ${messages.length} messages in database`);
} catch (error) {
console.log('ā¹ļø Database query requires MongoDB connection');
}
// Event monitoring
client.on('session:connected', (session) => {
console.log(`ā
Session connected: ${session.phoneNumber}`);
});
client.on('session:disconnected', (session) => {
console.log(`ā Session disconnected: ${session.phoneNumber}`);
});
client.on('message:sent', (messageId, recipient) => {
console.log(`š¤ Message ${messageId} sent to ${recipient}`);
});
client.on('message:failed', (error, recipient) => {
console.log(`ā Message failed to ${recipient}: ${error.message}`);
});
client.on('queue:processed', (itemId, result) => {
console.log(`ā
Queue item ${itemId} processed successfully`);
});
client.on('webhook:received', (event, data) => {
console.log(`š£ Webhook received: ${event}`);
});
console.log('\nš Enhanced client demo running!');
console.log('š” Webhook server listening on http://localhost:3001/webhook');
console.log('š¾ Data automatically syncing to MongoDB');
console.log('š¬ Messages queued with rate limiting');
console.log('š Sessions persisted and auto-reconnecting');
console.log('\nPress Ctrl+C to stop...');
// Keep the process running
process.on('SIGINT', async () => {
console.log('\nš Shutting down gracefully...');
await client.stop();
console.log('ā
Enhanced client stopped');
process.exit(0);
});
} catch (error) {
console.error('ā Error:', error);
}
}
// Handle unhandled rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Run the example
if (require.main === module) {
main().catch(console.error);
}
export { main as enhancedClientExample };