evolution-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEvolution API Skill
Evolution API 技能指南
Expert assistance for building WhatsApp integrations and multi-channel messaging automation using Evolution API - an open-source platform for WhatsApp, chatbots, and business communication.
为使用Evolution API构建WhatsApp集成与多渠道消息自动化提供专业支持——Evolution API是一款面向WhatsApp、聊天机器人及商务通信的开源平台。
When to Use This Skill
何时使用本技能
This skill should be used when:
- Building WhatsApp integrations and chatbots
- Creating automated messaging systems
- Integrating WhatsApp with business applications
- Setting up multi-channel customer service platforms
- Implementing chatbot flows with Typebot, Chatwoot, or Dify
- Connecting WhatsApp to CRM systems
- Building AI-powered conversational applications
- Setting up webhook-based message handling
- Implementing event-driven messaging architectures
- Managing WhatsApp Business API connections
- Integrating with OpenAI for intelligent responses
- Setting up message queuing with RabbitMQ, Kafka, or SQS
- Storing media files in S3 or MinIO
- Questions about Evolution API configuration and deployment
- Troubleshooting WhatsApp connection issues
本技能适用于以下场景:
- 构建WhatsApp集成与聊天机器人
- 创建自动化消息系统
- 将WhatsApp与商务应用集成
- 搭建多渠道客户服务平台
- 结合Typebot、Chatwoot或Dify实现聊天机器人流程
- 将WhatsApp与CRM系统连接
- 构建AI驱动的对话式应用
- 基于Webhook的消息处理配置
- 实现事件驱动的消息架构
- 管理WhatsApp Business API连接
- 集成OpenAI实现智能响应
- 结合RabbitMQ、Kafka或SQS搭建消息队列
- 将媒体文件存储至S3或MinIO
- Evolution API配置与部署相关问题
- WhatsApp连接故障排查
Overview
概述
What is Evolution API?
什么是Evolution API?
Evolution API is an open-source WhatsApp integration platform that:
- Provides RESTful API for WhatsApp messaging
- Supports both Baileys (free) and Official WhatsApp Business API
- Integrates with multiple chatbot and automation platforms
- Offers comprehensive webhook and event system
- Enables business messaging automation
- Completely free and self-hosted
Evolution from CodeChat:
"Originally built as a WhatsApp control API using the Baileys library based on CodeChat, the platform has evolved significantly."
Evolution API是一款开源的WhatsApp集成平台,具备以下特性:
- 提供WhatsApp消息的RESTful API
- 同时支持Baileys(免费版)与官方WhatsApp Business API
- 可与多款聊天机器人及自动化平台集成
- 拥有完善的Webhook与事件系统
- 支持商务消息自动化
- 完全免费且可自托管
从CodeChat演进而来:
"最初基于CodeChat的Baileys库构建为WhatsApp控制API,该平台现已实现重大演进。"
Key Features
核心功能
Messaging Capabilities:
- Send and receive WhatsApp messages
- Media support (images, videos, audio, documents)
- Group management and operations
- Contact management
- Message history and search
- Read receipts and status updates
Integration Ecosystem:
- Typebot: Visual chatbot builder
- Chatwoot: Customer service platform
- Dify: AI agent management
- OpenAI: AI-powered responses and audio transcription
- Flowise: Low-code AI workflow builder
- N8N: Workflow automation
Technical Features:
- RESTful API with comprehensive endpoints
- Webhook system for real-time events
- WebSocket support for live updates
- Message queue integration (RabbitMQ, Kafka, SQS)
- Database persistence (PostgreSQL, MySQL)
- Redis caching for performance
- S3/MinIO for media storage
- Docker deployment ready
消息能力:
- 发送与接收WhatsApp消息
- 支持媒体内容(图片、视频、音频、文档)
- 群组管理与操作
- 联系人管理
- 消息历史记录与搜索
- 已读回执与状态更新
集成生态:
- Typebot:可视化聊天机器人构建器
- Chatwoot:客户服务平台
- Dify:AI Agent管理平台
- OpenAI:AI驱动的响应与音频转写
- Flowise:低代码AI工作流构建器
- N8N:工作流自动化工具
技术特性:
- 具备全面端点的RESTful API
- 用于实时事件的Webhook系统
- 支持WebSocket实现实时更新
- 集成消息队列(RabbitMQ、Kafka、SQS)
- 数据库持久化(PostgreSQL、MySQL)
- Redis缓存提升性能
- S3/MinIO媒体存储
- 支持Docker部署
Installation
安装
Prerequisites
前置要求
bash
undefinedbash
undefinedNode.js 18+ or Docker
Node.js 18+ 或 Docker
node --version # v18.0.0 or higher
node --version # v18.0.0 或更高版本
Database (optional but recommended)
数据库(可选但推荐)
PostgreSQL 12+ or MySQL 8+
PostgreSQL 12+ 或 MySQL 8+
Redis (optional, for caching)
Redis(可选,用于缓存)
Redis 6+
Redis 6+
undefinedundefinedInstallation Methods
安装方式
Option 1: Docker (Recommended)
选项1:Docker(推荐)
bash
undefinedbash
undefinedClone the repository
克隆仓库
git clone https://github.com/EvolutionAPI/evolution-api.git
cd evolution-api
git clone https://github.com/EvolutionAPI/evolution-api.git
cd evolution-api
Create environment file
创建环境文件
cp .env.example .env
cp .env.example .env
Edit environment variables
编辑环境变量
nano .env
nano .env
Start with Docker Compose
使用Docker Compose启动
docker-compose up -d
docker-compose up -d
Check logs
查看日志
docker-compose logs -f evolution-api
**Docker Compose Example:**
```yaml
version: '3.8'
services:
evolution-api:
image: atendai/evolution-api:latest
container_name: evolution-api
ports:
- "8080:8080"
environment:
- SERVER_URL=https://your-domain.com
- DATABASE_ENABLED=true
- DATABASE_PROVIDER=postgresql
- DATABASE_CONNECTION_URI=postgresql://user:pass@postgres:5432/evolution
- AUTHENTICATION_API_KEY=your-secret-key-here
volumes:
- evolution_instances:/evolution/instances
restart: unless-stopped
postgres:
image: postgres:15
container_name: postgres
environment:
- POSTGRES_USER=evolution
- POSTGRES_PASSWORD=your-db-password
- POSTGRES_DB=evolution
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
redis:
image: redis:7
container_name: redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
volumes:
evolution_instances:
postgres_data:
redis_data:docker-compose logs -f evolution-api
**Docker Compose示例:**
```yaml
version: '3.8'
services:
evolution-api:
image: atendai/evolution-api:latest
container_name: evolution-api
ports:
- "8080:8080"
environment:
- SERVER_URL=https://your-domain.com
- DATABASE_ENABLED=true
- DATABASE_PROVIDER=postgresql
- DATABASE_CONNECTION_URI=postgresql://user:pass@postgres:5432/evolution
- AUTHENTICATION_API_KEY=your-secret-key-here
volumes:
- evolution_instances:/evolution/instances
restart: unless-stopped
postgres:
image: postgres:15
container_name: postgres
environment:
- POSTGRES_USER=evolution
- POSTGRES_PASSWORD=your-db-password
- POSTGRES_DB=evolution
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
redis:
image: redis:7
container_name: redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
volumes:
evolution_instances:
postgres_data:
redis_data:Option 2: NVM (Node Version Manager)
选项2:NVM(Node版本管理器)
bash
undefinedbash
undefinedInstall NVM
安装NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
Reload shell
重新加载shell
source ~/.bashrc
source ~/.bashrc
Install Node.js 18+
安装Node.js 18+
nvm install 18
nvm use 18
nvm install 18
nvm use 18
Clone repository
克隆仓库
git clone https://github.com/EvolutionAPI/evolution-api.git
cd evolution-api
git clone https://github.com/EvolutionAPI/evolution-api.git
cd evolution-api
Install dependencies
安装依赖
npm install
npm install
Copy environment file
复制环境文件
cp .env.example .env
cp .env.example .env
Edit configuration
编辑配置
nano .env
nano .env
Build
构建
npm run build
npm run build
Start production
启动生产环境
npm run start:prod
npm run start:prod
Or development mode
或启动开发模式
npm run start:dev
undefinednpm run start:dev
undefinedOption 3: PM2 (Process Manager)
选项3:PM2(进程管理器)
bash
undefinedbash
undefinedAfter NVM installation above
完成上述NVM安装后
Install PM2 globally
全局安装PM2
npm install -g pm2
npm install -g pm2
Start with PM2
使用PM2启动
pm2 start dist/src/main.js --name evolution-api
pm2 start dist/src/main.js --name evolution-api
Save PM2 configuration
保存PM2配置
pm2 save
pm2 save
Setup auto-restart on boot
设置开机自启
pm2 startup
undefinedpm2 startup
undefinedConfiguration
配置
Essential Environment Variables
关键环境变量
bash
undefinedbash
undefinedServer Configuration
服务器配置
SERVER_TYPE=http # or https
SERVER_PORT=8080
SERVER_URL=https://your-domain.com # For webhooks
SERVER_TYPE=http # 或 https
SERVER_PORT=8080
SERVER_URL=https://your-domain.com # 用于Webhook
Authentication
身份验证
AUTHENTICATION_API_KEY=your-secret-api-key-here
AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true
AUTHENTICATION_API_KEY=your-secret-api-key-here
AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true
Database (Recommended for production)
数据库(生产环境推荐)
DATABASE_ENABLED=true
DATABASE_PROVIDER=postgresql # or mysql
DATABASE_CONNECTION_URI=postgresql://user:pass@localhost:5432/evolution?schema=public
DATABASE_CONNECTION_CLIENT_NAME=evolution_instance
DATABASE_ENABLED=true
DATABASE_PROVIDER=postgresql # 或 mysql
DATABASE_CONNECTION_URI=postgresql://user:pass@localhost:5432/evolution?schema=public
DATABASE_CONNECTION_CLIENT_NAME=evolution_instance
Data Persistence
数据持久化
DATABASE_SAVE_DATA_INSTANCE=true
DATABASE_SAVE_DATA_NEW_MESSAGE=true
DATABASE_SAVE_MESSAGE_UPDATE=true
DATABASE_SAVE_DATA_CONTACTS=true
DATABASE_SAVE_DATA_CHATS=true
DATABASE_SAVE_DATA_INSTANCE=true
DATABASE_SAVE_DATA_NEW_MESSAGE=true
DATABASE_SAVE_MESSAGE_UPDATE=true
DATABASE_SAVE_DATA_CONTACTS=true
DATABASE_SAVE_DATA_CHATS=true
Redis Cache (Optional but recommended)
Redis缓存(可选但推荐)
CACHE_REDIS_ENABLED=true
CACHE_REDIS_URI=redis://localhost:6379/6
CACHE_REDIS_PREFIX_KEY=evolution
CACHE_REDIS_ENABLED=true
CACHE_REDIS_URI=redis://localhost:6379/6
CACHE_REDIS_PREFIX_KEY=evolution
CORS
CORS配置
CORS_ORIGIN=*
CORS_METHODS=GET,POST,PUT,DELETE
CORS_CREDENTIALS=true
CORS_ORIGIN=*
CORS_METHODS=GET,POST,PUT,DELETE
CORS_CREDENTIALS=true
Logging
日志配置
LOG_LEVEL=INFO # ERROR, WARN, DEBUG, INFO, LOG, VERBOSE
LOG_COLOR=true
LOG_BAILEYS=error # fatal, error, warn, info, debug, trace
LOG_LEVEL=INFO # ERROR, WARN, DEBUG, INFO, LOG, VERBOSE
LOG_COLOR=true
LOG_BAILEYS=error # fatal, error, warn, info, debug, trace
Instance Management
实例管理
DEL_INSTANCE=false # Auto-delete after X minutes (false = never)
DEL_INSTANCE=false # X分钟后自动删除(false表示永不删除)
Language
语言设置
LANGUAGE=en # or pt, es, etc.
undefinedLANGUAGE=en # 或 pt、es等
undefinedWhatsApp Configuration
WhatsApp配置
bash
undefinedbash
undefinedSession Configuration
会话配置
CONFIG_SESSION_PHONE_CLIENT=Evolution API
CONFIG_SESSION_PHONE_NAME=Chrome
CONFIG_SESSION_PHONE_CLIENT=Evolution API
CONFIG_SESSION_PHONE_NAME=Chrome
QR Code Settings
二维码设置
QRCODE_LIMIT=30 # Seconds before regeneration
QRCODE_COLOR=#175197 # QR code color
QRCODE_LIMIT=30 # 重新生成前的超时时间(秒)
QRCODE_COLOR=#175197 # 二维码颜色
WhatsApp Business API (Official)
WhatsApp Business API(官方版)
WA_BUSINESS_TOKEN_WEBHOOK=evolution
WA_BUSINESS_URL=https://graph.facebook.com
WA_BUSINESS_VERSION=v20.0
WA_BUSINESS_LANGUAGE=en_US
undefinedWA_BUSINESS_TOKEN_WEBHOOK=evolution
WA_BUSINESS_URL=https://graph.facebook.com
WA_BUSINESS_VERSION=v20.0
WA_BUSINESS_LANGUAGE=en_US
undefinedWebhook Configuration
Webhook配置
bash
undefinedbash
undefinedGlobal Webhook
全局Webhook
WEBHOOK_GLOBAL_ENABLED=true
WEBHOOK_GLOBAL_URL=https://your-webhook-endpoint.com/webhook
WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=true
WEBHOOK_GLOBAL_ENABLED=true
WEBHOOK_GLOBAL_URL=https://your-webhook-endpoint.com/webhook
WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=true
Event-specific webhooks
事件专属Webhook
WEBHOOK_EVENTS_APPLICATION_STARTUP=true
WEBHOOK_EVENTS_QRCODE_UPDATED=true
WEBHOOK_EVENTS_MESSAGES_SET=true
WEBHOOK_EVENTS_MESSAGES_UPSERT=true
WEBHOOK_EVENTS_MESSAGES_UPDATE=true
WEBHOOK_EVENTS_MESSAGES_DELETE=true
WEBHOOK_EVENTS_SEND_MESSAGE=true
WEBHOOK_EVENTS_CONTACTS_SET=true
WEBHOOK_EVENTS_CONTACTS_UPSERT=true
WEBHOOK_EVENTS_CONTACTS_UPDATE=true
WEBHOOK_EVENTS_PRESENCE_UPDATE=true
WEBHOOK_EVENTS_CHATS_SET=true
WEBHOOK_EVENTS_CHATS_UPSERT=true
WEBHOOK_EVENTS_CHATS_UPDATE=true
WEBHOOK_EVENTS_CHATS_DELETE=true
WEBHOOK_EVENTS_GROUPS_UPSERT=true
WEBHOOK_EVENTS_GROUPS_UPDATE=true
WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
WEBHOOK_EVENTS_CONNECTION_UPDATE=true
WEBHOOK_EVENTS_CALL=true
WEBHOOK_EVENTS_TYPEBOT_START=true
WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=true
WEBHOOK_EVENTS_ERRORS=true
WEBHOOK_EVENTS_ERRORS_WEBHOOK=true
undefinedWEBHOOK_EVENTS_APPLICATION_STARTUP=true
WEBHOOK_EVENTS_QRCODE_UPDATED=true
WEBHOOK_EVENTS_MESSAGES_SET=true
WEBHOOK_EVENTS_MESSAGES_UPSERT=true
WEBHOOK_EVENTS_MESSAGES_UPDATE=true
WEBHOOK_EVENTS_MESSAGES_DELETE=true
WEBHOOK_EVENTS_SEND_MESSAGE=true
WEBHOOK_EVENTS_CONTACTS_SET=true
WEBHOOK_EVENTS_CONTACTS_UPSERT=true
WEBHOOK_EVENTS_CONTACTS_UPDATE=true
WEBHOOK_EVENTS_PRESENCE_UPDATE=true
WEBHOOK_EVENTS_CHATS_SET=true
WEBHOOK_EVENTS_CHATS_UPSERT=true
WEBHOOK_EVENTS_CHATS_UPDATE=true
WEBHOOK_EVENTS_CHATS_DELETE=true
WEBHOOK_EVENTS_GROUPS_UPSERT=true
WEBHOOK_EVENTS_GROUPS_UPDATE=true
WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
WEBHOOK_EVENTS_CONNECTION_UPDATE=true
WEBHOOK_EVENTS_CALL=true
WEBHOOK_EVENTS_TYPEBOT_START=true
WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=true
WEBHOOK_EVENTS_ERRORS=true
WEBHOOK_EVENTS_ERRORS_WEBHOOK=true
undefinedIntegration Configurations
集成配置
Typebot:
bash
TYPEBOT_API_VERSION=latest # or specific versionChatwoot:
bash
CHATWOOT_ENABLED=true
CHATWOOT_MESSAGE_READ=true
CHATWOOT_MESSAGE_DELETE=true
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgresql://...
CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=trueOpenAI:
bash
OPENAI_ENABLED=trueDify:
bash
DIFY_ENABLED=trueRabbitMQ:
bash
RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://user:pass@localhost:5672
RABBITMQ_EXCHANGE_NAME=evolution_exchange
RABBITMQ_GLOBAL_ENABLED=trueAWS SQS:
bash
SQS_ENABLED=true
SQS_ACCESS_KEY_ID=your-access-key
SQS_SECRET_ACCESS_KEY=your-secret-key
SQS_ACCOUNT_ID=123456789
SQS_REGION=us-east-1S3/MinIO Storage:
bash
S3_ENABLED=true
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-key
S3_BUCKET=evolution
S3_ENDPOINT=s3.amazonaws.com # or minio endpoint
S3_PORT=443
S3_USE_SSL=trueWebSocket:
bash
WEBSOCKET_ENABLED=true
WEBSOCKET_GLOBAL_EVENTS=falseTypebot:
bash
TYPEBOT_API_VERSION=latest # 或指定版本Chatwoot:
bash
CHATWOOT_ENABLED=true
CHATWOOT_MESSAGE_READ=true
CHATWOOT_MESSAGE_DELETE=true
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgresql://...
CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=trueOpenAI:
bash
OPENAI_ENABLED=trueDify:
bash
DIFY_ENABLED=trueRabbitMQ:
bash
RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://user:pass@localhost:5672
RABBITMQ_EXCHANGE_NAME=evolution_exchange
RABBITMQ_GLOBAL_ENABLED=trueAWS SQS:
bash
SQS_ENABLED=true
SQS_ACCESS_KEY_ID=your-access-key
SQS_SECRET_ACCESS_KEY=your-secret-key
SQS_ACCOUNT_ID=123456789
SQS_REGION=us-east-1S3/MinIO存储:
bash
S3_ENABLED=true
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-key
S3_BUCKET=evolution
S3_ENDPOINT=s3.amazonaws.com # 或MinIO端点
S3_PORT=443
S3_USE_SSL=trueWebSocket:
bash
WEBSOCKET_ENABLED=true
WEBSOCKET_GLOBAL_EVENTS=falseQuick Start
快速入门
1. Create Instance
1. 创建实例
bash
undefinedbash
undefinedUsing cURL
使用cURL
curl -X POST https://your-domain.com/instance/create
-H "apikey: your-api-key"
-H "Content-Type: application/json"
-d '{ "instanceName": "my-whatsapp-bot", "qrcode": true, "integration": "WHATSAPP-BAILEYS" }'
-H "apikey: your-api-key"
-H "Content-Type: application/json"
-d '{ "instanceName": "my-whatsapp-bot", "qrcode": true, "integration": "WHATSAPP-BAILEYS" }'
curl -X POST https://your-domain.com/instance/create
-H "apikey: your-api-key"
-H "Content-Type: application/json"
-d '{ "instanceName": "my-whatsapp-bot", "qrcode": true, "integration": "WHATSAPP-BAILEYS" }'
-H "apikey: your-api-key"
-H "Content-Type: application/json"
-d '{ "instanceName": "my-whatsapp-bot", "qrcode": true, "integration": "WHATSAPP-BAILEYS" }'
Response includes QR code
响应包含二维码
{
"instance": {
"instanceName": "my-whatsapp-bot",
"status": "created"
},
"qrcode": {
"code": "data:image/png;base64,...",
"base64": "..."
}
}
undefined{
"instance": {
"instanceName": "my-whatsapp-bot",
"status": "created"
},
"qrcode": {
"code": "data:image/png;base64,...",
"base64": "..."
}
}
undefined2. Connect WhatsApp
2. 连接WhatsApp
Scan the QR code with WhatsApp on your phone:
- Open WhatsApp
- Go to Settings > Linked Devices
- Click "Link a Device"
- Scan the QR code from the API response
使用手机上的WhatsApp扫描二维码:
- 打开WhatsApp
- 进入设置 > 已链接设备
- 点击“链接设备”
- 扫描API响应中的二维码
3. Check Connection Status
3. 检查连接状态
bash
curl -X GET https://your-domain.com/instance/connectionState/my-whatsapp-bot \
-H "apikey: your-api-key"bash
curl -X GET https://your-domain.com/instance/connectionState/my-whatsapp-bot \
-H "apikey: your-api-key"Response
响应
{
"instance": {
"instanceName": "my-whatsapp-bot",
"state": "open"
}
}
undefined{
"instance": {
"instanceName": "my-whatsapp-bot",
"state": "open"
}
}
undefined4. Send Message
4. 发送消息
bash
curl -X POST https://your-domain.com/message/sendText/my-whatsapp-bot \
-H "apikey: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"number": "5511999999999",
"text": "Hello from Evolution API!"
}'bash
curl -X POST https://your-domain.com/message/sendText/my-whatsapp-bot \
-H "apikey: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"number": "5511999999999",
"text": "Hello from Evolution API!"
}'API Endpoints
API 端点
Instance Management
实例管理
bash
undefinedbash
undefinedCreate instance
创建实例
POST /instance/create
{
"instanceName": "bot-name",
"qrcode": true,
"integration": "WHATSAPP-BAILEYS" # or WHATSAPP-BUSINESS
}
POST /instance/create
{
"instanceName": "bot-name",
"qrcode": true,
"integration": "WHATSAPP-BAILEYS" # 或 WHATSAPP-BUSINESS
}
List instances
列出实例
GET /instance/fetchInstances
GET /instance/fetchInstances
Get instance info
获取实例信息
GET /instance/connectionState/{instanceName}
GET /instance/connectionState/{instanceName}
Restart instance
重启实例
PUT /instance/restart/{instanceName}
PUT /instance/restart/{instanceName}
Logout instance
登出实例
DELETE /instance/logout/{instanceName}
DELETE /instance/logout/{instanceName}
Delete instance
删除实例
DELETE /instance/delete/{instanceName}
undefinedDELETE /instance/delete/{instanceName}
undefinedMessaging
消息功能
Text Messages:
bash
POST /message/sendText/{instanceName}
{
"number": "5511999999999",
"text": "Your message here"
}Media Messages:
bash
undefined文本消息:
bash
POST /message/sendText/{instanceName}
{
"number": "5511999999999",
"text": "Your message here"
}媒体消息:
bash
undefinedImage
图片
POST /message/sendMedia/{instanceName}
{
"number": "5511999999999",
"mediatype": "image",
"media": "https://example.com/image.jpg", # or base64
"caption": "Image caption"
}
POST /message/sendMedia/{instanceName}
{
"number": "5511999999999",
"mediatype": "image",
"media": "https://example.com/image.jpg", # 或base64格式
"caption": "Image caption"
}
Video
视频
POST /message/sendMedia/{instanceName}
{
"number": "5511999999999",
"mediatype": "video",
"media": "https://example.com/video.mp4",
"caption": "Video caption"
}
POST /message/sendMedia/{instanceName}
{
"number": "5511999999999",
"mediatype": "video",
"media": "https://example.com/video.mp4",
"caption": "Video caption"
}
Audio
音频
POST /message/sendWhatsAppAudio/{instanceName}
{
"number": "5511999999999",
"audio": "https://example.com/audio.mp3" # or base64
}
POST /message/sendWhatsAppAudio/{instanceName}
{
"number": "5511999999999",
"audio": "https://example.com/audio.mp3" # 或base64格式
}
Document
文档
POST /message/sendMedia/{instanceName}
{
"number": "5511999999999",
"mediatype": "document",
"media": "https://example.com/file.pdf",
"fileName": "document.pdf"
}
**Advanced Messages:**
```bashPOST /message/sendMedia/{instanceName}
{
"number": "5511999999999",
"mediatype": "document",
"media": "https://example.com/file.pdf",
"fileName": "document.pdf"
}
**高级消息:**
```bashLocation
位置
POST /message/sendLocation/{instanceName}
{
"number": "5511999999999",
"latitude": "-23.550520",
"longitude": "-46.633308",
"name": "Location Name",
"address": "Address details"
}
POST /message/sendLocation/{instanceName}
{
"number": "5511999999999",
"latitude": "-23.550520",
"longitude": "-46.633308",
"name": "Location Name",
"address": "Address details"
}
Contact
联系人
POST /message/sendContact/{instanceName}
{
"number": "5511999999999",
"contact": [{
"fullName": "John Doe",
"wuid": "5511888888888",
"phoneNumber": "+55 11 98888-8888"
}]
}
POST /message/sendContact/{instanceName}
{
"number": "5511999999999",
"contact": [{
"fullName": "John Doe",
"wuid": "5511888888888",
"phoneNumber": "+55 11 98888-8888"
}]
}
List Message (Interactive)
列表消息(交互式)
POST /message/sendList/{instanceName}
{
"number": "5511999999999",
"title": "Choose an option",
"description": "Select one option below",
"buttonText": "Options",
"footerText": "Footer text",
"sections": [{
"title": "Section 1",
"rows": [{
"title": "Option 1",
"description": "Description 1",
"rowId": "opt1"
}]
}]
}
POST /message/sendList/{instanceName}
{
"number": "5511999999999",
"title": "Choose an option",
"description": "Select one option below",
"buttonText": "Options",
"footerText": "Footer text",
"sections": [{
"title": "Section 1",
"rows": [{
"title": "Option 1",
"description": "Description 1",
"rowId": "opt1"
}]
}]
}
Button Message
按钮消息
POST /message/sendButtons/{instanceName}
{
"number": "5511999999999",
"title": "Button Message",
"description": "Choose an action",
"buttons": [{
"type": "replyButton",
"displayText": "Button 1",
"id": "btn1"
}],
"footerText": "Footer"
}
undefinedPOST /message/sendButtons/{instanceName}
{
"number": "5511999999999",
"title": "Button Message",
"description": "Choose an action",
"buttons": [{
"type": "replyButton",
"displayText": "Button 1",
"id": "btn1"
}],
"footerText": "Footer"
}
undefinedGroups
群组管理
bash
undefinedbash
undefinedCreate group
创建群组
POST /group/create/{instanceName}
{
"subject": "Group Name",
"participants": ["5511999999999", "5511888888888"]
}
POST /group/create/{instanceName}
{
"subject": "Group Name",
"participants": ["5511999999999", "5511888888888"]
}
Update group info
更新群组信息
PUT /group/updateGroupPicture/{instanceName}
{
"groupJid": "groupid@g.us",
"image": "base64-image-data"
}
PUT /group/updateGroupPicture/{instanceName}
{
"groupJid": "groupid@g.us",
"image": "base64-image-data"
}
Add participants
添加参与者
POST /group/updateParticipant/{instanceName}
{
"groupJid": "groupid@g.us",
"action": "add", # or remove, promote, demote
"participants": ["5511999999999"]
}
POST /group/updateParticipant/{instanceName}
{
"groupJid": "groupid@g.us",
"action": "add", # 或 remove、promote、demote
"participants": ["5511999999999"]
}
Leave group
退出群组
DELETE /group/leaveGroup/{instanceName}
{
"groupJid": "groupid@g.us"
}
undefinedDELETE /group/leaveGroup/{instanceName}
{
"groupJid": "groupid@g.us"
}
undefinedContacts & Profile
联系人与个人资料
bash
undefinedbash
undefinedGet profile picture
获取个人资料图片
GET /chat/profilePic/{instanceName}?number=5511999999999
GET /chat/profilePic/{instanceName}?number=5511999999999
Get contacts
获取联系人
GET /chat/findContacts/{instanceName}?id=5511999999999
GET /chat/findContacts/{instanceName}?id=5511999999999
Update profile name
更新个人资料名称
PUT /chat/updateProfileName/{instanceName}
{
"name": "My Bot Name"
}
PUT /chat/updateProfileName/{instanceName}
{
"name": "My Bot Name"
}
Update profile status
更新个人资料状态
PUT /chat/updateProfileStatus/{instanceName}
{
"status": "Available 24/7"
}
PUT /chat/updateProfileStatus/{instanceName}
{
"status": "Available 24/7"
}
Update profile picture
更新个人资料图片
PUT /chat/updateProfilePicture/{instanceName}
{
"picture": "base64-image-data"
}
undefinedPUT /chat/updateProfilePicture/{instanceName}
{
"picture": "base64-image-data"
}
undefinedWebhooks
Webhook管理
bash
undefinedbash
undefinedSet instance webhook
设置实例Webhook
POST /webhook/set/{instanceName}
{
"url": "https://your-webhook.com/endpoint",
"webhook_by_events": true,
"webhook_base64": false,
"events": [
"QRCODE_UPDATED",
"MESSAGES_UPSERT",
"MESSAGES_UPDATE",
"SEND_MESSAGE",
"CONNECTION_UPDATE"
]
}
POST /webhook/set/{instanceName}
{
"url": "https://your-webhook.com/endpoint",
"webhook_by_events": true,
"webhook_base64": false,
"events": [
"QRCODE_UPDATED",
"MESSAGES_UPSERT",
"MESSAGES_UPDATE",
"SEND_MESSAGE",
"CONNECTION_UPDATE"
]
}
Get webhook info
获取Webhook信息
GET /webhook/find/{instanceName}
undefinedGET /webhook/find/{instanceName}
undefinedIntegration Examples
集成示例
Typebot Integration
Typebot集成
bash
undefinedbash
undefinedSet Typebot on instance
为实例设置Typebot
POST /typebot/set/{instanceName}
{
"enabled": true,
"url": "https://typebot.io",
"typebot": "typebot-flow-id",
"expire": 20, # Minutes of inactivity
"keywordFinish": "exit",
"delayMessage": 1000,
"unknownMessage": "I didn't understand",
"listeningFromMe": false
}
POST /typebot/set/{instanceName}
{
"enabled": true,
"url": "https://typebot.io",
"typebot": "typebot-flow-id",
"expire": 20, # 无活动超时时间(分钟)
"keywordFinish": "exit",
"delayMessage": 1000,
"unknownMessage": "I didn't understand",
"listeningFromMe": false
}
Start Typebot session
启动Typebot会话
POST /typebot/start/{instanceName}
{
"url": "https://typebot.io",
"typebot": "flow-id",
"remoteJid": "5511999999999@s.whatsapp.net",
"startSession": true,
"variables": [{
"name": "userName",
"value": "John"
}]
}
POST /typebot/start/{instanceName}
{
"url": "https://typebot.io",
"typebot": "flow-id",
"remoteJid": "5511999999999@s.whatsapp.net",
"startSession": true,
"variables": [{
"name": "userName",
"value": "John"
}]
}
Change Typebot status
修改Typebot状态
POST /typebot/changeStatus/{instanceName}
{
"remoteJid": "5511999999999@s.whatsapp.net",
"status": "paused" # or closed
}
undefinedPOST /typebot/changeStatus/{instanceName}
{
"remoteJid": "5511999999999@s.whatsapp.net",
"status": "paused" # 或 closed
}
undefinedChatwoot Integration
Chatwoot集成
bash
undefinedbash
undefinedEnable Chatwoot
启用Chatwoot
POST /chatwoot/set/{instanceName}
{
"enabled": true,
"accountId": "123",
"token": "chatwoot-api-token",
"url": "https://app.chatwoot.com",
"signMsg": true,
"reopenConversation": true,
"conversationPending": false
}
undefinedPOST /chatwoot/set/{instanceName}
{
"enabled": true,
"accountId": "123",
"token": "chatwoot-api-token",
"url": "https://app.chatwoot.com",
"signMsg": true,
"reopenConversation": true,
"conversationPending": false
}
undefinedOpenAI Integration
OpenAI集成
bash
undefinedbash
undefinedSet OpenAI
设置OpenAI
POST /openai/set/{instanceName}
{
"enabled": true,
"apiKey": "sk-...",
"model": "gpt-4o",
"maxTokens": 2000,
"temperature": 0.7,
"systemMessages": [{
"role": "system",
"content": "You are a helpful assistant."
}],
"assistantMessages": [{
"role": "assistant",
"content": "How can I help you?"
}]
}
undefinedPOST /openai/set/{instanceName}
{
"enabled": true,
"apiKey": "sk-...",
"model": "gpt-4o",
"maxTokens": 2000,
"temperature": 0.7,
"systemMessages": [{
"role": "system",
"content": "You are a helpful assistant."
}],
"assistantMessages": [{
"role": "assistant",
"content": "How can I help you?"
}]
}
undefinedDify Integration
Dify集成
bash
undefinedbash
undefinedSet Dify
设置Dify
POST /dify/set/{instanceName}
{
"enabled": true,
"apiUrl": "https://api.dify.ai/v1",
"apiKey": "app-...",
"botType": "chatbot", # or agent, workflow
"expire": 20,
"keywordFinish": "exit"
}
undefinedPOST /dify/set/{instanceName}
{
"enabled": true,
"apiUrl": "https://api.dify.ai/v1",
"apiKey": "app-...",
"botType": "chatbot", # 或 agent、workflow
"expire": 20,
"keywordFinish": "exit"
}
undefinedWebhook Handling
Webhook 处理
Webhook Structure
Webhook 结构
javascript
// Example webhook payload
{
"event": "messages.upsert",
"instance": "my-whatsapp-bot",
"data": {
"key": {
"remoteJid": "5511999999999@s.whatsapp.net",
"fromMe": false,
"id": "BAE5F4...",
"participant": null
},
"pushName": "John Doe",
"message": {
"conversation": "Hello, how are you?"
},
"messageType": "conversation",
"messageTimestamp": 1234567890,
"instanceId": "instance-uuid",
"source": "android"
},
"destination": "https://your-webhook.com/endpoint",
"date_time": "2024-01-01T12:00:00.000Z",
"server_url": "https://your-evolution-api.com",
"apikey": "your-api-key"
}javascript
// 示例Webhook负载
{
"event": "messages.upsert",
"instance": "my-whatsapp-bot",
"data": {
"key": {
"remoteJid": "5511999999999@s.whatsapp.net",
"fromMe": false,
"id": "BAE5F4...",
"participant": null
},
"pushName": "John Doe",
"message": {
"conversation": "Hello, how are you?"
},
"messageType": "conversation",
"messageTimestamp": 1234567890,
"instanceId": "instance-uuid",
"source": "android"
},
"destination": "https://your-webhook.com/endpoint",
"date_time": "2024-01-01T12:00:00.000Z",
"server_url": "https://your-evolution-api.com",
"apikey": "your-api-key"
}Node.js Webhook Handler
Node.js Webhook 处理器
javascript
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', async (req, res) => {
const { event, instance, data } = req.body;
console.log(`Received event: ${event} from instance: ${instance}`);
// Handle different events
switch (event) {
case 'messages.upsert':
// New message received
const message = data.message?.conversation ||
data.message?.extendedTextMessage?.text || '';
const from = data.key.remoteJid;
const fromMe = data.key.fromMe;
if (!fromMe && message) {
console.log(`Message from ${from}: ${message}`);
// Process message and send response
await sendResponse(instance, from, message);
}
break;
case 'connection.update':
// Connection status changed
console.log('Connection status:', data);
break;
case 'qrcode.updated':
// New QR code generated
console.log('QR Code updated:', data.qrcode);
break;
default:
console.log('Unhandled event:', event);
}
// Always respond 200 OK
res.sendStatus(200);
});
async function sendResponse(instance, to, originalMessage) {
const response = await fetch(`https://your-api.com/message/sendText/${instance}`, {
method: 'POST',
headers: {
'apikey': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
number: to.replace('@s.whatsapp.net', ''),
text: `You said: ${originalMessage}`
})
});
return response.json();
}
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});javascript
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', async (req, res) => {
const { event, instance, data } = req.body;
console.log(`Received event: ${event} from instance: ${instance}`);
// 处理不同事件
switch (event) {
case 'messages.upsert':
// 收到新消息
const message = data.message?.conversation ||
data.message?.extendedTextMessage?.text || '';
const from = data.key.remoteJid;
const fromMe = data.key.fromMe;
if (!fromMe && message) {
console.log(`Message from ${from}: ${message}`);
// 处理消息并发送响应
await sendResponse(instance, from, message);
}
break;
case 'connection.update':
// 连接状态变更
console.log('Connection status:', data);
break;
case 'qrcode.updated':
// 生成新二维码
console.log('QR Code updated:', data.qrcode);
break;
default:
console.log('Unhandled event:', event);
}
// 始终返回200 OK
res.sendStatus(200);
});
async function sendResponse(instance, to, originalMessage) {
const response = await fetch(`https://your-api.com/message/sendText/${instance}`, {
method: 'POST',
headers: {
'apikey': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
number: to.replace('@s.whatsapp.net', ''),
text: `You said: ${originalMessage}`
})
});
return response.json();
}
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});Python Webhook Handler
Python Webhook 处理器
python
from flask import Flask, request
import requests
app = Flask(__name__)
API_URL = "https://your-evolution-api.com"
API_KEY = "your-api-key"
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
event = data.get('event')
instance = data.get('instance')
event_data = data.get('data')
print(f"Received event: {event} from instance: {instance}")
if event == 'messages.upsert':
handle_message(instance, event_data)
elif event == 'connection.update':
handle_connection(event_data)
elif event == 'qrcode.updated':
handle_qrcode(event_data)
return '', 200
def handle_message(instance, data):
from_me = data['key'].get('fromMe', False)
if from_me:
return
message = (data.get('message', {}).get('conversation') or
data.get('message', {}).get('extendedTextMessage', {}).get('text') or '')
remote_jid = data['key']['remoteJid']
number = remote_jid.replace('@s.whatsapp.net', '')
print(f"Message from {number}: {message}")
# Send response
send_message(instance, number, f"You said: {message}")
def send_message(instance, number, text):
url = f"{API_URL}/message/sendText/{instance}"
headers = {
'apikey': API_KEY,
'Content-Type': 'application/json'
}
payload = {
'number': number,
'text': text
}
response = requests.post(url, json=payload, headers=headers)
return response.json()
def handle_connection(data):
print(f"Connection update: {data}")
def handle_qrcode(data):
print(f"QR Code updated")
if __name__ == '__main__':
app.run(port=3000)python
from flask import Flask, request
import requests
app = Flask(__name__)
API_URL = "https://your-evolution-api.com"
API_KEY = "your-api-key"
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
event = data.get('event')
instance = data.get('instance')
event_data = data.get('data')
print(f"Received event: {event} from instance: {instance}")
if event == 'messages.upsert':
handle_message(instance, event_data)
elif event == 'connection.update':
handle_connection(event_data)
elif event == 'qrcode.updated':
handle_qrcode(event_data)
return '', 200
def handle_message(instance, data):
from_me = data['key'].get('fromMe', False)
if from_me:
return
message = (data.get('message', {}).get('conversation') or
data.get('message', {}).get('extendedTextMessage', {}).get('text') or '')
remote_jid = data['key']['remoteJid']
number = remote_jid.replace('@s.whatsapp.net', '')
print(f"Message from {number}: {message}")
# 发送响应
send_message(instance, number, f"You said: {message}")
def send_message(instance, number, text):
url = f"{API_URL}/message/sendText/{instance}"
headers = {
'apikey': API_KEY,
'Content-Type': 'application/json'
}
payload = {
'number': number,
'text': text
}
response = requests.post(url, json=payload, headers=headers)
return response.json()
def handle_connection(data):
print(f"Connection update: {data}")
def handle_qrcode(data):
print(f"QR Code updated")
if __name__ == '__main__':
app.run(port=3000)Advanced Use Cases
高级用例
1. AI-Powered Customer Service Bot
1. AI驱动的客户服务机器人
javascript
const OpenAI = require('openai');
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function handleCustomerMessage(instance, from, message) {
// Get conversation history from database
const history = await getConversationHistory(from);
// Get AI response
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful customer service agent." },
...history,
{ role: "user", content: message }
]
});
const aiResponse = completion.choices[0].message.content;
// Save to history
await saveToHistory(from, message, aiResponse);
// Send response
await sendMessage(instance, from, aiResponse);
}javascript
const OpenAI = require('openai');
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function handleCustomerMessage(instance, from, message) {
// 从数据库获取对话历史
const history = await getConversationHistory(from);
// 获取AI响应
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful customer service agent." },
...history,
{ role: "user", content: message }
]
});
const aiResponse = completion.choices[0].message.content;
// 保存至历史记录
await saveToHistory(from, message, aiResponse);
// 发送响应
await sendMessage(instance, from, aiResponse);
}2. Group Management Bot
2. 群组管理机器人
javascript
async function handleGroupCommand(instance, groupJid, command, sender) {
const isAdmin = await checkIfAdmin(instance, groupJid, sender);
if (!isAdmin) {
await sendMessage(instance, groupJid, "Only admins can use this command");
return;
}
switch (command) {
case '/welcome':
await setWelcomeMessage(groupJid);
break;
case '/rules':
await sendGroupRules(instance, groupJid);
break;
case '/ban':
const userToRemove = extractUserFromCommand(command);
await removeParticipant(instance, groupJid, userToRemove);
break;
}
}javascript
async function handleGroupCommand(instance, groupJid, command, sender) {
const isAdmin = await checkIfAdmin(instance, groupJid, sender);
if (!isAdmin) {
await sendMessage(instance, groupJid, "Only admins can use this command");
return;
}
switch (command) {
case '/welcome':
await setWelcomeMessage(groupJid);
break;
case '/rules':
await sendGroupRules(instance, groupJid);
break;
case '/ban':
const userToRemove = extractUserFromCommand(command);
await removeParticipant(instance, groupJid, userToRemove);
break;
}
}3. Broadcast System
3. 广播系统
javascript
async function sendBroadcast(instance, recipients, message) {
const results = [];
for (const recipient of recipients) {
try {
await sendMessage(instance, recipient, message);
results.push({ recipient, status: 'sent' });
// Delay to avoid rate limiting
await delay(1000);
} catch (error) {
results.push({ recipient, status: 'failed', error: error.message });
}
}
return results;
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}javascript
async function sendBroadcast(instance, recipients, message) {
const results = [];
for (const recipient of recipients) {
try {
await sendMessage(instance, recipient, message);
results.push({ recipient, status: 'sent' });
// 延迟避免触发频率限制
await delay(1000);
} catch (error) {
results.push({ recipient, status: 'failed', error: error.message });
}
}
return results;
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}4. Media Downloader Bot
4. 媒体下载机器人
javascript
async function handleMediaMessage(instance, data) {
const messageType = data.messageType;
if (['imageMessage', 'videoMessage', 'documentMessage'].includes(messageType)) {
// Download media
const media = data.message[messageType];
const buffer = await downloadMedia(instance, data.key.id);
// Upload to S3
const s3Url = await uploadToS3(buffer, media.mimetype);
// Save to database
await saveMediaReference({
messageId: data.key.id,
type: messageType,
url: s3Url,
from: data.key.remoteJid,
timestamp: data.messageTimestamp
});
}
}javascript
async function handleMediaMessage(instance, data) {
const messageType = data.messageType;
if (['imageMessage', 'videoMessage', 'documentMessage'].includes(messageType)) {
// 下载媒体
const media = data.message[messageType];
const buffer = await downloadMedia(instance, data.key.id);
// 上传至S3
const s3Url = await uploadToS3(buffer, media.mimetype);
// 保存至数据库
await saveMediaReference({
messageId: data.key.id,
type: messageType,
url: s3Url,
from: data.key.remoteJid,
timestamp: data.messageTimestamp
});
}
}Production Best Practices
生产环境最佳实践
1. Security
1. 安全配置
bash
undefinedbash
undefinedUse strong API key
使用强API密钥
AUTHENTICATION_API_KEY=$(openssl rand -hex 32)
AUTHENTICATION_API_KEY=$(openssl rand -hex 32)
Enable HTTPS
启用HTTPS
SERVER_TYPE=https
SERVER_TYPE=https
Restrict CORS
限制CORS
CORS_ORIGIN=https://your-frontend.com
CORS_CREDENTIALS=true
CORS_ORIGIN=https://your-frontend.com
CORS_CREDENTIALS=true
Use environment-specific configs
使用环境专属配置
.env.production, .env.staging, .env.development
.env.production、.env.staging、.env.development
undefinedundefined2. High Availability
2. 高可用性
yaml
undefinedyaml
undefineddocker-compose.yml with replicas
带副本的docker-compose.yml
services:
evolution-api:
image: atendai/evolution-api:latest
deploy:
replicas: 3
update_config:
parallelism: 1
delay: 10s
restart_policy:
condition: on-failure
max_attempts: 3
environment:
- DATABASE_ENABLED=true
- CACHE_REDIS_ENABLED=true
Load balancer
nginx:
image: nginx:alpine
ports:
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- evolution-api
undefinedservices:
evolution-api:
image: atendai/evolution-api:latest
deploy:
replicas: 3
update_config:
parallelism: 1
delay: 10s
restart_policy:
condition: on-failure
max_attempts: 3
environment:
- DATABASE_ENABLED=true
- CACHE_REDIS_ENABLED=true
负载均衡器
nginx:
image: nginx:alpine
ports:
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- evolution-api
undefined3. Monitoring
3. 监控配置
bash
undefinedbash
undefinedEnable detailed logging
启用详细日志
LOG_LEVEL=DEBUG
LOG_COLOR=true
LOG_BAILEYS=info
LOG_LEVEL=DEBUG
LOG_COLOR=true
LOG_BAILEYS=info
Use external monitoring
使用外部监控工具
- Prometheus for metrics
- Prometheus 用于指标监控
- Grafana for dashboards
- Grafana 用于可视化仪表盘
- Sentry for error tracking
- Sentry 用于错误追踪
Health check endpoint
健康检查端点
undefinedundefined4. Backup Strategy
4. 备份策略
bash
undefinedbash
undefinedDatabase backups
数据库备份
pg_dump -h localhost -U evolution evolution > backup_$(date +%Y%m%d).sql
pg_dump -h localhost -U evolution evolution > backup_$(date +%Y%m%d).sql
Instance data backup
实例数据备份
tar -czf instances_backup_$(date +%Y%m%d).tar.gz /evolution/instances/
tar -czf instances_backup_$(date +%Y%m%d).tar.gz /evolution/instances/
Automated backups with cron
使用cron实现自动备份
0 2 * * * /scripts/backup.sh
undefined0 2 * * * /scripts/backup.sh
undefined5. Rate Limiting
5. 频率限制
javascript
// Implement rate limiting in webhook handler
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests, please try again later.'
});
app.use('/webhook', limiter);javascript
// 在Webhook处理器中实现频率限制
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 限制每个IP在窗口时间内的请求数为100
message: 'Too many requests, please try again later.'
});
app.use('/webhook', limiter);Troubleshooting
故障排查
Common Issues
常见问题
QR Code Not Generating
二维码无法生成
bash
undefinedbash
undefinedCheck instance status
检查实例状态
curl -X GET https://your-api.com/instance/connectionState/instance-name
-H "apikey: your-api-key"
-H "apikey: your-api-key"
curl -X GET https://your-api.com/instance/connectionState/instance-name
-H "apikey: your-api-key"
-H "apikey: your-api-key"
Restart instance
重启实例
curl -X PUT https://your-api.com/instance/restart/instance-name
-H "apikey: your-api-key"
-H "apikey: your-api-key"
curl -X PUT https://your-api.com/instance/restart/instance-name
-H "apikey: your-api-key"
-H "apikey: your-api-key"
Check logs
查看日志
docker-compose logs -f evolution-api
undefineddocker-compose logs -f evolution-api
undefinedMessages Not Sending
消息无法发送
bash
undefinedbash
undefinedVerify connection
验证连接状态
GET /instance/connectionState/{instanceName}
GET /instance/connectionState/{instanceName}
Check if number is valid
检查号码格式是否正确
Format: Country code + number (no +, no spaces)
格式:国家代码+号码(无+号,无空格)
Example: 5511999999999
示例:5511999999999
Verify API key
验证API密钥
curl -X GET https://your-api.com/instance/fetchInstances
-H "apikey: your-api-key"
-H "apikey: your-api-key"
undefinedcurl -X GET https://your-api.com/instance/fetchInstances
-H "apikey: your-api-key"
-H "apikey: your-api-key"
undefinedWebhook Not Receiving Events
Webhook无法接收事件
bash
undefinedbash
undefinedVerify webhook configuration
验证Webhook配置
GET /webhook/find/{instanceName}
GET /webhook/find/{instanceName}
Test webhook endpoint
测试Webhook端点
curl -X POST https://your-webhook.com/endpoint
-H "Content-Type: application/json"
-d '{"test": "data"}'
-H "Content-Type: application/json"
-d '{"test": "data"}'
curl -X POST https://your-webhook.com/endpoint
-H "Content-Type: application/json"
-d '{"test": "data"}'
-H "Content-Type: application/json"
-d '{"test": "data"}'
Check webhook URL is publicly accessible
检查Webhook URL是否可公开访问
Use ngrok for local development:
本地开发可使用ngrok:
ngrok http 3000
undefinedngrok http 3000
undefinedDatabase Connection Errors
数据库连接错误
bash
undefinedbash
undefinedTest database connection
测试数据库连接
psql "postgresql://user:pass@localhost:5432/evolution"
psql "postgresql://user:pass@localhost:5432/evolution"
Check environment variables
检查环境变量
echo $DATABASE_CONNECTION_URI
echo $DATABASE_CONNECTION_URI
Verify database exists
验证数据库是否存在
psql -l | grep evolution
psql -l | grep evolution
Run migrations if needed
如有需要运行迁移
npm run migration:run
undefinednpm run migration:run
undefinedInstance Disconnects Frequently
实例频繁断开连接
bash
undefinedbash
undefinedEnable keep-alive
启用保持连接
Check mobile connection
检查手机网络连接
Verify phone battery saver is off
验证手机省电模式已关闭
Check WhatsApp version is up to date
检查WhatsApp版本是否为最新
Increase session timeout
增加会话超时时间
CONFIG_SESSION_PHONE_CLIENT=Evolution API
QRCODE_LIMIT=60 # Increase timeout
undefinedCONFIG_SESSION_PHONE_CLIENT=Evolution API
QRCODE_LIMIT=60 # 增加超时时间
undefinedPerformance Optimization
性能优化
1. Enable Caching
1. 启用缓存
bash
undefinedbash
undefinedRedis cache
Redis缓存
CACHE_REDIS_ENABLED=true
CACHE_REDIS_URI=redis://localhost:6379/6
CACHE_REDIS_SAVE_INSTANCES=true
undefinedCACHE_REDIS_ENABLED=true
CACHE_REDIS_URI=redis://localhost:6379/6
CACHE_REDIS_SAVE_INSTANCES=true
undefined2. Database Optimization
2. 数据库优化
bash
undefinedbash
undefinedIndex frequently queried fields
为频繁查询的字段创建索引
CREATE INDEX idx_messages_instance ON messages(instanceId);
CREATE INDEX idx_messages_jid ON messages(remoteJid);
CREATE INDEX idx_messages_timestamp ON messages(messageTimestamp);
CREATE INDEX idx_messages_instance ON messages(instanceId);
CREATE INDEX idx_messages_jid ON messages(remoteJid);
CREATE INDEX idx_messages_timestamp ON messages(messageTimestamp);
Partition large tables
对大表进行分区
Clean old messages periodically
定期清理旧消息
DELETE FROM messages WHERE messageTimestamp < NOW() - INTERVAL '90 days';
undefinedDELETE FROM messages WHERE messageTimestamp < NOW() - INTERVAL '90 days';
undefined3. Media Storage
3. 媒体存储优化
bash
undefinedbash
undefinedUse S3 for media files
使用S3存储媒体文件
S3_ENABLED=true
S3_BUCKET=evolution-media
S3_ENABLED=true
S3_BUCKET=evolution-media
Don't save media in database
不在数据库中存储媒体
DATABASE_SAVE_DATA_NEW_MESSAGE=false
undefinedDATABASE_SAVE_DATA_NEW_MESSAGE=false
undefined4. Message Queue
4. 消息队列优化
bash
undefinedbash
undefinedUse RabbitMQ for high volume
高并发场景使用RabbitMQ
RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://localhost:5672
RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://localhost:5672
Or SQS for AWS deployments
AWS部署场景使用SQS
SQS_ENABLED=true
undefinedSQS_ENABLED=true
undefinedMigration Guide
迁移指南
From WhatsApp Web.js
从WhatsApp Web.js迁移
javascript
// WhatsApp Web.js
const { Client } = require('whatsapp-web.js');
const client = new Client();
client.on('message', msg => {
if (msg.body === 'ping') {
msg.reply('pong');
}
});
client.initialize();
// Evolution API equivalent
app.post('/webhook', (req, res) => {
const { event, data } = req.body;
if (event === 'messages.upsert') {
const message = data.message?.conversation;
if (message === 'ping') {
sendMessage(data.instance, data.key.remoteJid, 'pong');
}
}
res.sendStatus(200);
});javascript
// WhatsApp Web.js
const { Client } = require('whatsapp-web.js');
const client = new Client();
client.on('message', msg => {
if (msg.body === 'ping') {
msg.reply('pong');
}
});
client.initialize();
// Evolution API 等效实现
app.post('/webhook', (req, res) => {
const { event, data } = req.body;
if (event === 'messages.upsert') {
const message = data.message?.conversation;
if (message === 'ping') {
sendMessage(data.instance, data.key.remoteJid, 'pong');
}
}
res.sendStatus(200);
});From Baileys Directly
从Baileys直接迁移
Evolution API is built on Baileys, so migration is straightforward. Instead of managing Baileys directly, use Evolution API's REST endpoints.
Evolution API基于Baileys构建,因此迁移过程简单直接。无需直接管理Baileys,只需使用Evolution API的REST端点即可。
API Reference Summary
API 参考摘要
Base URL Structure
基础URL结构
https://your-domain.com/{endpoint}/{instanceName}https://your-domain.com/{endpoint}/{instanceName}Authentication
身份验证
bash
undefinedbash
undefinedAll requests require API key header
所有请求均需携带API密钥头
apikey: your-api-key
undefinedapikey: your-api-key
undefinedMain Endpoint Categories
主要端点分类
- - Instance management
/instance/* - - Send messages
/message/* - - Chat and contact operations
/chat/* - - Group management
/group/* - - Webhook configuration
/webhook/* - - Typebot integration
/typebot/* - - Chatwoot integration
/chatwoot/* - - OpenAI integration
/openai/* - - Dify integration
/dify/*
- - 实例管理
/instance/* - - 消息发送
/message/* - - 聊天与联系人操作
/chat/* - - 群组管理
/group/* - - Webhook配置
/webhook/* - - Typebot集成
/typebot/* - - Chatwoot集成
/chatwoot/* - - OpenAI集成
/openai/* - - Dify集成
/dify/*
Resources
资源
Official Links
官方链接
- Documentation: https://doc.evolution-api.com/
- GitHub: https://github.com/EvolutionAPI/evolution-api
- Website: https://evolution-api.com
Community
社区资源
- GitHub Discussions: https://github.com/EvolutionAPI/evolution-api/discussions
- Issues: https://github.com/EvolutionAPI/evolution-api/issues
Integration Partners
集成合作伙伴
- Typebot: https://typebot.io
- Chatwoot: https://chatwoot.com
- Dify: https://dify.ai
- N8N: https://n8n.io
- Flowise: https://flowiseai.com
- Typebot:https://typebot.io
- Chatwoot:https://chatwoot.com
- Dify:https://dify.ai
- N8N:https://n8n.io
- Flowise:https://flowiseai.com
License
许可证
Evolution API is licensed under Apache License 2.0 with specific requirements regarding branding notifications in implementations.
Note: This skill provides comprehensive guidance for building WhatsApp integrations with Evolution API. Always ensure compliance with WhatsApp's Terms of Service and local regulations when deploying messaging solutions.
Evolution API采用Apache License 2.0许可证,对实现中的品牌通知有特定要求。
注意:本技能为使用Evolution API构建WhatsApp集成提供全面指导。部署消息解决方案时,请始终确保符合WhatsApp的服务条款及当地法规。