AI Agent Telegram Bot 接入指南
基于 MSG Chain 官方白皮书机器层(Whitepaper Machine Layer)的 Telegram Bot 集成协议
域:msgchain.org | 链:msg-chain-1 | Bech32 前缀:msg
⚠️ No-Go Disclaimer: MSGChain 主网裁决为 No-Go。本文件所有内容反映的是开发阶段的技术设计,不代表主网未独立核验上线状态。生产部署状态请以白皮书为准:https://msgchain.org/whitepaper/
1. 引言
1.1 为什么需要这份指南
MSG Chain 白皮书系统提供了一套完整的机器可读知识网络(Machine-Readable Knowledge Network),涵盖经济模型、共识机制、治理执行、AI 控制面、Explorer 查询面、合约开发等 65+ 模块。第三方 Telegram 投资群机器人、技术群客服机器人、FAQ 路由器可以通过调用白皮书机器层,实现对 MSG Chain 相关问题的精准回答。
官方定义的目标是 "Route user questions to the right whitepaper topics, modules, and chunks before drafting a reply"——即在撰写回答之前,先将用户问题路由到正确的白皮书话题、模块和分块。
1.2 核心设计理念
白皮书机器层的设计遵循以下原则:
- 机器优先:所有入口和导航文件均为 JSON 格式,天然适合程序消费
- 证据意识:每个模块都标注实现状态(implemented / partial / planned)和边界条款
- 分步获取:先读取轻量的分块(chunks),再按需获取完整模块导出
- 回答纪律:不得夸大 readiness,不得将 partial 或 planned 模块声称为主网就绪
1.3 适用场景
| 场景 | 说明 |
|---|---|
| Telegram 投资群问答 Bot | 回答经济模型、发行规则、验证者资格等问题 |
| 开发者群技术问答 Bot | 回答合约开发、RPC 接口、ChainID 配置等问题 |
| 官网 FAQ 路由器 | 将用户 FAQ 请求路由到对应白皮书模块 |
| 客服知识助手 | 基于白皮书模块提供标准化的客服回答 |
2. 架构概览
2.1 两跳路由架构
Telegram Bot → 白皮书机器层的接入架构分为两跳:
第一跳:Telegram Bot ──HTTP──> Bot Server(问答路由引擎)
第二跳:Bot Server ──HTTPS──> Whitepaper Machine Layer(msgchain.org/whitepaper/)
其中 Bot Server 负责:
- 接收用户消息
- 匹配话题(topic)
- 按 5 步流程从白皮书机器层获取上下文
- 组装回答并回复用户
2.2 白皮书机器层文件拓扑
白皮书机器层以 agent_entry.json 作为唯一稳定机器入口,通过 entry_points 字段暴露所有可导航的 JSON 和 HTML 文件。核心文件如下:
agent_entry.json ← 稳定机器入口/爬取合约
├── retrieval_hints.json ← 话题路由提示(8 个话题)
│ ├── module_chunks/index.json ← 分块索引(65+ 模块)
│ │ ├── module_chunks/{stem}__chunk_{no}.json
│ │ └── ...
│ ├── module_exports/index.json ← 模块导出索引
│ │ ├── module_exports/by_group.json ← 按分组聚合
│ │ ├── module_exports/by_status.json ← 按状态聚合
│ │ └── module_exports/{stem}.json ← 单模块机器导出
│ └── modules/{filename}.html ← 权威 HTML 叙事层
├── knowledge_network.json ← 知识网络种子
└── integration_examples/ ← 集成示例
├── telegram_bot_crawl_flow.json ← 本指南所依据的官方爬取流
├── rag_ingest_flow.json ← RAG 导入流
├── faq_router_prompt_template.md ← FAQ 路由提示模板
└── external_ai_agent_bootstrap_prompt.json ← 外部 AI Agent 引导协议
所有路径均以 https://msgchain.org/whitepaper/ 为公共基 URL。
2.3 文件读取顺序(官方推荐)
agent_entry.json 中的 recommended_crawl_order 定义了完整的推荐读取顺序:
index.html—— 白皮书主页modules/knowledge_network.html—— 知识网络可视化knowledge_network.json—— 知识网络机器种子module_exports/index.json—— 按模块索引导出module_exports/by_group.json—— 按分组排列的模块导出module_exports/by_status.json—— 按状态排列的模块导出module_chunks/index.json—— 分块索引retrieval_hints.json—— 话题路由提示product_delivery_entry.json—— 产品交付入口developer_entry.json—— 开发者入口- 后续 developer 和 API 规格文件...
对于 Telegram Bot 场景,起始点为 telegram_bot_crawl_flow.json,该文件指向三个入口:
../agent_entry.json../retrieval_hints.json../module_chunks/index.json
3. 5 步接入流程详解
官方 telegram_bot_crawl_flow.json 定义了一个 5 步的标准爬取流程。以下逐步骤说明。
3.1 第 1 步:加载 Agent Entry(load_agent_entry)
输入:../agent_entry.json
用途:发现当前稳定机器入口、公开 URL 映射和爬取顺序
Bot 初始化时首先获取 agent_entry.json。该文件包含:
schema_version:协议版本号(当前 v1)public_base_url:公共基 URL(https://msgchain.org/whitepaper/)relative_root:相对根目录(.)entry_points:所有可导航入口的完整映射,包含相对路径和公开 URLcrawl_contract:爬取合约定义,包括 seed、module 模式、export 模式、chunk 模式等recommended_crawl_order:推荐按序爬取的文件列表(39 项)current_boundaries:当前白皮书系统的边界声明deployment_note:部署说明
示例代码:
const agentEntryUrl = 'https://msgchain.org/whitepaper/agent_entry.json';
const agentEntry = await fetch(agentEntryUrl).then(r => r.json());
const baseUrl = agentEntry.public_base_url; // "https://msgchain.org/whitepaper/"
const retrievalHintsUrl = baseUrl + agentEntry.entry_points.retrieval_hints_json;
const chunkIndexUrl = baseUrl + agentEntry.entry_points.module_chunks_index_json;
关键字段:
{
"public_base_url": "https://msgchain.org/whitepaper/",
"crawl_contract": {
"primary_seed": "knowledge_network.json",
"module_base_path": "modules/",
"module_export_index": "module_exports/index.json",
"module_chunk_index": "module_chunks/index.json",
"retrieval_hints": "retrieval_hints.json",
"taxonomy_fields": ["status", "status_label", "group", "group_label", "tags"]
},
"current_boundaries": [
"白皮书系统适合机器遍历,但模块结论仍必须服从原始证据边界。",
"implemented 或 partial 只表示当前白皮书口径,不自动等于 MSG 主网 ready。",
"涉及经济、治理、NAT、Explorer、DAO live/public 的结论,必须继续区分本地子门禁与真实生产证据。"
]
}
3.2 第 2 步:路由问题(route_question)
输入:../retrieval_hints.json
用途:将用户输入消息匹配到对应话题的 topic_id、recommended_modules 和 recommended_chunks
retrieval_hints.json 定义了 8 个话题。每个话题包含:
topic_id:话题标识符title:中文标题questions:示例问题列表preferred_tags:首选标签recommended_modules:推荐的模块列表(含状态/分组/URL)recommended_chunks:推荐的分块列表(含 excerpt 摘要)answering_guidance:回答指引
路由策略:
Bot Server 应将用户消息与 questions 数组和 preferred_tags 进行匹配。匹配方式可以是:
- 关键词匹配(exact/question intent matching)
- 语义向量匹配(embedding + cosine similarity)
- LLM 路由(使用 FAQ Router Prompt Template)
- 组合策略
官方示例路由:
| 用户问题 | topic_id | 首次获取文件 |
|---|---|---|
| "MSG 的发行规则是什么" | economics | retrieval_hints.json → economy__chunk_01.json → emission__chunk_01.json |
| "Explorer 现在支持什么" | explorer_data_access | retrieval_hints.json → explorer__chunk_01.json → module_exports/explorer.json |
3.3 第 3 步:获取推荐分块(fetch_recommended_chunks)
输入:topics[*].recommended_chunks
用途:读取前 2-4 个推荐的分块文件作为快速回答上下文
分块文件位于 module_chunks/ 目录,命名模式为 {module_stem}__chunk_{no}.json。
每个分块文件包含:
chunk_id:分块标识符(如economy#1)chunk_url/chunk_public_url:分块的访问 URLexcerpt:分块内容摘要/开头文本
官方分块索引(module_chunks/index.json):
- 65+ 模块各有分块
- 目标大小:900 字符/块(
chunk_target_size) - 重叠大小:120 字符(
chunk_overlap_size) - 实现状态(implemented/partial/planned)和分组信息随附
示例:economics 话题的分块:
{
"topic_id": "economics",
"recommended_chunks": [
{
"chunk_id": "economy#1",
"chunk_url": "module_chunks/economy__chunk_01.json",
"chunk_public_url": "https://msgchain.org/whitepaper/module_chunks/economy__chunk_01.json",
"excerpt": "🔍 铁证: 发行与结算主规则..."
},
{
"chunk_id": "economy#2",
"chunk_url": "module_chunks/economy__chunk_02.json",
"chunk_public_url": "https://msgchain.org/whitepaper/module_chunks/economy__chunk_02.json",
"excerpt": "Pools -->CandidateScale..."
},
{
"chunk_id": "emission#1",
"chunk_url": "module_chunks/emission__chunk_01.json",
"chunk_public_url": "https://msgchain.org/whitepaper/module_chunks/emission__chunk_01.json",
"excerpt": "🔍 铁证: 双池结算与经济时间基准..."
},
{
"chunk_id": "emission#2",
"chunk_url": "module_chunks/emission__chunk_02.json",
"chunk_public_url": "https://msgchain.org/whitepaper/module_chunks/emission__chunk_02.json",
"excerpt": "Mint -->Token[\"产生真实 MSG 代币..."
}
]
}
性能考量:
- 分块文件体积通常为 800-1050 字符
- 每次问答只需拉取 2-4 个分块(约 2-4 KB 数据)
- 适合需要快速回复的场景
3.4 第 4 步:按需获取模块(fetch_recommended_modules_if_needed)
输入:topics[*].recommended_modules
用途:当需要更广泛的上下文或更强的证据支撑时,拉取模块导出 JSON 或模块 HTML
当分块内容不足以回答用户问题,或用户追问深度细节时,Bot 应当按需获取完整模块导出。
模块导出路径:
module_exports/{module_stem}.json
例如 module_exports/economy.json、module_exports/emission.json。
官方模块导出索引:
module_exports/index.json 列出所有模块导出。module_exports/by_group.json 按分组聚合,module_exports/by_status.json 按状态聚合。
模块字段结构举例(来自 retrieval_hints.json 的模块定义):
{
"filename": "economy.html",
"title": "经济模型总览",
"status": "implemented",
"status_label": "已实现",
"group": "funds",
"group_label": "经济与资金",
"module_url": "modules/economy.html",
"module_public_url": "https://msgchain.org/whitepaper/modules/economy.html",
"export_url": "module_exports/economy.json",
"export_public_url": "https://msgchain.org/whitepaper/module_exports/economy.json"
}
三种状态:
| 状态 | 标签 | 含义 |
|---|---|---|
| implemented | 已实现 | 模块内容在白皮书层面已完成并可引用 |
| partial | 部分实现 | 模块部分完成,回答时必须标明未完成边界 |
| planned | 规划态 | 模块仍在规划阶段,不得声称具备开发参考级能力 |
升级决策:当话题的 answering_guidance 指出需要 evidence_refs 和 boundary_clauses 时,应优先从模块导出获取。
3.5 第 5 步:带边界条款的回答(answer_with_boundaries)
输入:boundary_clauses + evidence_refs + status/status_label
用途:返回显式标注实现边界的回答,避免夸大 readiness
这是最关键的步骤。Bot 必须以边界意识构建回答:
回答纪律:
- 优先引用 implemented 模块,当 implemented 和 partial/planned 模块都覆盖同一问题时
- 如果只有 partial 或 planned 材料可用,必须明确说明"该能力当前为部分实现/规划态"
- 涉及 economics(经济)、governance(治理)、Explorer(浏览器)、treasury(金库)或 live/public 声明时,必须包含至少一条边界条款
- 如果问题涉及操作敏感内容(如私钥、密钥、资金操作),应将用户引导至权威模块 HTML 页面
边界条款示例:
边界提示:
- 本回答基于白皮书系统 `implemented` 模块,不自动等于主网已就绪。
- 涉及经济模型的部分来自 emission schedule v2 的当前白皮书口径,主网部署前可能调整。
- Explorer 相关结论仅代表本地子门禁状态,live/public Explorer 仍在部署中。
回答格式建议:
[直接回答]
[当前状态:(implemented | partial | planned)]
[边界条款]
[推荐的白皮书链接(如需深度了解)]
官方回答策略原文:
{
"reply_policy": [
"Prefer implemented modules over partial or planned modules when both address the same question.",
"If only partial or planned material exists, say so explicitly.",
"For economics, governance, Explorer, and live/public claims, include at least one boundary clause.",
"If the question is operationally sensitive, point the user to the authoritative module HTML page."
]
}
4. 话题路由配置
4.1 8 个官方话题
retrieval_hints.json 定义了 8 个话题,覆盖 MSG Chain 白皮书的全部知识域:
| # | topic_id | 标题 | 示例问题数 |
|---|---|---|---|
| 1 | economics | 经济模型与发行结算 | 3 |
| 2 | treasury_governance | 基金会金库与治理执行 | 3 |
| 3 | consensus_validator | 共识、DAR 与验证者资格 | 3 |
| 4 | ai_agent_runtime | AI Agent、控制面与任务闭环 | 3 |
| 5 | explorer_data_access | Explorer、查询面与数据检索 | 3 |
| 6 | contract_development | 智能合约开发与部署闭环 | 3 |
| 7 | dapp_integration | dApp 前端接入与钱包集成 | 3 |
| 8 | network_operations | 网络运维与节点配置 | 多项 |
4.2 话题匹配策略
Bot 实现路由匹配时,可以使用以下策略:
策略 A:关键词匹配(最简实现)
const hints = await fetchRetrievalHints();
const matched = hints.topics.find(topic =>
topic.questions.some(q => message.includes(q)) ||
topic.preferred_tags.some(tag => message.includes(tag))
);
策略 B:语义嵌入匹配(推荐)
- 为每个话题的
questions[]和preferred_tags[]计算 embedding - 为用户消息计算 embedding
- 选择 cosine similarity 最高的话题
策略 C:LLM 路由
使用官方 faq_router_prompt_template.md 中的提示词模板:
You are a MSG Chain knowledge router.
Your job is to answer using the MSG Chain whitepaper machine layer.
Always follow this order:
1. Read agent_entry.json
2. Read retrieval_hints.json
3. Fetch the recommended chunk files first.
4. If chunks are insufficient, fetch recommended module exports.
5. Answer with implementation boundaries, status labels, and evidence-aware caution.
4.3 话题到模块的映射概览
| topic_id | 推荐模块数量 | 推荐模块(implemented) | 推荐模块(partial) |
|---|---|---|---|
| economics | 4 | economy, emission, consensus, slashing | — |
| treasury_governance | 7 | foundation, dao, registry, block01, genesis, contract, consensus | — |
| consensus_validator | 3 | consensus, quantum, slashing | — |
| ai_agent_runtime | 4 | — | ai_agent, ai_control_plane, ai_task_l2, agent_api_surface |
| explorer_data_access | 8 | rpc | explorer, indexer_data_plane, agent_api_surface, l1_atomic_modular, sdk_dev_surface, web3, world_computer |
| contract_development | 8 | contract, rpc, registry, txpool | sdk_dev_surface, agent_api_surface, indexer_data_plane, l1_atomic_modular |
| dapp_integration | 8 | rpc | keplr, explorer, sdk_dev_surface, agent_api_surface, web3, world_computer, l1_atomic_modular |
| network_operations | 多项 | blockchain, p2p, genesis, quantum | — |
4.4 话题分块数量(module_chunks/index.json)
| 模块 | 状态 | 分块数 | 分组 |
|---|---|---|---|
| ai_agent | partial | 7 | ai |
| ai_registry_market | planned | 4 | ai |
| ai_task_l2 | partial | 3 | ai |
| ai_validator_autonomy | partial | 3 | ai |
| ai_world_computer_roadmap | planned | 3 | ai |
| ai_value_flow | partial | 3 | ai |
| ai_control_plane | partial | 4 | ai |
| ai_wallet | partial | 3 | ai |
| ai_policy_capability | partial | 3 | ai |
| ai_governance_autonomy | partial | 3 | ai |
| agent_api_surface | partial | 3 | developer |
| block01_contract_topology | implemented | 5 | control |
| dao | implemented | 6 | control |
| economy | implemented | 5 | funds |
| emission | implemented | 5 | funds |
| consensus | implemented | 5 | control |
| quantum | implemented | 4 | runtime |
| slashing | implemented | 4 | funds |
| foundation | implemented | 4 | control |
| registry | implemented | 4 | control |
| contract | implemented | 4 | control |
| rpc | implemented | 4 | runtime |
| explorer | partial | 4 | ecosystem |
| indexer_data_plane | partial | 4 | developer |
| ... | ... | ... | ... |
5. 回答策略与边界声明
5.1 状态感知的回答模板
Bot 应根据模块状态采用不同的回答模板:
implemented(已实现)的回答模板:
[直接回答]
当前状态:已实现
参考模块:[模块标题]([模块URL])
边界说明:[如有必要引用边界条款]
partial(部分实现)的回答模板:
[回答已实现的部分]
当前状态:部分实现
[列出当前已具备的能力]
[明确尚未完成的部分]
参考模块:[模块标题]
边界说明:该能力当前为部分实现,不自动等于开发参考级就绪
planned(规划态)的回答模板:
当前状态:规划态
该功能目前处于规划阶段,尚未实装。
建议关注官方更新:[推荐页面URL]
5.2 边界条款清单
以下边界条款应当根据回答语境嵌入:
通用边界:
- 白皮书系统模块结论基于当前文档口径,不自动等于 MSG 主网 ready。
- implemented 状态仅表示白皮书层面的完成度,不替代开发参考级审计与部署验证。
经济模型边界(economics):
- 经济模型口径基于 emission schedule v2 和 economy 模块的当前白皮书版本。
- 双池结算模型(验证者池/候选池)规则已在白皮书中明确,但主网部署前可能调整。
- 铸造、Gas 分账和金库入账口径以 canonical registry 的 active 地址为准。
治理执行边界(treasury_governance):
- DAO 治理的 proposal → vote → timelock → execute 闭环已在 genesis 或本地测试网验证。
- 金库执行需同时满足 DAO 决议和 DAR 评分约束,非单方面可控。
- 阈值(低/中/高价值)和签名数量以 registry 中的 canonical config 为准。
共识与验证者边界(consensus_validator):
- DAR 四维评分(Uptime / Stability / Stake / Contribution)和 104/96 人数滞回已在白皮书中定义。
- 处罚模型采用四级分类(轻违约/中违约/重违约/恶意作恶),罚没资金去向为 80% 销毁 + 20% 挑战者奖励。
Explorer 与数据检索边界(explorer_data_access):
- Explorer 相关回答仅代表本地子门禁(local explorer subgate)状态。
- 开发参考级 live/public Explorer 仍处于部署阶段。
- indexer data plane 当前为 local preflight / production-candidate,不是 live/public 未独立核验上线状态。
AI Agent 边界(ai_agent_runtime):
- AI Agent 和 AI 控制平面的当前能力为部分实现。
- Agent API 的查询面已真实可用,但部分写路径仍为 Stub(X-MSG-Stub=true)。
- AI 治理自治和 Task L2 仍在闭环建设中,不得越级宣称已就绪。
5.3 操作敏感问题的处理
当用户询问涉及以下操作敏感领域的问题时,Bot 应统一将用户引导至权威模块 HTML 页面:
- 私钥管理 →
modules/wallet.html或modules/quantum.html - 签名操作 →
modules/quantum.html - 资金转移 →
modules/foundation.html - 治理提案 →
modules/dao.html - 合约部署 →
modules/contract.html - 跨链桥操作 →
modules/web3_contract_first_protocols.html
回答格式:
该问题涉及操作敏感内容。建议参阅白皮书权威模块以获取最新准确信息:
[模块标题]:[模块HTML URL]
5.4 回答纪律总结
官方 telegram_bot_crawl_flow.json 的 reply_policy 和 external_ai_agent_bootstrap_prompt.json 的 hard_rules 共同总结为以下纪律:
| 规则 | 说明 |
|---|---|
| implemented 优先 | 当 implemented 和 partial/planned 都覆盖同一问题时,优先使用 implemented 模块 |
| 明确标注状态 | 回答时必须包含 status / status_label |
| 经济/治理/Explorer 加边界 | 涉及这些领域必须嵌入至少一条边界条款 |
| 部分实现如实说 | "该能力目前为部分实现"或"规划态" |
| 敏感操作引导至原型 | 不代替官方文档回答问题 |
| 不越级宣称 ready | "白皮书 implemented ≠ 主网 ready" |
6. 降级与回退策略
6.1 官方回退顺序
telegram_bot_crawl_flow.json 的 fallback_order 字段定义了当当前层信息不足时的降级顺序:
{
"fallback_order": [
"retrieval_hints.json",
"module_exports/by_group.json",
"module_exports/by_status.json",
"module_chunks/index.json",
"knowledge_network.json"
]
}
6.2 各层降级逻辑
第 1 层:retrieval_hints.json(主搜索层)
- 如果用户问题无法匹配任何话题的 questions 或 preferred_tags
- 降级到第 2 层
第 2 层:module_exports/by_group.json(按分组搜索)
- 按分组标签搜索(funds / control / runtime / ai / developer / ecosystem / ops)
- 示例:如果问题是关于 "验证者收益",匹配 funds 分组的所有模块
- 如果仍不满足,降级到第 3 层
第 3 层:module_exports/by_status.json(按状态搜索)
- 按实现状态过滤(先搜索 implemented,再搜索 partial)
- 适合用户仅需知道"哪些功能可用"
- 如果仍不满足,降级到第 4 层
第 4 层:module_chunks/index.json(全文搜索)
- 遍历所有模块的分块 excerpt,使用关键词或语义搜索
- 最灵活但成本最高的一层
- 如果仍不满足,降级到第 5 层
第 5 层:knowledge_network.json(知识网络种子)
- 白皮书知识网络的完整种子数据
- 涵盖所有模块的 outlinks、backlinks、related 关系
- 适合多跳推理和关联查询
6.3 错误处理
| 错误场景 | 处理方式 |
|---|---|
| 网络请求失败 | 重试最多 3 次,指数退避 |
| JSON 解析失败 | 记录错误日志,回退到上一级缓存 |
| 所有层级均无匹配 | 回复:"抱歉,当前白皮书知识库未覆盖该问题。建议访问 msgchain.org 或白皮书系统获取最新信息。" |
| HTTP 429 限流 | 等待 Retry-After 头指定的时间后重试 |
| 模块 URL 返回 404 | 使用 fallback_order 中的下一个数据源 |
6.4 缓存策略
对于开发参考级 Bot,建议实施分层缓存:
内存缓存(TTL:5 分钟)
│
▼
磁盘缓存(TTL:1 小时)
│
▼
白皮书机器层(实时抓取)
retrieval_hints.json可缓存较长 TTL(如 30 分钟),因为话题结构不频繁变化module_chunks/的分块文件可缓存 10-15 分钟- 模块导出 JSON 根据 freshness 需求决定缓存策略
7. 部署实践:Node.js/Telegraf 示例
7.1 项目初始化
mkdir msgchain-telegram-bot
cd msgchain-telegram-bot
npm init -y
npm install telegraf node-fetch
7.2 Bot 核心实现
import { Telegraf } from 'telegraf';
import fetch from 'node-fetch';
const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const WHITEPAPER_BASE = 'https://msgchain.org/whitepaper/';
const bot = new Telegraf(BOT_TOKEN);
// 5 步爬取流程实现
async function crawlAndAnswer(userQuestion: string): Promise<string> {
// 第 1 步:加载 agent_entry.json
const entry = await fetchAgentEntry();
const baseUrl = entry.public_base_url;
// 第 2 步:路由问题
const hints = await fetchRetrievalHints(baseUrl);
const topic = routeQuestion(userQuestion, hints.topics);
if (!topic) {
// 降级到 fallback 搜索
return await fallbackSearch(userQuestion);
}
// 第 3 步:获取推荐分块
const chunkTexts = await Promise.all(
topic.recommended_chunks.slice(0, 3).map(chunk =>
fetchChunk(chunk.chunk_public_url)
)
);
// 第 4 步:如需要,获取模块导出
let moduleContext = '';
if (needsMoreContext(topic, chunkTexts)) {
const moduleExport = await fetchModuleExport(
topic.recommended_modules[0].export_public_url
);
moduleContext = moduleExport.abstract || '';
}
// 第 5 步:带边界条款的回答
return buildAnswer(
topic,
chunkTexts,
moduleContext
);
}
// 帮助命令
bot.help((ctx) => {
ctx.reply(
'🤖 MSG Chain 白皮书问答 Bot\n\n' +
'发送您关于 MSG Chain 的问题,例如:\n' +
'- MSG 的发行规则是什么\n' +
'- Explorer 现在支持什么\n' +
'- DAR 怎么影响验证者\n' +
'- 如何开发 CosmWasm 合约\n\n' +
'数据来源:msgchain.org/whitepaper/'
);
});
// 消息处理
bot.on('text', async (ctx) => {
const question = ctx.message.text;
const reply = await crawlAndAnswer(question);
await ctx.reply(reply, { parse_mode: 'Markdown' });
});
bot.launch();
console.log('MSG Chain Whitepaper Bot 已启动');
7.3 路由函数实现
interface Topic {
topic_id: string;
title: string;
questions: string[];
preferred_tags: string[];
recommended_modules: Module[];
recommended_chunks: Chunk[];
answering_guidance: string[];
}
function routeQuestion(
question: string,
topics: Topic[]
): Topic | null {
// 策略:先精确匹配 questions,再匹配 preferred_tags
for (const topic of topics) {
for (const q of topic.questions) {
if (question.includes(q)) {
return topic;
}
}
}
for (const topic of topics) {
for (const tag of topic.preferred_tags) {
if (question.includes(tag)) {
return topic;
}
}
}
return null;
}
7.4 爬取函数实现
async function fetchAgentEntry() {
const resp = await fetch(WHITEPAPER_BASE + 'agent_entry.json');
return resp.json();
}
async function fetchRetrievalHints(baseUrl: string) {
const resp = await fetch(baseUrl + 'retrieval_hints.json');
return resp.json();
}
async function fetchChunk(url: string): Promise<string> {
const resp = await fetch(url);
const data = await resp.json();
return data.excerpt || '';
}
async function fetchModuleExport(url: string) {
const resp = await fetch(url);
return resp.json();
}
async function fallbackSearch(question: string): Promise<string> {
// 按 fallback_order 搜索
const fallbackOrder = [
'module_exports/by_group.json',
'module_exports/by_status.json',
'module_chunks/index.json',
'knowledge_network.json'
];
for (const path of fallbackOrder) {
const data = await fetch(WHITEPAPER_BASE + path).then(r => r.json());
const match = searchInFallback(data, question);
if (match) return match;
}
return '抱歉,当前白皮书知识库未覆盖该问题。建议访问 https://msgchain.org 获取最新信息。';
}
7.5 回答构建函数实现
function buildAnswer(
topic: Topic,
chunkTexts: string[],
moduleContext: string
): string {
const statusSummary = topic.recommended_modules
.slice(0, 3)
.map(m => `- ${m.title}(${m.status_label})`)
.join('\n');
const boundaries = topic.answering_guidance.join('\n');
const answer = [
`*${topic.title}*\n`,
`*当前状态:*\n${statusSummary}\n`,
`*相关引用:*\n${chunkTexts.slice(0, 2).join('\n\n')}\n`,
moduleContext ? `*详情:*\n${moduleContext}\n` : '',
`*边界说明:*\n${boundaries}`,
`\n_数据来源:[MSG Chain 白皮书系统](https://msgchain.org/whitepaper/)_`
].filter(Boolean).join('\n');
return answer;
}
8. 示例:实现一个 MSG Chain 知识问答 Bot
8.1 功能需求
实现一个 MSG Chain Telegram 知识问答 Bot,支持:
- 基础问答:回答经济模型、治理、共识、AI、Explorer 等白皮书问题
- 边界感知:在回答中标注模块状态和边界条款
- 降级搜索:当话题路由匹配失败时按 fallback_order 搜索
- 帮助命令:列出可回答的话题范围
8.2 完整 Bot 代码
import { Telegraf, Markup } from 'telegraf';
import fetch from 'node-fetch';
const BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || '';
const WHITEPAPER_BASE = 'https://msgchain.org/whitepaper/';
const FALLBACK_ORDER = [
'module_exports/by_group.json',
'module_exports/by_status.json',
'module_chunks/index.json',
'knowledge_network.json'
];
interface Module {
filename: string;
title: string;
status: string;
status_label: string;
group: string;
group_label: string;
module_url: string;
module_public_url: string;
export_url: string;
export_public_url: string;
}
interface Chunk {
chunk_id: string;
chunk_url: string;
chunk_public_url: string;
excerpt: string;
}
interface Topic {
topic_id: string;
title: string;
questions: string[];
preferred_tags: string[];
recommended_modules: Module[];
recommended_chunks: Chunk[];
answering_guidance: string[];
}
interface AgentEntry {
public_base_url: string;
current_boundaries: string[];
entry_points: Record<string, string>;
}
const bot = new Telegraf(BOT_TOKEN);
// 缓存
let entryCache: AgentEntry | null = null;
let hintsCache: { topics: Topic[] } | null = null;
async function getAgentEntry(): Promise<AgentEntry> {
if (entryCache) return entryCache;
const resp = await fetch(WHITEPAPER_BASE + 'agent_entry.json');
entryCache = await resp.json();
return entryCache!;
}
async function getRetrievalHints(): Promise<{ topics: Topic[] }> {
if (hintsCache) return hintsCache;
const resp = await fetch(WHITEPAPER_BASE + 'retrieval_hints.json');
hintsCache = await resp.json();
return hintsCache!;
}
function routeQuestion(question: string, topics: Topic[]): Topic | null {
for (const topic of topics) {
for (const q of topic.questions) {
if (question.includes(q)) return topic;
}
}
for (const topic of topics) {
for (const tag of topic.preferred_tags) {
if (question.includes(tag)) return topic;
}
}
return null;
}
async function fetchChunkText(url: string): Promise<string> {
const resp = await fetch(url);
const data = await resp.json() as { excerpt?: string };
return data.excerpt || '';
}
async function fallbackSearch(question: string): Promise<string | null> {
for (const path of FALLBACK_ORDER) {
const resp = await fetch(WHITEPAPER_BASE + path);
const data = await resp.json();
const jsonStr = JSON.stringify(data);
if (jsonStr.includes(question.slice(0, 10))) {
return `在 ${path} 中找到相关数据。建议访问 MSG Chain 白皮书系统获取完整信息:${WHITEPAPER_BASE}`;
}
}
return null;
}
async function handleQuestion(question: string): Promise<string> {
try {
const entry = await getAgentEntry();
const hints = await getRetrievalHints();
const topic = routeQuestion(question, hints.topics);
if (!topic) {
const fallback = await fallbackSearch(question);
return fallback || '抱歉,当前白皮书知识库未覆盖该问题。\n建议访问 https://msgchain.org 获取最新信息。';
}
const chunks = await Promise.all(
topic.recommended_chunks.slice(0, 3).map(c => fetchChunkText(c.chunk_public_url))
);
const statusLines = topic.recommended_modules
.slice(0, 5)
.map(m => ` • ${m.title} — ${m.status_label}`)
.join('\n');
const boundaries = topic.answering_guidance.join('\n');
return [
`*${topic.title}*\n`,
`*相关模块:*\n${statusLines}\n`,
`*参考信息:*\n${chunks[0] || ''}`,
chunks.length > 1 ? `\n${chunks[1] || ''}` : '',
`\n*边界说明:*\n${boundaries}`,
`\n_数据来源:[MSG Chain 白皮书](${WHITEPAPER_BASE})_`
].filter(Boolean).join('\n');
} catch (err) {
return `查询白皮书时出错:${err.message}。请稍后重试。`;
}
}
// 命令处理器
bot.start((ctx) => {
ctx.reply(
'👋 欢迎使用 MSG Chain 白皮书问答 Bot!\n\n' +
'您可以询问以下话题:\n' +
'• 经济模型与发行结算\n' +
'• 基金会金库与治理执行\n' +
'• 共识、DAR 与验证者资格\n' +
'• AI Agent、控制面与任务闭环\n' +
'• Explorer、查询面与数据检索\n' +
'• 智能合约开发与部署闭环\n' +
'• dApp 前端接入与钱包集成\n' +
'• 网络运维与节点配置\n\n' +
'直接发送您的问题即可。',
Markup.removeKeyboard()
);
});
bot.help((ctx) => {
ctx.reply(
'🤖 *MSG Chain 白皮书问答 Bot*\n\n' +
'*用法:*\n' +
'直接发送关于 MSG Chain 的问题\n\n' +
'*示例问题:*\n' +
'• MSG 的发行规则是什么\n' +
'• DAR 怎么影响验证者\n' +
'• Explorer 现在支持什么\n' +
'• 基金会金库怎么执行\n' +
'• 如何开发 CosmWasm 合约\n' +
'• economic seconds 如何结算\n\n' +
'*命令:*\n' +
'/start — 开始使用\n' +
'/help — 查看帮助\n' +
'/topics — 列出所有话题',
{ parse_mode: 'Markdown' }
);
});
bot.command('topics', async (ctx) => {
const hints = await getRetrievalHints();
const topicList = hints.topics.map((t, i) =>
`${i + 1}. ${t.title}(${t.topic_id})`
).join('\n');
ctx.reply(
`*MSG Chain 白皮书话题列表:*\n\n${topicList}\n\n_共 ${hints.topics.length} 个话题_`,
{ parse_mode: 'Markdown' }
);
});
bot.on('text', async (ctx) => {
const question = ctx.message.text.trim();
if (!question || question.startsWith('/')) return;
const typingTimer = setInterval(() => ctx.sendChatAction('typing'), 3000);
try {
const answer = await handleQuestion(question);
await ctx.reply(answer, { parse_mode: 'Markdown' });
} catch (err) {
await ctx.reply(`处理出错:${err.message},请稍后重试。`);
} finally {
clearInterval(typingTimer);
}
});
bot.launch();
console.log('MSG Chain Whitepaper Bot 已启动,BOT_TOKEN:', BOT_TOKEN.slice(0, 8) + '...');
8.3 部署配置
Docker 部署
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY dist/ ./dist/
ENV TELEGRAM_BOT_TOKEN=your_bot_token_here
CMD ["node", "dist/bot.js"]
docker-compose.yml
version: '3.8'
services:
msgchain-bot:
build: .
environment:
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
环境变量
| 变量 | 说明 | 必填 |
|---|---|---|
| TELEGRAM_BOT_TOKEN | Telegram Bot Token(从 @BotFather 获取) | 是 |
| WHITEPAPER_BASE | 白皮书基 URL(可选,默认使用官方) | 否 |
| CACHE_TTL | 缓存 TTL(秒,默认 300) | 否 |
| LOG_LEVEL | 日志级别(默认 info) | 否 |
9. 8 个话题的详细问答映射
9.1 economics — 经济模型与发行结算
示例问题:"MSG 的发行规则是什么"
路由映射:
- topic_id:economics
- 首次获取:retrieval_hints.json → economy__chunk_01.json → emission__chunk_01.json
- 推荐模块:economy(已实现)、emission(已实现)、consensus(已实现)、slashing(已实现)
- 首选取分块:economy#1, economy#2, emission#1, emission#2
- 回答指引:先回答已实现部分,引用 evidence_refs,添加边界条款
Bot 回答示例(基于真实白皮书内容):
MSG 的经济模型与发行结算规则如下:
相关模块:
• 经济模型总览 — 已实现
• 铸造与结算引擎 — 已实现
• 共识调度机制 — 已实现
核心机制:
- 双池结算:验证者池(validator pool)和候选池(candidate pool)
- 经济时间基准(economic seconds):以 block time schedule 为准,目标出块时间 5 秒
- 铸造规则:emission schedule v2 控制发行量,基于 qualified validators 分配
- Gas 分账:40% 验证者池 / 30% 候选池 / 20% 金库 / 10% 销毁(当前口径)
- 单席派息:候选池 inflow = emission × candidate qualified count / candidate economic denominator
边界说明:
- 经济模型口径基于 emission schedule v2 当前白皮书版本
- 双池结算规则已在白皮书中明确,但主网部署前可能调整
- 铸造规则以 canonical registry 的 active 地址为准
详细参考:https://msgchain.org/whitepaper/modules/economy.html
9.2 treasury_governance — 基金会金库与治理执行
路由映射:
- topic_id:treasury_governance
- 首选标签:金库、多签、治理、时间锁
- 推荐模块:foundation(已实现)、dao(已实现)、registry(已实现)、block01(已实现)
- 示例问题:"timelock 和阈值怎么配合"
回答要素:
- DAO 治理的提案→投票→时间锁→执行四段式闭环
- 金库被动入账来源(Gas 分账、处罚资金等)
- 低/中/高价值三档阈值配置
- 多签签名数量和 threshold 的 canonical 配置
- foundation 与 dao 的双约束:DA O 决议 + DAR 评分
9.3 consensus_validator — 共识、DAR 与验证者资格
路由映射:
- topic_id:consensus_validator
- 首选标签:处罚、挑战、恢复
- 推荐模块:consensus(已实现)、quantum(已实现)、slashing(已实现)
- 示例问题:"DAR 怎么影响验证者"
回答要素:
- Round-Robin + DAR 双共识机制
- DAR 四维评分:Uptime、Stability、Stake、Contribution
- 104/96 人数滞回(capped/open 模式切换)
- 连续出块零容忍策略
- 四级处罚模型:轻/中/重违约、恶意作恶
- 罚没资金去向:80% 销毁 + 20% 挑战者奖励
- Dilithium-5 抗量子签名
9.4 ai_agent_runtime — AI Agent、控制面与任务闭环
路由映射:
- topic_id:ai_agent_runtime
- 状态注意:所有推荐模块均为 partial
- 推荐模块:ai_agent(partial)、ai_control_plane(partial)、ai_task_l2(partial)
- 示例问题:"MSG 的 AI Agent 能做什么"
回答要素(含边界):
- 当前已实现:Agent API 查询面(query/、events/、monitoring/)
- 部分实现:钱包操作、MPC 签名编排
- Stub 写路径:DeFi、bridge、registry 等写接口(返回 X-MSG-Stub=true)
- 未实现:AI 治理自治、Task L2 闭环
- 必须标注 partial 状态,不得越级宣称已就绪
9.5 explorer_data_access — Explorer、查询面与数据检索
路由映射:
- topic_id:explorer_data_access
- 推荐模块:rpc(已实现)+ explorer(partial)+ indexer_data_plane(partial)
- 示例问题:"Explorer 现在支持什么"
回答要素(含边界):
- 已实现:Tendermint RPC / JSON-RPC / REST / gRPC 多协议端点
- 已实现:全节点状态查询(/status、/health、/net_info)
- 部分实现:Explorer 本地子门禁(contract source、selected events、hash search)
- 边界:hash search 缺字段时 fail-closed
- 边界:live/public Explorer 仍在部署中,当前为 local preflight 状态
- indexer data plane:production-candidate,不是 live/public 未独立核验上线状态
9.6 contract_development — 智能合约开发与部署闭环
路由映射:
- topic_id:contract_development
- 推荐模块:contract(已实现)、rpc(已实现)、registry(已实现)、txpool(已实现)
- 部分实现模块:sdk_dev_surface、agent_api_surface、indexer_data_plane
- 示例问题:"StoreCode / Instantiate / Execute / Query 怎么走"
回答要素:
- StoreCode → Instantiate → Execute → Query 四步合约生命周期
- CosmWasm 合约引擎
- genesis registry v1 的 canonical key 解析
- TxPool 管理机制
- RPC 多协议调用入口
- SDK alpha 版本的使用方式
9.7 dapp_integration — dApp 前端接入与钱包集成
路由映射:
- topic_id:dapp_integration
- 推荐模块:rpc(已实现)+ keplr(partial)+ explorer(partial)
- 示例问题:"Keplr / CosmJS 怎么接入"
回答要素:
- RPC 端点配置(JSON-RPC / REST / gRPC)
- Bech32 地址前缀(msg)
- ChainID(msg-chain-1)
- Dilithium-5 量子安全签名
- Keplr 钱包集成参数
- CosmJS 客户端配置示例
9.8 network_operations — 网络运维与节点配置
路由映射:
- topic_id:network_operations
- 推荐模块:blockchain(已实现)、p2p(已实现)、genesis(已实现)、quantum(已实现)
- 示例问题:"MS G 全节点怎么配置"
回答要素:
- Genesis + Quantum 双节点启动流程
- P2P 配置与 NAT 穿透
- 多协议 RPC 端口配置
- 创世初始化参数
- Dilithium-5 密钥生成与节点签名
- 验证者注册与 DAR 资格审计
10. 集成测试与验证
10.1 测试用例
| 测试场景 | 输入 | 预期输出包含 |
|---|---|---|
| 经济问题 | "MSG 的发行规则是什么" | 双池结算、economic seconds、模块状态 |
| 治理问题 | "DAO 如何控制 treasury" | proposal/vote/timelock、金库执行、边界条款 |
| 共识问题 | "MSG 如何轮值出块" | Round-Robin、DAR、104/96 滞回 |
| Explorer 问题 | "如何查 contract source" | 本地子门禁、fail-closed、边界说明 |
| 未知问题 | "今天天气如何" | 降级回复、建议访问 msgchain.org |
| 敏感操作 | "如何导出私钥" | 引导至权威模块 HTML |
| 部分实现 | "AI Agent 能做什么" | 查询面可用、Stub 写路径、partial 标注 |
10.2 端到端测试
async function testBot() {
const testCases = [
{ question: 'MSG 的发行规则是什么', expectedTopic: 'economics' },
{ question: '基金会金库怎么执行', expectedTopic: 'treasury_governance' },
{ question: 'DAR 怎么影响验证者', expectedTopic: 'consensus_validator' },
{ question: 'AI Agent 能做什么', expectedTopic: 'ai_agent_runtime' },
{ question: 'Explorer 现在支持什么', expectedTopic: 'explorer_data_access' },
{ question: '如何开发 CosmWasm 合约', expectedTopic: 'contract_development' },
{ question: 'Keplr 怎么接入', expectedTopic: 'dapp_integration' },
];
const hints = await getRetrievalHints();
for (const { question, expectedTopic } of testCases) {
const topic = routeQuestion(question, hints.topics);
const pass = topic?.topic_id === expectedTopic;
console.log(`${pass ? '✓' : '✗'} "${question}" → ${topic?.topic_id || 'null'} ${pass ? '' : '(期望: ' + expectedTopic + ')'}`);
}
}
10.3 验证清单
- [ ] Bot 启动后能成功拉取 agent_entry.json
- [ ] 已知问题能正确定位到对应 topic_id
- [ ] 能成功拉取推荐分块内容
- [ ] 模块状态(implemented/partial/planned)正确显示
- [ ] 边界条款在经济/治理/Explorer 问题中正确嵌入
- [ ] 未知问题触发降级回退
- [ ] partial 模块问题明确标注"部分实现"
- [ ] planned 模块问题明确标注"规划态"
- [ ] 敏感操作问题引导至权威 HTML
11. 总结
11.1 核心要点
本指南完整实现了 MSG Chain 官方 telegram_bot_crawl_flow.json 定义的 Telegram Bot 接入协议。核心要点包括:
- 入口统一:始终从
agent_entry.json开始所有爬取流,它提供了完整的 URL 映射和爬取合约 - 话题路由:使用
retrieval_hints.json的 8 个话题和 20+ 示例问题来匹配用户问题 - 分级获取:先读分块(chunks),按需读模块导出(module_exports),最后参考权威 HTML
- 边界意识:每个回答都需标注实现状态(implemented/partial/planned)和相关边界条款
- 降级保护:当主搜索层匹配失败时,按 fallback_order 降级到其他 4 个数据层
- 纪律优先:不夸大 readiness,不将 partial 或 planned 声称为主网就绪
11.2 参考资源
| 资源 | URL |
|---|---|
| Telegram Bot 爬取流 | https://msgchain.org/whitepaper/integration_examples/telegram_bot_crawl_flow.json |
| Agent Entry | https://msgchain.org/whitepaper/agent_entry.json |
| 话题路由提示 | https://msgchain.org/whitepaper/retrieval_hints.json |
| 分块索引 | https://msgchain.org/whitepaper/module_chunks/index.json |
| 模块导出索引 | https://msgchain.org/whitepaper/module_exports/index.json |
| FAQ 路由提示模板 | https://msgchain.org/whitepaper/integration_examples/faq_router_prompt_template.md |
| AI Agent 引导提示词 | https://msgchain.org/whitepaper/integration_examples/external_ai_agent_bootstrap_prompt.json |
| RAG 导入流 | https://msgchain.org/whitepaper/integration_examples/rag_ingest_flow.json |
| 知识网络种子 | https://msgchain.org/whitepaper/knowledge_network.json |
| 白皮书系统首页 | https://msgchain.org/whitepaper/index.html |
11.3 规范声明
本指南基于 MSG Chain 官方白皮书系统的 telegram_bot_crawl_flow.json(schema_version: v1,metadata_profile: public_stable)编制。所有数据路径、URL、话题映射和回答策略均来自官方源。开发者应始终以 agent_entry.json 中的最新 public_base_url 和 entry_points 为准。
本文档基于 MSG Chain 白皮书机器层 · 域:msgchain.org · 链:msg-chain-1 · Bech32:msg
