Event System
Event System
Section titled “Event System”Evolution API Lite features a comprehensive event-driven architecture that allows you to receive real-time updates about WhatsApp activities. The system supports multiple delivery methods including Webhooks, RabbitMQ, SQS, Pusher, and WebSockets.
Architecture Overview
Section titled “Architecture Overview”The event system is built around the EventManager which coordinates event distribution across multiple channels:
Event Types
Section titled “Event Types”The system supports a comprehensive set of event types that cover all WhatsApp activities:
Connection Events
Section titled “Connection Events”APPLICATION_STARTUP- API server startupINSTANCE_CREATE- New instance createdINSTANCE_DELETE- Instance deletedCONNECTION_UPDATE- Connection status changesQRCODE_UPDATED- QR code updated for authenticationREMOVE_INSTANCE- Instance removed from memoryLOGOUT_INSTANCE- Instance logged out
Message Events
Section titled “Message Events”MESSAGES_SET- Initial message history loadedMESSAGES_UPSERT- New messages received or sentMESSAGES_EDITED- Messages editedMESSAGES_UPDATE- Message status updated (delivered, read, etc.)MESSAGES_DELETE- Messages deletedSEND_MESSAGE- Message sent confirmation
Contact Events
Section titled “Contact Events”CONTACTS_SET- Initial contacts loadedCONTACTS_UPSERT- New contacts added or updatedCONTACTS_UPDATE- Contact information updatedPRESENCE_UPDATE- Contact presence status changed (online, offline, typing)
Chat Events
Section titled “Chat Events”CHATS_SET- Initial chat list loadedCHATS_UPSERT- New chats created or updatedCHATS_UPDATE- Chat information updatedCHATS_DELETE- Chats deleted
Group Events
Section titled “Group Events”GROUPS_UPSERT- Group information updatedGROUP_UPDATE- Group settings changedGROUP_PARTICIPANTS_UPDATE- Group participants added/removed/promoted
Other Events
Section titled “Other Events”CALL- Incoming or outgoing callsLABELS_EDIT- Message labels editedLABELS_ASSOCIATION- Labels associated with messagesTYPEBOT_START- Typebot conversation startedTYPEBOT_CHANGE_STATUS- Typebot status changed
Event Delivery Methods
Section titled “Event Delivery Methods”1. Webhooks
Section titled “1. Webhooks”Webhooks deliver events via HTTP POST requests to your specified endpoints.
Configuration
Section titled “Configuration”# Global webhook configurationWEBHOOK_GLOBAL_ENABLED=trueWEBHOOK_GLOBAL_URL=https://your-server.com/webhookWEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false
# Event-specific configurationWEBHOOK_EVENTS_MESSAGES_UPSERT=trueWEBHOOK_EVENTS_CONNECTION_UPDATE=trueInstance-Specific Webhooks
Section titled “Instance-Specific Webhooks”Configure webhooks per instance during creation:
curl -X POST http://localhost:8080/instance/create \ -H "Content-Type: application/json" \ -H "apikey: YOUR_GLOBAL_API_KEY" \ -d '{ "instanceName": "my-instance", "integration": "WHATSAPP-BAILEYS", "webhook": { "enabled": true, "url": "https://your-server.com/webhook", "byEvents": false, "base64": true, "headers": { "Authorization": "Bearer your-token" }, "events": [ "MESSAGES_UPSERT", "CONNECTION_UPDATE" ] } }'Webhook Payload Format
Section titled “Webhook Payload Format”{ "event": "messages.upsert", "instance": "my-instance", "data": { "key": { "remoteJid": "5511999999999@s.whatsapp.net", "fromMe": false, "id": "3EB0C767D82B632A2E4A" }, "message": { "conversation": "Hello World!" }, "messageTimestamp": 1640995200, "pushName": "John Doe" }, "destination": "https://your-server.com/webhook", "date_time": "2023-12-01T10:30:00.000Z", "sender": "5511999999999@s.whatsapp.net", "server_url": "http://localhost:8080", "apikey": "instance-token"}Webhook Features
Section titled “Webhook Features”- Retry Logic: Automatic retry with exponential backoff (up to 10 attempts)
- Custom Headers: Add authentication or custom headers
- Event Filtering: Subscribe to specific events only
- Base64 Media: Option to include media as base64 in webhook payload
- By Events: Send events to different endpoints based on event type
2. RabbitMQ
Section titled “2. RabbitMQ”Publish events to RabbitMQ exchanges for distributed processing.
Configuration
Section titled “Configuration”RABBITMQ_ENABLED=trueRABBITMQ_URI=amqp://localhost:5672RABBITMQ_EXCHANGE_NAME=evolution_exchangeRABBITMQ_GLOBAL_ENABLED=true
# Event configurationRABBITMQ_EVENTS_MESSAGES_UPSERT=trueRABBITMQ_EVENTS_CONNECTION_UPDATE=trueExchange and Routing
Section titled “Exchange and Routing”- Exchange Type: Topic exchange
- Routing Key Pattern:
{instanceName}.{event} - Example:
my-instance.messages.upsert
Message Format
Section titled “Message Format”{ "event": "messages.upsert", "instance": "my-instance", "data": { /* event data */ }, "date_time": "2023-12-01T10:30:00.000Z", "sender": "5511999999999@s.whatsapp.net"}3. Amazon SQS
Section titled “3. Amazon SQS”Send events to AWS SQS queues for cloud-based processing.
Configuration
Section titled “Configuration”SQS_ENABLED=trueSQS_ACCESS_KEY_ID=your-access-keySQS_SECRET_ACCESS_KEY=your-secret-keySQS_ACCOUNT_ID=123456789012SQS_REGION=us-east-1Queue Naming
Section titled “Queue Naming”Queues are automatically created with the pattern: {instanceName}-{event}
4. Pusher
Section titled “4. Pusher”Real-time events via Pusher channels for web applications.
Configuration
Section titled “Configuration”PUSHER_ENABLED=truePUSHER_GLOBAL_ENABLED=truePUSHER_GLOBAL_APP_ID=your-app-idPUSHER_GLOBAL_KEY=your-keyPUSHER_GLOBAL_SECRET=your-secretPUSHER_GLOBAL_CLUSTER=us2PUSHER_GLOBAL_USE_TLS=trueChannel Structure
Section titled “Channel Structure”- Channel:
{instanceName} - Event:
{event-type}
5. WebSockets
Section titled “5. WebSockets”Real-time bidirectional communication via WebSocket connections.
Configuration
Section titled “Configuration”WEBSOCKET_ENABLED=trueWEBSOCKET_GLOBAL_EVENTS=trueConnection
Section titled “Connection”const ws = new WebSocket('ws://localhost:8080')
ws.on('message', (data) => { const event = JSON.parse(data) console.log('Received event:', event)})Event Manager Implementation
Section titled “Event Manager Implementation”The EventManager class coordinates all event delivery:
Key Features
Section titled “Key Features”- Multi-Channel Distribution: Events are sent to all configured channels simultaneously
- Instance-Specific Configuration: Each instance can have different event settings
- Event Filtering: Configure which events to receive per channel
- Error Handling: Robust error handling with logging and retry mechanisms
Event Flow
Section titled “Event Flow”Configuration Examples
Section titled “Configuration Examples”Complete Instance Configuration
Section titled “Complete Instance Configuration”{ "instanceName": "production-bot", "integration": "WHATSAPP-BAILEYS", "webhook": { "enabled": true, "url": "https://api.mycompany.com/whatsapp/webhook", "byEvents": true, "base64": false, "headers": { "Authorization": "Bearer prod-token-123", "X-Instance": "production-bot" }, "events": ["MESSAGES_UPSERT", "CONNECTION_UPDATE", "CONTACTS_UPDATE"] }, "rabbitmq": { "enabled": true, "events": ["MESSAGES_UPSERT", "SEND_MESSAGE"] }, "websocket": { "enabled": true, "events": ["CONNECTION_UPDATE", "QRCODE_UPDATED"] }}Global Event Configuration
Section titled “Global Event Configuration”# Enable global webhooks for all instancesWEBHOOK_GLOBAL_ENABLED=trueWEBHOOK_GLOBAL_URL=https://api.mycompany.com/global-webhook
# Enable specific events globallyWEBHOOK_EVENTS_MESSAGES_UPSERT=trueWEBHOOK_EVENTS_CONNECTION_UPDATE=trueWEBHOOK_EVENTS_INSTANCE_CREATE=trueWEBHOOK_EVENTS_INSTANCE_DELETE=true
# RabbitMQ global configurationRABBITMQ_GLOBAL_ENABLED=trueRABBITMQ_EVENTS_MESSAGES_UPSERT=trueRABBITMQ_EVENTS_SEND_MESSAGE=trueBest Practices
Section titled “Best Practices”Webhook Security
Section titled “Webhook Security”- Use HTTPS endpoints in production
- Implement webhook signature verification
- Add authentication headers
- Validate incoming payloads
Error Handling
Section titled “Error Handling”- Implement proper error handling in webhook endpoints
- Return appropriate HTTP status codes (200 for success)
- Log webhook failures for debugging
- Set up monitoring and alerting
Performance
Section titled “Performance”- Use asynchronous processing for webhook handlers
- Implement proper database connection pooling
- Consider using queues for heavy processing
- Monitor event delivery latency
Scaling
Section titled “Scaling”- Use RabbitMQ or SQS for distributed processing
- Implement horizontal scaling for webhook handlers
- Use load balancers for webhook endpoints
- Monitor queue depths and processing rates
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”- Webhook Timeouts: Ensure webhook endpoints respond quickly (< 30 seconds)
- Missing Events: Check event configuration and instance status
- Duplicate Events: Implement idempotency in event handlers
- Connection Issues: Verify network connectivity and credentials
Debugging
Section titled “Debugging”Enable webhook logging to debug event delivery:
LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKSMonitoring
Section titled “Monitoring”Monitor these metrics for healthy event delivery:
- Event delivery success rates
- Webhook response times
- Queue depths (RabbitMQ/SQS)
- Error rates and types
This comprehensive event system provides the foundation for building reactive WhatsApp applications that respond to real-time events across multiple delivery channels.