@akson/chatsuite-sdk
v2.0.0
Published
Production-ready TypeScript SDK for ChatSuite - WhatsApp automation with built-in session management, message queuing, webhook server, and database sync
Maintainers
Readme
ChatSuite SDK 🚀
Production-ready TypeScript SDK for ChatSuite - WhatsApp automation with comprehensive session management, message operations, webhooks, and enterprise-grade automation features.
✨ Core Features
- 🗄️ Session Management: Complete session lifecycle with QR code handling
- 📬 Message Operations: Text, media, interactive messages, polls, reactions
- 👥 Group Management: Create, manage, and moderate WhatsApp groups
- 📞 Contact Management: Check registration, manage contacts, profile pictures
- 📝 Status Updates: Post and manage WhatsApp status (stories)
- 🔗 Webhook Integration: Real-time event handling
- 🧪 Production Ready: Comprehensive error handling and TypeScript support
🚀 Enhanced Automation Features
- 🤖 Bot Framework: Command parsing, middleware, conversation management
- 📬 Message Queue: Rate limiting, bulk operations, priority handling, retry logic
- 🗄️ Database Sync: MongoDB integration with field mapping and transformers
- 🔄 Polling Service: Smart message syncing with adaptive intervals
- 💾 Session Management: Health monitoring, auto-recovery, persistence
- 📊 Metrics Collection: Performance monitoring, observability, multiple exporters
- 🔄 Migration Helper: Format adapters and compatibility layers
📈 Dramatic Code Reduction
With the enhanced SDK features, reduce implementation complexity by 80-96%:
| Feature | Without SDK | With SDK | Reduction | |---------|-------------|----------|-----------| | Session Management | 120 lines | 10 lines | 92% | | Database Sync | 80 lines | 15 lines | 81% | | Message Queue | 60 lines | 8 lines | 87% | | Bot Framework | 100 lines | 25 lines | 75% | | Complete Project | 775 lines | 30 lines | 96% |
Installation
npm install @akson/chatsuite-sdk
# or
yarn add @akson/chatsuite-sdk
# or
pnpm add @akson/chatsuite-sdk⚡ Quick Start
Basic Usage
import { WhatsAppClient } from '@akson/chatsuite-sdk';
const client = new WhatsAppClient({
apiToken: 'wa_your_token_here'
});
// Send a message
await client.messages.sendText('+1234567890', '[email protected]', 'Hello!');🚀 Complete Automation (30 lines replaces 775+ lines!)
import { WhatsAppClient, ConsoleExporter } from '@akson/chatsuite-sdk';
const client = new WhatsAppClient({
apiToken: 'wa_your_token_here'
});
// Complete WhatsApp automation in just a few lines
const automation = await client.createAutomation('+1234567890', {
name: 'My WhatsApp Bot',
webhookUrl: 'https://my-server.com/webhook',
// Bot with commands and middleware
bot: {
prefix: '!',
maxCommandsPerMinute: 10
},
// Message queue with rate limiting
queue: {
maxConcurrent: 5,
rateLimitPerMinute: 30
},
// Database sync
database: {
uri: 'mongodb://localhost:27017',
collections: {
messages: 'whatsapp_messages',
chats: 'whatsapp_chats'
}
},
// Smart polling
polling: {
interval: 5 * 60 * 1000,
strategy: 'smart'
},
// Metrics collection
metrics: {
enabled: true,
collectors: ['messages', 'sessions'],
exporters: [new ConsoleExporter()]
}
});
// Bot is ready with all features!
console.log('Automation active:', automation);🤖 Enhanced Automation Features
Bot Framework
Create sophisticated bots with command parsing and middleware:
// Create bot
const bot = client.createBot('+1234567890', {
prefix: '!',
maxCommandsPerMinute: 10
});
// Add middleware
bot.use(middleware.userContext(getUserFromDB));
bot.use(middleware.logging());
// Add commands
bot.addCommand({
name: 'order',
description: 'Check order status',
handler: async (context, args) => {
const orderId = args[0];
const order = await getOrder(orderId);
return `Order ${orderId}: ${order.status}`;
}
});
bot.start();Message Queue
Handle bulk messaging with rate limiting and priorities:
// Create queue
const queue = client.createMessageQueue({
maxConcurrent: 5,
rateLimitPerMinute: 30
});
// Add messages
await queue.enqueue({
tel: '+1234567890',
chatId: '[email protected]',
content: { text: 'Urgent notification!' },
type: 'text',
priority: 'urgent'
});
queue.start();Database Sync
Automatically sync WhatsApp data to MongoDB:
// Create database adapter
const dbAdapter = client.createDatabaseAdapter({
uri: 'mongodb://localhost:27017',
collections: { messages: 'whatsapp_messages' },
fieldMapping: {
'key.id': 'messageId',
'messageTimestamp': {
target: 'timestamp',
transform: (ts) => new Date(ts * 1000)
}
}
});
await dbAdapter.connect();
await dbAdapter.sync('messages', messages);Polling Service
Smart message syncing with adaptive intervals:
// Create polling service
const poller = client.createPollingService('+1234567890', {
interval: 5 * 60 * 1000,
strategy: 'smart'
});
poller.start();Session Management
Advanced session handling with health monitoring:
// Create session manager
const sessionManager = client.createSessionManager({
autoRestart: true,
healthCheckInterval: 60000
});
await sessionManager.restoreSession('+1234567890');Metrics Collection
Monitor performance and collect observability data:
// Create metrics collector
const metrics = client.createMetricsCollector({
enabled: true,
exporters: [new ConsoleExporter(), new PrometheusExporter()]
});
metrics.increment('messages_sent_total');
metrics.histogram('message_duration_ms', duration);📱 Core API Features
Session Management
// List sessions
const sessions = await client.sessions.list();
// Quick session setup with QR polling
const result = await client.quickStart('+1234567890', 'My Bot');
console.log('Scan QR:', result.session.qr);Messages
// Send text
await client.messages.sendText('+1234567890', '[email protected]', 'Hello!');
// Send interactive buttons
await client.messages.sendButtons('+1234567890', '[email protected]', 'Choose:', [
{ id: '1', text: 'Option 1' },
{ id: '2', text: 'Option 2' }
]);
// Send polls
await client.messages.sendPoll('+1234567890', '[email protected]', 'Question?', [
'Option A', 'Option B'
]);Groups & Business
// Create group
const group = await client.groups.create({
tel: '+1234567890',
name: 'Team Chat',
participants: ['[email protected]', '[email protected]']
});
// Business catalog
const products = await client.business.listProducts('+1234567890');
await client.business.createCart('+1234567890', '[email protected]');Error Handling
import { WhatsAppClient, ApiError } from '@akson/chatsuite-sdk';
try {
await client.messages.sendText(tel, to, text);
} catch (error) {
if (error instanceof ApiError) {
console.error('API Error:', {
message: error.message,
status: error.status,
code: error.code
});
}
}TypeScript Support
Full TypeScript definitions included:
import {
WhatsAppClient,
Session,
Message,
Contact,
Group,
ApiError
} from '@akson/chatsuite-sdk';Authentication
Get your API token from the ChatSuite dashboard:
const client = new WhatsAppClient({
apiToken: 'wa_your_token_here',
baseUrl: 'https://your-instance.com', // optional
timeout: 30000, // optional
maxRetries: 3 // optional
});Documentation
- Changelog - Version history and changes
- Examples - Usage examples and integration guides
- TypeScript Types - Complete type definitions
Support
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 📖 API Reference: https://api.chatsuite.com/docs
License
MIT License - see LICENSE file for details.
