UNPKG

@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
/** * 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 };