mcpField
E
evolution-api

evolution-api

github.com/aeonbridge开发095 次安装40 周前更新
代码仓库

关于 evolution-api

Evolution API Skill 为使用 Evolution API 构建 WhatsApp 集成、聊天机器人和消息自动化提供参考。它面向需要配置消息接口、事件处理及业务系统连接的开发者,内容涵盖 REST API、Webhook 和多种集成方式。

主要功能

  1. 01WhatsApp 文本与媒体消息
  2. 02群组及联系人管理
  3. 03Webhook 与实时事件
  4. 04连接聊天机器人和自动化平台
  5. 05队列、数据库与媒体存储配置

适用场景

  1. 01构建 WhatsApp 客户服务机器人
  2. 02将 WhatsApp 消息接入 CRM
  3. 03通过 Webhook 处理实时消息事件
  4. 04配置群组管理或消息广播流程

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/aeonbridge/ab-anthropic-claude-skills --skill evolution-api

安装后在 Claude Code 中输入/evolution-api确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
.gitkeep
references/
.gitkeep
scripts/
.gitkeep

详细介绍

Evolution API 技能

为使用 Evolution API 构建 WhatsApp 集成和多渠道消息自动化提供专家级帮助。Evolution API 是一个用于 WhatsApp、聊天机器人和商务通信的开源平台。

何时使用此技能

此技能适用于以下场景:

  • 构建 WhatsApp 集成和聊天机器人
  • 创建自动化消息系统
  • 将 WhatsApp 与业务应用集成
  • 搭建多渠道客户服务平台
  • 使用 Typebot、Chatwoot 或 Dify 实现聊天机器人流程
  • 将 WhatsApp 连接到 CRM 系统
  • 构建 AI 驱动的对话应用
  • 搭建基于 webhook 的消息处理机制
  • 实现事件驱动的消息架构
  • 管理 WhatsApp Business API 连接
  • 与 OpenAI 集成以生成智能回复
  • 使用 RabbitMQ、Kafka 或 SQS 搭建消息队列
  • 将媒体文件存储在 S3 或 MinIO 中
  • 询问 Evolution API 的配置和部署
  • 排查 WhatsApp 连接问题

概述

什么是 Evolution API?

Evolution API 是一个开源 WhatsApp 集成平台,具有以下功能:

  • 提供用于 WhatsApp 消息的 RESTful API
  • 同时支持 Baileys(免费)和官方 WhatsApp Business API
  • 可与多个聊天机器人和自动化平台集成
  • 提供全面的 webhook 和事件系统
  • 实现商务消息自动化
  • 完全免费且可自托管

从 CodeChat 演进而来:

“该平台最初基于 CodeChat 使用 Baileys 库构建,是一个 WhatsApp 控制 API,如今已得到显著发展。”

主要功能

消息功能:

  • 发送和接收 WhatsApp 消息
  • 支持媒体(图片、视频、音频、文档)
  • 群组管理和操作
  • 联系人管理
  • 消息历史记录和搜索
  • 已读回执和状态更新

集成生态系统:

  • Typebot:可视化聊天机器人构建工具
  • Chatwoot:客户服务平台
  • Dify:AI Agent 管理
  • OpenAI:AI 驱动的回复和音频转录
  • Flowise:低代码 AI 工作流构建工具
  • N8N:工作流自动化

技术特性:

  • 提供全面端点的 RESTful API
  • 用于实时事件的 webhook 系统
  • 支持 WebSocket 实时更新
  • 消息队列集成(RabbitMQ、Kafka、SQS)
  • 数据库持久化(PostgreSQL、MySQL)
  • 使用 Redis 缓存提升性能
  • 使用 S3/MinIO 存储媒体
  • 可通过 Docker 部署

安装

先决条件
# Node.js 18+ or Docker
node --version  # v18.0.0 or higher

# Database (optional but recommended)
# PostgreSQL 12+ or MySQL 8+

# Redis (optional, for caching)
# Redis 6+
安装方式
选项 1:Docker(推荐)
# Clone the repository
git clone https://github.com/EvolutionAPI/evolution-api.git
cd evolution-api

