渠道系统
渠道(Channel)将外部即时通讯平台的消息接入 CocoCat。所有渠道统一通过场景进行路由。
渠道生命周期管理 (ChannelManager)
定义于 cococat/core/channel_manager.py:
ChannelManager 负责渠道的 connect/disconnect/auto-reconnect 生命周期。 拥有 _instances(渠道实例字典)和 _status(渠道状态字典)。
connect(target_type, target_id, channel_type, config, ctx)— 创建、接线、启动渠道disconnect(target_type, target_id, channel_type)— 停止并移除渠道auto_reconnect(ctx, loop)— 启动时自动重连已启用且有凭证的渠道
路由处理器(routes/channels.py)不再直接管理频道状态,改为委托 ctx.channel_manager。
抽象层
定义于 cococat/core/channels/:
python
class Channel(ABC):
channel_type: str = ""
@abstractmethod
def start(self, scene_id: str, config: dict):
"""启动频道监听"""
@abstractmethod
def send(self, reply: str, user_id: str):
"""发送回复到外部平台"""渠道实现
| 渠道 | 文件 | 协议 | 说明 |
|---|---|---|---|
| 微信公众号 | channels/wechat.py | XML 消息 + 签名验证 | 被动回复,需公网 IP |
| 企业微信 | channels/weixin.py | JSON API | 支持应用消息 |
| 飞书 | channels/feishu.py | JSON API + Webhook | 卡片消息支持 |
| Web API | channels/web_api.py | HTTP REST | 通用 JSON 接口 |
| Telegram | channels/telegram.py | Bot API Polling | 无额外依赖,长轮询 |
| Discord | channels/discord.py | discord.py Bot | 需安装 discord.py |
入口管理器 (SceneKeeper)
定义于 cococat/core/scene_keeper.py:
SceneKeeper
├── 读取 scenes/*/entries.json 获取通道配置
├── 为每个注册的通道启动后台线程
├── 线程内: 监听 → 解析 → 路由到场景
└── 支持动态增加/移除消息路由
外部消息(微信/飞书等)
↓
SceneKeeper 后台线程收到消息
↓
解析: 提取 text, user_id, platform
↓
scene_router.py: 根据场景 ID 查找
↓
写入目标 agent 的 mailbox
↓
agent 心跳线程读取并处理
↓
回复通过 channel.send() 返回entries.json
定义于 scenes/{scene_name}/entries.json:
json
{
"channels": [
{
"type": "wechat",
"config": {
"app_id": "wx_xxx",
"token": "xxx",
"encoding_aes_key": "xxx"
}
},
{
"type": "web_api",
"config": {
"endpoint": "/api/channel/web",
"api_key": "sk-xxx"
}
}
]
}通道验证
验证脚本提供端到端验证:
bash
python -m cococat.verify_channel --channel wechat --scene customer-service验证步骤:发送测试消息 → 检查 agent 是否收到 → 确认回复成功返回。
Telegram 渠道
定义于 channels/telegram.py:
python
class TelegramChannel(Channel):
channel_type = "telegram"- 协议:Bot API 长轮询(
getUpdates),无需 webhook - 无额外依赖:仅使用
requests库 - 实现:后台线程轮询,
offset追踪已读 update - 消息:解析
message.text,以chat_id作为user_id
entries.json 配置
json
{
"type": "telegram",
"config": {
"bot_token": "123456:ABC-DEF..."
}
}启动验证
启动时调用 getMe 验证 bot token 有效性,失败则打印错误并退出。
Discord 渠道
定义于 channels/discord.py:
python
class DiscordChannel(Channel):
channel_type = "discord"- 协议:discord.py Bot,Gateway Intents
- 依赖:需安装
discord.py(pip install discord.py) - 实现:后台线程运行
client.run(),异步事件循环 - 消息:
on_message事件,忽略 bot 自身消息
entries.json 配置
json
{
"type": "discord",
"config": {
"bot_token": "MTIzNDU2Nzg5..."
}
}Intents
启用 message_content intent 以读取用户消息内容(需在 Discord Developer Portal 开启)。