第八章:消息网关集成
消息网关概念
消息网关(Messaging Gateway)是 Hermes Agent 与外部通信平台之间的桥梁。它允许用户通过 Telegram、Discord、Slack 等即时通讯工具与 Agent 进行交互,将 Agent 的能力延伸到日常使用的协作工具中。
消息网关的核心架构包含以下组件:
- 适配器层:为每个通信平台提供统一的接口适配
- 消息路由器:根据消息内容和来源决定处理策略
- 会话管理器:维护跨平台的多轮对话状态
- 任务队列:处理异步任务的调度和执行
- 事件总线:在各组件之间传递消息和事件
# .hermes/messaging.yaml - 消息网关配置
messaging:
enabled: true
# 网关端口(接收 webhook)
port: 8080
# 消息路由规则
routing:
default_channel: "direct"
# 会话管理
sessions:
timeout: 1800 # 会话超时时间(秒)
max_sessions: 100 # 最大并发会话数
Telegram Bot 接入配置
Telegram 是最常用的消息接入方式之一,通过 Bot API 与 Hermes Agent 集成。
创建 Bot 并获取 Token
# 在 Telegram 中搜索 @BotFather,发送 /newbot
# 获取 Bot Token,格式如:123456789:ABCdefGHIjklmNOpqrsTUVwxyz
配置 Hermes Agent 连接 Telegram
# .hermes/messaging.yaml
messaging:
platforms:
telegram:
enabled: true
bot_token: "123456789:ABCdefGHIjklmNOpqrsTUVwxyz"
# 允许与 Bot 交互的用户白名单
allowed_users:
- "your_telegram_username"
- 123456789 # 也可以用用户 ID
# 命令配置
commands:
start:
description: "启动与 Agent 的会话"
handler: "handle_start"
status:
description: "查看当前任务状态"
handler: "handle_status"
help:
description: "显示帮助信息"
handler: "handle_help"
# 消息处理配置
message:
max_length: 4096 # 单条消息最大长度
parse_mode: "Markdown" # 支持 Markdown 或 HTML
enable_typing: true # 显示"正在输入"状态
启动消息网关
# 启动 Hermes Agent 并启用消息网关
hermes-agent --messaging
# 验证 Bot 是否在线
# 在 Telegram 中向 Bot 发送 /start
# Bot 应回复欢迎消息
Discord / Slack 集成
Discord Bot 配置
messaging:
platforms:
discord:
enabled: true
bot_token: "${DISCORD_BOT_TOKEN}"
application_id: "123456789012345678"
# 频道白名单
allowed_channels:
- "123456789012345678" # 频道 ID
- "ai-agent-discussion"
# 权限配置
permissions:
- read_message_history
- send_messages
- embed_links
- attach_files
# 消息处理
message:
max_length: 2000
enable_threads: true # 在讨论串中回复
enable_mentions: true # 支持 @提及
Slack App 配置
messaging:
platforms:
slack:
enabled: true
bot_token: "xoxb-xxxxx"
app_token: "xapp-xxxxx"
signing_secret: "${SLACK_SIGNING_SECRET}"
# 工作区与频道配置
workspace: "your-workspace"
channels:
- "#ai-agent"
- "#dev-requests"
# Slack 特有配置
features:
slash_commands:
- command: "/agent"
description: "向 Hermes Agent 发送请求"
handler: "handle_slash_command"
shortcuts:
- name: "Review Code"
callback_id: "review_code"
description: "使用 Agent 审查当前代码片段"
消息路由策略
消息路由决定了 Agent 如何处理来自不同平台、不同用户的消息。合理的路由策略可以提高响应效率并避免冲突。
# 消息路由配置(Python DSL)
from hermes.messaging import Router, Route
router = Router()
# 按平台路由
@router.route(platform="telegram", command="/status")
async def handle_telegram_status(message):
return await get_current_task_status()
# 按关键词路由
@router.route(keywords=["部署", "发布", "deploy"])
async def handle_deploy_request(message):
return await execute_deploy_workflow(message)
# 按用户角色路由
@router.route(role="admin")
async def handle_admin_command(message):
if message.text.startswith("!"):
return await execute_admin_command(message)
| 路由策略 | 优先级 | 适用场景 | 示例 |
|---|---|---|---|
| 命令路由 | 最高 | 明确的指令性请求 | /deploy, /status |
| 关键词路由 | 高 | 基于内容意图匹配 | 包含"部署"的消息 |
| 平台路由 | 中 | 跨平台差异化处理 | Telegram vs Slack |
| 用户路由 | 中 | 基于发送者的策略 | 管理员 vs 普通用户 |
| 默认路由 | 低 | 通用处理 | 未匹配规则的请求 |
异步任务处理模式
消息网关支持同步和异步两种处理模式。对于耗时较长的任务,异步模式是更好的选择:
messaging:
# 异步任务配置
async_tasks:
enabled: true
# 任务队列
queue:
type: "redis" # 支持 redis / memory / rabbitmq
redis_url: "redis://localhost:6379/0"
max_queue_size: 1000
# 任务通知
notifications:
on_complete: true # 任务完成时通知用户
on_fail: true # 任务失败时通知用户
progress_updates: true # 定期发送进度更新
# 超时配置
timeout:
default: 300 # 默认超时 5 分钟
max: 3600 # 最大超时 1 小时
异步任务处理流程
# 异步任务处理示例
from hermes.messaging import AsyncTask, task_handler
@task_handler
async def handle_long_running_task(message):
# 1. 立即回复确认消息
await message.reply("收到请求,正在处理中...")
# 2. 创建异步任务
task = AsyncTask(
task_id=generate_uuid(),
user=message.sender,
platform=message.platform
)
# 3. 执行耗时操作
result = await task.run(
lambda: perform_complex_operation()
)
# 4. 发送结果通知
await message.reply(f"任务完成!结果:{result}")
对比表:各平台接入方式与能力差异
| 能力维度 | Telegram | Discord | Slack |
|---|---|---|---|
| 消息格式 | Markdown/HTML | Markdown/嵌入 | Block Kit |
| 消息长度限制 | 4096 字符 | 2000 字符 | 40000 字符 |
| 文件上传 | 支持(50MB 限制) | 支持(25MB 限制) | 支持(1GB 限制) |
| 富文本交互 | 内联键盘 | 斜杠命令/按钮 | 快捷方式/模态框 |
| 线程回复 | 有限支持 | 原生支持 | 原生支持 |
| Bot 发现 | 搜索用户名 | 邀请至频道 | 安装到工作区 |
| 速率限制 | 30 条/秒 | 50 条/秒 | 依应用类型而定 |
| 用户认证 | Token 白名单 | OAuth2 | Slack 签名 |
| Webhook 支持 | Polling | Gateway | Events API |
| 免费额度 | 完全免费 | 完全免费 | 有限免费消息 |
实际应用场景
场景:多团队协作开发
某团队使用 Slack 进行日常沟通,同时使用 Telegram 作为告警通道。通过 Hermes Agent 的消息网关,两条渠道可以协同工作:
messaging:
platforms:
slack:
channels:
"#dev-team": # 开发团队频道
mode: "interactive" # 支持完整交互
"#code-reviews": # 代码审查频道
mode: "read-only" # 仅发送审查结果
telegram:
group: "-1001234567890" # 告警群组
mode: "alert-only" # 仅发送关键告警
# Slack 中与 Agent 交互
用户: "/agent 帮我审查 PR #42 的代码"
Agent: "正在审查 PR #42,预计需要 2 分钟..."
# Telegram 中接收结果
Agent: "[代码审查完成] PR #42 审查结果:发现 3 个潜在问题,
2 个性能优化建议。详细报告已发送至 #code-reviews。"
通过消息网关,Hermes Agent 不再局限于终端使用,而是融入了团队的日常协作流程,大幅提升了 AI 辅助开发的便捷性和可及性。下一章我们将探讨语音模式与多模态能力。