# Create environment file
cp .env.example .env

# Edit environment variables
nano .env

# Start with Docker Compose
docker-compose up -d

# Check logs
docker-compose logs -f evolution-api

Docker Compose 示例:

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:
选项 2:NVM(Node 版本管理器)
# Install NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Reload shell
source ~/.bashrc

# Install Node.js 18+
nvm install 18
nvm use 18

# Clone repository
git clone https://github.com/EvolutionAPI/evolution-api.git
cd evolution-api

# Install dependencies
npm install

# Copy environment file
cp .env.example .env

# Edit configuration
nano .env

# Build
npm run build

# Start production
npm run start:prod

# Or development mode
npm run start:dev
选项 3:PM2(进程管理器)
# After NVM installation above

# Install PM2 globally
npm install -g pm2

# Start with PM2
pm2 start dist/src/main.js --name evolution-api

# Save PM2 configuration
pm2 save

# Setup auto-restart on boot
pm2 startup

配置

必需的环境变量
# Server Configuration
SERVER_TYPE=http                    # or https
SERVER_PORT=8080
SERVER_URL=https://your-domain.com  # For webhooks

# Authentication
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

# 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

# Redis Cache (Optional but recommended)
CACHE_REDIS_ENABLED=true
CACHE_REDIS_URI=redis://localhost:6379/6
CACHE_REDIS_PREFIX_KEY=evolution

# CORS
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

# Instance Management
DEL_INSTANCE=false                  # Auto-delete after X minutes (false = never)

# Language
LANGUAGE=en                         # or pt, es, etc.
WhatsApp 配置
# Session Configuration
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

# WhatsApp Business API (Official)
WA_BUSINESS_TOKEN_WEBHOOK=evolution
WA_BUSINESS_URL=https://graph.facebook.com
WA_BUSINESS_VERSION=v20.0
WA_BUSINESS_LANGUAGE=en_US
Webhook 配置
# Global Webhook
WEBHOOK_GLOBAL_ENABLED=true
WEBHOOK_GLOBAL_URL=https://your-webhook-endpoint.com/webhook
WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=true

# Event-specific webhooks
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
集成配置

Typebot:

TYPEBOT_API_VERSION=latest          # or specific version

Chatwoot:

CHATWOOT_ENABLED=true
CHATWOOT_MESSAGE_READ=true
CHATWOOT_MESSAGE_DELETE=true
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgresql://...
CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=true

OpenAI:

OPENAI_ENABLED=true

Dify:

DIFY_ENABLED=true

RabbitMQ:

RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://user:pass@localhost:5672
RABBITMQ_EXCHANGE_NAME=evolution_exchange
RABBITMQ_GLOBAL_ENABLED=true

AWS SQS:

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-1

S3/MinIO 存储:

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=true

WebSocket:

WEBSOCKET_ENABLED=true
WEBSOCKET_GLOBAL_EVENTS=false

快速开始

1. 创建实例
# Using 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"
  }'

# Response includes QR code
{
  "instance": {
    "instanceName": "my-whatsapp-bot",
    "status": "created"
  },
  "qrcode": {
    "code": "data:image/png;base64,...",
    "base64": "..."
  }
}
2. 连接 WhatsApp

使用手机上的 WhatsApp 扫描二维码:

  1. 打开 WhatsApp
  2. 前往“设置”>“已关联的设备”
  3. 点击“关联设备”
  4. 扫描 API 响应中的二维码
3. 检查连接状态
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"
  }
}
4. 发送消息
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 端点

实例管理
# Create instance
POST /instance/create
{
  "instanceName": "bot-name",
  "qrcode": true,
  "integration": "WHATSAPP-BAILEYS"  # or WHATSAPP-BUSINESS
}

# List instances
GET /instance/fetchInstances

# Get instance info
GET /instance/connectionState/{instanceName}

# Restart instance
PUT /instance/restart/{instanceName}

# Logout instance
DELETE /instance/logout/{instanceName}

