docs(im): add Telegram and DingTalk platform documentation

- add setup guides for both WebSocket and Webhook modes
- document streaming reply mechanisms (editMessage / AI card)
- update architecture diagrams, data model, and config reference
This commit is contained in:
nullkey
2026-03-24 20:19:41 +08:00
committed by lyingbug
parent 1bf6603271
commit 804a17d58c
+334 -28
View File
@@ -1,6 +1,6 @@
# IM 集成开发文档
WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书、Slack)接入 WeKnora 知识问答管道,支持在 IM 中直接向 AI 提问并获得实时流式回答。
WeKnora 的 IM 集成模块将企业即时通讯平台(企业微信、飞书、Slack、Telegram、钉钉)接入 WeKnora 知识问答管道,支持在 IM 中直接向 AI 提问并获得实时流式回答。
IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置通过前端 Agent 编辑器管理,存储在数据库中。
@@ -10,6 +10,8 @@ IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置
- [企业微信接入](#企业微信接入)
- [飞书接入](#飞书接入)
- [Slack 接入](#slack-接入)
- [Telegram 接入](#telegram-接入)
- [钉钉接入](#钉钉接入)
- [前端管理](#前端管理)
- [架构总览](#架构总览)
- [数据模型](#数据模型)
@@ -21,6 +23,8 @@ IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置
- [企业微信 (WeCom)](#企业微信-wecom)
- [飞书 (Feishu)](#飞书-feishu)
- [Slack](#slack)
- [Telegram](#telegram)
- [钉钉 (DingTalk)](#钉钉-dingtalk)
- [斜杠指令系统](#斜杠指令系统)
- [QA 队列与限流](#qa-队列与限流)
- [流式输出机制](#流式输出机制)
@@ -328,6 +332,142 @@ Slack 提供两种接入模式,推荐使用 WebSocket (Socket Mode) 模式,
---
### Telegram 接入
Telegram 提供两种接入模式,推荐使用 WebSocket(长轮询)模式,无需公网域名。
#### 方式一:WebSocket 模式(长轮询,推荐)
> 无需公网域名,适合快速验证和内网部署。
**第一步:创建 Telegram Bot**
1. 在 Telegram 中搜索 [@BotFather](https://t.me/BotFather) 并开始对话
2. 发送 `/newbot`,按提示填写 Bot 名称和用户名
3. 创建完成后获取 **Bot Token**(格式如 `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`)
**第二步:在 WeKnora 中添加 IM 渠道**
1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道**
2. 填写配置:
- **平台**:选择「Telegram」
- **接入模式**:选择「WebSocket」
- **输出模式**:选择「流式输出」(推荐)
- **Bot Token**:填入从 BotFather 获取的 Token
3. 保存
启动后日志出现以下内容表示连接成功:
```
[IM] Telegram long polling connecting...
```
此时在 Telegram 中给 Bot 发送消息即可收到 AI 回复。
---
#### 方式二:Webhook 模式
> 需要公网可达的回调地址(HTTPS)。
**第一步:创建 Telegram Bot 并获取凭证**
同上,通过 BotFather 创建 Bot 并获取 Bot Token。
**第二步:在 WeKnora 中添加 IM 渠道**
1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道**
2. 填写配置:
- **平台**:选择「Telegram」
- **接入模式**:选择「Webhook」
- **Bot Token**:填入 Bot Token
- **Secret Token**(可选):自定义密钥,用于验证回调请求的 `X-Telegram-Bot-Api-Secret-Token` 头
3. 保存后,复制渠道卡片上显示的**回调地址**
**第三步:配置 Webhook**
通过 Telegram Bot API 设置 Webhook:
```bash
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{"url": "<YOUR_CALLBACK_URL>", "secret_token": "<YOUR_SECRET_TOKEN>"}'
```
> 注意:Telegram Webhook 必须使用 HTTPS。
---
### 钉钉接入
钉钉提供两种接入模式,推荐使用 Stream 模式(WebSocket),无需公网域名。
#### 方式一:WebSocket 模式(Stream,推荐)
> 无需公网域名,适合快速验证和内网部署。
**第一步:创建钉钉机器人**
1. 登录 [钉钉开放平台](https://open-dev.dingtalk.com/) → **应用开发** → **创建应用**
2. 在应用详情页 → **添加应用能力** → 添加 **机器人** 能力
3. 在 **凭证与基础信息** 页获取:
- **Client ID**(AppKey)
- **Client Secret**(AppSecret)
**第二步:配置机器人**
1. 在应用详情页 → **机器人** → 配置消息接收模式为 **Stream 模式**
2.(可选)如需流式 AI 卡片效果,在 **互动卡片** 中创建一个 **AI 卡片模板**,记录 **Card Template ID**
**第三步:在 WeKnora 中添加 IM 渠道**
1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道**
2. 填写配置:
- **平台**:选择「钉钉」
- **接入模式**:选择「WebSocket」
- **输出模式**:选择「流式输出」(推荐)
- **Client ID**:填入 AppKey
- **Client Secret**:填入 AppSecret
- **Card Template ID**(可选):填入 AI 卡片模板 ID,启用后流式回复将以 AI 卡片形式展示
3. 保存
启动后日志出现以下内容表示连接成功:
```
[IM] DingTalk Stream connecting...
```
> **关于 AI 卡片**:配置 Card Template ID 后,流式回复将通过钉钉 AI 卡片实时展示打字效果;未配置时流式内容将在结束后一次性发送。
---
#### 方式二:Webhook 模式
> 需要公网可达的回调地址。
**第一步:创建钉钉机器人并获取凭证**
同上,创建应用并获取 Client ID 和 Client Secret。
**第二步:在 WeKnora 中添加 IM 渠道**
1. 进入 Agent 编辑器 → **IM 集成** → **添加渠道**
2. 填写配置:
- **平台**:选择「钉钉」
- **接入模式**:选择「Webhook」
- **Client ID**:填入 AppKey
- **Client Secret**:填入 AppSecret
- **Card Template ID**(可选):同上
3. 保存后,复制渠道卡片上显示的**回调地址**
**第三步:配置钉钉事件订阅**
1. 在应用详情页 → **机器人** → 配置消息接收模式为 **HTTP 模式**
2. **消息接收地址**:粘贴从 WeKnora 复制的回调地址
3. 钉钉会通过 HmacSHA256 签名验证回调请求
---
## 前端管理
IM 渠道在 Agent 编辑器的 **IM 集成** 标签页中管理(仅编辑模式可见,创建 Agent 时不显示)。
@@ -335,7 +475,7 @@ IM 渠道在 Agent 编辑器的 **IM 集成** 标签页中管理(仅编辑模
### 渠道列表
每个渠道以卡片形式展示,包含:
- **平台标识**:企业微信(绿色)/ 飞书(蓝色)/ Slack(紫色)
- **平台标识**:企业微信(绿色)/ 飞书(蓝色)/ Slack(紫色)/ Telegram(蓝色)/ 钉钉(蓝色)
- **渠道名称**:用户自定义
- **接入模式**:WebSocket / Webhook
- **输出模式**:流式输出 / 完整输出
@@ -358,19 +498,19 @@ IM 渠道在 Agent 编辑器的 **IM 集成** 标签页中管理(仅编辑模
┌──────────────────────────────────────────────────────────────────────────────┐
│ IM 集成架构 │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 企业微信 │ │ 飞书 │ │ Slack │ IM 平台层 │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ Webhook/WS │ Webhook/WS │ Webhook/WS │
│ ─────┼───────────────┼───────────────┼────────────────────────────────── │
│ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ WeCom │ │ Feishu │ │ Slack │ 平台适配器层 (im.Adapter) │
│ │ Adapter │ │ Adapter │ │ Adapter │ · 消息解密、解析 │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ · 签名验证 │
│ │ │ │ · 回复发送、流式推送 │
│ ─────┼───────────────┼───────────────┼────────────────────────────────── │
│ └───────────────┼───────────────┘ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 企业微信 │ │ 飞书 │ │ Slack │ │ Telegram │ │ 钉钉 │ IM层│
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ WH/WS │ WH/WS │ WH/WS │ WH/LP │ WH/Stream │
│ ─────┼─────────────┼────────────┼─────────────┼─────────────┼────────── │
│ ▼ ▼ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ WeCom │ │ Feishu │ │ Slack │ │ Telegram │ │ DingTalk │ 适配 │
│ │ Adapter │ │ Adapter │ │ Adapter │ │ Adapter │ │ Adapter │ 器层 │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │ │
│ ─────┼─────────────┼─────────────┼──────────────┼─────────────┼──────── │
│ └─────────────┼─────────────┼──────────────┘─────────────┘ │
│ ▼ │
│ ┌──────────────────────────────────┐ │
│ │ im.Service │ 服务编排层 │
@@ -419,7 +559,7 @@ CREATE TABLE im_channels (
id VARCHAR(36) PRIMARY KEY,
tenant_id BIGINT NOT NULL,
agent_id VARCHAR(36) NOT NULL, -- 绑定的 Agent ID
platform VARCHAR(20) NOT NULL, -- 'wecom' | 'feishu' | 'slack'
platform VARCHAR(20) NOT NULL, -- 'wecom' | 'feishu' | 'slack' | 'telegram' | 'dingtalk'
name VARCHAR(255) NOT NULL DEFAULT '',
enabled BOOLEAN NOT NULL DEFAULT true,
mode VARCHAR(20) NOT NULL DEFAULT 'websocket', -- 'webhook' | 'websocket'
@@ -443,6 +583,10 @@ CREATE TABLE im_channels (
| 飞书 | Webhook | `app_id`, `app_secret`, `verification_token`, `encrypt_key` |
| Slack | WebSocket | `app_token`, `bot_token` |
| Slack | Webhook | `bot_token`, `signing_secret` |
| Telegram | WebSocket | `bot_token` |
| Telegram | Webhook | `bot_token`, `secret_token`(可选) |
| 钉钉 | WebSocket | `client_id`, `client_secret`, `card_template_id`(可选) |
| 钉钉 | Webhook | `client_id`, `client_secret`, `card_template_id`(可选) |
### im_channel_sessions 表
@@ -494,7 +638,7 @@ CREATE TABLE im_channels (
```go
type IncomingMessage struct {
Platform Platform // "wecom" | "feishu" | "slack"
Platform Platform // "wecom" | "feishu" | "slack" | "telegram" | "dingtalk"
MessageType MessageType // "text" | "file" | "image"
UserID string // 平台用户标识
UserName string // 显示名 (可选)
@@ -832,6 +976,157 @@ EndStream:
---
### Telegram
统一适配器同时支持 Webhook 和长轮询模式,原生实现 `StreamSender` 和 `FileDownloader` 接口。
#### Webhook 模式
```
Telegram 服务器 ──HTTP POST──▶ /api/v1/im/callback/{channel_id}
│
Secret Token 验证(可选)
解析 JSON → IncomingMessage
│
通过 Telegram Bot API 回复
```
- **签名验证:** 通过 `X-Telegram-Bot-Api-Secret-Token` 请求头与配置的 `secret_token` 进行常量时间比较
- **消息类型:** `text`(文本)、`document`(文件,通过 file_id 下载)、`photo`(图片,自动选择最大尺寸)
- **群消息处理:** 自动去除 `@bot` 提及前缀
#### 长轮询模式 (Long Polling)
Telegram 的 WebSocket 模式实际使用长轮询(Long Polling)而非真正的 WebSocket,通过持续调用 `getUpdates` API 获取新消息。
```
LongConnClient ──HTTP POST──▶ https://api.telegram.org/bot<token>/getUpdates
│
1. 发送 getUpdates (timeout=30s,长轮询)
2. 解析返回的 Update 列表
3. 更新 offset 以确认已处理
4. 循环继续
5. 错误时退避 3 秒重试
```
- **超时设置:** HTTP 客户端 35s,长轮询 timeout 30s
- **消息确认:** 通过 `offset` 参数自动确认已处理的消息
#### 流式回复
Telegram 的流式输出基于消息编辑 (editMessageText) 实现:
```
StartStream:
1. POST sendMessage → 发送初始 "正在思考..." 消息,获取 message_id
SendStreamChunk:
2. POST editMessageText → 根据 message_id 更新消息内容(累积全文)
EndStream:
3. POST editMessageText → 最终更新,启用 Markdown 解析
```
每次 `SendStreamChunk` 发送的是**累积全文**而非增量,最小编辑间隔 500ms(避免触发 Telegram 速率限制)。
**Think 块处理:** 流式输出中的 `<think>...</think>` 块会被转换为 Telegram 引用块格式:
```
> 💭 *思考过程*
> [thinking content line 1]
> [thinking content line 2]
```
**孤立流清理:** 后台协程每 1 分钟扫描超过 5 分钟未关闭的流式消息,自动清理(防止内存泄漏)。
#### 文件下载
Telegram 支持文件和图片消息的下载,流程:
1. 调用 `getFile` API 获取文件路径
2. 通过 `https://api.telegram.org/file/bot<token>/<file_path>` 下载文件
#### 源码文件
| 文件 | 职责 |
|------|------|
| `internal/im/telegram/adapter.go` | 事件解析、Secret Token 验证、流式实现(editMessage)、文件下载 |
| `internal/im/telegram/longconn.go` | 长轮询客户端:getUpdates 循环、offset 管理、错误退避 |
---
### 钉钉 (DingTalk)
统一适配器同时支持 Webhook 和 Stream 模式,原生实现 `StreamSender` 接口。支持可选的 AI 卡片流式输出。
#### Webhook 模式
```
钉钉服务器 ──HTTP POST──▶ /api/v1/im/callback/{channel_id}
│
HmacSHA256 签名验证
解析 JSON → IncomingMessage
│
通过 sessionWebhook 或 OpenAPI 回复
```
- **签名验证:** 使用 `client_secret` 对 `timestamp + "\n" + secret` 进行 HmacSHA256 签名,Base64 编码后与请求头 `Sign` 比较,时间戳 1 小时内有效
- **回复方式:** 优先使用回调消息体中的 `sessionWebhook` 回复(适用于群聊场景),失败或不可用时降级到 OpenAPI
- 群聊:`/v1.0/robot/groupMessages/send`
- 私聊:`/v1.0/robot/oToMessages/batchSend`
- **消息格式:** Markdown 格式(`sampleMarkdown`)
- **认证:** 通过 `/v1.0/oauth2/accessToken` 获取 Access Token,带缓存(提前 5 分钟刷新)
#### Stream 模式 (WebSocket)
通过钉钉官方 SDK (`github.com/open-dingtalk/dingtalk-stream-sdk-go`) 建立 Stream 连接,事件推送与 Webhook 等价,无需公网域名,内置自动重连。
```
LongConnClient ══Stream══▶ 钉钉 Stream 服务
│
1. 使用 ClientID + ClientSecret 建立连接
2. 注册 ChatBot 回调处理
3. 接收消息事件
4. SDK 内置重连和心跳
```
#### 流式回复 (AI 卡片)
钉钉的流式输出基于 **AI 互动卡片** 实现(需配置 `card_template_id`):
```
StartStream:
1. POST /v1.0/card/instances/createAndDeliver → 创建并投递 AI 卡片
SendStreamChunk:
2. PUT /v1.0/card/streaming → 流式更新卡片内容(累积全文)
EndStream:
3. PUT /v1.0/card/streaming (isFinalize=true) → 标记流式结束
```
每次 `SendStreamChunk` 发送的是**累积全文**(`isFull: true`),最小更新间隔 500ms。
**无卡片模板时的降级策略:** 未配置 `card_template_id` 时,流式内容在内存中累积,`EndStream` 时一次性通过 `sessionWebhook` 或 OpenAPI 发送完整回复。
**Think 块处理:** 使用与飞书相同的 Markdown 引用块格式(`MarkdownThinkStyle`):
```
> 💭 **思考过程**
> [thinking content line 1]
> [thinking content line 2]
```
**孤立流清理:** 后台协程每 1 分钟扫描超过 5 分钟未关闭的流,自动清理防止内存泄漏。
#### 源码文件
| 文件 | 职责 |
|------|------|
| `internal/im/dingtalk/adapter.go` | 事件解析、HmacSHA256 签名验证、AI 卡片流式实现、Access Token 缓存、OpenAPI 调用 |
| `internal/im/dingtalk/longconn.go` | Stream 客户端(封装钉钉 SDK)、ChatBot 消息分发 |
---
## 斜杠指令系统
IM 渠道支持斜杠指令(Slash Commands),用户在聊天中输入 `/指令名` 即可触发,无需经过 QA 管道,且不受限流约束。
@@ -961,7 +1256,7 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus
### 内容处理
- **Think 块过滤/转换**:`<think>...</think>` 块在飞书中转换为引用块展示,在其他平台中过滤
- **Think 块过滤/转换**:`<think>...</think>` 块在飞书和钉钉中转换为 Markdown 引用块展示,在 Telegram 中转换为引用块(斜体标题),在其他平台中过滤
- **工具事件展示**:Agent 工具调用实时展示调用状态
- 调用中:`⏳ [工具名]`(包裹在 think 块内)
- 调用成功:`✅ [工具名] · [摘要]`
@@ -970,11 +1265,11 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus
- **空内容回退**:流式过程中无可见内容产生时,回退到完整回复模式 (`fallbackNonStream`)
- **完整持久化**:完整内容(含 thinking)持久化到数据库,确保历史完整
### 飞书流式特殊处理
### 平台流式特殊处理
- **"正在思考..." 占位**:流式初始化后立即显示占位文本,提升用户感知
- **孤立流清理**:后台协程每 `streamReaperInterval`(1 分钟)扫描超过 `streamOrphanTTL`(5 分钟)未关闭的流,自动关闭防止内存泄漏
- **Think 块转换**:将 `<think>` 标签转换为飞书 Markdown 引用块(`> 💭 **思考过程**`)
- **"正在思考..." 占位**:飞书和 Telegram 在流式初始化后立即显示占位文本,提升用户感知
- **孤立流清理**:飞书、Telegram、钉钉的后台协程每 `streamReaperInterval`(1 分钟)扫描超过 `streamOrphanTTL`(5 分钟)未关闭的流,自动关闭防止内存泄漏
- **Think 块转换**:飞书和钉钉将 `<think>` 标签转换为 Markdown 引用块(`> 💭 **思考过程**`),Telegram 使用斜体标题(`> 💭 *思考过程*`)
---
@@ -1004,6 +1299,7 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus
| 飞书 | GetMessageResource API(通过 FileKey) |
| 企业微信 Webhook | PicUrl 直接下载 或 MediaId 临时素材 API |
| 企业微信 WebSocket | 加密附件 URL + per-message AES 密钥解密 |
| Telegram | getFile API 获取文件路径 + HTTPS 下载(支持文档和图片) |
---
@@ -1023,8 +1319,13 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus
| `rateLimitWindow` | 60s | 限流滑动窗口大小 |
| `rateLimitMaxRequests` | 10 | 每用户每窗口最大请求数 |
| `metricsLogInterval` | 30s | 队列指标日志上报周期 |
| `streamOrphanTTL` | 5 min | 飞书孤立流超时时间 |
| `streamReaperInterval` | 1 min | 飞书孤立流清理扫描周期 |
| `streamOrphanTTL` | 5 min | 飞书/Telegram/钉钉 孤立流超时时间 |
| `streamReaperInterval` | 1 min | 飞书/Telegram/钉钉 孤立流清理扫描周期 |
| Telegram 编辑间隔 | 500ms | editMessageText 最小调用间隔(避免速率限制)|
| Telegram 长轮询超时 | 30s | getUpdates timeout 参数 |
| Telegram 错误退避 | 3s | getUpdates 失败后等待时间 |
| DingTalk 卡片更新间隔 | 500ms | AI 卡片流式更新最小间隔 |
| DingTalk 签名有效期 | 1h | Webhook 回调签名时间戳有效窗口 |
| WeCom WS 心跳 | 30s | WebSocket 保活频率 |
| WeCom WS 读超时 | 90s | 3 × 心跳间隔,允许一次心跳丢失 |
| WeCom WS 重连退避 | 1s → 30s | 指数退避,上限 30 秒 |
@@ -1049,7 +1350,10 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus
| 排队等待超时 | 超过 60s 自动丢弃,回复 "您的消息等待超时,请重新发送。" |
| 消息限流 | 滑动窗口内超过 10 次,回复限流提示 |
| 飞书孤立流 | 每分钟扫描,超过 5 分钟未关闭的自动结束 |
| Telegram/钉钉孤立流 | 同飞书,每分钟扫描并自动清理 |
| 企业微信群聊回复失败 | appchat API 失败时降级到用户私聊 |
| 钉钉 AI 卡片创建失败 | 降级到 sessionWebhook 或 OpenAPI 回复 |
| 钉钉 sessionWebhook 不可用 | 降级到 OpenAPI(群聊/私聊分别调用不同端点) |
---
@@ -1062,11 +1366,11 @@ QA 管道 ──chunk──chunk──chunk──▶ EventBus
在 `internal/im/<platform>/` 下创建适配器:
```go
package dingtalk
package myplatform
type Adapter struct { /* 平台配置 */ }
func (a *Adapter) Platform() im.Platform { return "dingtalk" }
func (a *Adapter) Platform() im.Platform { return "myplatform" }
func (a *Adapter) VerifyCallback(c *gin.Context) error { /* 签名验证 */ }
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) { /* 解析消息 */ }
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error { /* 发送回复 */ }
@@ -1077,17 +1381,19 @@ func (a *Adapter) HandleURLVerification(c *gin.Context) bool { /* URL 验证 */
- 实现 `im.StreamSender` 以支持流式输出
- 实现 `im.FileDownloader` 以支持文件消息自动保存到知识库
> 可参考已有的 Telegram(纯 HTTP API)和 DingTalk(SDK + AI 卡片)适配器作为实现参考。
### 2. 注册适配器工厂
在 `internal/container/container.go` 的 `registerIMAdapterFactories` 中注册工厂函数:
```go
imService.RegisterAdapterFactory("dingtalk", func(ctx context.Context, channel *im.IMChannel, msgHandler func(*im.IncomingMessage)) (im.Adapter, im.CancelFunc, error) {
imService.RegisterAdapterFactory("myplatform", func(ctx context.Context, channel *im.IMChannel, msgHandler func(*im.IncomingMessage)) (im.Adapter, im.CancelFunc, error) {
creds := parseCredentials(channel.Credentials)
appKey := getString(creds, "app_key")
appSecret := getString(creds, "app_secret")
adapter := dingtalk.NewAdapter(appKey, appSecret)
adapter := myplatform.NewAdapter(appKey, appSecret)
// WebSocket 模式需要启动长连接
if channel.Mode == "websocket" {