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

406 lines (351 loc) 10.7 kB
import { WhatsAppClient, BotFramework, MessageQueue, MongoDBAdapter, PollingService, SessionManager, MetricsCollector, ConsoleExporter, middleware } from '@akson/chatsuite-sdk'; /** * Example 1: Complete WhatsApp Automation Setup * * This example shows how to set up a complete WhatsApp automation * with all enhanced features in just a few lines of code. */ async function completeAutomationExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Complete automation setup with all features const automation = await client.createAutomation('+1234567890', { name: 'My WhatsApp Bot', webhookUrl: 'https://my-server.com/webhook', // Bot framework configuration bot: { prefix: '!', caseSensitive: false, maxCommandsPerMinute: 10 }, // Message queue configuration queue: { maxConcurrent: 5, rateLimitPerMinute: 30, retryAttempts: 3 }, // Database sync configuration database: { uri: 'mongodb://localhost:27017', collections: { messages: 'whatsapp_messages', chats: 'whatsapp_chats', contacts: 'whatsapp_contacts' } }, // Polling service configuration polling: { interval: 5 * 60 * 1000, // 5 minutes strategy: 'smart' }, // Metrics collection metrics: { enabled: true, collectors: ['messages', 'sessions', 'performance'], exporters: [new ConsoleExporter({ interval: 60000 })] } }); // Bot is now ready with all features! console.log('Automation setup complete:', automation); } /** * Example 2: Bot Framework Usage * * Shows how to create a sophisticated bot with commands, * middleware, and conversation handling. */ async function botFrameworkExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Create bot const bot = client.createBot('+1234567890', { prefix: '!', caseSensitive: false, maxCommandsPerMinute: 10, defaultResponse: 'Command not found. Type !help for available commands.' }); // Add middleware bot.use(middleware.logging()); bot.use(middleware.userContext(async (senderId) => { // Load user from your database return { id: senderId, permissions: ['customer'] }; })); // Add commands bot.addCommand({ name: 'hello', description: 'Say hello', handler: async (context, args) => { return `Hello ${context.user?.id || 'there'}! 👋`; } }); bot.addCommand({ name: 'order', description: 'Check order status', usage: '!order <order_id>', permissions: ['customer'], handler: async (context, args) => { const orderId = args[0]; if (!orderId) { return 'Please provide an order ID. Usage: !order <order_id>'; } // Check order in database const order = await checkOrderStatus(orderId); return order ? `Order ${orderId}: ${order.status}` : 'Order not found'; } }); // Start bot and listen for messages bot.start(); // In your webhook handler, process messages: // await bot.processMessage(incomingMessage); } /** * Example 3: Message Queue for Bulk Operations * * Shows how to use the message queue for rate-limited * bulk message sending with priority handling. */ async function messageQueueExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Create message queue const queue = client.createMessageQueue({ maxConcurrent: 3, rateLimitPerMinute: 20, retryAttempts: 3, batchSize: 10 }); // Listen for events queue.on('message:completed', ({ message, result }) => { console.log(`Message sent to ${message.chatId}:`, result); }); queue.on('message:failed', ({ message, error }) => { console.error(`Failed to send message to ${message.chatId}:`, error); }); queue.on('stats:updated', (stats) => { console.log('Queue stats:', stats); }); // Start processing queue.start(); // Add messages to queue const customers = [ { chatId: '1234567890@c.us', priority: 'urgent' as const }, { chatId: '1234567891@c.us', priority: 'normal' as const }, { chatId: '1234567892@c.us', priority: 'low' as const } ]; for (const customer of customers) { await queue.enqueue({ tel: '+1234567890', chatId: customer.chatId, content: { text: 'Hello! This is an automated message.' }, type: 'text', priority: customer.priority, maxRetries: 3 }); } // Bulk enqueue const bulkMessages = customers.map(customer => ({ tel: '+1234567890', chatId: customer.chatId, content: { text: 'Bulk message update!' }, type: 'text' as const, priority: 'normal' as const, maxRetries: 3 })); await queue.enqueueBatch(bulkMessages); } /** * Example 4: Database Sync Adapter * * Shows how to automatically sync WhatsApp data * to MongoDB with field mapping and transformers. */ async function databaseSyncExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Create database adapter const dbAdapter = client.createDatabaseAdapter({ uri: 'mongodb://localhost:27017', database: 'whatsapp_data', collections: { messages: 'whatsapp_messages', chats: 'whatsapp_chats', contacts: 'whatsapp_contacts' }, fieldMapping: { 'key.id': 'messageId', 'key.remoteJid': 'chatId', 'key.fromMe': 'fromMe', 'messageTimestamp': { target: 'timestamp', transform: (ts: number) => new Date(parseInt(ts.toString()) * 1000) }, 'pushName': 'senderName', 'message.conversation': 'text' }, transformers: { messageType: (data: any) => { if (data.message?.conversation) return 'text'; if (data.message?.imageMessage) return 'image'; if (data.message?.videoMessage) return 'video'; return 'unknown'; } } }); // Connect to database await dbAdapter.connect(); // Listen for sync events dbAdapter.on('document:inserted', ({ original, transformed }) => { console.log('New message synced:', transformed.messageId); }); // Sync messages (this would typically be called from webhook or polling) const messages = await client.messages.list({ tel: '+1234567890', limit: 100 }); const syncResult = await dbAdapter.sync('messages', messages); console.log('Sync result:', syncResult); } /** * Example 5: Polling Service * * Shows how to set up automatic message polling * with smart scheduling and activity tracking. */ async function pollingServiceExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Create polling service const poller = client.createPollingService('+1234567890', { interval: 5 * 60 * 1000, // 5 minutes strategy: 'smart', // Only poll active chats adaptiveInterval: true, // Adjust based on activity batchSize: 50 }); // Listen for polling events poller.on('sync:start', ({ estimatedTime }) => { console.log(`Starting message sync (ETA: ${estimatedTime}ms)`); }); poller.on('sync:complete', ({ processed, duration }) => { console.log(`Synced ${processed} chats in ${duration}ms`); }); poller.on('interval:adjusted', ({ oldInterval, newInterval, activityScore }) => { console.log(`Polling interval adjusted: ${oldInterval}ms → ${newInterval}ms (activity: ${activityScore})`); }); // Start polling poller.start(); // Get stats const stats = poller.getStats(); console.log('Polling stats:', stats); } /** * Example 6: Session Manager * * Shows how to use advanced session management * with health monitoring and auto-recovery. */ async function sessionManagerExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Create session manager const sessionManager = client.createSessionManager({ autoRestart: true, maxRestartAttempts: 3, restartDelay: 30000, healthCheckInterval: 60000 }); // Listen for session events sessionManager.on('session:qr', ({ tel, qr }) => { console.log(`QR Code for ${tel}:`, qr); }); sessionManager.on('session:restored', ({ tel }) => { console.log(`Session ${tel} restored successfully`); }); sessionManager.on('session:restarted', ({ tel }) => { console.log(`Session ${tel} automatically restarted`); }); sessionManager.on('health:check:unhealthy', ({ tel, state }) => { console.warn(`Session ${tel} is unhealthy: ${state}`); }); // Restore session with automatic management await sessionManager.restoreSession('+1234567890', { name: 'Managed Session', autoRestart: true, healthCheckInterval: 30000 }); // Get health metrics const healthMetrics = sessionManager.getHealthMetrics('+1234567890'); console.log('Health metrics:', healthMetrics); } /** * Example 7: Metrics Collection * * Shows how to collect and export performance metrics * for monitoring and observability. */ async function metricsExample() { const client = new WhatsAppClient({ apiToken: 'wa_your_token_here' }); // Create metrics collector const metrics = client.createMetricsCollector({ enabled: true, collectors: ['messages', 'sessions', 'performance'], flushInterval: 30000, maxBufferSize: 100, exporters: [ new ConsoleExporter({ detailed: true }) ] }); // Track message operations metrics.increment('messages_sent_total', { type: 'text' }); metrics.histogram('message_send_duration_ms', 1250); // Track performance with timer const timer = metrics.startTimer('send_message'); try { await client.messages.sendText('+1234567890', '1234567890@c.us', 'Hello!'); timer(true); // Success } catch (error) { timer(false); // Failed } // Custom metrics metrics.gauge('active_sessions', 5); metrics.increment('api_errors_total', { endpoint: '/messages', error: 'rate_limit' }); // Get current metrics const currentMetrics = metrics.getMetrics(); console.log('Current metrics:', currentMetrics); } // Helper function for bot example async function checkOrderStatus(orderId: string): Promise<{ status: string } | null> { // Simulate database lookup const orders = { '12345': { status: 'delivered' }, '67890': { status: 'in_transit' } }; return orders[orderId] || null; } // Export examples for use export { completeAutomationExample, botFrameworkExample, messageQueueExample, databaseSyncExample, pollingServiceExample, sessionManagerExample, metricsExample };