# Delete instance
DELETE /instance/delete/{instanceName}
消息

文本消息:

POST /message/sendText/{instanceName}
{
  "number": "5511999999999",
  "text": "Your message here"
}

媒体消息:

# Image
POST /message/sendMedia/{instanceName}
{
  "number": "5511999999999",
  "mediatype": "image",
  "media": "https://example.com/image.jpg",  # or base64
  "caption": "Image caption"
}

# Video
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
}

# Document
POST /message/sendMedia/{instanceName}
{
  "number": "5511999999999",
  "mediatype": "document",
  "media": "https://example.com/file.pdf",
  "fileName": "document.pdf"
}

高级消息:

# Location
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"
  }]
}

# 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"
    }]
  }]
}

# 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"
}
群组
# Create group
POST /group/create/{instanceName}
{
  "subject": "Group Name",
  "participants": ["5511999999999", "5511888888888"]
}

# Update group info
PUT /group/updateGroupPicture/{instanceName}
{
  "groupJid": "[email protected]",
  "image": "base64-image-data"
}

# Add participants
POST /group/updateParticipant/{instanceName}
{
  "groupJid": "[email protected]",
  "action": "add",  # or remove, promote, demote
  "participants": ["5511999999999"]
}

# Leave group
DELETE /group/leaveGroup/{instanceName}
{
  "groupJid": "[email protected]"
}
联系人和个人资料
# Get profile picture
GET /chat/profilePic/{instanceName}?number=5511999999999

# Get contacts
GET /chat/findContacts/{instanceName}?id=5511999999999

# Update profile name
PUT /chat/updateProfileName/{instanceName}
{
  "name": "My Bot Name"
}

# Update profile status
PUT /chat/updateProfileStatus/{instanceName}
{
  "status": "Available 24/7"
}

# Update profile picture
PUT /chat/updateProfilePicture/{instanceName}
{
  "picture": "base64-image-data"
}
Webhook
# Set instance 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"
  ]
}

# Get webhook info
GET /webhook/find/{instanceName}

集成示例

Typebot 集成
# Set Typebot on instance
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
}

# Start Typebot session
POST /typebot/start/{instanceName}
{
  "url": "https://typebot.io",
  "typebot": "flow-id",
  "remoteJid": "[email protected]",
  "startSession": true,
  "variables": [{
    "name": "userName",
    "value": "John"
  }]
}

# Change Typebot status
POST /typebot/changeStatus/{instanceName}
{
  "remoteJid": "[email protected]",
  "status": "paused"  # or closed
}
Chatwoot 集成
# Enable Chatwoot
POST /chatwoot/set/{instanceName}
{
  "enabled": true,
  "accountId": "123",
  "token": "chatwoot-api-token",
  "url": "https://app.chatwoot.com",
  "signMsg": true,
  "reopenConversation": true,
  "conversationPending": false
}
OpenAI 集成
# Set 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?"
  }]
}
Dify 集成
# Set Dify
POST /dify/set/{instanceName}
{
  "enabled": true,
  "apiUrl": "https://api.dify.ai/v1",
  "apiKey": "app-...",
  "botType": "chatbot",  # or agent, workflow
  "expire": 20,
  "keywordFinish": "exit"
}

Webhook 处理

Webhook 结构
// Example webhook payload
{
  "event": "messages.upsert",
  "instance": "my-whatsapp-bot",
  "data": {
    "key": {
      "remoteJid": "[email protected]",
      "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 处理程序
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');
});
Python Webhook 处理程序
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)

高级用例

1. AI 驱动的客户服务机器人
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);
}
2. 群组管理机器人
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. 广播系统
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));
}
4. 媒体下载机器人
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
    });
  }
}

生产环境最佳实践

1. 安全性
# Use strong API key
AUTHENTICATION_API_KEY=$(openssl rand -hex 32)

# Enable HTTPS
SERVER_TYPE=https

# Restrict CORS
CORS_ORIGIN=https://your-frontend.com
CORS_CREDENTIALS=true

