Hive Telegram Bot Tool:基于 MCP 的 Telegram 消息与文档发送工具实战指南
Hive Telegram Bot Tool:基于 MCP 的 Telegram 消息与文档发送工具实战指南
导读
本指南以 Telegram Bot Tool 文档 为主体,结合 telegram_tool.py 源码与 test_telegram_tool.py 测试用例,完整讲解 Hive(Multi-Agent Harness for Production AI)中 Aden Tools 的 Telegram 集成能力:从 Bot 创建、Token 配置、Chat ID 获取,到通过 MCP 工具发送消息、文档、图片、视频,以及消息编辑、转发、删除、置顶等全套操作。读完本文,你将能在自己的 Agent 工作流中把通知、告警、报告直接投递到 Telegram 用户、群组或频道。
工具概览:不只是发消息
文档开篇介绍的两个核心工具 telegram_send_message 与 telegram_send_document,只是该模块能力的子集。从 telegram_tool.py 的 register_tools() 可以看出,实际向 MCP 服务器注册了 13 个工具,可归纳为四类:
| 类别 | 工具 | 对应 Bot API 方法 |
|---|---|---|
| 消息管理 | telegram_send_message、telegram_edit_message、telegram_delete_message、telegram_forward_message |
sendMessage / editMessageText / deleteMessage / forwardMessage |
| 媒体发送 | telegram_send_document、telegram_send_photo、telegram_send_video |
sendDocument / sendPhoto / sendVideo |
| 聊天信息与动作 | telegram_get_chat、telegram_get_chat_member_count、telegram_send_chat_action |
getChat / getChatMemberCount / sendChatAction |
| 置顶管理 | telegram_pin_message、telegram_unpin_message、telegram_set_chat_description |
pinChatMessage / unpinChatMessage / setChatDescription |
工具注册发生在 tools/init.py 的 register_telegram(mcp, credentials=credentials),凭据规格在 credentials/telegram.py 中集中定义。
前置准备:Bot、Token 与 Chat ID
1. 创建 Telegram Bot
- 打开 Telegram,搜索 BotFather(Telegram 官方机器人);
- 发送
/newbot并按提示操作; - 为机器人指定显示名称与用户名;
- 复制 BotFather 返回的 HTTP API Token,形如
123456789:ABCdefGHIjklMNOpqrsTUVwxyz。
2. 配置 Token
文档提供了两种方式,推荐第二种并配合源码说明其优先级:
方式一:环境变量
export TELEGRAM_BOT_TOKEN="your-bot-token-here"
方式二:Hive 凭据存储(Credential Store)
工具内部通过 _get_token() 解析 Token(见 telegram_tool.py):优先调用 credentials.get("telegram") 从 CredentialStoreAdapter 读取;仅在未传入凭据适配器时回退到 os.getenv("TELEGRAM_BOT_TOKEN")。
结合 base.py 的 _get_raw() 可知,凭据解析优先级为:测试覆盖值 > os.environ 环境变量 > .env 文件(支持热更新,每次调用都重新读取,无需重启 MCP 服务器)。Telegram 的凭据规格在 credentials/telegram.py 中声明了 env_var="TELEGRAM_BOT_TOKEN"、credential_id="telegram"、credential_key="bot_token",并设置 required=True、startup_required=False(即缺失时不会阻塞服务器启动,但调用相关工具会返回错误)。
3. 获取 Chat ID
- 与你的 Bot 开始对话并发送任意消息;
- 访问
https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates; - 在返回 JSON 的
result[].message.chat.id字段中找到你的 Chat ID。
群组场景:先把 Bot 拉入群组并赋予必要权限,再调用 getUpdates 查看。注意:公开频道的 Chat ID 也可直接用 @用户名 形式作为 chat_id 传入(源码注释明确支持 numeric ID 或 @username)。
使用示例:从基础到进阶
以下示例均基于 MCP 工具函数,可直接在 Agent 提示或脚本中调用。
发送普通消息
telegram_send_message(
chat_id="123456789",
text="Hello from Hive!",
parse_mode="HTML",
)
带格式的消息
# HTML 格式
telegram_send_message(
chat_id="123456789",
text="<b>Alert:</b> Task completed successfully!",
parse_mode="HTML",
)
# Markdown 格式
telegram_send_message(
chat_id="123456789",
text="*Bold* and _italic_ text",
parse_mode="Markdown",
)
源码中 parse_mode 仅在非空时写入请求 payload,因此传空字符串即纯文本(见 telegram_tool.py)。
发送文档
telegram_send_document(
chat_id="123456789",
document="https://example.com/report.pdf",
caption="Weekly Report",
)
document 参数支持 URL 或 Telegram 已存在的 file_id(源码 docstring 明确说明)。
静默通知
telegram_send_message(
chat_id="123456789",
text="Background update completed",
disable_notification=True,
)
适合后台任务、低优先级流水线通知,避免打扰用户。同样的 disable_notification 参数也适用于 telegram_forward_message 与 telegram_pin_message。
更多实战能力
源码还提供了文档未展开但测试已覆盖的能力:
# 发送图片(URL 或 file_id)
telegram_send_photo(chat_id="123456789", photo="https://example.com/chart.png", caption="Q3 报表")
# 发送视频(URL 或 file_id,支持 MP4,单文件不超过 50MB,超时放宽至 60s)
telegram_send_video(chat_id="123456789", video="https://example.com/demo.mp4", duration=120)
# 编辑已发送的消息(仅能编辑 Bot 自己的消息)
telegram_edit_message(chat_id="123456789", message_id=42, text="<b>Updated:</b> 状态已变更", parse_mode="HTML")
# 删除消息(Bot 自己的消息 48 小时内可删;有权限时可删任意消息)
telegram_delete_message(chat_id="123456789", message_id=42)
# 转发消息(保留原始发送者署名)
telegram_forward_message(chat_id="456", from_chat_id="123", message_id=789)
# 发送"正在输入"等聊天动作(约 5 秒后或 Bot 发消息后消失)
telegram_send_chat_action(chat_id="123456789", action="typing")
# 查询聊天元信息(标题、类型、描述、权限)
telegram_get_chat(chat_id="123456789")
# 统计群成员数量
telegram_get_chat_member_count(chat_id="123456789")
# 置顶 / 取消置顶(message_id 传 0 表示取消最近一条置顶)
telegram_pin_message(chat_id="123456789", message_id=42)
telegram_unpin_message(chat_id="123456789", message_id=0)
# 修改群组/频道描述(最长 255 字符,超长会被工具直接拦截)
telegram_set_chat_description(chat_id="-1001234567890", description="项目进度同步群")
其中 telegram_send_chat_action 内部维护了合法动作白名单(typing、upload_photo、upload_document、record_video、upload_video、record_voice、upload_voice、find_location、choose_sticker),传入非法值会在本地直接返回错误字典,不发任何 API 请求(见 telegram_tool.py)。
API 参考
telegram_send_message
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| chat_id | str | 是 | 目标 Chat ID 或 @用户名 |
| text | str | 是 | 消息文本(1-4096 字符) |
| parse_mode | str | 否 | "HTML" 或 "Markdown",空为纯文本 |
| disable_notification | bool | 否 | 静默发送,默认 False |
telegram_send_document
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| chat_id | str | 是 | 目标 Chat ID 或 @用户名 |
| document | str | 是 | 文档 URL 或 file_id |
| caption | str | 否 | 说明文字(0-1024 字符) |
| parse_mode | str | 否 | caption 的格式模式 |
其余工具的参数同样可在 telegram_tool.py 中各函数的 docstring 中查到,例如 telegram_send_video 的 duration(视频时长秒数,0 表示省略)、telegram_unpin_message 的 message_id=0(取消最近置顶)等。
错误处理:错误字典约定
文档强调"工具失败时返回错误字典"而不是抛异常——这是 MCP 工具层的统一约定,保证 LLM 能直接读取结构化错误并自我修正。错误字典的生成逻辑集中在 _TelegramClient._handle_response()(见 telegram_tool.py),与 HTTP 状态码一一对应:
{"error": "Invalid Telegram bot token"} # HTTP 401
{"error": "Bad request: <description>"} # HTTP 400
{"error": "Bot was blocked by the user or lacks permissions"} # HTTP 403
{"error": "Chat not found"} # HTTP 404
{"error": "Rate limit exceeded. Try again later."} # HTTP 429
{"error": "Telegram API error (HTTP <code>): <description>"} # 其他 4xx/5xx
此外还有两类运行时错误(源码 try/except 层):
{"error": "Telegram request timed out"} # httpx.TimeoutException
{"error": "Network error: <详情>"} # httpx.RequestError
以及未配置 Token 时的引导性错误:
{"error": "Telegram bot token not configured",
"help": "Set TELEGRAM_BOT_TOKEN environment variable or configure via credential store. Get your token from @BotFather on Telegram."}
凭据健康检查:除了运行时错误,credentials/telegram.py 还声明了健康检查端点 https://api.telegram.org/bot{token}/getMe(GET 方法),可在 Agent 执行前用轻量请求预验证 Token 有效性,机制见 health_check.py。
源码原理:一次消息发送的完整调用链
以 telegram_send_message 为例,完整链路为:
- MCP 工具函数
telegram_send_message被调用(telegram_tool.py); _get_client()调用_get_token()解析 Token;若缺失,直接返回带help提示的错误字典;- 构造
_TelegramClient(token),其_base_url为https://api.telegram.org/bot{token}(常量TELEGRAM_API_BASE定义于文件顶部); - 客户端通过
httpx.post()向/sendMessage发送 JSON payload,超时 30 秒(视频上传放宽至 60 秒); _handle_response()按状态码归一化结果:2xx 直接透传 Telegram 响应 JSON(含ok、message_id、chat等字段),非 2xx 映射为错误字典。
值得注意的工程细节:客户端层(_TelegramClient)会原样抛出网络异常,而 MCP 工具层负责捕获并转换为错误字典。这一点在 test_telegram_tool.py 的 TestErrorHandling 与 TestNewOperationsErrorHandling 中被刻意区分测试:直接调用客户端方法会抛出 httpx.ConnectError/httpx.TimeoutException,而调用 MCP 工具函数则返回结构化错误字典——这保证 Agent 场景下的容错性,同时保留底层调试能力。
测试验证:行为即契约
tools/tests/tools/test_telegram_tool.py 以 mock 方式(unittest.mock.patch 拦截 httpx.post/httpx.get)验证了以下契约,可作为理解工具行为的权威依据:
- URL 构造:
test_base_url断言请求 URL 以https://api.telegram.org/bot开头且包含完整 Token; - payload 组装:
test_send_message_with_parse_mode、test_send_photo_no_caption等验证可选参数仅在传入时写入请求体; - 错误映射:
test_handle_response_401/400/403/404/429逐一验证状态码到错误文案的映射; - 凭据来源:
test_credentials_adapter_used验证传入 CredentialStoreAdapter 时优先使用 store 中的 Token(请求 URL 中可看到token_from_store); - 无 Token 降级:
test_send_message_no_token_error与test_new_tools_return_error_without_token验证所有工具在无 Token 时统一返回"not configured"错误; - 注册完整性:
test_register_tools_creates_tools断言 13 个工具全部注册到 FastMCP。
实战建议
- 通知管道:在 Agent 关键节点(任务完成、异常、超时重试)接入
telegram_send_message,配合disable_notification区分高/低优先级; - 报告分发:用
telegram_send_document/telegram_send_photo推送生成的 PDF、图表等产物,文档支持 URL 或 file_id,便于复用已上传文件; - 群组运营:结合
telegram_set_chat_description与telegram_pin_message维护群组信息墙,但需确保 Bot 具备对应管理员权限(源码注释明确提示); - 凭据治理:优先使用 Hive 凭据存储而非裸环境变量,借助其健康检查能力在 Agent 启动前就发现失效 Token,减少运行期错误。