# Use environment-specific configs
# .env.production, .env.staging, .env.development
2. 高可用性
# docker-compose.yml with replicas
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
3. 监控
# Enable detailed logging
LOG_LEVEL=DEBUG
LOG_COLOR=true
LOG_BAILEYS=info

# Use external monitoring
# - Prometheus for metrics
# - Grafana for dashboards
# - Sentry for error tracking

# Health check endpoint
curl https://your-api.com/health
4. 备份策略
# Database backups
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/

# Automated backups with cron
0 2 * * * /scripts/backup.sh
5. 速率限制
// 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);

故障排除

常见问题
无法生成二维码
# Check instance status
curl -X GET https://your-api.com/instance/connectionState/instance-name \
  -H "apikey: your-api-key"

# Restart instance
curl -X PUT https://your-api.com/instance/restart/instance-name \
  -H "apikey: your-api-key"

# Check logs
docker-compose logs -f evolution-api
无法发送消息
# Verify connection
GET /instance/connectionState/{instanceName}

# Check if number is valid
# Format: Country code + number (no +, no spaces)
# Example: 5511999999999

# Verify API key
curl -X GET https://your-api.com/instance/fetchInstances \
  -H "apikey: your-api-key"
Webhook 未收到事件
# Verify webhook configuration
GET /webhook/find/{instanceName}

# Test webhook endpoint
curl -X POST https://your-webhook.com/endpoint \
  -H "Content-Type: application/json" \
  -d '{"test": "data"}'

# Check webhook URL is publicly accessible
# Use ngrok for local development:
ngrok http 3000
数据库连接错误
# Test database connection
psql "postgresql://user:pass@localhost:5432/evolution"

# Check environment variables
echo $DATABASE_CONNECTION_URI

# Verify database exists
psql -l | grep evolution

# Run migrations if needed
npm run migration:run
实例频繁断开连接
# Enable keep-alive
# Check mobile connection
# Verify phone battery saver is off
# Check WhatsApp version is up to date

# Increase session timeout
CONFIG_SESSION_PHONE_CLIENT=Evolution API
QRCODE_LIMIT=60  # Increase timeout

性能优化

1. 启用缓存
# Redis cache
CACHE_REDIS_ENABLED=true
CACHE_REDIS_URI=redis://localhost:6379/6
CACHE_REDIS_SAVE_INSTANCES=true
2. 数据库优化
# Index 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);

# Partition large tables
# Clean old messages periodically
DELETE FROM messages WHERE messageTimestamp < NOW() - INTERVAL '90 days';
3. 媒体存储
# Use S3 for media files
S3_ENABLED=true
S3_BUCKET=evolution-media

# Don't save media in database
DATABASE_SAVE_DATA_NEW_MESSAGE=false
4. 消息队列
# Use RabbitMQ for high volume
RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://localhost:5672

# Or SQS for AWS deployments
SQS_ENABLED=true

迁移指南

从 WhatsApp Web.js 迁移
// 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);
});
直接从 Baileys 迁移

Evolution API 基于 Baileys 构建,因此迁移很简单。无需直接管理 Baileys,只需使用 Evolution API 的 REST 端点。

API 参考摘要

基础 URL 结构
https://your-domain.com/{endpoint}/{instanceName}
身份验证
# All requests require API key header
apikey: your-api-key
主要端点类别
  • /instance/* - 实例管理
  • /message/* - 发送消息
  • /chat/* - 聊天和联系人操作
  • /group/* - 群组管理
  • /webhook/* - Webhook 配置
  • /typebot/* - Typebot 集成
  • /chatwoot/* - Chatwoot 集成
  • /openai/* - OpenAI 集成
  • /dify/* - Dify 集成

资源

官方链接
社区
集成合作伙伴

许可证

Evolution API 采用 Apache License 2.0 许可,并对实现中的品牌标识通知提出了特定要求。


注意:本技能为使用 Evolution API 构建 WhatsApp 集成提供全面指导。部署消息解决方案时,请务必遵守 WhatsApp 服务条款及当地法规。

评论

支持 Markdown