Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

feat(channels): 接入 Telegram、Slack、Discord

dyk981ab4470bea01
diff --git a/README.md b/README.md
index 7fdf8c4..f4b8deb 100644
--- a/README.md
+++ b/README.md
@@ -45,7 +45,7 @@
# 🤖 AnyModelBot
-AnyModelBot 是一个本地优先的 AI 智能体应用,支持 Windows、macOS 和 Linux。一个机器人就是一个人设,带着自己的默认模型、工作区和记忆。你可以在应用里和它聊天,也可以在微信、飞书里找它。它能读写文件、执行命令、操作你的桌面,一旦要越出自己的工作区,就会先问你。
+AnyModelBot 是一个本地优先的 AI 智能体应用,支持 Windows、macOS 和 Linux。一个机器人就是一个人设,带着自己的默认模型、工作区和记忆。你可以在应用里和它聊天,也可以在微信、飞书、Telegram、Slack、Discord 里找它。它能读写文件、执行命令、操作你的桌面,一旦要越出自己的工作区,就会先问你。
对话、记忆、文件和 API Key 都留在你的设备上。模型来自 [Modelflare](https://modelflare.dev/?utm_source=anymodelbot&utm_campaign=amb_readme):一个账户,任意模型,按 token 计费。AnyModelBot 本身没有订阅。
@@ -189,7 +189,7 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
- **每个机器人三档权限。** *只读*、*工作区*(默认:只能写自己的文件夹,越界先问你)、*完全权限*(不进沙箱;递归删除仍会先问)。
- **审批卡片,没有意外。** 越界的操作会停下来,等你回答。
- **重启了也会告诉你。** 应用退出或崩溃时还没处理完的消息,下次启动会在原对话里说一声,请你重新发送,不会自动重做。
-- **斜杠命令**,如 `/model`、`/reset`,在应用里和微信、飞书对话中都能用。
+- **斜杠命令**,如 `/model`、`/reset`,在应用和各个聊天渠道里都能用。
<p align="center">
<img src="docs/assets/features/agent-files.gif" alt="机器人整理一个杂乱的文件夹:先列出文件、给出方案,移动工作区之外的文件前弹出审批卡片" width="100%">
@@ -201,7 +201,7 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
- **接着问。** 在微信里引用结果、在飞书里回复那条消息,就是继续问这个任务。
- **规则。** 「每天早上 8 点看看 X 的价格,低于 200 告诉我」会建成一条规则,到点就去查,有值得说的才告诉你。想先看看它会怎么做,就说「先观察」:只记下本会说什么,不发消息、不改文件,看过几次再改成执行。
- **「需要你」。** 所有机器人在等你回答、批准或重试的事都在侧栏这一行里;没事时这一行不出现。信息面板的「任务」组列着这个机器人的任务和规则,每一步都看得到。
-- **不吵你。** 只推结果、要你决定的事和失败,进展不推。默认 22:00 到 08:00 免打扰;主动消息每天有上限(微信 3 条、飞书 5 条),多了合成一条。
+- **不吵你。** 只推结果、要你决定的事和失败,进展不推。默认 22:00 到 08:00 免打扰;主动消息每天有上限(微信 3 条,其他渠道 5 条),多了合成一条。
- **有预算。** 每个任务、每条规则都有预算(任务默认 1 美元,规则每次 0.1 美元、每月 3 美元),快用完时停下问你,可以在任务详情和规则编辑器里改。
- **随时暂停。** 机器人设置 › 主动消息里一个开关暂停后台工作,聊天照常。
- **用完会清理。** 任务和运行记录留 30 天;任务文件夹 30 天没动过会自动删除,不来问你,任务详情里写着哪天删,想留就点保留。运行记录能导出成 Markdown。
@@ -242,6 +242,7 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
- **记忆会延续。** 机器人用 Markdown 保存三层记忆(团队、机器人、群),会过滤看起来像密钥的内容。
- **长对话也能用下去。** 上下文快满之前,上下文管家会压缩,或开一个新段并带上交接摘要。
- **微信和飞书。** 微信扫码连接,飞书机器人支持流式回复卡片;微信还能收发图片和文件。
+- **Telegram、Slack、Discord。** 在信息面板填 token 连接,不需要公网地址;回复边写边显示,能收发图片和文件。目前只处理单聊,审批和提问回复文字。
- **四种运行方式。** 桌面版、命令行、Docker,以及 `127.0.0.1:3600` 的本地网页控制台。
<p align="center">
@@ -255,7 +256,7 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
## 🔒 本地优先,也好看
- **数据留在你手里。** 对话、记忆、文件和 API Key 都存放在你的设备上。本地控制台只监听 `127.0.0.1`,桌面版每次启动都会生成新的访问令牌。
-- **只听主人的。** 机器人默认只回应主人(扫码登录的微信;飞书连上后第一个给它发消息的人,也就是你)和你允许的人。其他人发消息只会收到一句提示,不会调用模型;你在信息面板里,或在聊天里回复「同意 编号」放行。
+- **只听主人的。** 机器人默认只回应主人(扫码登录的微信;飞书、Telegram、Slack、Discord 连上后第一个给它发消息的人,也就是你)和你允许的人。其他人发消息只会收到一句提示,不会调用模型;你在信息面板里,或在聊天里回复「同意 编号」放行。
- **回复不会丢。** 回复先存到本地再发;网络断了会自动重试,应用重启后接着发;你在微信里超过 24 小时没说话时,回复先留着,等你下次发消息时一起送到。
- **遥测保持关闭。** 内置电脑操作驱动的遥测已关闭,内置网关以关闭自动更新的方式运行。
- **浅色、深色或跟随系统。** 六个机器人角色,眼睛会跟着你的鼠标转。
@@ -278,10 +279,10 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
| 智能体跑在哪 | 你自己的电脑或服务器 | xAI 的云端电脑 | OpenAI 的云端电脑 | Anthropic 的云端 |
| 能用的模型 | GPT、Claude、Gemini、Grok、DeepSeek、Kimi、GLM 等 70+ 个(经 Modelflare) | 以 xAI 的 Grok 模型为主 | OpenAI 的模型 | Claude(Opus 5.5) |
| 费用 | 应用免费,模型按 token 计费 | 订阅 | ChatGPT Pro / Business Premium 订阅 | Claude Pro / Max 订阅 |
-| 在哪找它 | 桌面应用(Windows、macOS、Linux)、Docker、微信、飞书 | 桌面应用、iPhone | ChatGPT、Slack、Teams | iOS、Android、claude.ai |
+| 在哪找它 | 桌面应用(Windows、macOS、Linux)、Docker、微信、飞书、Telegram、Slack、Discord | 桌面应用、iPhone | ChatGPT、Slack、Teams | iOS、Android、claude.ai |
| 现在能用吗 | 直接下载 | 测试版 | 部分地区开放 | 研究预览,美国候补名单 |
-AnyModelBot 同样能在后台干活:交代的任务可以在后台跑完,再把结果发到微信或飞书;需要你批准或回答时,它会出现在侧栏的「需要你」里。机器人做的每一步都看得见,越出工作区的操作先问你。
+AnyModelBot 同样能在后台干活:交代的任务可以在后台跑完,再把结果发到你用的聊天渠道;需要你批准或回答时,它会出现在侧栏的「需要你」里。机器人做的每一步都看得见,越出工作区的操作先问你。
> [!NOTE]
> 其他产品的信息来自 2026 年 10 月的公开报道,可能已有变化,以各家官方说明为准。Grok Bot、dots、Claude Duet 分别是 xAI、OpenAI、Anthropic 的产品和商标,AnyModelBot 与它们没有关联。
@@ -297,7 +298,7 @@ AnyModelBot 同样能在后台干活:交代的任务可以在后台跑完,
| :--- | :--- |
| 对话与会话(本地 SQLite 数据库) | 模型回答所需的提示词、文件内容和工具结果,经 Modelflare 发给你选定的供应商 |
| 记忆(Markdown 文件) | 你让机器人用电脑操作看屏幕时的屏幕截图 |
-| 每个机器人工作区里的文件 | 你通过微信、飞书收发的消息,会经过这两个平台 |
+| 每个机器人工作区里的文件 | 你通过聊天渠道收发的消息,会经过对应的平台 |
| 你的 API Key 和登录令牌 | 你登录 Modelflare 的过程,发生在 modelflare.dev |
| 设置 | |
@@ -316,7 +317,7 @@ Modelflare 会保留请求日志;保留什么、保留多久,见它的[信
| 模型网关 | [magpie](https://github.com/yetone/magpie)(Go,MIT),随应用打包并由应用启动 |
| 智能体运行时 | [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)(MIT),作为独立进程运行 |
| 电脑操作 | [Cua Driver](https://github.com/trycua/cua),随应用打包 |
-| 渠道 | 飞书(长连接 + 流式卡片)、微信(iLink) |
+| 渠道 | 飞书(长连接 + 流式卡片)、微信(iLink)、Telegram(长轮询)、Slack(Socket Mode)、Discord(Gateway) |
| 测试与 CI | Vitest、GitHub Actions |
# 📝 路线图
@@ -324,10 +325,10 @@ Modelflare 会保留请求日志;保留什么、保留多久,见它的[信
我们正在探索的方向。它们不是承诺,顺序也不是排期。
- [x] **定时任务**:让机器人按时间表自己干活(已上线,就是上面的规则)。
-- [ ] **群聊**:目前飞书机器人只处理一对一对话。
+- [ ] **群聊**:目前各聊天渠道只处理一对一对话。
- [ ] **英文界面**:目前应用界面只有简体中文。
- [ ] **macOS 电脑操作**:在更多真机上验证 direct 模式,让它脱离 Beta。
-- [ ] **独立的手机应用**:目前可以从微信或飞书找到你的机器人。
+- [ ] **独立的手机应用**:目前可以从微信、飞书、Telegram、Slack、Discord 找到你的机器人。
有别的想法?欢迎提 [issue](https://github.com/modelflare-ai/AnyModelBot/issues) 或发起[讨论](https://github.com/modelflare-ai/AnyModelBot/discussions)。我们决定要做的事项,会用 [`roadmap`](https://github.com/modelflare-ai/AnyModelBot/labels/roadmap) 标签跟踪。
diff --git a/README_en.md b/README_en.md
index 7667fbc..cb1f993 100644
--- a/README_en.md
+++ b/README_en.md
@@ -45,7 +45,7 @@
# 🤖 AnyModelBot
-AnyModelBot is a local-first AI agent app for Windows, macOS and Linux. A bot is a persona with its own default model, workspace and memory. Chat with it in the app, or reach it from WeChat and Feishu. Let it read and write files, run commands and operate your desktop, with an approval prompt whenever it steps outside its workspace.
+AnyModelBot is a local-first AI agent app for Windows, macOS and Linux. A bot is a persona with its own default model, workspace and memory. Chat with it in the app, or reach it from WeChat, Feishu, Telegram, Slack or Discord. Let it read and write files, run commands and operate your desktop, with an approval prompt whenever it steps outside its workspace.
Your conversations, memory, files and API keys live on your device. Models come from [Modelflare](https://modelflare.dev/?utm_source=anymodelbot&utm_campaign=amb_readme): one account, any model, priced per token. AnyModelBot itself has no subscription.
@@ -189,7 +189,7 @@ A bot is more than a chat window: it has a persona, a default model, its own wor
- **Three permission presets per bot.** *Read-only*, *Workspace* (the default: write inside the bot's own folder, ask before anything outside) and *Full access* (no sandbox; recursive deletes still ask first).
- **Approval cards, not surprises.** Out-of-bounds actions stop and wait for your answer.
- **Told after a restart.** A message still in progress when the app quit or crashed is flagged in its conversation at the next start, so you can send it again; nothing is redone on its own.
-- **Slash commands** such as `/model` and `/reset` work in the app and in WeChat and Feishu chats.
+- **Slash commands** such as `/model` and `/reset` work in the app and in every chat channel.
<p align="center">
<img src="docs/assets/features/agent-files.gif" alt="A bot tidies a messy folder: it lists the files, proposes a plan, and an approval card asks before moving files outside its workspace" width="100%">
@@ -201,7 +201,7 @@ A bot is more than a chat window: it has a persona, a default model, its own wor
- **Follow-ups.** Quote the result in WeChat, or reply to it in Feishu, to keep talking to that task.
- **Rules.** "Every morning at 8, check X's price and tell me if it drops below 200" becomes a rule that checks on schedule and tells you only when something matters. To see how it behaves first, say "observe first": it records what it would have said, and sends nothing and changes no files. Once it looks right, switch it to act.
- **Needs you.** Everything any bot is waiting on you for, an answer, an approval or a retry, sits in one sidebar row that is only there when something needs you. The info panel's Tasks group lists the bot's tasks and rules, with every step visible.
-- **Quiet by default.** Only results, decisions and failures are pushed, never progress. Quiet hours are 22:00 to 08:00, and unprompted messages are capped per day (3 on WeChat, 5 on Feishu), with the rest merged into one.
+- **Quiet by default.** Only results, decisions and failures are pushed, never progress. Quiet hours are 22:00 to 08:00, and unprompted messages are capped per day (3 on WeChat, 5 on other channels), with the rest merged into one.
- **Budgets.** Every task and rule has a budget (1 US dollar per task; 0.10 per rule run and 3 a month), and work stops and asks when it runs out. Change them in the task details and the rule editor.
- **Pause anytime.** One switch in bot settings › Proactive messages pauses background work; chat carries on.
- **Cleans up after itself.** Tasks and run logs are kept for 30 days. A task folder unused for 30 days is deleted without asking; the task details show the date, and Keep holds on to it. Run logs export as Markdown.
@@ -242,6 +242,7 @@ The full story, in Chinese: [AnyModelBot 超级智能体](./docs/blog/superagent
- **Memory that carries over.** Bots keep Markdown memory at three levels (team, bot and group) and filter out anything that looks like a secret.
- **Long chats stay usable.** A context steward compacts or starts a fresh segment with a hand-off summary before the window fills up.
- **WeChat and Feishu.** Scan a QR code to connect WeChat, or connect a Feishu bot with streaming reply cards. WeChat also carries images and files.
+- **Telegram, Slack and Discord.** Paste a token in the info panel. No public address needed. Replies appear as they're written, and images and files work both ways. Direct messages only for now, and approvals and questions are answered by text.
- **Four ways to run it.** Desktop app, command line, Docker, or the local web console at `127.0.0.1:3600`.
<p align="center">
@@ -255,7 +256,7 @@ The full story, in Chinese: [AnyModelBot 超级智能体](./docs/blog/superagent
## 🔒 Local-first, and easy on the eyes
- **Your data stays with you.** Conversations, memory, files and API keys are stored on your device. The local console listens on `127.0.0.1` only, and the desktop app generates a fresh access token on every launch.
-- **It answers to you.** By default a bot replies only to its owner (the WeChat account that scanned the QR code; on Feishu, the first person to message it after you connect it, which is you) and the people you allow. Anyone else gets a one-line notice and no model is called; you let them in from the info panel, or by replying `yes <code>` in chat.
+- **It answers to you.** By default a bot replies only to its owner (the WeChat account that scanned the QR code; on Feishu, Telegram, Slack and Discord, the first person to message it after you connect it, which is you) and the people you allow. Anyone else gets a one-line notice and no model is called; you let them in from the info panel, or by replying `yes <code>` in chat.
- **Replies are not lost.** A reply is saved locally before it is sent; network errors are retried, sending resumes after a restart, and when WeChat's 24-hour window has closed the reply waits and arrives with your next message.
- **Telemetry kept off.** Telemetry in the bundled computer-use driver is switched off, and the built-in gateway runs with auto-update disabled.
- **Light, dark or follow the system.** Six bot characters, and their eyes follow your pointer.
@@ -278,10 +279,10 @@ In the second half of 2026, xAI's [Grok Bot](https://x.ai/bot), OpenAI's [dots](
| Where the agent runs | Your own computer or server | xAI's cloud computer | OpenAI's cloud computer | Anthropic's cloud |
| Models | GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more (through Modelflare) | Mainly xAI's Grok models | OpenAI's models | Claude (Opus 5.5) |
| Cost | Free app, models billed per token | Subscription | ChatGPT Pro / Business Premium subscription | Claude Pro / Max subscription |
-| Where you reach it | Desktop app (Windows, macOS, Linux), Docker, WeChat, Feishu | Desktop app, iPhone | ChatGPT, Slack, Teams | iOS, Android, claude.ai |
+| Where you reach it | Desktop app (Windows, macOS, Linux), Docker, WeChat, Feishu, Telegram, Slack, Discord | Desktop app, iPhone | ChatGPT, Slack, Teams | iOS, Android, claude.ai |
| Availability | Download it now | Beta | Select markets | Research preview, US waitlist |
-AnyModelBot works in the background too: a task you hand over can finish in the background and send its result to WeChat or Feishu, and anything that needs your approval or answer shows up under "Needs you" in the sidebar. Every step a bot takes is visible, and anything outside its workspace asks you first.
+AnyModelBot works in the background too: a task you hand over can finish in the background and send its result to your chat app, and anything that needs your approval or answer shows up under "Needs you" in the sidebar. Every step a bot takes is visible, and anything outside its workspace asks you first.
> [!NOTE]
> Details about the other products come from public reports as of October 2026 and may have changed; check each vendor's official information. Grok Bot, dots and Claude Duet are products and trademarks of xAI, OpenAI and Anthropic respectively. AnyModelBot is not affiliated with them.
@@ -297,7 +298,7 @@ AnyModelBot works in the background too: a task you hand over can finish in the
| :--- | :--- |
| Conversations and sessions (local SQLite database) | The prompts, files and tool results a model needs to answer, sent through Modelflare to the provider you chose |
| Memory (Markdown files) | Screenshots, when you ask a bot to look at your screen with computer use |
-| Files in each bot's workspace | Messages you exchange over WeChat or Feishu, which pass through those platforms |
+| Files in each bot's workspace | Messages you exchange over chat channels, which pass through those platforms |
| Your API key and sign-in tokens | Your sign-in with Modelflare, which happens at modelflare.dev |
| Settings | |
@@ -316,7 +317,7 @@ Modelflare keeps request logs; its [Trust Center](https://modelflare.dev/trust?u
| Model gateway | [magpie](https://github.com/yetone/magpie) (Go, MIT), bundled and started by the app |
| Agent runtime | [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (MIT), run as a separate process |
| Computer use | [Cua Driver](https://github.com/trycua/cua), bundled |
-| Channels | Feishu (long connection + streaming cards), WeChat (iLink) |
+| Channels | Feishu (long connection + streaming cards), WeChat (iLink), Telegram (long polling), Slack (Socket Mode), Discord (Gateway) |
| Tests and CI | Vitest, GitHub Actions |
# 📝 Roadmap
@@ -324,10 +325,10 @@ Modelflare keeps request logs; its [Trust Center](https://modelflare.dev/trust?u
Directions we are exploring. They are not promises, and the order is not a schedule.
- [x] **Scheduled tasks**: let a bot run work on a timer (shipped as rules, above).
-- [ ] **Group chats**: Feishu bots handle one-to-one chats today.
+- [ ] **Group chats**: chat channels handle one-to-one chats today.
- [ ] **English interface**: the app UI is Simplified Chinese today.
- [ ] **macOS computer use**: verify direct mode on more real machines and move it out of Beta.
-- [ ] **A standalone mobile app**: today you reach your bots from WeChat or Feishu.
+- [ ] **A standalone mobile app**: today you reach your bots from WeChat, Feishu, Telegram, Slack or Discord.
Have a different idea? Open an [issue](https://github.com/modelflare-ai/AnyModelBot/issues) or start a [discussion](https://github.com/modelflare-ai/AnyModelBot/discussions). Items we pick up are tracked with the [`roadmap`](https://github.com/modelflare-ai/AnyModelBot/labels/roadmap) label.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 92beff8..5b7a9fa 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -80,6 +80,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- htm 3.1.1 — Apache-2.0
- qrcode 1.5.4 — MIT
- qrcode-terminal 0.12.0 — Apache-2.0(见包内 LICENSE)
+- ws 8.22.0 — MIT
传递依赖的许可证随各自包保存在 node_modules 中。桌面版另含 Electron(MIT)及 Chromium 等组件,其许可证位于安装目录的 LICENSE 与 LICENSES.chromium.html。
diff --git a/THIRD_PARTY_NOTICES_en.md b/THIRD_PARTY_NOTICES_en.md
index 6e463f5..1b029ab 100644
--- a/THIRD_PARTY_NOTICES_en.md
+++ b/THIRD_PARTY_NOTICES_en.md
@@ -80,6 +80,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- htm 3.1.1 — Apache-2.0
- qrcode 1.5.4 — MIT
- qrcode-terminal 0.12.0 — Apache-2.0 (see the LICENSE in the package)
+- ws 8.22.0 — MIT
Licenses of transitive dependencies are kept with each package in node_modules. The desktop app also includes Electron (MIT) and components such as Chromium; their licenses are in LICENSE and LICENSES.chromium.html in the install directory.
diff --git a/docs/development.md b/docs/development.md
index 2735cbe..8d6033e 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -17,7 +17,7 @@ src/
prompts/ 交给代理模型的全部提示词:人设、聊天规则、记忆说明、每段第一条消息、技能说明
llm/ OpenAI 兼容客户端(模型接入接口)
magpie/ 内置 magpie 守护:隔离目录、空闲端口、自动生成密钥、健康检查、崩溃重启、干净退出
- channels/ feishu/(长连接 + CardKit) weixin/(iLink,MIT 声明见 LICENSE.openclaw-weixin)
+ channels/ feishu/(长连接 + CardKit) weixin/(iLink,MIT 声明见 LICENSE.openclaw-weixin) messenger/(Telegram、Slack、Discord,共用一套收发)
store/ SQLite(node:sqlite,无需原生编译)
account/ Modelflare 账户:PKCE 回环登录、令牌轮换、余额与提醒、机器人预算 Key、模型能力与参考价
web/ 管理界面服务(JSON API + 流式对话 SSE)
diff --git a/docs/development_en.md b/docs/development_en.md
index f33eb3a..e3dcde6 100644
--- a/docs/development_en.md
+++ b/docs/development_en.md
@@ -17,7 +17,7 @@ src/
prompts/ every prompt the agent model reads: persona, chat rules, memory guide, a segment's first message, skills
llm/ OpenAI-compatible client (model access interface)
magpie/ magpie supervisor: isolated directories, free port, generated secret, health checks, crash restart, clean exit
- channels/ feishu/ (long connection + CardKit) weixin/ (iLink; MIT notice in LICENSE.openclaw-weixin)
+ channels/ feishu/ (long connection + CardKit) weixin/ (iLink; MIT notice in LICENSE.openclaw-weixin) messenger/ (Telegram, Slack, Discord, sharing one send and receive path)
store/ SQLite (node:sqlite, no native build)
account/ Modelflare account: PKCE loopback sign-in, token rotation, balance and reminders, per-bot budget keys, model capabilities and reference prices
web/ console server (JSON API + streaming chat over SSE)
diff --git a/docs/privacy.md b/docs/privacy.md
index 94c30b2..874f856 100644
--- a/docs/privacy.md
+++ b/docs/privacy.md
@@ -27,6 +27,7 @@
| API Key | 内置网关的隔离配置 `magpie/config/` | 每次模型请求作为鉴权发给 Modelflare | Modelflare |
| 微信登录态与同步游标 | 数据目录内(`weixin/` 等) | 与微信 iLink 接口通信时会 | 腾讯微信 |
| 飞书 App ID / Secret | 数据目录内的配置 | 与飞书开放平台建立长连接时会 | 飞书 |
+| Telegram、Slack、Discord 的 token | `anymodel.db` | 与对应平台通信时会 | 你接入的平台 |
| 允许名单与使用请求 | `anymodel.db`:谁能用哪个机器人、陌生人发来的第一条消息(截断,帮你认出是谁) | 不会 | — |
| 待发送的回复 | `anymodel.db` 的出站队列:还没发出去的消息内容和原因,包括等对方下次发消息再发的微信消息(最多留 7 天;发出去的留 7 天、发不出去的留 30 天后删除) | 发送时会 | 微信 / 飞书 |
| 后台任务和规则 | `anymodel.db`(任务、规则、运行记录,留 30 天);任务文件夹在 `workspaces/<机器人>/tasks/`,30 天没动过会删除(先在「需要你」里告诉你);它们的会话记录在 `dsh/<机器人>/sessions/`,随任务一起删除 | 运行时会 | 同对话:作为模型请求的上下文,经 Modelflare 发给你选定的供应商 |
@@ -69,6 +70,7 @@
- 生成图片或视频时,从 docs.modelflare.dev 读取该模型的请求格式。
- 微信渠道:与 `ilinkai.weixin.qq.com` 通信,并从微信 CDN 下载你发来的图片和文件。
- 飞书渠道:与飞书开放平台保持长连接。
+- Telegram、Slack、Discord 渠道:接入后与 `api.telegram.org`、`slack.com`、`discord.com` 及其文件地址通信,用来收发消息和你发来的文件。
- Windows 上开启代理模式且系统里没有可用的 PowerShell 7 时,从微软官方发布地址下载 PowerShell 7(可用 `AMB_PWSH_AUTO_INSTALL=0` 关闭,详见[开发文档](./development.md))。
## 电脑操作与截图
@@ -79,7 +81,7 @@
## 渠道
-- 你在微信、飞书里和机器人收发的消息,会经过腾讯、飞书的服务器,受这两个平台各自的隐私政策约束。
+- 你在微信、飞书、Telegram、Slack、Discord 里和机器人收发的消息,会经过这些平台的服务器,受它们各自的隐私政策约束。
- 默认只有主人和你允许的人能和机器人对话;其他人发来的消息不会交给模型,只登记成使用请求(见 [开发文档](./development.md#谁能使用机器人))。
## 如何删除数据
@@ -87,4 +89,4 @@
1. 退出 AnyModelBot(托盘菜单 → 退出)。
2. 删除上面表格里的数据目录。Docker:`docker rm -f amb && docker volume rm amb-data`。
3. 在 Modelflare 个人资料页的「已授权的应用」里撤销 AnyModelBot 的授权。
-4. 如有需要,在飞书开放平台停用你创建的应用,在微信里解除与机器人的绑定。
+4. 如有需要,在飞书开放平台停用你创建的应用,在微信里解除与机器人的绑定;在 Telegram(@BotFather)、Slack、Discord 上删除你创建的机器人。
diff --git a/docs/privacy_en.md b/docs/privacy_en.md
index 005110f..62648c0 100644
--- a/docs/privacy_en.md
+++ b/docs/privacy_en.md
@@ -27,6 +27,7 @@ This document explains what AnyModelBot stores where, what leaves your device, a
| API key | The gateway's isolated config in `magpie/config/` | As authentication on every model request to Modelflare | Modelflare |
| WeChat sign-in state and sync cursor | Inside the data directory (`weixin/` and others) | When talking to the WeChat iLink API | Tencent WeChat |
| Feishu App ID / Secret | Configuration inside the data directory | When opening the long connection to the Feishu Open Platform | Feishu |
+| Telegram, Slack and Discord tokens | `anymodel.db` | When talking to that platform | The platform you connected |
| Allowlist and access requests | `anymodel.db`: who may use which bot, and the first message a stranger sent (truncated, so you can tell who it is) | No | — |
| Replies waiting to be sent | `anymodel.db` outbox: unsent message content and the reason, including WeChat messages held until the person writes again (kept up to 7 days; sent ones are deleted after 7 days, undeliverable ones after 30) | When they are sent | WeChat / Feishu |
| Background tasks and rules | `anymodel.db` (tasks, rules and run logs, kept 30 days); task folders in `workspaces/<bot>/tasks/`, deleted after 30 days unused (you are told first in Needs you); their session files in `dsh/<bot>/sessions/`, deleted with the task | While they run | As for chats: context in model requests, sent through Modelflare to the provider you chose |
@@ -69,6 +70,7 @@ Besides model requests, the app goes online to:
- Read a model's request format from docs.modelflare.dev when generating images or video.
- WeChat channel: talk to `ilinkai.weixin.qq.com` and download images and files you send from the WeChat CDN.
- Feishu channel: keep a long connection to the Feishu Open Platform.
+- Telegram, Slack and Discord channels: once connected, talk to `api.telegram.org`, `slack.com`, `discord.com` and their file hosts to send and receive messages and the files you send.
- On Windows, with agent mode on and no working PowerShell 7 on the system, download PowerShell 7 from Microsoft's official release location (turn this off with `AMB_PWSH_AUTO_INSTALL=0`; see the [development guide](./development_en.md)).
## Computer use and screenshots
@@ -79,7 +81,7 @@ Besides model requests, the app goes online to:
## Channels
-- Messages you exchange with a bot on WeChat or Feishu pass through Tencent's or Feishu's servers and are subject to those platforms' privacy policies.
+- Messages you exchange with a bot on WeChat, Feishu, Telegram, Slack or Discord pass through those platforms' servers and are subject to their privacy policies.
- By default only the owner and people you allow can talk to a bot; messages from anyone else are not given to a model, only recorded as access requests (see the [developer guide](./development_en.md#who-can-use-a-bot)).
## Deleting your data
@@ -87,4 +89,4 @@ Besides model requests, the app goes online to:
1. Quit AnyModelBot (tray menu → Quit).
2. Delete the data directory from the table above. Docker: `docker rm -f amb && docker volume rm amb-data`.
3. Revoke AnyModelBot under "Authorized apps" on your Modelflare profile page.
-4. If needed, disable the app you created on the Feishu Open Platform and unbind the bot in WeChat.
+4. If needed, disable the app you created on the Feishu Open Platform, unbind the bot in WeChat, and delete the bots you created on Telegram (@BotFather), Slack and Discord.
diff --git a/package-lock.json b/package-lock.json
index 28586db..d1d1bd5 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,13 +13,15 @@
"htm": "^3.1.1",
"preact": "^11.0.2",
"qrcode": "^1.5.4",
- "qrcode-terminal": "^0.12.0"
+ "qrcode-terminal": "^0.12.0",
+ "ws": "8.22.0"
},
"devDependencies": {
"@electron/asar": "^3.4.1",
"@types/node": "^22.20.5",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
+ "@types/ws": "^8.18.1",
"electron": "44.7.0",
"electron-builder": "^26.18.0",
"tsx": "^4.23.15",
@@ -1445,6 +1447,16 @@
"@types/node": "*"
}
},
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@typescript/typescript-aix-ppc64": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
diff --git a/package.json b/package.json
index c4551b1..25b6dd8 100644
--- a/package.json
+++ b/package.json
@@ -37,13 +37,15 @@
"htm": "^3.1.1",
"preact": "^11.0.2",
"qrcode": "^1.5.4",
- "qrcode-terminal": "^0.12.0"
+ "qrcode-terminal": "^0.12.0",
+ "ws": "8.22.0"
},
"devDependencies": {
"@electron/asar": "^3.4.1",
"@types/node": "^22.20.5",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
+ "@types/ws": "^8.18.1",
"electron": "44.7.0",
"electron-builder": "^26.18.0",
"tsx": "^4.23.15",
diff --git a/site/src/data/third-party.en.md b/site/src/data/third-party.en.md
index 6e463f5..1b029ab 100644
--- a/site/src/data/third-party.en.md
+++ b/site/src/data/third-party.en.md
@@ -80,6 +80,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- htm 3.1.1 — Apache-2.0
- qrcode 1.5.4 — MIT
- qrcode-terminal 0.12.0 — Apache-2.0 (see the LICENSE in the package)
+- ws 8.22.0 — MIT
Licenses of transitive dependencies are kept with each package in node_modules. The desktop app also includes Electron (MIT) and components such as Chromium; their licenses are in LICENSE and LICENSES.chromium.html in the install directory.
diff --git a/site/src/data/third-party.md b/site/src/data/third-party.md
index 92beff8..5b7a9fa 100644
--- a/site/src/data/third-party.md
+++ b/site/src/data/third-party.md
@@ -80,6 +80,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- htm 3.1.1 — Apache-2.0
- qrcode 1.5.4 — MIT
- qrcode-terminal 0.12.0 — Apache-2.0(见包内 LICENSE)
+- ws 8.22.0 — MIT
传递依赖的许可证随各自包保存在 node_modules 中。桌面版另含 Electron(MIT)及 Chromium 等组件,其许可证位于安装目录的 LICENSE 与 LICENSES.chromium.html。
diff --git a/src/app.ts b/src/app.ts
index 67d2f7d..c2cac71 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -10,12 +10,15 @@ import { deferNotice, interruptedText, takeInterrupted, type Interrupted } from
import { Outbox } from "./core/outbox.js";
import { Delivery, type DeliveryOptions } from "./core/delivery.js";
import { AccessControl } from "./core/access.js";
-import type { ChannelStatus } from "./core/types.js";
+import { MESSENGERS, MESSENGER_LABEL, isMessenger, type ChannelStatus, type MessengerId } from "./core/types.js";
import { MagpieSupervisor } from "./magpie/supervisor.js";
import { FeishuChannel } from "./channels/feishu/channel.js";
import { LarkTransport, type FeishuTransport } from "./channels/feishu/transport.js";
import { WeixinChannel } from "./channels/weixin/channel.js";
import { WeixinLogin } from "./channels/weixin/login.js";
+import { MessengerChannel } from "./channels/messenger/channel.js";
+import { MESSENGER_FIELDS, createTransport, telegramOffsetKey } from "./channels/messenger/index.js";
+import { PlatformError, type MessengerTransport } from "./channels/messenger/transport.js";
import { startWebServer, type WebServer } from "./web/server.js";
import { initFileLog, logFilePath, logger, mask, registerSecret } from "./log.js";
import { AgentManager } from "./agent/manager.js";
@@ -100,6 +103,8 @@ export function appVersion(): string {
export interface AppOptions {
/** 测试注入:替换飞书传输层 */
feishuTransport?: (bot: Bot) => FeishuTransport;
+ /** 测试用:替换 Telegram、Slack、Discord 的传输层 */
+ messengerTransport?: (id: MessengerId, botId: string, credentials: Record<string, string>) => MessengerTransport;
/** 测试注入:替换 iLink 的 fetch */
weixinFetch?: typeof fetch;
weixinPollTimeoutMs?: number;
@@ -122,6 +127,10 @@ interface BotChannels {
feishuError?: string;
weixin?: WeixinChannel;
weixinLogin?: WeixinLogin;
+ /** Telegram、Slack、Discord */
+ messengers?: Partial<Record<MessengerId, MessengerChannel>>;
+ /** 启动失败或凭据失效的原因(信息面板显示) */
+ messengerErrors?: Partial<Record<MessengerId, string>>;
}
export class App {
@@ -314,6 +323,7 @@ export class App {
try {
if (to.channel === "weixin") return !!ch?.weixin?.tell(to.peerId, text, id);
if (to.channel === "feishu") return !!ch?.feishu?.notify(to.peerId, text, id);
+ if (isMessenger(to.channel)) return !!ch?.messengers?.[to.channel]?.notify(to.peerId, text, id);
} catch (e) {
log.warn("notify failed", { bot: to.botId, channel: to.channel, message: (e as Error).message });
}
@@ -462,6 +472,11 @@ export class App {
// 飞书:发给主人;还没设主人时发到最近的单聊
const chat = ch?.feishu ? (this.access.owner(bot.id, "feishu")?.peerId ?? this.store.listConversations(bot.id).find((c) => c.channel === "feishu" && c.kind === "dm")?.peerId) : undefined;
if (chat && ch?.feishu?.notify(chat, text)) return true;
+ // 其他平台:发给主人(连上之后第一个发消息的人)
+ for (const id of MESSENGERS) {
+ const owner = this.access.owner(bot.id, id)?.peerId;
+ if (owner && ch?.messengers?.[id]?.notify(owner, text)) return true;
+ }
} catch (e) {
log.warn("push to owner failed", { bot: bot.id, message: (e as Error).message.slice(0, 200) });
}
@@ -634,6 +649,7 @@ export class App {
sent = true;
} else if (conv.channel === "weixin" && ch?.weixin) sent = await ch.weixin.notify(conv.peerId, text);
else if (conv.channel === "feishu" && ch?.feishu) sent = await ch.feishu.notify(conv.peerId, text);
+ else if (isMessenger(conv.channel)) sent = !!ch?.messengers?.[conv.channel]?.notify(conv.peerId, text);
} catch (e) {
log.warn("restart notice failed", { conversationId: conv.id, message: (e as Error).message.slice(0, 200) });
}
@@ -799,6 +815,81 @@ export class App {
this.runtime.registerReplier(bot.id, "weixin", (conv, _handle, key) => ({ out: wx.followUp(conv.peerId, key) }));
detached(() => wx.start());
}
+ for (const id of MESSENGERS) this.startMessenger(bot, id, ch);
+ }
+
+ /** 填了凭据、还没在跑的平台:连上 */
+ private startMessenger(bot: Bot, id: MessengerId, ch: BotChannels): void {
+ const acct = this.store.getMessengerAccount(bot.id, id);
+ if (!acct || ch.messengers?.[id]) return;
+ for (const secret of Object.values(acct.credentials)) registerSecret(secret);
+ const transport = this.opts.messengerTransport?.(id, bot.id, acct.credentials) ?? createTransport(id, bot.id, acct.credentials, this.store);
+ const channel = new MessengerChannel(bot.id, transport, this.runtime, this.queue, this.outbox);
+ channel.delivery = this.delivery;
+ channel.onFatal = (detail) => {
+ (ch.messengerErrors ??= {})[id] = detail;
+ this.notice("warn", t("app.messenger_failed", { name: this.store.getBot(bot.id)?.name ?? bot.name, channel: MESSENGER_LABEL[id], message: detail }));
+ };
+ (ch.messengers ??= {})[id] = channel;
+ if (ch.messengerErrors) delete ch.messengerErrors[id];
+ // 代理自己醒来的一轮(后台命令结束):经出站队列发到这个会话
+ this.runtime.registerReplier(bot.id, id, (conv, _handle, key) => ({ out: channel.followUp(conv.peerId, key) }));
+ detached(() => channel.start()).catch((e) => channel.onFatal?.((e as Error).message));
+ log.info(`bot ${bot.id}: ${id} starting`);
+ }
+
+ private async stopMessenger(botId: string, id: MessengerId): Promise<void> {
+ const ch = this.channels.get(botId);
+ this.runtime.registerReplier(botId, id, undefined);
+ await ch?.messengers?.[id]?.stop().catch(() => {});
+ if (ch?.messengers) delete ch.messengers[id];
+ if (ch?.messengerErrors) delete ch.messengerErrors[id];
+ }
+
+ /**
+ * 连接(或改凭据):留空的凭据沿用已保存的。凭据被平台拒绝就报错、不保存;一时连不上平台照样保存,渠道自己会重试。
+ * 换了一个机器人(凭据变了):主人对不上了,连上后第一个发消息的人成为主人;Telegram 的收取位置也作废。
+ */
+ async connectMessenger(botId: string, id: MessengerId, input: Record<string, unknown>): Promise<void> {
+ const old = this.store.getMessengerAccount(botId, id);
+ const credentials: Record<string, string> = {};
+ for (const field of MESSENGER_FIELDS[id]) {
+ credentials[field] = String(input[field] ?? "").trim() || (old?.credentials[field] ?? "");
+ if (!credentials[field]) throw new PlatformError(t("channel.messengerMissing", { channel: MESSENGER_LABEL[id] }), true);
+ }
+ const transport = this.opts.messengerTransport?.(id, botId, credentials) ?? createTransport(id, botId, credentials, this.store);
+ let name = old?.name ?? "";
+ try {
+ name = (await transport.verify?.())?.name ?? name;
+ } catch (e) {
+ if ((e as PlatformError).rejected) throw e;
+ log.warn("couldn't verify the credentials now, saving anyway", { channel: id, message: (e as Error).message.slice(0, 200) });
+ }
+ const changed = MESSENGER_FIELDS[id].some((f) => f !== "appToken" && credentials[f] !== old?.credentials[f]);
+ await this.stopMessenger(botId, id);
+ if (changed) {
+ this.access.resetOwner(botId, id);
+ if (id === "telegram") this.store.deleteKV(telegramOffsetKey(botId));
+ }
+ this.store.saveMessengerAccount({ botId, channel: id, credentials, name });
+ await this.startBot(botId);
+ }
+
+ async disconnectMessenger(botId: string, id: MessengerId): Promise<void> {
+ await this.stopMessenger(botId, id);
+ this.access.resetOwner(botId, id);
+ this.store.deleteMessengerAccount(botId, id);
+ if (id === "telegram") this.store.deleteKV(telegramOffsetKey(botId));
+ }
+
+ /** 信息面板的一行:状态、平台上的名字、已保存凭据的掩码(界面显示"留空不修改") */
+ private messengerStatus(botId: string, id: MessengerId): ChannelStatus & { account?: { name: string; saved: Record<string, string> } } {
+ const acct = this.store.getMessengerAccount(botId, id);
+ if (!acct) return { state: "disabled", since: 0 };
+ const ch = this.channels.get(botId);
+ const error = ch?.messengerErrors?.[id];
+ const st: ChannelStatus = error ? { state: "error", detail: error, since: Date.now() } : ch?.messengers?.[id]?.status ?? { state: "disabled", since: 0 };
+ return { ...st, account: { name: acct.name, saved: Object.fromEntries(Object.entries(acct.credentials).map(([k, v]) => [k, mask(v)])) } };
}
async stopBot(botId: string): Promise<void> {
@@ -807,6 +898,7 @@ export class App {
ch.weixinLogin?.cancel();
this.runtime.registerReplier(botId, "feishu", undefined);
this.runtime.registerReplier(botId, "weixin", undefined);
+ for (const id of MESSENGERS) await this.stopMessenger(botId, id);
await ch.feishu?.stop().catch(() => {});
await ch.weixin?.stop().catch(() => {});
this.channels.delete(botId);
@@ -856,7 +948,7 @@ export class App {
await this.startBot(botId);
}
- channelStatus(botId: string): { feishu: ChannelStatus; weixin: ChannelStatus & { login?: unknown; quota?: unknown } } {
+ channelStatus(botId: string): { feishu: ChannelStatus; weixin: ChannelStatus & { login?: unknown; quota?: unknown } } & Record<MessengerId, ChannelStatus> {
const bot = this.store.getBot(botId);
const ch = this.channels.get(botId);
const feishu: ChannelStatus = !bot?.feishuAppId
@@ -877,6 +969,9 @@ export class App {
login: ch?.weixinLogin?.snapshot,
quota,
},
+ telegram: this.messengerStatus(botId, "telegram"),
+ slack: this.messengerStatus(botId, "slack"),
+ discord: this.messengerStatus(botId, "discord"),
};
}
}
diff --git a/src/channels/messenger/channel.ts b/src/channels/messenger/channel.ts
new file mode 100644
index 0000000..badb54d
--- /dev/null
+++ b/src/channels/messenger/channel.ts
@@ -0,0 +1,356 @@
+import type { ChannelStatus, InboundEvent, OutboundOp, Part, ReplySession } from "../../core/types.js";
+import { Dedup, KeyedQueue } from "../../core/queue.js";
+import type { BotRuntime } from "../../core/runtime.js";
+import { Gone, Later, Outbox, ReplyIds, sentText, stableId } from "../../core/outbox.js";
+import type { Delivery } from "../../core/delivery.js";
+import type { OutboxBody, OutboxKind, OutboxRow } from "../../store/db.js";
+import { sniffImageMime } from "../weixin/api.js";
+import { logger } from "../../log.js";
+import { t, t as tr } from "../../i18n/index.js";
+import { splitMarkdown } from "./format.js";
+import { PlatformError, type MessengerMessage, type MessengerTransport } from "./transport.js";
+
+/** 改消息的间隔:三个平台里最严的 Telegram 约每秒一次,再留点余量 */
+export const EDIT_THROTTLE_MS = 1500;
+/** "正在输入"的续期间隔(Telegram 5 秒后消失,Discord 10 秒) */
+const TYPING_EVERY_MS = 4500;
+/** 文件临时发不出去时先重试这么多次,再改发一句说明 */
+const FILE_RETRIES = 2;
+/** ack、审批提示:过一会儿就没意义了,发不出去不必一直等 */
+const SHORT_TTL_MS = 10 * 60_000;
+
+/** 网络断开、限流这类过一会儿可能就好的错误(平台拒绝、本地文件读不了、文件太大不算) */
+function transient(e: unknown): boolean {
+ const x = e as { rejected?: boolean; syscall?: string };
+ if (x?.rejected) return false;
+ return !(x?.syscall && ["open", "read", "stat"].includes(x.syscall)) && !/too large|过大/i.test(String((e as Error)?.message));
+}
+
+/**
+ * 把一条出站记录发到平台。文字按平台上限切段;有流式显示的那条消息时第一段改写它(改写可以重复做,不会多出消息),
+ * 它被删了或太旧改不了就发新的。progress 记下已发出的段数,崩溃重启后从下一段接着发。
+ */
+export async function deliverMessenger(transport: MessengerTransport, row: OutboxRow, progress: (n: number) => void, retry = true): Promise<void> {
+ const b = row.body;
+ if (row.kind === "file") {
+ const name = b.name ?? tr("channel.fileFallback");
+ if (row.progress === 0) {
+ try {
+ await transport.sendFile(row.peerId, b.path ?? "", name);
+ return;
+ } catch (e) {
+ if (retry && transient(e) && row.attempts < FILE_RETRIES) throw e;
+ logger(`${transport.id}.send`).warn("file send failed", { name, message: (e as Error).message.slice(0, 200) });
+ }
+ progress(1);
+ }
+ await transport.sendText(row.peerId, tr("channel.file_failed", { name }), stableId(row.id, 1));
+ return;
+ }
+ const chunks = splitMarkdown(sentText(b).trim(), transport.maxText);
+ for (let i = row.progress; i < chunks.length; i++) {
+ if (i === 0 && b.editId) {
+ try {
+ await transport.editText(row.peerId, b.editId, chunks[0]);
+ progress(1);
+ continue;
+ } catch (e) {
+ if (!(e as PlatformError)?.rejected) throw e;
+ logger(`${transport.id}.send`).warn("couldn't edit the live message, sending a new one", { message: (e as Error).message.slice(0, 200) });
+ }
+ }
+ await transport.sendText(row.peerId, chunks[i], stableId(row.id, i));
+ progress(i + 1);
+ }
+}
+
+/** 回复会话把消息交给出站队列需要的东西:key 由入站消息推出(同一条入站的第 n 条回复 id 固定) */
+export interface MessengerOutbox {
+ outbox: Outbox;
+ botId: string;
+ key: string;
+ ttlMs?: number;
+}
+
+/**
+ * 回复会话:等第一句话时显示"正在输入",开始说话后发一条消息、不断改写它(节流),结束时写成最终回复(太长的后面几段发新消息)。
+ * 最终回复、文件、提问先写进出站队列(持久化、按会话排队、失败重试);流式的中间内容不经过它,发不出去就算了。
+ * 审批和提问发文字(编号回复),没有按钮。
+ */
+export class MessengerReply implements ReplySession {
+ private messageId: string | undefined;
+ private latest = "";
+ private shown = "";
+ private interim: string[] = [];
+ private timer: NodeJS.Timeout | undefined;
+ private typingTimer: NodeJS.Timeout | undefined;
+ private inflight: Promise<void> = Promise.resolve();
+ private closed = false;
+ private ids = new ReplyIds();
+ private log;
+
+ constructor(
+ private transport: MessengerTransport,
+ private chatId: string,
+ private throttleMs: number,
+ private out?: MessengerOutbox,
+ ) {
+ this.log = logger(`${transport.id}.reply`);
+ }
+
+ async apply(op: OutboundOp): Promise<void> {
+ switch (op.type) {
+ case "typing":
+ return this.typing(op.on);
+ case "stream.start":
+ // 没有"正在输入"的平台(Slack):先发一条占位,不然生成期间对方什么也看不到
+ if (!this.transport.typing) {
+ this.latest = "…";
+ this.schedule();
+ }
+ return;
+ case "stream.update":
+ this.latest = op.text;
+ this.schedule();
+ return;
+ case "interim":
+ this.interim.push(op.text);
+ this.latest = this.interim.join("\n\n");
+ this.schedule();
+ return;
+ case "stream.finish":
+ return this.finish(op.text);
+ case "text":
+ // ack("收到,这条会并入…")过一会儿就没意义了,发不出去不必一直等
+ return this.post("text", { text: op.text }, this.ids.of(op.ack ? "ack" : "text", op.text), op.ack ? SHORT_TTL_MS : undefined);
+ case "file":
+ await this.inflight;
+ return this.post("file", { path: op.path, name: op.name }, this.ids.of("file", op.path));
+ case "interactive": {
+ const text = op.requestId
+ ? op.prompt // 代理请求:提示里已含编号/回复方式
+ : `${op.prompt}${op.options?.length ? "\n" + op.options.map((o, i) => `${i + 1}. ${o}`).join("\n") + "\n" + t("channel.reply_with_number") : ""}`;
+ return this.post("text", { text }, this.ids.of("prompt", op.requestId ?? text), SHORT_TTL_MS);
+ }
+ }
+ }
+
+ private async typing(on: boolean): Promise<void> {
+ clearInterval(this.typingTimer);
+ this.typingTimer = undefined;
+ if (!on || !this.transport.typing) return;
+ const send = () => void this.transport.typing!(this.chatId).catch((e) => this.log.debug("typing failed", { message: (e as Error).message }));
+ send();
+ this.typingTimer = setInterval(send, TYPING_EVERY_MS);
+ this.typingTimer.unref?.();
+ }
+
+ private schedule(): void {
+ if (this.closed || this.timer) return;
+ this.timer = setTimeout(() => {
+ this.timer = undefined;
+ this.inflight = this.inflight.then(() => this.flush());
+ }, this.throttleMs);
+ }
+
+ /** 流式显示:放不下时显示最新的部分(最终回复会写全) */
+ private async flush(): Promise<void> {
+ const max = this.transport.maxText;
+ const text = this.latest.length > max ? `…${this.latest.slice(-(max - 1))}` : this.latest;
+ if (this.closed || !text.trim() || text === this.shown) return;
+ try {
+ if (this.messageId) await this.transport.editText(this.chatId, this.messageId, text);
+ else this.messageId = await this.transport.sendText(this.chatId, text);
+ this.shown = text;
+ } catch (e) {
+ this.log.warn("live update failed", { message: (e as Error).message.slice(0, 200) });
+ }
+ }
+
+ private async finish(answer: string): Promise<void> {
+ // 最后没再说话时,回复就是中间说的最后一句:不重复
+ const before = this.interim.at(-1) === answer ? this.interim.slice(0, -1) : this.interim;
+ const text = [...before, answer].filter(Boolean).join("\n\n");
+ this.closed = true;
+ clearTimeout(this.timer);
+ this.timer = undefined;
+ await this.inflight;
+ await this.typing(false);
+ return this.post("text", { text, ...(this.messageId ? { editId: this.messageId } : {}) }, this.ids.final());
+ }
+
+ /** 交给出站队列(先落库再发,等第一次发送结束);没有队列就直接发(单元测试) */
+ private async post(kind: OutboxKind, body: OutboxBody, role: string, ttlMs?: number): Promise<void> {
+ if (this.out) {
+ const { outbox, botId, key } = this.out;
+ await outbox.send({ id: `${this.transport.id}:${botId}:${key}:${role}`, botId, channel: this.transport.id, peerId: this.chatId, kind, body, ttlMs: ttlMs ?? this.out.ttlMs });
+ return;
+ }
+ const row = { id: `${role}`, kind, body, peerId: this.chatId, replyTo: "", progress: 0, attempts: 0 } as OutboxRow;
+ try {
+ await deliverMessenger(this.transport, row, () => {}, false);
+ } catch (e) {
+ if (!(e instanceof Gone)) throw e;
+ }
+ }
+}
+
+/** 这条消息 → 运行时的 parts:引用的那句、文字、文件(下载好的带 data,失败的带 error) */
+export function messengerParts(m: MessengerMessage, got?: Map<MessengerMessage["files"][number], Buffer | Error>): Part[] {
+ const parts: Part[] = [];
+ if (m.quote) parts.push({ type: "quote", text: m.quote });
+ if (m.text) parts.push({ type: "text", text: m.text });
+ if (m.unsupported) parts.push({ type: "text", text: t("channel.unsupported_message", { type: m.unsupported }) });
+ for (const f of m.files) {
+ if (f.type === "voice") {
+ parts.push({ type: "voice" });
+ continue;
+ }
+ const base = { type: f.type, ...(f.name ? { name: f.name } : {}) };
+ const r = got?.get(f);
+ if (r instanceof Error) parts.push({ ...base, error: r.message.slice(0, 120) });
+ else if (r) {
+ const mime = f.type === "image" ? sniffImageMime(r) : undefined;
+ parts.push({ ...base, data: r, ...(mime ? { mime } : {}) });
+ } else parts.push(base);
+ }
+ return parts;
+}
+
+/** 一个机器人在一个平台上的渠道:只处理单聊,准入、审批、队列和飞书、微信走同一条路 */
+export class MessengerChannel {
+ status: ChannelStatus = { state: "disabled", since: Date.now() };
+ private dedup = new Dedup();
+ private log;
+ /** 测试用:等待所有已入队任务 */
+ readonly pending = new Set<Promise<void>>();
+ /** 主动消息的送达规则(App 设):对方发消息时,排着的主动消息先发,合成一条摘要 */
+ delivery: Delivery | undefined;
+ /** 凭据失效,重连也没用:App 显示一条提示 */
+ onFatal: ((detail: string) => void) | undefined;
+ private unregister: (() => void) | undefined;
+ private running = false;
+
+ constructor(
+ private botId: string,
+ private transport: MessengerTransport,
+ private runtime: BotRuntime,
+ private queue: KeyedQueue,
+ readonly outbox: Outbox,
+ private throttleMs = EDIT_THROTTLE_MS,
+ ) {
+ this.log = logger(transport.id);
+ }
+
+ private get id() {
+ return this.transport.id;
+ }
+
+ async start(): Promise<void> {
+ this.running = true;
+ // 上线:出站队列里这个机器人在这个平台上的消息(含上次没发完的)由这里发
+ this.unregister ??= this.outbox.register(this.botId, this.id, async (row, progress) => {
+ if (!this.running) throw new Later(tr("channel.laterNotRunning"));
+ await deliverMessenger(this.transport, row, progress);
+ });
+ await this.transport.start(
+ (m) => void this.onMessage(m),
+ (state, detail, fatal) => {
+ if (state === this.status.state && detail === this.status.detail) return;
+ this.status = { state, detail, since: Date.now() };
+ this.log.info(`bot ${this.botId} ${state}`, detail ? { detail } : undefined);
+ if (fatal) this.onFatal?.(detail ?? "");
+ },
+ );
+ }
+
+ async stop(): Promise<void> {
+ this.running = false;
+ this.unregister?.();
+ this.unregister = undefined;
+ await this.transport.stop();
+ this.status = { state: "disabled", since: Date.now() };
+ }
+
+ /** 同步返回,处理放入每会话串行队列。返回这条是不是第一次见到 */
+ onMessage(m: MessengerMessage): boolean {
+ if (!m.id || !this.dedup.firstSeen(m.id)) return false;
+ // 群聊不处理:准入规则还没有定(access.ts 对群是放行的,所以不能往下走)
+ if (!m.dm) return true;
+ const ev: InboundEvent = {
+ id: m.id,
+ channel: this.id,
+ botId: this.botId,
+ conversation: { kind: "dm", id: m.chatId },
+ sender: { id: m.senderId, ...(m.senderName ? { name: m.senderName } : {}) },
+ parts: messengerParts(m),
+ replyHandle: { messageId: m.id, chatId: m.chatId },
+ receivedAt: Date.now(),
+ };
+ // 人在:排着的主动消息(免打扰、每天上限)不用再等,排在这次的回复前面
+ const delivery = this.delivery;
+ if (delivery) this.outbox.release(this.botId, this.id, m.chatId, (rows) => delivery.combine(rows));
+ // 审批/提问回复、准入在入队前处理(正在进行的回合正等着它);没处理掉但带 ack 的:先说一声,消息照常入队
+ const intercepted = this.runtime.interceptReply(ev);
+ if (intercepted.ack) {
+ const ack = this.reply(m.chatId, `${m.id}:ack`, SHORT_TTL_MS);
+ this.track(ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message })));
+ }
+ if (intercepted.handled) return true;
+ this.track(
+ this.queue.run(`${this.id}:${this.botId}:${m.chatId}`, async () => {
+ const reply = this.reply(m.chatId, m.id);
+ try {
+ if (m.files.length) ev.parts = messengerParts(m, await this.download(m));
+ await this.runtime.handle(ev, reply);
+ } catch (e) {
+ this.log.error("handle failed", { message: (e as Error).message });
+ await reply.apply({ type: "text", text: t("channel.handle_failed", { message: (e as Error).message }) }).catch(() => {});
+ }
+ }),
+ );
+ return true;
+ }
+
+ private reply(chatId: string, key: string, ttlMs?: number): MessengerReply {
+ return new MessengerReply(this.transport, chatId, this.throttleMs, { outbox: this.outbox, botId: this.botId, key, ttlMs });
+ }
+
+ private track(p: Promise<void>): void {
+ this.pending.add(p);
+ void p.finally(() => this.pending.delete(p));
+ }
+
+ /** 逐个下载;失败的记下原因(消息照常处理,文字里会说明没下载成功) */
+ private async download(m: MessengerMessage): Promise<Map<MessengerMessage["files"][number], Buffer | Error>> {
+ const out = new Map<MessengerMessage["files"][number], Buffer | Error>();
+ for (const f of m.files) {
+ if (f.type === "voice") continue;
+ try {
+ out.set(f, await f.download());
+ } catch (e) {
+ this.log.warn("file download failed", { type: f.type, message: (e as Error).message.slice(0, 200) });
+ out.set(f, e as Error);
+ }
+ }
+ return out;
+ }
+
+ /** 代理自己醒来的一轮(后台命令结束):和普通回复一样经出站队列,id 由 key 推出 */
+ followUp(chatId: string, key: string): ReplySession {
+ return this.reply(chatId, key);
+ }
+
+ /** 主动发一条通知到单聊(使用请求、批准结果、余额提醒):进出站队列;id 不给时同样的内容一分钟内只发一次 */
+ notify(chatId: string, text: string, id?: string): boolean {
+ if (!chatId) return false;
+ const key = id ?? `notice:${this.botId}:${this.id}:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
+ void this.outbox.send({ id: key, botId: this.botId, channel: this.id, peerId: chatId, kind: "notice", body: { text } });
+ return true;
+ }
+
+ async idle(): Promise<void> {
+ while (this.pending.size) await Promise.all([...this.pending]);
+ await this.outbox.idle();
+ }
+}
diff --git a/src/channels/messenger/discord.ts b/src/channels/messenger/discord.ts
new file mode 100644
index 0000000..c5f6084
--- /dev/null
+++ b/src/channels/messenger/discord.ts
@@ -0,0 +1,221 @@
+import WebSocket from "ws";
+import { logger } from "../../log.js";
+import { PlatformError, fetchFile, readForUpload, type MessengerFile, type MessengerMessage, type MessengerTransport, type StateFn } from "./transport.js";
+import { fenceTables } from "./format.js";
+
+const log = logger("discord");
+/** 官方上限 2000 */
+const MAX_TEXT = 1950;
+/** 没有 Nitro 的机器人一次最多传 10 MB */
+const MAX_UPLOAD = 10 * 1024 * 1024;
+const GATEWAY = "wss://gateway.discord.gg/?v=10&encoding=json";
+/** 只要单聊消息。单聊里的正文不需要 Message Content 这个特权 intent */
+const INTENT_DIRECT_MESSAGES = 1 << 12;
+const RECONNECT_MS = [1000, 5000, 15_000, 30_000];
+/** token 不对、intent 不对这些:重连也没用(官方文档的 close code 列表) */
+const FATAL_CLOSE = new Map<number, string>([
+ [4004, "the bot token was rejected"],
+ [4010, "invalid shard"],
+ [4011, "sharding required"],
+ [4012, "invalid API version"],
+ [4013, "invalid intents"],
+ [4014, "disallowed intents"],
+]);
+
+/** MESSAGE_CREATE → 归一化。机器人(包括自己)发的跳过 */
+export function discordMessage(d: any, download: (url: string) => Promise<Buffer>): MessengerMessage | undefined {
+ if (!d?.id || !d.channel_id || !d.author || d.author.bot) return undefined;
+ const files: MessengerFile[] = [];
+ for (const a of d.attachments ?? []) {
+ if (!a.url) continue;
+ const mime = String(a.content_type ?? "");
+ const type: MessengerFile["type"] = mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
+ files.push({ type, ...(type === "file" ? { name: String(a.filename ?? "file") } : {}), download: () => download(a.url) });
+ }
+ const name = d.author.global_name || d.author.username;
+ const quote = d.referenced_message?.content;
+ return {
+ id: String(d.id),
+ chatId: String(d.channel_id),
+ // 服务器里的消息带 guild_id
+ dm: !d.guild_id,
+ senderId: String(d.author.id),
+ ...(name ? { senderName: String(name) } : {}),
+ text: String(d.content ?? ""),
+ files,
+ ...(quote ? { quote: String(quote) } : {}),
+ };
+}
+
+/** Discord:Gateway 长连接收消息(不需要公网地址),REST 发消息 */
+export class DiscordTransport implements MessengerTransport {
+ readonly id = "discord" as const;
+ readonly maxText = MAX_TEXT;
+ private socket: WebSocket | undefined;
+ private stopped = true;
+ private retry: NodeJS.Timeout | undefined;
+ private heartbeat: NodeJS.Timeout | undefined;
+ private failures = 0;
+ /** 断线后接着上次的位置(RESUME),期间的消息平台会补发 */
+ private session: { id: string; url: string } | undefined;
+ private seq: number | null = null;
+
+ constructor(
+ private token: string,
+ private o: { fetchImpl?: typeof fetch; baseUrl?: string; gatewayUrl?: string; reconnectMs?: readonly number[] } = {},
+ ) {}
+
+ private get base(): string {
+ return this.o.baseUrl ?? "https://discord.com/api/v10";
+ }
+ private get fetch(): typeof fetch {
+ return this.o.fetchImpl ?? fetch;
+ }
+
+ private async call<T = any>(method: string, route: string, body?: Record<string, unknown> | FormData): Promise<T> {
+ const form = body instanceof FormData;
+ const res = await this.fetch(`${this.base}${route}`, {
+ method,
+ headers: { authorization: `Bot ${this.token}`, "user-agent": "DiscordBot (https://anymodel.bot, 1)", ...(body && !form ? { "content-type": "application/json" } : {}) },
+ ...(body ? { body: form ? body : JSON.stringify(body) } : {}),
+ signal: AbortSignal.timeout(form ? 120_000 : 30_000),
+ });
+ if (res.status === 204) return undefined as T;
+ const data = (await res.json().catch(() => undefined)) as (T & { message?: string }) | undefined;
+ if (res.ok) return data as T;
+ // 限流和服务器错误过一会儿就好;其余(没有权限、消息没了、对方关了私信)重试也没用
+ throw new PlatformError(`discord ${method} ${route}: ${res.status} ${data?.message ?? ""}`.trim(), res.status < 500 && res.status !== 429, res.status === 401);
+ }
+
+ async verify(): Promise<{ name: string }> {
+ const me = await this.call("GET", "/users/@me");
+ return { name: String(me.username ?? "") };
+ }
+
+ async start(onMessage: (m: MessengerMessage) => void, onState: StateFn): Promise<void> {
+ this.stopped = false;
+ onState("connecting");
+ this.connect(onMessage, onState);
+ }
+
+ async stop(): Promise<void> {
+ this.stopped = true;
+ clearTimeout(this.retry);
+ clearInterval(this.heartbeat);
+ this.socket?.terminate();
+ this.socket = undefined;
+ this.session = undefined;
+ this.seq = null;
+ }
+
+ private connect(onMessage: (m: MessengerMessage) => void, onState: StateFn): void {
+ if (this.stopped) return;
+ const socket = (this.socket = new WebSocket(this.session?.url ?? this.o.gatewayUrl ?? GATEWAY));
+ let acked = true;
+ const send = (op: number, d: unknown) => socket.readyState === WebSocket.OPEN && socket.send(JSON.stringify({ op, d }));
+ socket.on("message", (raw) => {
+ let p: any;
+ try {
+ p = JSON.parse(raw.toString());
+ } catch {
+ return;
+ }
+ if (typeof p.s === "number") this.seq = p.s;
+ switch (p.op) {
+ case 10: {
+ // HELLO:开始心跳,然后登录或接上次的会话
+ clearInterval(this.heartbeat);
+ acked = true;
+ this.heartbeat = setInterval(() => {
+ // 上一次心跳没回:连接已经断了(官方要求这时重连)
+ if (!acked) return socket.terminate();
+ acked = false;
+ send(1, this.seq);
+ }, Number(p.d?.heartbeat_interval ?? 41_250));
+ this.heartbeat.unref?.();
+ if (this.session) send(6, { token: this.token, session_id: this.session.id, seq: this.seq });
+ else send(2, { token: this.token, intents: INTENT_DIRECT_MESSAGES, properties: { os: process.platform, browser: "anymodel-bot", device: "anymodel-bot" } });
+ return;
+ }
+ case 11:
+ acked = true;
+ return;
+ case 1:
+ send(1, this.seq);
+ return;
+ case 7:
+ // 平台要我们换连接:断开,走重连(RESUME)
+ socket.close(4000);
+ return;
+ case 9:
+ // 会话失效:能不能接上由 d 决定,不能就重新登录
+ if (!p.d) {
+ this.session = undefined;
+ this.seq = null;
+ }
+ socket.close(4000);
+ return;
+ case 0:
+ if (p.t === "READY") {
+ this.session = { id: String(p.d.session_id), url: `${String(p.d.resume_gateway_url ?? GATEWAY).replace(/\/$/, "")}/?v=10&encoding=json` };
+ this.failures = 0;
+ onState("connected");
+ } else if (p.t === "RESUMED") {
+ this.failures = 0;
+ onState("connected");
+ } else if (p.t === "MESSAGE_CREATE") {
+ const m = discordMessage(p.d, (u) => this.download(u));
+ if (m) onMessage(m);
+ }
+ return;
+ }
+ });
+ socket.on("error", (e) => log.warn("gateway error", { message: e.message.slice(0, 200) }));
+ socket.on("close", (code) => {
+ if (this.socket !== socket || this.stopped) return;
+ clearInterval(this.heartbeat);
+ const fatal = FATAL_CLOSE.get(code);
+ if (fatal) return onState("error", `discord gateway: ${fatal}`, true);
+ // 这两种接不上了,重新登录
+ if (code === 4007 || code === 4009) {
+ this.session = undefined;
+ this.seq = null;
+ }
+ onState("connecting", "reconnecting");
+ const delays = this.o.reconnectMs ?? RECONNECT_MS;
+ clearTimeout(this.retry);
+ this.retry = setTimeout(() => this.connect(onMessage, onState), delays[Math.min(this.failures++, delays.length - 1)]);
+ this.retry.unref?.();
+ });
+ }
+
+ private async download(url: string): Promise<Buffer> {
+ return (await fetchFile(this.fetch, url)).buffer;
+ }
+
+ async sendText(chatId: string, text: string, key?: string): Promise<string> {
+ // nonce:平台几分钟内对同一 nonce 只发一次(重试不会重复);不让消息里的 @ 真的提醒到人
+ const r = await this.call<{ id: string }>("POST", `/channels/${chatId}/messages`, {
+ content: fenceTables(text),
+ allowed_mentions: { parse: [] },
+ ...(key ? { nonce: key.slice(0, 25), enforce_nonce: true } : {}),
+ });
+ return r.id;
+ }
+
+ async editText(chatId: string, messageId: string, text: string): Promise<void> {
+ await this.call("PATCH", `/channels/${chatId}/messages/${messageId}`, { content: fenceTables(text), allowed_mentions: { parse: [] } });
+ }
+
+ async sendFile(chatId: string, filePath: string, name: string): Promise<void> {
+ const data = await readForUpload(filePath, MAX_UPLOAD);
+ const form = new FormData();
+ form.set("payload_json", JSON.stringify({ allowed_mentions: { parse: [] } }));
+ form.set("files[0]", new Blob([new Uint8Array(data)]), name);
+ await this.call("POST", `/channels/${chatId}/messages`, form);
+ }
+
+ async typing(chatId: string): Promise<void> {
+ await this.call("POST", `/channels/${chatId}/typing`);
+ }
+}
diff --git a/src/channels/messenger/format.ts b/src/channels/messenger/format.ts
new file mode 100644
index 0000000..055394b
--- /dev/null
+++ b/src/channels/messenger/format.ts
@@ -0,0 +1,113 @@
+/**
+ * 模型写的 Markdown → 各平台能显示的格式。Discord 基本原样;Slack 有自己的 mrkdwn;Telegram 用 HTML 模式(比 MarkdownV2 好转义)。
+ * 只转常见的(标题、粗斜体、删除线、行内代码、代码块、链接、列表)。转错了 Telegram 会拒收,那时改发纯文本(见 telegram.ts)。
+ */
+import { splitText } from "../../core/types.js";
+
+/** 代码块的开头那行:长语言名也算在内,切段时补的 ``` 不会撑破上限 */
+const FENCE_MARGIN = 32;
+
+/**
+ * 按段落切长文本,切在代码块中间时收好这一段、下一段重新打开,每段都能单独显示。
+ * 同样的文字切法总是一样(出站队列按第几段续发靠这个)。
+ */
+export function splitMarkdown(text: string, limit: number): string[] {
+ const out: string[] = [];
+ let open = "";
+ for (const chunk of splitText(text, limit - FENCE_MARGIN)) {
+ const body = open ? `${open}\n${chunk}` : chunk;
+ let fence = open;
+ for (const line of chunk.split("\n")) if (/^\s*```/.test(line)) fence = fence ? "" : line.trim().slice(0, FENCE_MARGIN - 8);
+ open = fence;
+ out.push(open ? `${body}\n\`\`\`` : body);
+ }
+ return out;
+}
+
+/** Markdown 表格在这几个平台上都不显示成表格:放进代码块,至少列是对齐的 */
+export function fenceTables(md: string): string {
+ const lines = md.split("\n");
+ const out: string[] = [];
+ let inCode = false;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (/^\s*```/.test(line)) inCode = !inCode;
+ const starts = !inCode && /^\s*\|.*\|\s*$/.test(line) && /^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(lines[i + 1] ?? "");
+ if (!starts) {
+ out.push(line);
+ continue;
+ }
+ out.push("```");
+ while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) out.push(lines[i++]);
+ out.push("```");
+ i--;
+ }
+ return out.join("\n");
+}
+
+/** 分开代码块和普通文字;没关上的代码块算到结尾 */
+function segments(md: string): Array<{ code: boolean; text: string; lang?: string }> {
+ const out: Array<{ code: boolean; text: string; lang?: string }> = [];
+ const re = /^[ \t]*```([^\n`]*)\n?([\s\S]*?)(?:^[ \t]*```[ \t]*$|$(?![\s\S]))/gm;
+ let at = 0;
+ for (const m of md.matchAll(re)) {
+ if (m.index > at) out.push({ code: false, text: md.slice(at, m.index) });
+ out.push({ code: true, text: m[2].replace(/\n$/, ""), lang: m[1].trim() });
+ at = m.index + m[0].length;
+ }
+ if (at < md.length) out.push({ code: false, text: md.slice(at) });
+ return out;
+}
+
+/** 行内代码先换成占位符(里面的星号不算强调),render 把内容转好,restore 换回来 */
+function stashCode(s: string, render: (code: string) => string): { text: string; restore: (s: string) => string } {
+ const codes: string[] = [];
+ const text = s.replace(/`([^`\n]+)`/g, (_, c: string) => `\u0000${codes.push(render(c)) - 1}\u0000`);
+ return { text, restore: (x) => x.replace(/\u0000(\d+)\u0000/g, (_, n: string) => codes[Number(n)]) };
+}
+
+const escapeHtml = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+
+/** Markdown → Telegram 的 HTML */
+export function toTelegramHtml(md: string): string {
+ return segments(fenceTables(md))
+ .map((seg) => {
+ if (seg.code) return `<pre>${escapeHtml(seg.text)}</pre>`;
+ const { text, restore } = stashCode(escapeHtml(seg.text), (c) => `<code>${c}</code>`);
+ const out = text
+ .replace(/^[ \t]*#{1,6}[ \t]+(.+?)[ \t]*#*[ \t]*$/gm, "<b>$1</b>")
+ .replace(/^([ \t]*)[-*+][ \t]+/gm, "$1• ")
+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, (_, label: string, url: string) => `<a href="${url.replace(/"/g, "&quot;")}">${label}</a>`)
+ .replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*/g, "<b>$1</b>")
+ .replace(/(?<![\w_])__(?=\S)(.+?)(?<=\S)__(?![\w_])/g, "<b>$1</b>")
+ .replace(/(?<![\w*])\*(?=[^\s*])([^*\n]+?)(?<=[^\s*])\*(?![\w*])/g, "<i>$1</i>")
+ .replace(/(?<![\w_])_(?=[^\s_])([^_\n]+?)(?<=[^\s_])_(?![\w_])/g, "<i>$1</i>")
+ .replace(/~~(?=\S)(.+?)(?<=\S)~~/g, "<s>$1</s>");
+ return restore(out);
+ })
+ .join("")
+ .trim();
+}
+
+/** Markdown → Slack 的 mrkdwn */
+export function toSlackMrkdwn(md: string): string {
+ // 粗体换成占位符,等单星号的斜体转完再换回 *x*,否则会被当成斜体再转一次
+ const BOLD = "\u0001";
+ return segments(fenceTables(md))
+ .map((seg) => {
+ if (seg.code) return `\`\`\`\n${seg.text}\n\`\`\``;
+ const { text, restore } = stashCode(seg.text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"), (c) => `\`${c}\``);
+ const out = text
+ .replace(/^[ \t]*#{1,6}[ \t]+(.+?)[ \t]*#*[ \t]*$/gm, `${BOLD}$1${BOLD}`)
+ .replace(/^([ \t]*)[-*+][ \t]+/gm, "$1• ")
+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, "<$2|$1>")
+ .replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*/g, `${BOLD}$1${BOLD}`)
+ .replace(/(?<![\w_])__(?=\S)(.+?)(?<=\S)__(?![\w_])/g, `${BOLD}$1${BOLD}`)
+ .replace(/(?<![\w*])\*(?=[^\s*])([^*\n]+?)(?<=[^\s*])\*(?![\w*])/g, "_$1_")
+ .replace(/~~(?=\S)(.+?)(?<=\S)~~/g, "~$1~")
+ .replaceAll(BOLD, "*");
+ return restore(out);
+ })
+ .join("")
+ .trim();
+}
diff --git a/src/channels/messenger/index.ts b/src/channels/messenger/index.ts
new file mode 100644
index 0000000..628ab2a
--- /dev/null
+++ b/src/channels/messenger/index.ts
@@ -0,0 +1,32 @@
+import type { MessengerId } from "../../core/types.js";
+import type { Store } from "../../store/db.js";
+import { DiscordTransport } from "./discord.js";
+import { SlackTransport } from "./slack.js";
+import { TelegramTransport } from "./telegram.js";
+import type { MessengerTransport } from "./transport.js";
+
+/** 每个平台要填的凭据(界面的输入框也按这个来) */
+export const MESSENGER_FIELDS: Readonly<Record<MessengerId, readonly string[]>> = {
+ telegram: ["token"],
+ slack: ["botToken", "appToken"],
+ discord: ["token"],
+};
+
+/** Telegram 长轮询收到哪了:存在 KV 里,重启后接着收;换了机器人要清掉 */
+export const telegramOffsetKey = (botId: string) => `telegram-offset:${botId}`;
+
+export function createTransport(id: MessengerId, botId: string, credentials: Record<string, string>, store: Store): MessengerTransport {
+ switch (id) {
+ case "telegram":
+ return new TelegramTransport(credentials.token, {
+ offset: {
+ get: () => Number(store.getKV(telegramOffsetKey(botId)) ?? 0) || 0,
+ set: (n) => store.setKV(telegramOffsetKey(botId), String(n)),
+ },
+ });
+ case "slack":
+ return new SlackTransport(credentials.botToken, credentials.appToken);
+ case "discord":
+ return new DiscordTransport(credentials.token);
+ }
+}
diff --git a/src/channels/messenger/slack.ts b/src/channels/messenger/slack.ts
new file mode 100644
index 0000000..13f8c88
--- /dev/null
+++ b/src/channels/messenger/slack.ts
@@ -0,0 +1,195 @@
+import WebSocket from "ws";
+import { logger } from "../../log.js";
+import { toSlackMrkdwn } from "./format.js";
+import { PlatformError, fetchFile, readForUpload, type MessengerFile, type MessengerMessage, type MessengerTransport, type StateFn } from "./transport.js";
+
+const log = logger("slack");
+/** 官方建议一条不超过 4000 字 */
+const MAX_TEXT = 3900;
+const RECONNECT_MS = [1000, 5000, 15_000, 30_000];
+/** 多久 ping 一次;两轮没回 pong 就当连接断了(断网、电脑睡醒后 TCP 可能一直不报错) */
+const PING_MS = 30_000;
+/** 这些错误重试也没用,也不是暂时的:凭据不对了 */
+const AUTH_ERRORS = new Set(["invalid_auth", "not_authed", "account_inactive", "token_revoked", "token_expired", "not_allowed_token_type", "app_uninstalled"]);
+/** 这些是暂时的:其余都算平台拒绝 */
+const TRANSIENT_ERRORS = new Set(["ratelimited", "internal_error", "fatal_error", "service_unavailable", "request_timeout", "team_added_to_org"]);
+
+/**
+ * events_api 里的一个事件 → 归一化。只认真人发的消息:机器人自己的、改消息删消息这类系统事件都跳过。
+ * 引用没有办法拿到原文(Slack 的回复事件不带被回复的内容)。
+ */
+export function slackMessage(ev: any, download: (url: string) => Promise<Buffer>): MessengerMessage | undefined {
+ if (ev?.type !== "message" || !ev.user || !ev.channel || !ev.ts || ev.bot_id) return undefined;
+ if (ev.subtype && ev.subtype !== "file_share") return undefined;
+ const files: MessengerFile[] = [];
+ for (const f of ev.files ?? []) {
+ const url = f.url_private_download ?? f.url_private;
+ if (!url) continue;
+ const mime = String(f.mimetype ?? "");
+ const type: MessengerFile["type"] = mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
+ files.push({ type, ...(type === "file" ? { name: String(f.name ?? "file") } : {}), download: () => download(url) });
+ }
+ return {
+ id: `${ev.channel}:${ev.ts}`,
+ chatId: String(ev.channel),
+ dm: ev.channel_type === "im",
+ senderId: String(ev.user),
+ text: String(ev.text ?? ""),
+ files,
+ };
+}
+
+/** Slack:Socket Mode 收消息(不需要公网地址),Web API 发消息 */
+export class SlackTransport implements MessengerTransport {
+ readonly id = "slack" as const;
+ readonly maxText = MAX_TEXT;
+ private socket: WebSocket | undefined;
+ private stopped = true;
+ private retry: NodeJS.Timeout | undefined;
+ private ping: NodeJS.Timeout | undefined;
+ private failures = 0;
+
+ constructor(
+ private botToken: string,
+ private appToken: string,
+ private o: { fetchImpl?: typeof fetch; baseUrl?: string; reconnectMs?: readonly number[]; pingMs?: number } = {},
+ ) {}
+
+ private get base(): string {
+ return this.o.baseUrl ?? "https://slack.com/api";
+ }
+ private get fetch(): typeof fetch {
+ return this.o.fetchImpl ?? fetch;
+ }
+
+ private async call<T = any>(method: string, body: Record<string, unknown> = {}, token = this.botToken): Promise<T> {
+ const res = await this.fetch(`${this.base}/${method}`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json; charset=utf-8" },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (res.status === 429 || res.status >= 500) throw new PlatformError(`slack ${method}: HTTP ${res.status}`);
+ const data = (await res.json().catch(() => undefined)) as ({ ok?: boolean; error?: string } & T) | undefined;
+ if (data?.ok) return data;
+ const code = data?.error ?? `HTTP ${res.status}`;
+ throw new PlatformError(`slack ${method}: ${code}`, !TRANSIENT_ERRORS.has(code), AUTH_ERRORS.has(code));
+ }
+
+ async verify(): Promise<{ name: string }> {
+ if (!this.botToken.startsWith("xoxb-")) throw new PlatformError("Slack: the bot token starts with xoxb-", true);
+ if (!this.appToken.startsWith("xapp-")) throw new PlatformError("Slack: the app-level token starts with xapp-", true);
+ const me = await this.call("auth.test");
+ await this.call("apps.connections.open", {}, this.appToken);
+ return { name: [me.user ? `@${me.user}` : "", me.team].filter(Boolean).join(" · ") };
+ }
+
+ async start(onMessage: (m: MessengerMessage) => void, onState: StateFn): Promise<void> {
+ this.stopped = false;
+ onState("connecting");
+ void this.connect(onMessage, onState);
+ }
+
+ async stop(): Promise<void> {
+ this.stopped = true;
+ clearTimeout(this.retry);
+ clearInterval(this.ping);
+ this.socket?.terminate();
+ this.socket = undefined;
+ }
+
+ private reconnect(onMessage: (m: MessengerMessage) => void, onState: StateFn): void {
+ if (this.stopped) return;
+ clearInterval(this.ping);
+ const delays = this.o.reconnectMs ?? RECONNECT_MS;
+ clearTimeout(this.retry);
+ this.retry = setTimeout(() => void this.connect(onMessage, onState), delays[Math.min(this.failures++, delays.length - 1)]);
+ this.retry.unref?.();
+ }
+
+ private async connect(onMessage: (m: MessengerMessage) => void, onState: StateFn): Promise<void> {
+ if (this.stopped) return;
+ let url: string;
+ try {
+ ({ url } = await this.call<{ url: string }>("apps.connections.open", {}, this.appToken));
+ } catch (e) {
+ const err = e as PlatformError;
+ // Socket Mode 没开、app token 失效:要用户去改设置,一直重连没有意义
+ if (err.fatal || err.rejected) return onState("error", err.message, true);
+ onState("error", err.message);
+ return this.reconnect(onMessage, onState);
+ }
+ if (this.stopped) return;
+ const socket = (this.socket = new WebSocket(url));
+ let alive = true;
+ socket.on("pong", () => (alive = true));
+ socket.on("message", (raw) => {
+ let msg: any;
+ try {
+ msg = JSON.parse(raw.toString());
+ } catch {
+ return;
+ }
+ if (msg.type === "hello") {
+ this.failures = 0;
+ onState("connected");
+ clearInterval(this.ping);
+ this.ping = setInterval(() => {
+ if (!alive) return socket.terminate();
+ alive = false;
+ socket.ping();
+ }, this.o.pingMs ?? PING_MS);
+ this.ping.unref?.();
+ } else if (msg.type === "disconnect") {
+ // Slack 要换连接了:关掉,走重连
+ socket.close();
+ } else if (msg.envelope_id) {
+ // 三秒内要回执,否则 Slack 会重发;处理在队列里做
+ socket.send(JSON.stringify({ envelope_id: msg.envelope_id }));
+ if (msg.type === "events_api") {
+ const m = slackMessage(msg.payload?.event, (u) => this.download(u));
+ if (m) onMessage(m);
+ }
+ }
+ });
+ socket.on("error", (e) => log.warn("socket error", { message: e.message.slice(0, 200) }));
+ socket.on("close", () => {
+ if (this.socket !== socket || this.stopped) return;
+ onState("connecting", "reconnecting");
+ this.reconnect(onMessage, onState);
+ });
+ }
+
+ private async download(url: string): Promise<Buffer> {
+ const { buffer, contentType } = await fetchFile(this.fetch, url, { headers: { authorization: `Bearer ${this.botToken}` } });
+ // 没有 files:read 权限时 Slack 不报错,返回登录页
+ if (contentType.startsWith("text/html")) throw new Error("the Slack app needs the files:read scope");
+ return buffer;
+ }
+
+ async sendText(chatId: string, text: string): Promise<string> {
+ const r = await this.call<{ ts: string }>("chat.postMessage", { channel: chatId, text: toSlackMrkdwn(text), unfurl_links: false, unfurl_media: false });
+ return r.ts;
+ }
+
+ async editText(chatId: string, messageId: string, text: string): Promise<void> {
+ await this.call("chat.update", { channel: chatId, ts: messageId, text: toSlackMrkdwn(text) });
+ }
+
+ /** 三步:要一个上传地址 → 传上去 → 发到会话 */
+ async sendFile(chatId: string, filePath: string, name: string): Promise<void> {
+ const data = await readForUpload(filePath);
+ const form = new URLSearchParams({ filename: name, length: String(data.length) });
+ const res = await this.fetch(`${this.base}/files.getUploadURLExternal`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${this.botToken}`, "content-type": "application/x-www-form-urlencoded" },
+ body: form,
+ signal: AbortSignal.timeout(30_000),
+ });
+ const up = (await res.json().catch(() => undefined)) as { ok?: boolean; error?: string; upload_url?: string; file_id?: string } | undefined;
+ if (!up?.ok || !up.upload_url || !up.file_id) throw new PlatformError(`slack files.getUploadURLExternal: ${up?.error ?? `HTTP ${res.status}`}`, !TRANSIENT_ERRORS.has(up?.error ?? "") && res.status < 500);
+ const put = await this.fetch(up.upload_url, { method: "POST", body: new Uint8Array(data), signal: AbortSignal.timeout(120_000) });
+ if (!put.ok) throw new PlatformError(`slack file upload: HTTP ${put.status}`);
+ await this.call("files.completeUploadExternal", { files: [{ id: up.file_id, title: name }], channel_id: chatId });
+ }
+}
diff --git a/src/channels/messenger/telegram.ts b/src/channels/messenger/telegram.ts
new file mode 100644
index 0000000..af44a3c
--- /dev/null
+++ b/src/channels/messenger/telegram.ts
@@ -0,0 +1,190 @@
+import path from "node:path";
+import { logger } from "../../log.js";
+import { toTelegramHtml } from "./format.js";
+import { PlatformError, fetchFile, readForUpload, type MessengerFile, type MessengerMessage, type MessengerTransport, type StateFn } from "./transport.js";
+
+const log = logger("telegram");
+/** 官方上限 4096(按解析后的文字算),留点余量 */
+const MAX_TEXT = 4000;
+/** Bot API 只能下载 20 MB 以内的文件 */
+const MAX_DOWNLOAD = 20 * 1024 * 1024;
+/** Bot API 只能上传 50 MB 以内的文件;图片单独是 10 MB */
+const MAX_PHOTO = 10 * 1024 * 1024;
+const PHOTO_EXT = new Set([".jpg", ".jpeg", ".png", ".webp"]);
+const POLL_SECONDS = 30;
+const BACKOFF_MS = [2000, 5000, 15_000, 30_000];
+
+/** getUpdates 的一条消息 → 归一化。不是消息、没有发送者时返回 undefined */
+export function telegramMessage(u: any, download: (fileId: string) => Promise<Buffer>): MessengerMessage | undefined {
+ const m = u?.message;
+ if (!m?.chat || !m.from || m.from.is_bot) return undefined;
+ const files: MessengerFile[] = [];
+ const file = (type: MessengerFile["type"], fileId: string | undefined, name?: string) => {
+ if (fileId) files.push({ type, ...(name ? { name } : {}), download: () => download(fileId) });
+ };
+ // 照片有好几种尺寸,最后一个最大
+ if (Array.isArray(m.photo) && m.photo.length) file("image", m.photo.at(-1).file_id);
+ if (m.document) file("file", m.document.file_id, m.document.file_name || "file");
+ if (m.video) file("video", m.video.file_id);
+ if (m.video_note) file("video", m.video_note.file_id);
+ if (m.voice) file("voice", m.voice.file_id);
+ if (m.audio) file("file", m.audio.file_id, m.audio.file_name || "audio");
+ const reply = m.reply_to_message;
+ const quote = m.quote?.text || reply?.text || reply?.caption;
+ const text = String(m.text ?? m.caption ?? "");
+ const name = [m.from.first_name, m.from.last_name].filter(Boolean).join(" ") || m.from.username;
+ return {
+ id: `${m.chat.id}:${m.message_id}`,
+ chatId: String(m.chat.id),
+ dm: m.chat.type === "private",
+ senderId: String(m.from.id),
+ ...(name ? { senderName: String(name) } : {}),
+ // 打开机器人时 Telegram 自动发 /start:回一段帮助,不用花钱问模型
+ text: /^\/start(@\S+)?(\s|$)/.test(text) ? "/help" : text,
+ files,
+ ...(quote ? { quote: String(quote) } : {}),
+ ...(m.sticker ? { unsupported: "sticker" } : {}),
+ };
+}
+
+/** Telegram Bot API:长轮询收消息(离线时的消息平台留 24 小时,上线后接着收),不需要公网地址 */
+export class TelegramTransport implements MessengerTransport {
+ readonly id = "telegram" as const;
+ readonly maxText = MAX_TEXT;
+ private abort: AbortController | undefined;
+ private loop: Promise<void> | undefined;
+
+ constructor(
+ private token: string,
+ private o: {
+ fetchImpl?: typeof fetch;
+ baseUrl?: string;
+ /** 收到哪了(存进库里,重启后接着收,不会重复) */
+ offset?: { get: () => number; set: (n: number) => void };
+ pollSeconds?: number;
+ backoffMs?: readonly number[];
+ } = {},
+ ) {}
+
+ private get base(): string {
+ return this.o.baseUrl ?? "https://api.telegram.org";
+ }
+ private get fetch(): typeof fetch {
+ return this.o.fetchImpl ?? fetch;
+ }
+
+ private async call<T = any>(method: string, body: Record<string, unknown> | FormData = {}, signal?: AbortSignal): Promise<T> {
+ const form = body instanceof FormData;
+ const res = await this.fetch(`${this.base}/bot${this.token}/${method}`, {
+ method: "POST",
+ ...(form ? {} : { headers: { "content-type": "application/json" } }),
+ body: form ? body : JSON.stringify(body),
+ signal: signal ?? AbortSignal.timeout(form ? 120_000 : 30_000),
+ });
+ const data = (await res.json().catch(() => undefined)) as { ok?: boolean; result?: T; description?: string; error_code?: number } | undefined;
+ if (data?.ok) return data.result as T;
+ const code = data?.error_code ?? res.status;
+ // 限流和服务器错误过一会儿就好;其余(聊天不存在、被拉黑、参数不对)重试也没用
+ throw new PlatformError(`telegram ${method}: ${code} ${data?.description ?? ""}`.trim(), code < 500 && code !== 429, code === 401 || code === 404);
+ }
+
+ async verify(): Promise<{ name: string }> {
+ const me = await this.call("getMe");
+ return { name: me.username ? `@${me.username}` : String(me.first_name ?? "") };
+ }
+
+ async start(onMessage: (m: MessengerMessage) => void, onState: StateFn): Promise<void> {
+ if (this.loop) return;
+ const abort = (this.abort = new AbortController());
+ this.loop = this.run(onMessage, onState, abort.signal).finally(() => (this.loop = undefined));
+ }
+
+ async stop(): Promise<void> {
+ this.abort?.abort();
+ await this.loop?.catch(() => {});
+ }
+
+ private async run(onMessage: (m: MessengerMessage) => void, onState: StateFn, signal: AbortSignal): Promise<void> {
+ const backoff = this.o.backoffMs ?? BACKOFF_MS;
+ let failures = 0;
+ let offset = this.o.offset?.get() ?? 0;
+ onState("connecting");
+ // 配过 webhook 的机器人收不到长轮询,先清掉;失败了下面的 getUpdates 会报
+ await this.call("deleteWebhook", {}, AbortSignal.any([signal, AbortSignal.timeout(30_000)])).catch(() => {});
+ const seconds = this.o.pollSeconds ?? POLL_SECONDS;
+ while (!signal.aborted) {
+ try {
+ // 比长轮询多等一会儿:连接悄悄断了(电脑睡醒、换网络)时不会一直挂着
+ const limit = AbortSignal.any([signal, AbortSignal.timeout((seconds + 15) * 1000)]);
+ const updates = await this.call<any[]>("getUpdates", { offset, timeout: seconds, allowed_updates: ["message"] }, limit);
+ failures = 0;
+ onState("connected");
+ for (const u of updates) {
+ offset = Math.max(offset, Number(u.update_id) + 1);
+ const m = telegramMessage(u, (id) => this.download(id));
+ if (m) onMessage(m);
+ }
+ if (updates.length) this.o.offset?.set(offset);
+ } catch (e) {
+ if (signal.aborted) return;
+ const err = e as PlatformError;
+ if (err.fatal) {
+ onState("error", err.message, true);
+ return;
+ }
+ onState("error", err.message);
+ log.warn("getUpdates failed", { failures, message: err.message.slice(0, 200) });
+ await sleep(backoff[Math.min(failures++, backoff.length - 1)], signal);
+ }
+ }
+ }
+
+ private async download(fileId: string): Promise<Buffer> {
+ const f = await this.call("getFile", { file_id: fileId });
+ return (await fetchFile(this.fetch, `${this.base}/file/bot${this.token}/${f.file_path}`, {}, MAX_DOWNLOAD)).buffer;
+ }
+
+ /** 发 HTML;转出来的格式 Telegram 不认(标签嵌套不对之类)就发原文 */
+ private async formatted<T>(chunk: string, send: (fields: Record<string, unknown>) => Promise<T>): Promise<T> {
+ try {
+ return await send({ text: toTelegramHtml(chunk), parse_mode: "HTML" });
+ } catch (e) {
+ if (!/can't parse entities/i.test((e as Error).message)) throw e;
+ return send({ text: chunk });
+ }
+ }
+
+ async sendText(chatId: string, text: string): Promise<string> {
+ const r = await this.formatted(text, (f) => this.call("sendMessage", { chat_id: chatId, link_preview_options: { is_disabled: true }, ...f }));
+ return String(r.message_id);
+ }
+
+ async editText(chatId: string, messageId: string, text: string): Promise<void> {
+ try {
+ await this.formatted(text, (f) => this.call("editMessageText", { chat_id: chatId, message_id: Number(messageId), link_preview_options: { is_disabled: true }, ...f }));
+ } catch (e) {
+ // 内容没变:不算失败
+ if (!/message is not modified/i.test((e as Error).message)) throw e;
+ }
+ }
+
+ async sendFile(chatId: string, filePath: string, name: string): Promise<void> {
+ const data = await readForUpload(filePath);
+ const photo = PHOTO_EXT.has(path.extname(name).toLowerCase()) && data.length <= MAX_PHOTO;
+ const form = new FormData();
+ form.set("chat_id", chatId);
+ form.set(photo ? "photo" : "document", new Blob([new Uint8Array(data)]), name);
+ await this.call(photo ? "sendPhoto" : "sendDocument", form);
+ }
+
+ async typing(chatId: string): Promise<void> {
+ await this.call("sendChatAction", { chat_id: chatId, action: "typing" });
+ }
+}
+
+function sleep(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((r) => {
+ const t = setTimeout(r, ms);
+ signal.addEventListener("abort", () => (clearTimeout(t), r()), { once: true });
+ });
+}
diff --git a/src/channels/messenger/transport.ts b/src/channels/messenger/transport.ts
new file mode 100644
index 0000000..a12560c
--- /dev/null
+++ b/src/channels/messenger/transport.ts
@@ -0,0 +1,84 @@
+import fsp from "node:fs/promises";
+import type { ChannelStatus, MessengerId } from "../../core/types.js";
+import { t as tr } from "../../i18n/index.js";
+
+/**
+ * Telegram、Slack、Discord 共用的传输层接口:长连接或长轮询收消息,HTTP 接口发消息。
+ * 真实实现直接调平台的公开接口(没有 SDK);离线测试用假的替换。
+ */
+
+/** 对方发来的文件:处理这条消息时才下载(陌生人的不下载) */
+export interface MessengerFile {
+ type: "image" | "file" | "video" | "voice";
+ name?: string;
+ download: () => Promise<Buffer>;
+}
+
+export interface MessengerMessage {
+ /** 平台消息 id(去重用,在这个机器人的这个平台里唯一) */
+ id: string;
+ chatId: string;
+ /** 单聊。群里的消息目前不处理 */
+ dm: boolean;
+ senderId: string;
+ senderName?: string;
+ text: string;
+ files: MessengerFile[];
+ /** 这条回复的是哪句(平台给了原文时) */
+ quote?: string;
+ /** 处理不了的消息类型(贴纸等):回答时说明 */
+ unsupported?: string;
+}
+
+/** fatal:凭据失效,不再重连,要用户处理 */
+export type StateFn = (state: ChannelStatus["state"], detail?: string, fatal?: boolean) => void;
+
+export interface MessengerTransport {
+ readonly id: MessengerId;
+ /** 一条消息最多放多少字(留了余量) */
+ readonly maxText: number;
+ /** 检查凭据,返回平台上机器人的名字;凭据不对抛 rejected 的错误 */
+ verify?(): Promise<{ name: string }>;
+ start(onMessage: (m: MessengerMessage) => void, onState: StateFn): Promise<void>;
+ stop(): Promise<void>;
+ /** 发一条,返回消息 id。key 是确定的(同一条消息的同一段不变),平台能去重时用它 */
+ sendText(chatId: string, text: string, key?: string): Promise<string>;
+ editText(chatId: string, messageId: string, text: string): Promise<void>;
+ sendFile(chatId: string, filePath: string, name: string): Promise<void>;
+ /** 显示"正在输入"(几秒后自动消失);没有这个能力的平台不实现 */
+ typing?(chatId: string): Promise<void>;
+}
+
+/** 平台返回的错误。rejected = 平台明确拒绝,重试没用(见 core/outbox.ts);fatal = 凭据失效,重连也没用 */
+export class PlatformError extends Error {
+ constructor(
+ message: string,
+ readonly rejected = false,
+ readonly fatal = false,
+ ) {
+ super(message);
+ }
+}
+
+/** 收发文件的上限:进内存处理,太大的不接 */
+export const MAX_FILE_BYTES = 50 * 1024 * 1024;
+
+const tooLarge = (bytes: number, max: number) => new Error(tr("channel.too_large", { size: (bytes / 1048576).toFixed(1), max: Math.round(max / 1048576) }));
+
+/** 读要发的本地文件;太大的不读 */
+export async function readForUpload(filePath: string, max = MAX_FILE_BYTES): Promise<Buffer> {
+ const { size } = await fsp.stat(filePath);
+ if (size > max) throw tooLarge(size, max);
+ return fsp.readFile(filePath);
+}
+
+/** 下载对方发来的文件。先看声明的大小,再看实际大小 */
+export async function fetchFile(fetchImpl: typeof fetch, url: string, init: RequestInit = {}, max = MAX_FILE_BYTES): Promise<{ buffer: Buffer; contentType: string }> {
+ const res = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(120_000) });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const declared = Number(res.headers.get("content-length") ?? 0);
+ if (declared > max) throw tooLarge(declared, max);
+ const buffer = Buffer.from(await res.arrayBuffer());
+ if (buffer.length > max) throw tooLarge(buffer.length, max);
+ return { buffer, contentType: res.headers.get("content-type") ?? "" };
+}
diff --git a/src/core/access.ts b/src/core/access.ts
index 053ffc8..f17486f 100644
--- a/src/core/access.ts
+++ b/src/core/access.ts
@@ -1,7 +1,7 @@
/**
* 谁能和机器人对话:默认只有主人。代理跑在用户自己的电脑上(甚至可能是完全权限),陌生人找到机器人也不能驱动它。
*
- * - 主人:微信 = 扫码登录的那个微信;飞书(以及没拿到扫码者的微信)= 连上之后第一个发单聊消息的人
+ * - 主人:微信 = 扫码登录的那个微信;飞书、Telegram、Slack、Discord(以及没拿到扫码者的微信)= 连上之后第一个发单聊消息的人
* (先到先得;这条消息照常处理)。机器人设置里可以「更换」:清掉主人,下一个发消息的人成为主人。
* - 其他人发消息:登记成使用请求,只回一句"还没被允许"(同一个人每小时最多一次),不进队列、不碰模型、不花钱;
* 请求出现在信息面板里,也会带配对码发给主人(每个机器人每小时最多 3 条),主人回复「同意 1234」即可。
@@ -9,8 +9,8 @@
* - 本机网页控制台本来就可信;群聊目前没有渠道接入(飞书只收单聊,微信 iLink 没有群),保持原样不拦,接入群聊时再定规则。
*/
import crypto from "node:crypto";
-import type { InboundEvent } from "./types.js";
-import { eventText } from "./types.js";
+import type { InboundEvent, PushChannel } from "./types.js";
+import { MESSENGERS, MESSENGER_LABEL, eventText, isMessenger } from "./types.js";
import type { AccessEntry, Store } from "../store/db.js";
import { logger } from "../log.js";
import { t as tr } from "../i18n/index.js";
@@ -26,9 +26,9 @@ export const NOTICE_LIMIT = 3;
const NOTICE_WINDOW_MS = 3600_000;
export const approvedText = () => tr("access.approved");
-export type AccessChannel = "weixin" | "feishu";
-export const ACCESS_CHANNELS: AccessChannel[] = ["weixin", "feishu"];
-const channelLabel = (c: string) => (c === "weixin" ? tr("access.chWeixin") : c === "feishu" ? tr("access.chFeishu") : c === "web" ? tr("access.chWeb") : c);
+export type AccessChannel = PushChannel;
+export const ACCESS_CHANNELS: AccessChannel[] = ["weixin", "feishu", ...MESSENGERS];
+const channelLabel = (c: string) => (c === "weixin" ? tr("access.chWeixin") : c === "feishu" ? tr("access.chFeishu") : c === "web" ? tr("access.chWeb") : isMessenger(c) ? MESSENGER_LABEL[c] : c);
/** 主动发一条通知(App 经渠道和出站队列发);发不出去(对方 24 小时内没说过话、渠道没开)返回 false */
export type Notify = (to: { botId: string; channel: string; peerId: string }, text: string, id: string) => boolean;
@@ -283,7 +283,8 @@ export class AccessControl {
policyLine(botId: string): string {
const v = this.view(botId);
const allowed = v.entries.filter((e) => e.status === "allowed").length;
- const owners = ACCESS_CHANNELS.map((ch) => tr("access.ownerOf", { channel: channelLabel(ch), who: v.owners[ch] ? ` ${shortPeer(v.owners[ch]!.peerId)}` : tr("access.notSet") })).join(tr("access.listSep"));
+ // 微信、飞书总列;其他平台有主人才列,免得这一行全是"未设置"
+ const owners = ACCESS_CHANNELS.filter((ch) => !isMessenger(ch) || v.owners[ch]).map((ch) => tr("access.ownerOf", { channel: channelLabel(ch), who: v.owners[ch] ? ` ${shortPeer(v.owners[ch]!.peerId)}` : tr("access.notSet") })).join(tr("access.listSep"));
const req = v.requests.length ? tr("access.pendingRequests", { count: v.requests.length }) : "";
return tr("access.policy", { owners, allowed, req });
}
diff --git a/src/core/delivery.ts b/src/core/delivery.ts
index 95c12a0..ebb5901 100644
--- a/src/core/delivery.ts
+++ b/src/core/delivery.ts
@@ -23,6 +23,7 @@ import type { HeldGroup, Outbox } from "./outbox.js";
import { DEFAULT_QUIET, fmtWhen, inQuiet, minuteOf, nextAt, quietEnd, quietStart, startOfDay, systemTimeZone, type QuietHours } from "./quiet.js";
import { QUOTA_WINDOW_MS, WeixinQuota } from "../channels/weixin/quota.js";
import { combineHeld, filterMarkdown } from "../channels/weixin/channel.js";
+import { MESSENGER_LABEL, isMessenger, type PushChannel } from "./types.js";
import { logger } from "../log.js";
import { t as tr } from "../i18n/index.js";
@@ -58,8 +59,8 @@ export interface PushInput {
/** 确定的 id(同一 id 只发一次),如 task:<任务>:result:<run> */
id: string;
botId: string;
- channel: "weixin" | "feishu";
- /** 微信:用户 id;飞书:chat_id */
+ channel: PushChannel;
+ /** 微信:用户 id;飞书和其他平台:chat id */
peerId: string;
purpose: PushPurpose;
/** 是什么:任务标题、规则名(摘要、续期提醒、「需要你」里用) */
@@ -126,7 +127,7 @@ export interface AttentionItem {
actions: Array<"retry" | "dismiss">;
}
-const channelName = (c: string) => (c === "weixin" ? tr("delivery.chWeixin") : c === "feishu" ? tr("delivery.chFeishu") : c);
+const channelName = (c: string) => (c === "weixin" ? tr("delivery.chWeixin") : c === "feishu" ? tr("delivery.chFeishu") : isMessenger(c) ? MESSENGER_LABEL[c] : c);
const ACK = /^(ok|okay|k|好|好的|好滴|嗯|嗯嗯|收到|行|可以)[\s!!。.~~]*$/i;
const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();
diff --git a/src/core/outbox.ts b/src/core/outbox.ts
index d755581..9657f55 100644
--- a/src/core/outbox.ts
+++ b/src/core/outbox.ts
@@ -15,6 +15,7 @@
*/
import crypto from "node:crypto";
import type { OutboxBody, OutboxKind, OutboxPurpose, OutboxRow, Store } from "../store/db.js";
+import type { PushChannel } from "./types.js";
import { logger } from "../log.js";
import { t as tr } from "../i18n/index.js";
@@ -47,8 +48,8 @@ export const HOLD_TTL_MS = 7 * 86400_000;
export interface OutboxInput {
id: string;
botId: string;
- channel: "weixin" | "feishu";
- /** 微信:用户 id;飞书:单聊 chat_id */
+ channel: PushChannel;
+ /** 微信:用户 id;飞书和其他平台:单聊的 chat id */
peerId: string;
kind: OutboxKind;
body: OutboxBody;
diff --git a/src/core/types.ts b/src/core/types.ts
index 2813bbf..cb348aa 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -5,7 +5,17 @@
import type { ActivityStep } from "../agent/activity.js";
import { t, type MessageKey } from "../i18n/index.js";
-export type ChannelId = "feishu" | "weixin" | "web";
+/** 同一套接法的聊天平台(channels/messenger):填 token 连上,单聊,流式靠改消息 */
+export const MESSENGERS = ["telegram", "slack", "discord"] as const;
+export type MessengerId = (typeof MESSENGERS)[number];
+/** 平台名(品牌名,不分语言) */
+export const MESSENGER_LABEL: Readonly<Record<MessengerId, string>> = { telegram: "Telegram", slack: "Slack", discord: "Discord" };
+export const isMessenger = (c: string): c is MessengerId => (MESSENGERS as readonly string[]).includes(c);
+
+export type ChannelId = "feishu" | "weixin" | "web" | MessengerId;
+/** 消息经出站队列发到平台的渠道(网页对话不走出站队列) */
+export type PushChannel = Exclude<ChannelId, "web">;
+export const isPushChannel = (c: string): c is PushChannel => c === "weixin" || c === "feishu" || isMessenger(c);
export type Part =
| { type: "text"; text: string }
diff --git a/src/guide.ts b/src/guide.ts
index 34736c0..99d2124 100644
--- a/src/guide.ts
+++ b/src/guide.ts
@@ -29,7 +29,8 @@ export function normalizeGuide(v: unknown): GuideState {
export interface GuideFacts {
conversations: Array<{ messageCount: number; model: string }>;
bots: Array<{ id: string; defaultModel: string; feishuAppId: string }>;
- weixinBound: (botId: string) => boolean;
+ /** 微信扫码绑定了,或者连上了 Telegram、Slack、Discord */
+ channelBound: (botId: string) => boolean;
memoryCount: (botId: string) => number;
}
@@ -38,7 +39,7 @@ export function deriveGuide(f: GuideFacts): GuideStep[] {
// 一问一答至少两条消息
if (f.conversations.some((c) => c.messageCount >= 2)) out.push("hello");
if (f.conversations.some((c) => c.model) || f.bots.some((b) => b.defaultModel)) out.push("model");
- if (f.bots.some((b) => b.feishuAppId || f.weixinBound(b.id))) out.push("weixin");
+ if (f.bots.some((b) => b.feishuAppId || f.channelBound(b.id))) out.push("weixin");
if (f.bots.some((b) => f.memoryCount(b.id) > 0)) out.push("memory");
return out;
}
diff --git a/src/i18n/messages/app.ts b/src/i18n/messages/app.ts
index a386794..87c86c7 100644
--- a/src/i18n/messages/app.ts
+++ b/src/i18n/messages/app.ts
@@ -9,6 +9,7 @@ export const zh = {
default_bot_name: "我的助手",
default_bot_prompt: "你是一个乐于助人的中文助手,回答简洁准确。",
feishu_failed: "机器人「{name}」飞书长连接启动失败:{message}",
+ messenger_failed: "机器人「{name}」连不上 {channel},请在信息面板检查凭据:{message}",
feishu_history_denied: "机器人「{name}」读不到飞书的历史消息,离线时发来的消息补不上。在飞书开放平台给应用开通 im:message.history:readonly 权限即可。",
weixin_expired: "机器人「{name}」微信登录已过期,请在信息面板的「渠道」里重新扫码",
weixin_connected: "机器人「{name}」微信已连接",
@@ -34,6 +35,7 @@ export const en: Catalog<typeof zh> = {
default_bot_name: "My Assistant",
default_bot_prompt: "You are a helpful assistant. Answer concisely and accurately.",
feishu_failed: "Bot \"{name}\": Feishu long connection failed to start: {message}",
+ messenger_failed: "Bot \"{name}\" can't connect to {channel}. Check its credentials in the info panel: {message}",
feishu_history_denied: "Bot \"{name}\" can't read Feishu message history, so messages sent while it was offline can't be caught up. Grant the app the im:message.history:readonly scope in the Feishu Open Platform.",
weixin_expired: "Bot \"{name}\": WeChat sign-in expired. Scan the QR code again under Channels in the info panel",
weixin_connected: "Bot \"{name}\": WeChat connected",
diff --git a/src/i18n/messages/channel.ts b/src/i18n/messages/channel.ts
index 2a52b2d..ee4286e 100644
--- a/src/i18n/messages/channel.ts
+++ b/src/i18n/messages/channel.ts
@@ -15,6 +15,7 @@ export const zh = {
unsupported_message: "[暂不支持的消息类型:{type}]",
// 渠道状态(信息面板)
feishu_no_credentials: "未配置凭据",
+ messengerMissing: "{channel} 的凭据没有填全",
wx_login_required: "尚未扫码登录",
wx_expired: "登录已过期(-14),请在界面重新扫码",
// 微信扫码登录
@@ -48,7 +49,7 @@ export const zh = {
heldQuota: "本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条),等他下次发消息时再发",
heldReserved: "本轮剩下的条数留给后台任务的结果了,等他下次发消息时再发",
fileFallback: "文件",
- laterNotRunning: "微信渠道没有运行",
+ laterNotRunning: "渠道没有运行",
laterExpired: "微信登录已过期,等重新扫码",
feishuNoPush: "飞书传输层不支持主动发消息",
} satisfies Catalog;
@@ -65,6 +66,7 @@ export const en: Catalog<typeof zh> = {
card_action_failed: "Failed",
unsupported_message: "[Unsupported message type: {type}]",
feishu_no_credentials: "Credentials not configured",
+ messengerMissing: "{channel} credentials are incomplete",
wx_login_required: "Not signed in yet: scan the QR code",
wx_expired: "Sign-in expired (-14). Scan the QR code again in the app",
login_cancelled: "Cancelled",
@@ -96,7 +98,7 @@ export const en: Catalog<typeof zh> = {
heldQuota: "This turn's message allowance is used up (up to 10 replies within 24 hours of each message they send); it'll be sent next time they message",
heldReserved: "The rest of this turn's allowance is reserved for background task results; it'll be sent next time they message",
fileFallback: "file",
- laterNotRunning: "The WeChat channel isn't running",
+ laterNotRunning: "The channel isn't running",
laterExpired: "WeChat sign-in expired; waiting for a new QR scan",
feishuNoPush: "The Feishu transport can't send messages on its own",
};
diff --git a/src/store/db.ts b/src/store/db.ts
index eb87329..f82bfc6 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -67,6 +67,15 @@ export interface WeixinAccount {
updatedAt: number;
}
+/** Telegram、Slack、Discord 的连接凭据(只在本机库里,不随机器人设置返回给界面) */
+export interface MessengerAccount {
+ botId: string;
+ channel: string;
+ credentials: Record<string, string>;
+ /** 平台上机器人的名字(连接时查到的),信息面板显示 */
+ name: string;
+ updatedAt: number;
+}
export interface WeixinPeer {
botId: string;
userId: string;
@@ -160,6 +169,8 @@ export interface OutboxBody {
name?: string;
/** 飞书交互卡片 JSON(发不了时发 text) */
card?: Record<string, unknown>;
+ /** 流式显示用的那条消息(Telegram、Slack、Discord):最终回复的第一段改写它,改不了再发新的 */
+ editId?: string;
/** 飞书流式卡片:最终回复先写进这张卡片,失败再发文本 */
cardId?: string;
cardSeq?: number;
@@ -452,6 +463,9 @@ CREATE TABLE IF NOT EXISTS weixin_peers (
bot_id TEXT NOT NULL, user_id TEXT NOT NULL, context_token TEXT NOT NULL DEFAULT '',
quota_remaining INTEGER NOT NULL DEFAULT 0, window_started_at INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (bot_id, user_id));
+CREATE TABLE IF NOT EXISTS messenger_accounts (
+ bot_id TEXT NOT NULL, channel TEXT NOT NULL, credentials TEXT NOT NULL, name TEXT NOT NULL DEFAULT '',
+ updated_at INTEGER NOT NULL, PRIMARY KEY (bot_id, channel));
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS agent_sessions (
conversation_id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, session_id TEXT NOT NULL, updated_at INTEGER NOT NULL);
@@ -691,6 +705,7 @@ export class Store {
this.db.prepare("DELETE FROM conversations WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM weixin_accounts WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM weixin_peers WHERE bot_id = ?").run(id);
+ this.db.prepare("DELETE FROM messenger_accounts WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM agent_sessions WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM access WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM outbox WHERE bot_id = ?").run(id);
@@ -822,6 +837,30 @@ export class Store {
return picked;
}
+ // ---------- Telegram、Slack、Discord 的连接凭据 ----------
+ getMessengerAccount(botId: string, channel: string): MessengerAccount | undefined {
+ const r = this.db.prepare("SELECT * FROM messenger_accounts WHERE bot_id = ? AND channel = ?").get(botId, channel) as Row | undefined;
+ if (!r) return undefined;
+ let credentials: Record<string, string> = {};
+ try {
+ credentials = JSON.parse(String(r.credentials));
+ } catch {
+ /* 读不出来就当没填过,让用户重新填 */
+ }
+ return { botId, channel, credentials, name: String(r.name), updatedAt: Number(r.updated_at) };
+ }
+ saveMessengerAccount(a: Pick<MessengerAccount, "botId" | "channel" | "credentials" | "name">): void {
+ this.db
+ .prepare(
+ `INSERT INTO messenger_accounts(bot_id, channel, credentials, name, updated_at) VALUES(?, ?, ?, ?, ?)
+ ON CONFLICT(bot_id, channel) DO UPDATE SET credentials=excluded.credentials, name=excluded.name, updated_at=excluded.updated_at`,
+ )
+ .run(a.botId, a.channel, JSON.stringify(a.credentials), a.name, Date.now());
+ }
+ deleteMessengerAccount(botId: string, channel: string): void {
+ this.db.prepare("DELETE FROM messenger_accounts WHERE bot_id = ? AND channel = ?").run(botId, channel);
+ }
+
// ---------- weixin ----------
getWeixinAccount(botId: string): WeixinAccount | undefined {
const r = this.db.prepare("SELECT * FROM weixin_accounts WHERE bot_id = ?").get(botId) as Row | undefined;
diff --git a/src/tasks/attention.ts b/src/tasks/attention.ts
index be7e1ac..643662b 100644
--- a/src/tasks/attention.ts
+++ b/src/tasks/attention.ts
@@ -7,6 +7,7 @@
* - 系统通知每一项最多一次(takeNew:记在 KV 里,重启也算);问要不要改为执行的那种(suggest)不发。
* 健康时什么都没有:没有行、没有角标、没有通知。
*/
+import { MESSENGER_LABEL, isMessenger } from "../core/types.js";
import type { ApprovalRow, Store } from "../store/db.js";
import { defaultLine, questionsOf, type QuestionItem } from "../agent/approvals.js";
import type { AttentionItem as DeliveryItem } from "../core/delivery.js";
@@ -189,7 +190,7 @@ export class Attention {
}
}
-const channelLabel = (c: string) => (c === "weixin" ? tr("tasks.chWeixin") : c === "feishu" ? tr("tasks.chFeishu") : c === "web" ? tr("tasks.chWeb") : undefined);
+const channelLabel = (c: string) => (c === "weixin" ? tr("tasks.chWeixin") : c === "feishu" ? tr("tasks.chFeishu") : c === "web" ? tr("tasks.chWeb") : isMessenger(c) ? MESSENGER_LABEL[c] : undefined);
/**
* 审批中心那一份:还在等的提问和审批(聊天回合里的、后台任务的)。任务的以任务名为题,聊天里的以渠道为题:
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
index db8f6d9..089f25f 100644
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@ -40,6 +40,7 @@ import { sentText } from "../core/outbox.js";
import { ActivityLog, type ActivityStep } from "../agent/activity.js";
import { ResumeFailed, deliverables } from "../agent/host.js";
import { answerLine, defaultLine, defaultOf, parseAnswer, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";
+import { MESSENGER_LABEL, isMessenger, isPushChannel, type PushChannel } from "../core/types.js";
import { actionCardSpec } from "../channels/feishu/transport.js";
import { NUDGE, RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, attachmentsOf, rebrief, recoveryNote, resumeNote, retryNote, ruleBrief, ruleResultInput, ruleRules, taskBrief } from "../agent/prompts/index.js";
import type { BotSettings } from "../agent/settings.js";
@@ -91,6 +92,9 @@ import { t as tr } from "../i18n/index.js";
import { KEEP_MS, SWEEP_MS, WARN_MS, dirBytes, hasFiles, taskFolder } from "./retention.js";
import { ruleMarkdown, taskMarkdown, type ExportedTaskRun } from "./export.js";
+/** 引用一条消息时,平台会把原文一起给我们的渠道:靠引用就认得出是哪个任务的结果 */
+const QUOTES_ORIGINAL: ReadonlySet<string> = new Set(["weixin", "telegram", "discord"]);
+
const log = logger("tasks");
/** 每个机器人同时在进行的任务上限:再多就拒绝 task_start */
@@ -1192,10 +1196,10 @@ export class TaskService {
return;
}
const msg = oneLine(report?.message ?? "");
- const pushed = (conv.channel === "weixin" || conv.channel === "feishu") && !!this.o.delivery;
- // 结果后面那句「引用这条消息可以继续问」(失败那句本来就说了怎么办):微信总有;飞书只在结果回复在请求那条消息下时有
- // (回复链对得上才认得出是哪个任务,见 followUp)。连它一起不超过 300 字
- const hint = pushed && outcome === "done" ? (conv.channel === "weixin" ? tr("tasks.hintQuote") : task.originRef ? tr("tasks.hintReply") : "") : "";
+ const pushed = isPushChannel(conv.channel) && !!this.o.delivery;
+ // 结果后面那句「引用这条消息可以继续问」(失败那句本来就说了怎么办):引用时能带上原文的平台(微信、Telegram、Discord)总有;
+ // 飞书只在结果回复在请求那条消息下时有(回复链对得上才认得出是哪个任务,见 followUp);Slack 的回复不带原文,没有。连它一起不超过 300 字
+ const hint = pushed && outcome === "done" ? (QUOTES_ORIGINAL.has(conv.channel) ? tr("tasks.hintQuote") : task.originRef ? tr("tasks.hintReply") : "") : "";
const text = outcome === "done" ? clip(msg, MESSAGE_MAX - (hint ? hint.length + 2 : 0)) || tr("tasks.done", { title: task.title }) : tr("tasks.notDone", { title: task.title, why: clip(msg || error || tr("tasks.noResult"), MESSAGE_MAX) });
const files = outcome === "done" ? this.files(task, report?.files ?? []) : [];
if (pushed) this.post(conv, task, id, purpose, text, files, hint);
@@ -1205,9 +1209,9 @@ export class TaskService {
this.note(conv.id, outcome === "done" ? `[后台任务「${task.title}」已完成,已把结果发给用户] ${text}` : `[后台任务「${task.title}」失败了,已告诉用户] ${text}`);
}
- /** 微信、飞书:按主动消息的规则写进出站队列(同步落库;渠道没上线时等它上线) */
+ /** 聊天平台:按主动消息的规则写进出站队列(同步落库;渠道没上线时等它上线) */
private post(conv: Conversation, task: TaskRow, id: string, purpose: "result" | "failure", text: string, files: string[], hint: string): void {
- const channel = conv.channel as "weixin" | "feishu";
+ const channel = conv.channel as PushChannel;
const replyTo = channel === "feishu" ? task.originRef || replyHandle(this.store, conv.id).messageId || "" : "";
const notice = channel === "feishu" && !replyTo;
this.o.delivery!.push({
@@ -1533,7 +1537,7 @@ export class TaskService {
const delivery = this.o.delivery;
if (!a || !delivery || !this.started) return;
const conv = this.store.getConversation(conversationId);
- if (!conv || (conv.channel !== "weixin" && conv.channel !== "feishu")) return;
+ if (!conv || !isPushChannel(conv.channel)) return;
const rows = a.pending(conversationId).filter((r) => r.taskId).sort((x, y) => x.createdAt - y.createdAt);
const pushed = (r: ApprovalRow) => this.store.getOutbox(askId(r));
if (rows.some((r) => (pushed(r)?.status ?? "gone") !== "gone")) return;
@@ -1541,8 +1545,9 @@ export class TaskService {
const task = row ? this.store.getTask(row.taskId) : undefined;
if (!row || !task || task.endReason === "stopped") return;
const text = taskPromptText(row, task.title);
- const base = { id: askId(row), botId: task.botId, channel: conv.channel as "weixin" | "feishu", peerId: conv.peerId, purpose: "question" as const, subject: task.title, text, ref: `task:${task.id}` };
- if (conv.channel === "weixin") delivery.push({ ...base, raw: true });
+ const base = { id: askId(row), botId: task.botId, channel: conv.channel, peerId: conv.peerId, purpose: "question" as const, subject: task.title, text, ref: `task:${task.id}` };
+ // 只有飞书有卡片按钮;其他平台发文字,回复编号
+ if (conv.channel !== "feishu") delivery.push({ ...base, raw: true });
else {
const replyTo = task.originRef || replyHandle(this.store, conv.id).messageId || "";
const buttons = promptButtons(row);
@@ -2030,7 +2035,7 @@ export class TaskService {
endedAt: r.endedAt,
steps: this.activity(r.id),
}));
- const channel = ch === "weixin" ? tr("tasks.chWeixin") : ch === "feishu" ? tr("tasks.chFeishu") : ch ? tr("tasks.chWeb") : "";
+ const channel = ch === "weixin" ? tr("tasks.chWeixin") : ch === "feishu" ? tr("tasks.chFeishu") : ch && isMessenger(ch) ? MESSENGER_LABEL[ch] : ch ? tr("tasks.chWeb") : "";
return { title: task.title, text: taskMarkdown(this.view(task), origin && { ...origin, channel }, runs, this.timeZone, this.now()) };
}
@@ -2609,7 +2614,7 @@ export class TaskService {
const conv = this.store.getConversation(rule.conversationId);
if (!conv) return false;
if (this.store.getOutbox(id)) return true;
- if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.delivery) {
+ if (isPushChannel(conv.channel) && this.o.delivery) {
this.o.delivery.push({
id,
botId: rule.botId,
diff --git a/src/web/server.ts b/src/web/server.ts
index 34ccd26..0db2475 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -5,7 +5,8 @@ import crypto from "node:crypto";
import { createRequire } from "node:module";
import { appVersion, type App } from "../app.js";
import type { InboundEvent, OutboundOp, ReplySession } from "../core/types.js";
-import { eventText } from "../core/types.js";
+import { MESSENGERS, eventText, isMessenger, isPushChannel } from "../core/types.js";
+import type { PlatformError } from "../channels/messenger/transport.js";
import { findAppRoot } from "../magpie/supervisor.js";
import { logFilePath, logger, mask, readLogTail, registerSecret } from "../log.js";
import { diagnosticsReport, safeStatus, testAgent, testModel } from "../diagnostics.js";
@@ -22,7 +23,7 @@ import { defaultLine } from "../agent/approvals.js";
import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
import { pwshProbe, type PwshMode, type PwshStatus } from "../agent/pwsh.js";
-import { peerName, shortPeer, whoText } from "../core/access.js";
+import { ACCESS_CHANNELS, peerName, shortPeer, whoText, type AccessChannel } from "../core/access.js";
import type { AccessEntry, RuleMode } from "../store/db.js";
import { normalizeSchedule, type Schedule } from "../tasks/schedule.js";
import { exportFileName } from "../tasks/export.js";
@@ -719,7 +720,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
const derived = deriveGuide({
conversations: app.store.listConversations(),
bots,
- weixinBound: (id) => !!app.store.getWeixinAccount(id),
+ channelBound: (id) => !!app.store.getWeixinAccount(id) || MESSENGERS.some((c) => !!app.store.getMessengerAccount(id, c)),
// 机器人自己的记忆,或所有机器人共享的团队记忆,有一条就算记下过
memoryCount: (id) =>
[{ kind: "bot" as const, id }, { kind: "team" as const, id: "" }].reduce((n, s) => n + app.agent.memory.entries(s).length + app.agent.memory.topics(s).length, 0),
@@ -926,7 +927,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
// —— 谁能使用:主人、允许名单、使用请求 ——
if (sub === "access" && m === "GET") {
const v = app.access.view(id);
- const owner = (ch: "weixin" | "feishu") => {
+ const owner = (ch: AccessChannel) => {
const o = v.owners[ch];
if (!o) return null;
const e = (o.entryId ? app.store.getAccessById(o.entryId) : undefined) ?? { channel: ch, peerId: o.peerId, senderId: o.peerId, name: "" };
@@ -934,7 +935,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
};
return send(res, 200, {
policy: v.policy,
- owners: { weixin: owner("weixin"), feishu: owner("feishu") },
+ owners: Object.fromEntries(ACCESS_CHANNELS.map((ch) => [ch, owner(ch)])),
requests: v.requests.map(publicAccess),
entries: v.entries.filter((e) => e.status !== "owner").map(publicAccess),
});
@@ -951,7 +952,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
// 更换主人:清掉"第一个发消息"的主人,下一个发单聊消息的人成为主人(扫码登录的微信要重新扫码)
if (seg[2] === "access" && seg[3] === "owner" && seg.length === 5 && m === "DELETE") {
const ch = seg[4];
- if (ch !== "weixin" && ch !== "feishu") throw new HttpError(404, tr("web.noSuchChannel"));
+ if (!isPushChannel(ch)) throw new HttpError(404, tr("web.noSuchChannel"));
if (app.access.owner(id, ch)?.via === "login") throw new HttpError(409, tr("web.weixinOwnerRescan"));
app.access.resetOwner(id, ch);
return send(res, 200, { ok: true });
@@ -978,6 +979,19 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
await app.restartBot(id);
return send(res, 200, app.channelStatus(id));
}
+ if (isMessenger(sub) && m === "PUT") {
+ try {
+ await app.connectMessenger(id, sub, await readJson(req));
+ } catch (e) {
+ if ((e as PlatformError).rejected) throw new HttpError(400, (e as Error).message);
+ throw e;
+ }
+ return send(res, 200, app.channelStatus(id));
+ }
+ if (isMessenger(sub) && m === "DELETE") {
+ await app.disconnectMessenger(id, sub);
+ return send(res, 200, app.channelStatus(id));
+ }
if (sub === "weixin" && m === "PUT") {
const b = await readJson(req);
app.store.updateBot(id, { weixinEnabled: !!b.enabled });
diff --git a/test/guide.unit.test.ts b/test/guide.unit.test.ts
index ec8a2a9..9a8e788 100644
--- a/test/guide.unit.test.ts
+++ b/test/guide.unit.test.ts
@@ -18,14 +18,14 @@ describe("引导进度", () => {
});
it("推导:有过回复、换过模型、绑了渠道、记下过东西", () => {
- const none = { conversations: [], bots: [], weixinBound: () => false, memoryCount: () => 0 };
+ const none = { conversations: [], bots: [], channelBound: () => false, memoryCount: () => 0 };
expect(deriveGuide(none)).toEqual([]);
expect(deriveGuide({ ...none, conversations: [{ messageCount: 1, model: "" }] })).toEqual([]);
expect(
deriveGuide({
conversations: [{ messageCount: 2, model: "" }],
bots: [{ id: "a", defaultModel: "gpt-x", feishuAppId: "" }, { id: "b", defaultModel: "", feishuAppId: "" }],
- weixinBound: (id) => id === "b",
+ channelBound: (id) => id === "b",
memoryCount: (id) => (id === "a" ? 1 : 0),
}),
).toEqual(["hello", "model", "weixin", "memory"]);
diff --git a/test/helpers.ts b/test/helpers.ts
index dba0900..5461924 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -2,6 +2,8 @@ import http from "node:http";
import crypto from "node:crypto";
import type { AddressInfo } from "node:net";
import { HistoryDenied, type FeishuMessageEvent, type FeishuTransport } from "../src/channels/feishu/transport.js";
+import { PlatformError, type MessengerMessage, type MessengerTransport, type StateFn } from "../src/channels/messenger/transport.js";
+import type { MessengerId } from "../src/core/types.js";
export async function listen(handler: http.RequestListener): Promise<{ url: string; port: number; close: () => Promise<void>; server: http.Server }> {
const server = http.createServer(handler);
@@ -417,3 +419,64 @@ export async function approveInBrowser(mf: Awaited<ReturnType<typeof mockModelfl
mf.s.pending.set(code, { challenge: u.searchParams.get("code_challenge")!, redirect });
return fetch(`${redirect}?code=${code}&state=${encodeURIComponent(u.searchParams.get("state")!)}`);
}
+
+/** 假的 Telegram / Slack / Discord 传输层:记下发出去的和改过的消息,按需让某一步失败 */
+export class FakeMessenger implements MessengerTransport {
+ readonly maxText: number;
+ sent: Array<{ chatId: string; text: string; id: string }> = [];
+ edits: Array<{ chatId: string; id: string; text: string }> = [];
+ files: Array<{ chatId: string; name: string }> = [];
+ typed = 0;
+ started = 0;
+ stopped = 0;
+ /** verify 时抛这个(凭据被拒) */
+ rejectVerify: string | undefined;
+ failEdit: Error | undefined;
+ onMessage: ((m: MessengerMessage) => void) | undefined;
+ onState: StateFn | undefined;
+ private n = 0;
+ constructor(
+ readonly id: MessengerId = "telegram",
+ maxText = 4000,
+ ) {
+ this.maxText = maxText;
+ }
+ async verify() {
+ if (this.rejectVerify) throw new PlatformError(this.rejectVerify, true);
+ return { name: "@fake_bot" };
+ }
+ async start(onMessage: (m: MessengerMessage) => void, onState: StateFn) {
+ this.started++;
+ this.onMessage = onMessage;
+ this.onState = onState;
+ onState("connected");
+ }
+ async stop() {
+ this.stopped++;
+ }
+ async sendText(chatId: string, text: string) {
+ const id = String(++this.n);
+ this.sent.push({ chatId, text, id });
+ return id;
+ }
+ async editText(chatId: string, id: string, text: string) {
+ if (this.failEdit) throw this.failEdit;
+ this.edits.push({ chatId, id, text });
+ }
+ async sendFile(chatId: string, _path: string, name: string) {
+ this.files.push({ chatId, name });
+ }
+ async typing() {
+ this.typed++;
+ }
+ /** 对方看到的最后一句:发出去的那条,或它改写后的样子 */
+ lastShown(chatId: string): string | undefined {
+ const last = this.sent.filter((s) => s.chatId === chatId).at(-1);
+ return last && (this.edits.filter((e) => e.id === last.id).at(-1)?.text ?? last.text);
+ }
+}
+
+/** 一条假的单聊消息 */
+export function messengerEvent(text: string, opts: Partial<MessengerMessage> = {}): MessengerMessage {
+ return { id: crypto.randomUUID(), chatId: "chat_1", dm: true, senderId: "user_1", senderName: "Ann", text, files: [], ...opts };
+}
diff --git a/test/messenger.e2e.test.ts b/test/messenger.e2e.test.ts
new file mode 100644
index 0000000..ca5d6d9
--- /dev/null
+++ b/test/messenger.e2e.test.ts
@@ -0,0 +1,187 @@
+/**
+ * Telegram、Slack、Discord 端到端:真实 App/Web(外部模型端点模式)+ 假传输层。
+ * 连接和断开、第一个发消息的人成为主人、陌生人被拦、群里的不处理、文件下载、主动通知。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { refusalText } from "../src/core/access.js";
+import type { MessengerId } from "../src/core/types.js";
+import { FakeMessenger, messengerEvent, mockOpenAI, until } from "./helpers.js";
+
+let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+let app: App;
+let base: string;
+const fakes = new Map<MessengerId, FakeMessenger>();
+/** 下一个新建的传输层检查凭据时被拒 */
+let rejectNext = "";
+const created: Array<{ id: MessengerId; credentials: Record<string, string> }> = [];
+
+async function api(p: string, init: { method?: string; body?: unknown } = {}) {
+ const res = await fetch(base + "/amb/api" + p, {
+ method: init.method ?? "GET",
+ headers: init.body !== undefined ? { "content-type": "application/json" } : {},
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ });
+ return { status: res.status, json: (await res.json().catch(() => ({}))) as any };
+}
+const channel = (id: MessengerId) => app.channels.get("default")!.messengers![id]!;
+const say = async (id: MessengerId, text: string, o: Parameters<typeof messengerEvent>[1] = {}) => {
+ fakes.get(id)!.onMessage!(messengerEvent(text, o));
+ await channel(id).idle();
+};
+
+beforeAll(async () => {
+ llm = await mockOpenAI({ key: "gw-key" });
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-messenger-e2e-"));
+ const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_AGENT: "off" } });
+ app = new App(config, {
+ printQrToTerminal: false,
+ messengerTransport: (id, _bot, credentials) => {
+ created.push({ id, credentials });
+ const f = new FakeMessenger(id);
+ if (rejectNext) {
+ f.rejectVerify = rejectNext;
+ rejectNext = "";
+ }
+ // 检查凭据和真正连上用的是两个对象:测试看最后建的那个
+ fakes.set(id, f);
+ return f;
+ },
+ });
+ await app.start();
+ base = app.web!.url.replace(/\/$/, "");
+});
+
+afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+});
+
+describe("连接", () => {
+ it("凭据被拒:报错、不保存", async () => {
+ rejectNext = "telegram getMe: 401 Unauthorized";
+ const r = await api("/bots/default/telegram", { method: "PUT", body: { token: "bad" } });
+ expect(r.status).toBe(400);
+ expect(r.json.error ?? r.json.message).toContain("401");
+ expect(app.store.getMessengerAccount("default", "telegram")).toBeUndefined();
+ });
+
+ it("没填全:报错", async () => {
+ const r = await api("/bots/default/slack", { method: "PUT", body: { botToken: "xoxb-1" } });
+ expect(r.status).toBe(400);
+ });
+
+ it("连上:状态在线、显示平台上的名字;状态里没有完整的 token", async () => {
+ const r = await api("/bots/default/telegram", { method: "PUT", body: { token: "123456:SECRETSECRETSECRET" } });
+ expect(r.status).toBe(200);
+ await until(async () => (await api("/bots/default/channels")).json.telegram.state === "connected");
+ const st = (await api("/bots/default/channels")).json;
+ expect(st.telegram.account.name).toBe("@fake_bot");
+ expect(JSON.stringify(st)).not.toContain("SECRETSECRETSECRET");
+ expect(st.discord.state).toBe("disabled");
+ expect(st.feishu).toBeDefined();
+ expect(JSON.stringify((await api("/bots/default")).json)).not.toContain("SECRETSECRETSECRET");
+ });
+
+ it("不是平台的路径不受理;Slack 留空的 token 沿用已保存的", async () => {
+ await api("/bots/default/slack", { method: "PUT", body: { botToken: "xoxb-1", appToken: "xapp-1" } });
+ created.length = 0;
+ expect((await api("/bots/default/slack", { method: "PUT", body: { appToken: "xapp-2" } })).status).toBe(200);
+ expect(created.at(-1)).toMatchObject({ id: "slack", credentials: { botToken: "xoxb-1", appToken: "xapp-2" } });
+ await api("/bots/default/slack", { method: "DELETE" });
+ });
+
+ it("重启后接着连(凭据在库里);stopBot 会停掉", async () => {
+ const before = fakes.get("telegram")!;
+ await app.restartBot("default");
+ expect(before.stopped).toBe(1);
+ expect(fakes.get("telegram")).not.toBe(before);
+ expect(fakes.get("telegram")!.started).toBe(1);
+ });
+});
+
+describe("对话", () => {
+ it("第一个发消息的人成为主人,流式显示并写成最终回复", async () => {
+ expect((await api("/bots/default/access")).json.owners.telegram).toBeNull();
+ await say("telegram", "我是老板", { chatId: "boss", senderId: "boss", senderName: "Boss" });
+ expect(fakes.get("telegram")!.lastShown("boss")).toBe("[mock-a] 你说:我是老板");
+ expect((await api("/bots/default/access")).json.owners.telegram).toEqual({ via: "first-message", peer: "boss", name: "Boss" });
+ const conv = app.store.getConversation("default:telegram:boss");
+ expect(conv?.channel).toBe("telegram");
+ });
+
+ it("陌生人:只回一句、不碰模型;主人收到配对码,回复后对方能用", async () => {
+ const f = fakes.get("telegram")!;
+ const asked = llm.calls.length;
+ await say("telegram", "让我用用", { chatId: "guest", senderId: "guest", senderName: "Guest" });
+ expect(f.lastShown("guest")).toBe(refusalText());
+ expect(llm.calls.length).toBe(asked);
+ const notice = f.sent.filter((s) => s.chatId === "boss").at(-1)!.text;
+ const code = /\d{4}/.exec(notice)![0];
+ await say("telegram", `同意 ${code}`, { chatId: "boss", senderId: "boss" });
+ await until(() => f.sent.some((s) => s.chatId === "guest" && s.text !== refusalText()));
+ await say("telegram", "现在呢", { chatId: "guest", senderId: "guest" });
+ expect(f.lastShown("guest")).toBe("[mock-a] 你说:现在呢");
+ });
+
+ it("群里的消息不处理(不回复、不碰模型);重复投递只处理一次", async () => {
+ const f = fakes.get("telegram")!;
+ const asked = llm.calls.length;
+ const sent = f.sent.length;
+ await say("telegram", "群里说话", { chatId: "group", senderId: "boss", dm: false });
+ expect(f.sent.length).toBe(sent);
+ expect(llm.calls.length).toBe(asked);
+ await say("telegram", "一次", { id: "dup", chatId: "boss", senderId: "boss" });
+ const n = llm.calls.length;
+ await say("telegram", "一次", { id: "dup", chatId: "boss", senderId: "boss" });
+ expect(llm.calls.length).toBe(n);
+ });
+
+ it("收到的文件下载好交给运行时;下载失败时消息照常处理并说明原因", async () => {
+ let downloaded = 0;
+ const ok = { type: "file" as const, name: "报告.txt", download: async () => (downloaded++, Buffer.from("内容")) };
+ const bad = { type: "file" as const, name: "坏.txt", download: async () => { throw new Error("HTTP 500"); } };
+ await say("telegram", "看看", { chatId: "boss", senderId: "boss", files: [ok, bad] });
+ const last = String(llm.calls.at(-1)!.messages.at(-1)?.content);
+ expect(downloaded).toBe(1);
+ expect(last).toContain("[文件 报告.txt]");
+ expect(last).toContain("HTTP 500");
+ });
+
+ it("主动通知经出站队列发到主人;更换主人后下一个发消息的人成为主人", async () => {
+ const f = fakes.get("telegram")!;
+ expect(await app.pushToOwner("余额不足")).toBe(true);
+ await channel("telegram").idle();
+ expect(f.lastShown("boss")).toContain("余额不足");
+ expect((await api("/bots/default/access/owner/telegram", { method: "DELETE" })).status).toBe(200);
+ await say("telegram", "换我", { chatId: "new", senderId: "new", senderName: "New" });
+ expect((await api("/bots/default/access")).json.owners.telegram).toMatchObject({ peer: "new" });
+ });
+
+ it("断开:渠道停下、凭据清掉、主人清掉", async () => {
+ const f = fakes.get("telegram")!;
+ expect((await api("/bots/default/telegram", { method: "DELETE" })).status).toBe(200);
+ expect(f.stopped).toBe(1);
+ expect(app.store.getMessengerAccount("default", "telegram")).toBeUndefined();
+ const st = (await api("/bots/default/channels")).json;
+ expect(st.telegram.state).toBe("disabled");
+ expect(st.telegram.account).toBeUndefined();
+ expect((await api("/bots/default/access")).json.owners.telegram).toBeNull();
+ });
+});
+
+describe("连不上(凭据失效)", () => {
+ it("信息面板显示原因", async () => {
+ await api("/bots/default/discord", { method: "PUT", body: { token: "t" } });
+ const f = fakes.get("discord")!;
+ await until(() => !!f.onState);
+ f.onState!("error", "the bot token was rejected", true);
+ const st = (await api("/bots/default/channels")).json.discord;
+ expect(st).toMatchObject({ state: "error", detail: "the bot token was rejected" });
+ });
+});
+
diff --git a/test/messenger.unit.test.ts b/test/messenger.unit.test.ts
new file mode 100644
index 0000000..6808fe7
--- /dev/null
+++ b/test/messenger.unit.test.ts
@@ -0,0 +1,559 @@
+/**
+ * Telegram、Slack、Discord:格式转换、切段、出站发送、流式回复,以及三个传输层对平台接口的用法。
+ * 平台都是本地假的(假 fetch、本地 WebSocket 服务器);没有连过真实平台。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type { AddressInfo } from "node:net";
+import { WebSocketServer, type WebSocket } from "ws";
+import { afterEach, describe, expect, it } from "vitest";
+import { MessengerReply, deliverMessenger, messengerParts } from "../src/channels/messenger/channel.js";
+import { DiscordTransport, discordMessage } from "../src/channels/messenger/discord.js";
+import { fenceTables, splitMarkdown, toSlackMrkdwn, toTelegramHtml } from "../src/channels/messenger/format.js";
+import { SlackTransport, slackMessage } from "../src/channels/messenger/slack.js";
+import { TelegramTransport, telegramMessage } from "../src/channels/messenger/telegram.js";
+import { PlatformError, type MessengerMessage } from "../src/channels/messenger/transport.js";
+import type { OutboxRow } from "../src/store/db.js";
+import { FakeMessenger, listen, messengerEvent, until } from "./helpers.js";
+
+const noDownload = async () => Buffer.alloc(0);
+const row = (o: Partial<OutboxRow>) => ({ id: "r1", kind: "text", peerId: "c1", replyTo: "", progress: 0, attempts: 0, body: {}, ...o }) as OutboxRow;
+
+describe("格式转换", () => {
+ it("Telegram:常见的 Markdown 转成 HTML,尖括号转义,代码里的星号不算强调", () => {
+ expect(toTelegramHtml("# 标题\n**粗** *斜* ~~删~~ `a*b*c`")).toBe("<b>标题</b>\n<b>粗</b> <i>斜</i> <s>删</s> <code>a*b*c</code>");
+ expect(toTelegramHtml("a < b & c > d")).toBe("a &lt; b &amp; c &gt; d");
+ expect(toTelegramHtml("- 一\n- 二")).toBe("• 一\n• 二");
+ expect(toTelegramHtml("[官网](https://anymodel.bot/)")).toBe('<a href="https://anymodel.bot/">官网</a>');
+ expect(toTelegramHtml("```ts\nconst a = 1 < 2;\n```\n之后")).toBe("<pre>const a = 1 &lt; 2;</pre>\n之后");
+ });
+
+ it("Telegram:没关上的代码块算到结尾(流式显示时常见);变量名里的下划线不算斜体", () => {
+ expect(toTelegramHtml("开始\n```\ncode")).toBe("开始\n<pre>code</pre>");
+ expect(toTelegramHtml("snake_case_name 和 2*3*4")).toBe("snake_case_name 和 2*3*4");
+ });
+
+ it("Slack:粗体是单星号、斜体是下划线、链接是 <url|文字>,不把粗体再转成斜体", () => {
+ expect(toSlackMrkdwn("**粗** *斜* ~~删~~")).toBe("*粗* _斜_ ~删~");
+ expect(toSlackMrkdwn("## 标题")).toBe("*标题*");
+ expect(toSlackMrkdwn("[官网](https://anymodel.bot/)")).toBe("<https://anymodel.bot/|官网>");
+ expect(toSlackMrkdwn("a<b & `x**y**`")).toBe("a&lt;b &amp; `x**y**`");
+ expect(toSlackMrkdwn("```js\nlet a;\n```")).toBe("```\nlet a;\n```");
+ });
+
+ it("表格放进代码块,代码块里的不动", () => {
+ expect(fenceTables("前\n| a | b |\n|---|---|\n| 1 | 2 |\n后")).toBe("前\n```\n| a | b |\n|---|---|\n| 1 | 2 |\n```\n后");
+ const inCode = "```\n| a | b |\n|---|---|\n```";
+ expect(fenceTables(inCode)).toBe(inCode);
+ expect(fenceTables("a | b\nc | d")).toBe("a | b\nc | d");
+ });
+
+ it("切段:每段不超上限;切在代码块中间时收好这段、下一段重新打开;同样的文字切法不变", () => {
+ const text = "```ts\n" + Array.from({ length: 80 }, (_, i) => `line ${i}`).join("\n") + "\n```\n\n结尾";
+ const chunks = splitMarkdown(text, 200);
+ expect(chunks.length).toBeGreaterThan(2);
+ for (const c of chunks) {
+ expect(c.length).toBeLessThanOrEqual(200);
+ expect((c.match(/^```/gm) ?? []).length % 2).toBe(0);
+ }
+ expect(chunks[1].startsWith("```ts\n")).toBe(true);
+ expect(chunks.at(-1)).toContain("结尾");
+ expect(splitMarkdown(text, 200)).toEqual(chunks);
+ expect(splitMarkdown("", 200)).toEqual([]);
+ });
+});
+
+describe("出站发送", () => {
+ it("有流式消息:第一段改写它,后面几段发新消息,都记下进度", async () => {
+ const t = new FakeMessenger("telegram", 100);
+ const done: number[] = [];
+ await deliverMessenger(t, row({ body: { text: "第一段".repeat(20) + "\n\n" + "第二段".repeat(20), editId: "9" } }), (n) => done.push(n));
+ expect(t.edits).toHaveLength(1);
+ expect(t.edits[0].id).toBe("9");
+ expect(t.sent).toHaveLength(1);
+ expect(done).toEqual([1, 2]);
+ });
+
+ it("崩溃后重发:从下一段接着发,不再改写", async () => {
+ const t = new FakeMessenger("telegram", 100);
+ await deliverMessenger(t, row({ progress: 1, body: { text: "第一段".repeat(20) + "\n\n" + "第二段".repeat(20), editId: "9" } }), () => {});
+ expect(t.edits).toEqual([]);
+ expect(t.sent.map((s) => s.text.slice(0, 3))).toEqual(["第二段"]);
+ });
+
+ it("流式消息改不了了(平台拒绝):发新的;网络问题:抛出去,出站队列会重试", async () => {
+ const t = new FakeMessenger();
+ t.failEdit = new PlatformError("message to edit not found", true);
+ await deliverMessenger(t, row({ body: { text: "答案", editId: "9" } }), () => {});
+ expect(t.sent.map((s) => s.text)).toEqual(["答案"]);
+
+ const t2 = new FakeMessenger();
+ t2.failEdit = new Error("fetch failed");
+ await expect(deliverMessenger(t2, row({ body: { text: "答案", editId: "9" } }), () => {})).rejects.toThrow("fetch failed");
+ expect(t2.sent).toEqual([]);
+ });
+
+ it("文件发不出去:网络问题先重试,平台拒绝直接改发一句说明", async () => {
+ const t = new FakeMessenger();
+ t.sendFile = async () => {
+ throw new Error("socket hang up");
+ };
+ const r = row({ kind: "file", body: { path: "/x.pdf", name: "x.pdf" } });
+ await expect(deliverMessenger(t, r, () => {})).rejects.toThrow("socket hang up");
+ await deliverMessenger(t, { ...r, attempts: 2 }, () => {});
+ expect(t.sent[0].text).toContain("x.pdf");
+
+ const t2 = new FakeMessenger();
+ t2.sendFile = async () => {
+ throw new PlatformError("too big", true);
+ };
+ await deliverMessenger(t2, r, () => {});
+ expect(t2.sent[0].text).toContain("x.pdf");
+ });
+});
+
+describe("流式回复", () => {
+ it("等第一句话时只显示正在输入;开始说话后发一条再改写;结束时写成最终回复,不多发消息", async () => {
+ const t = new FakeMessenger();
+ const r = new MessengerReply(t, "c1", 5);
+ await r.apply({ type: "typing", on: true });
+ expect(t.typed).toBe(1);
+ await r.apply({ type: "stream.start" });
+ expect(t.sent).toEqual([]);
+ await r.apply({ type: "stream.update", text: "你" });
+ await until(() => t.sent.length === 1);
+ await r.apply({ type: "stream.update", text: "你好" });
+ await until(() => t.edits.length === 1);
+ await r.apply({ type: "stream.finish", text: "你好,世界" });
+ await r.apply({ type: "typing", on: false });
+ expect(t.sent).toHaveLength(1);
+ expect(t.lastShown("c1")).toBe("你好,世界");
+ });
+
+ it("没有正在输入的平台:先发一条占位,最终回复改写它", async () => {
+ const t = new FakeMessenger("slack");
+ t.typing = undefined as never;
+ const r = new MessengerReply(t, "c1", 5);
+ await r.apply({ type: "stream.start" });
+ await until(() => t.sent.length === 1);
+ expect(t.sent[0].text).toBe("…");
+ await r.apply({ type: "stream.finish", text: "答案" });
+ expect(t.sent).toHaveLength(1);
+ expect(t.lastShown("c1")).toBe("答案");
+ });
+
+ it("回合中间说的话留在最终回复前面;最后一句和回复一样时不重复", async () => {
+ const t = new FakeMessenger();
+ const r = new MessengerReply(t, "c1", 100_000);
+ await r.apply({ type: "interim", text: "先看看" });
+ await r.apply({ type: "interim", text: "看完了" });
+ await r.apply({ type: "stream.finish", text: "看完了" });
+ expect(t.sent.map((s) => s.text)).toEqual(["先看看\n\n看完了"]);
+ });
+
+ it("审批提示发文字", async () => {
+ const t = new FakeMessenger();
+ await new MessengerReply(t, "c1", 5).apply({ type: "interactive", kind: "ask_user", prompt: "选哪个", options: ["甲", "乙"] });
+ expect(t.sent[0].text).toContain("1. 甲");
+ });
+});
+
+describe("收到的消息", () => {
+ it("引用、文字、文件变成 parts;图片按文件头认格式;下载失败写明原因;语音不下载", () => {
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1]);
+ const img = { type: "image" as const, download: noDownload };
+ const bad = { type: "file" as const, name: "a.pdf", download: noDownload };
+ const voice = { type: "voice" as const, download: noDownload };
+ const m = messengerEvent("看图", { quote: "原话", files: [img, bad, voice] });
+ expect(messengerParts(m, new Map<any, Buffer | Error>([[img, png], [bad, new Error("too big")]]))).toEqual([
+ { type: "quote", text: "原话" },
+ { type: "text", text: "看图" },
+ { type: "image", data: png, mime: "image/png" },
+ { type: "file", name: "a.pdf", error: "too big" },
+ { type: "voice" },
+ ]);
+ });
+
+ it("Telegram:取最大的照片;/start 换成 /help;群里的标出来;贴纸说明不支持", async () => {
+ const got: string[] = [];
+ const base = { message_id: 7, chat: { id: 42, type: "private" }, from: { id: 1, first_name: "Ann", last_name: "Lee" } };
+ const m = telegramMessage({ message: { ...base, caption: "这张", photo: [{ file_id: "small" }, { file_id: "big" }] } }, async (id) => (got.push(id), Buffer.alloc(0)))!;
+ expect(m).toMatchObject({ id: "42:7", chatId: "42", dm: true, senderId: "1", senderName: "Ann Lee", text: "这张" });
+ await m.files[0].download();
+ expect(got).toEqual(["big"]);
+ expect(telegramMessage({ message: { ...base, text: "/start" } }, noDownload)!.text).toBe("/help");
+ expect(telegramMessage({ message: { ...base, text: "/startup 别动" } }, noDownload)!.text).toBe("/startup 别动");
+ expect(telegramMessage({ message: { ...base, chat: { id: -5, type: "group" }, text: "hi" } }, noDownload)!.dm).toBe(false);
+ expect(telegramMessage({ message: { ...base, sticker: { file_id: "s" } } }, noDownload)!.unsupported).toBe("sticker");
+ expect(telegramMessage({ message: { ...base, text: "好", reply_to_message: { text: "结果" } } }, noDownload)!.quote).toBe("结果");
+ expect(telegramMessage({ message: { ...base, from: { id: 2, is_bot: true }, text: "x" } }, noDownload)).toBeUndefined();
+ expect(telegramMessage({ edited_message: {} }, noDownload)).toBeUndefined();
+ });
+
+ it("Slack:只认真人发的;带文件的消息照收;频道里的不算单聊", () => {
+ const ev = { type: "message", channel: "D1", channel_type: "im", user: "U1", ts: "1.2", text: "hi" };
+ expect(slackMessage(ev, noDownload)).toMatchObject({ id: "D1:1.2", chatId: "D1", dm: true, senderId: "U1", text: "hi" });
+ expect(slackMessage({ ...ev, bot_id: "B1" }, noDownload)).toBeUndefined();
+ expect(slackMessage({ ...ev, subtype: "message_changed" }, noDownload)).toBeUndefined();
+ expect(slackMessage({ ...ev, channel_type: "channel" }, noDownload)!.dm).toBe(false);
+ const f = slackMessage({ ...ev, subtype: "file_share", files: [{ name: "a.png", mimetype: "image/png", url_private_download: "u" }, { name: "b.pdf", mimetype: "application/pdf", url_private: "v" }] }, noDownload)!;
+ expect(f.files.map((x) => [x.type, x.name])).toEqual([["image", undefined], ["file", "b.pdf"]]);
+ });
+
+ it("Discord:服务器里的不算单聊;机器人发的跳过;回复带原文", () => {
+ const d = { id: "9", channel_id: "C1", author: { id: "U1", global_name: "Ann" }, content: "hi", attachments: [] };
+ expect(discordMessage(d, noDownload)).toMatchObject({ id: "9", chatId: "C1", dm: true, senderId: "U1", senderName: "Ann", text: "hi" });
+ expect(discordMessage({ ...d, guild_id: "G" }, noDownload)!.dm).toBe(false);
+ expect(discordMessage({ ...d, author: { id: "B", bot: true } }, noDownload)).toBeUndefined();
+ expect(discordMessage({ ...d, referenced_message: { content: "结果" } }, noDownload)!.quote).toBe("结果");
+ expect(discordMessage({ ...d, attachments: [{ url: "u", filename: "a.mp4", content_type: "video/mp4" }] }, noDownload)!.files[0].type).toBe("video");
+ });
+});
+
+/** 假 fetch:按方法名回结果,记下每次调用 */
+function fakeTelegram(handler: (method: string, body: any) => any) {
+ const calls: Array<{ method: string; body: any }> = [];
+ const impl = (async (url: string, init?: RequestInit) => {
+ const method = String(url).split("/").at(-1)!;
+ const body = typeof init?.body === "string" ? JSON.parse(init.body) : init?.body;
+ calls.push({ method, body });
+ const out = await handler(method, body);
+ if (out?.__wait) await new Promise((_, rej) => init?.signal?.addEventListener("abort", () => rej(new Error("aborted"))));
+ return new Response(JSON.stringify(out?.error ? { ok: false, error_code: out.error, description: out.description ?? "" } : { ok: true, result: out }), { status: out?.error ?? 200 });
+ }) as unknown as typeof fetch;
+ return { calls, impl };
+}
+
+describe("Telegram 传输层", () => {
+ it("长轮询:收到的消息交出去,收取位置存下;下次从那里接着收;stop 能打断长轮询", async () => {
+ let offset = 0;
+ let batch: any[] = [{ update_id: 10, message: { message_id: 1, chat: { id: 5, type: "private" }, from: { id: 5, first_name: "A" }, text: "你好" } }];
+ const { calls, impl } = fakeTelegram((m) => {
+ if (m !== "getUpdates") return true;
+ const b = batch;
+ batch = [];
+ return b.length ? b : { __wait: true };
+ });
+ const t = new TelegramTransport("TOKEN", { fetchImpl: impl, offset: { get: () => offset, set: (n) => (offset = n) } });
+ const got: MessengerMessage[] = [];
+ const states: string[] = [];
+ await t.start((m) => got.push(m), (s) => states.push(s));
+ await until(() => got.length === 1);
+ expect(got[0].text).toBe("你好");
+ await until(() => offset === 11);
+ await until(() => calls.filter((c) => c.method === "getUpdates").at(-1)!.body.offset === 11);
+ expect(states).toContain("connected");
+ expect(calls[0].method).toBe("deleteWebhook");
+ await t.stop();
+ });
+
+ it("token 失效:报告一次、不再重试;另一个实例在收(409):报错但继续试", async () => {
+ const { impl } = fakeTelegram(() => ({ error: 401, description: "Unauthorized" }));
+ const t = new TelegramTransport("BAD", { fetchImpl: impl });
+ const states: Array<[string, boolean | undefined]> = [];
+ await t.start(() => {}, (s, _d, fatal) => states.push([s, fatal]));
+ await until(() => states.some(([, f]) => f));
+ expect(states.at(-1)).toEqual(["error", true]);
+ await t.stop();
+
+ let n = 0;
+ const { impl: conflict } = fakeTelegram((m) => (m === "getUpdates" ? (++n < 3 ? { error: 409, description: "Conflict" } : { __wait: true }) : true));
+ const t2 = new TelegramTransport("T", { fetchImpl: conflict, backoffMs: [1] });
+ await t2.start(() => {}, () => {});
+ await until(() => n >= 3);
+ await t2.stop();
+ });
+
+ it("发消息:先用 HTML,格式不被接受时发原文;改写内容没变不算错;平台拒绝和限流分得开", async () => {
+ let first = true;
+ const { calls, impl } = fakeTelegram((m, b) => {
+ if (m === "sendMessage" && b.parse_mode && first) {
+ first = false;
+ return { error: 400, description: "Bad Request: can't parse entities" };
+ }
+ if (m === "editMessageText") return { error: 400, description: "Bad Request: message is not modified" };
+ return { message_id: 33 };
+ });
+ const t = new TelegramTransport("T", { fetchImpl: impl });
+ expect(await t.sendText("5", "**粗")).toBe("33");
+ expect(calls.map((c) => [c.body.text, c.body.parse_mode])).toEqual([["**粗", "HTML"], ["**粗", undefined]]);
+ await t.editText("5", "33", "同样的");
+
+ const reject = new TelegramTransport("T", { fetchImpl: fakeTelegram(() => ({ error: 403, description: "bot was blocked" })).impl });
+ await expect(reject.sendText("5", "x")).rejects.toMatchObject({ rejected: true });
+ const limit = new TelegramTransport("T", { fetchImpl: fakeTelegram(() => ({ error: 429, description: "Too Many Requests" })).impl });
+ await expect(limit.sendText("5", "x")).rejects.toMatchObject({ rejected: false });
+ });
+
+ it("文件:图片走 sendPhoto,其他走 sendDocument;下载经 getFile", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tg-"));
+ const f = path.join(dir, "a.bin");
+ fs.writeFileSync(f, "x");
+ const { calls, impl } = fakeTelegram(() => ({ message_id: 1 }));
+ const t = new TelegramTransport("T", { fetchImpl: impl });
+ await t.sendFile("5", f, "图.png");
+ await t.sendFile("5", f, "报告.pdf");
+ expect(calls.map((c) => c.method)).toEqual(["sendPhoto", "sendDocument"]);
+ expect((calls[0].body as FormData).get("chat_id")).toBe("5");
+ expect(((calls[1].body as FormData).get("document") as File).name).toBe("报告.pdf");
+ });
+});
+
+/** 本地 WebSocket 服务器 */
+async function wsServer(onConn: (s: WebSocket, nth: number) => void) {
+ const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });
+ await new Promise((r) => wss.once("listening", r));
+ let n = 0;
+ wss.on("connection", (s) => onConn(s, ++n));
+ return {
+ url: `ws://127.0.0.1:${(wss.address() as AddressInfo).port}`,
+ close: () => new Promise((r) => (wss.clients.forEach((c) => c.terminate()), wss.close(r))),
+ };
+}
+
+const cleanups: Array<() => Promise<unknown>> = [];
+afterEach(async () => {
+ for (const c of cleanups.splice(0)) await c();
+});
+
+describe("Slack 传输层", () => {
+ const event = (n: number) => ({ envelope_id: `e${n}`, type: "events_api", payload: { event: { type: "message", channel: "D1", channel_type: "im", user: "U1", ts: `${n}.0`, text: `消息${n}` } } });
+
+ async function slackApi(ws: string, over: Record<string, any> = {}) {
+ const calls: Array<{ method: string; body: string; auth?: string }> = [];
+ const http = await listen(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ const method = req.url!.split("/").at(-1)!;
+ calls.push({ method, body: Buffer.concat(chunks).toString(), auth: req.headers.authorization });
+ const out = over[method] ?? (method === "apps.connections.open" ? { ok: true, url: ws } : method === "auth.test" ? { ok: true, user: "bot", team: "T" } : { ok: true, ts: "1.5" });
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(out));
+ });
+ cleanups.push(http.close);
+ return { calls, http };
+ }
+
+ it("连上:hello 之后算在线;每个事件都回执;Slack 要换连接时重连", async () => {
+ const acks: string[] = [];
+ const srv = await wsServer((s, nth) => {
+ s.on("message", (raw) => acks.push(JSON.parse(raw.toString()).envelope_id));
+ s.send(JSON.stringify({ type: "hello" }));
+ s.send(JSON.stringify(event(nth)));
+ if (nth === 1) s.send(JSON.stringify({ type: "disconnect", reason: "refresh_requested" }));
+ });
+ cleanups.push(srv.close);
+ const { http, calls } = await slackApi(srv.url);
+ const t = new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url, reconnectMs: [1] });
+ const got: MessengerMessage[] = [];
+ const states: string[] = [];
+ await t.start((m) => got.push(m), (s) => states.push(s));
+ await until(() => got.length === 2);
+ expect(got.map((m) => m.text)).toEqual(["消息1", "消息2"]);
+ await until(() => acks.length === 2);
+ expect(acks).toEqual(["e1", "e2"]);
+ expect(states.filter((s) => s === "connected")).toHaveLength(2);
+ expect(calls.filter((c) => c.method === "apps.connections.open").every((c) => c.auth === "Bearer xapp-1")).toBe(true);
+ await t.stop();
+ });
+
+ it("连接断了但没报错(pong 不回):自己发现并重连", async () => {
+ let conns = 0;
+ const srv = await wsServer((s) => {
+ conns++;
+ // 不回 pong:ws 默认自动回,这里关掉底层的自动回应
+ (s as any)._receiver.removeAllListeners("ping");
+ s.send(JSON.stringify({ type: "hello" }));
+ });
+ cleanups.push(srv.close);
+ const { http } = await slackApi(srv.url);
+ const t = new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url, reconnectMs: [1], pingMs: 10 });
+ await t.start(() => {}, () => {});
+ await until(() => conns >= 2);
+ await t.stop();
+ });
+
+ it("app token 失效或没开 Socket Mode:提示一次,不一直重连", async () => {
+ const { http } = await slackApi("ws://unused", { "apps.connections.open": { ok: false, error: "invalid_auth" } });
+ const t = new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url, reconnectMs: [1] });
+ const seen: Array<[string, boolean | undefined]> = [];
+ await t.start(() => {}, (s, _d, f) => seen.push([s, f]));
+ await until(() => seen.some(([, f]) => f));
+ expect(seen.at(-1)).toEqual(["error", true]);
+ await t.stop();
+ });
+
+ it("检查凭据:token 填反了直接说;机器人名字取自 auth.test", async () => {
+ const { http } = await slackApi("ws://unused");
+ await expect(new SlackTransport("xapp-1", "xoxb-1", { baseUrl: http.url }).verify()).rejects.toMatchObject({ rejected: true });
+ expect(await new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url }).verify()).toEqual({ name: "@bot · T" });
+ });
+
+ it("发消息转成 mrkdwn;限流算暂时的;平台拒绝的不重试", async () => {
+ const { http, calls } = await slackApi("ws://unused");
+ const t = new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url });
+ expect(await t.sendText("D1", "**粗**")).toBe("1.5");
+ expect(JSON.parse(calls[0].body)).toMatchObject({ channel: "D1", text: "*粗*" });
+ await t.editText("D1", "1.5", "改");
+ expect(calls[1].method).toBe("chat.update");
+ const { http: bad } = await slackApi("ws://unused", { "chat.postMessage": { ok: false, error: "channel_not_found" } });
+ await expect(new SlackTransport("xoxb-1", "xapp-1", { baseUrl: bad.url }).sendText("D1", "x")).rejects.toMatchObject({ rejected: true });
+ const { http: slow } = await slackApi("ws://unused", { "chat.postMessage": { ok: false, error: "ratelimited" } });
+ await expect(new SlackTransport("xoxb-1", "xapp-1", { baseUrl: slow.url }).sendText("D1", "x")).rejects.toMatchObject({ rejected: false });
+ });
+
+ it("没有 files:read 时 Slack 返回登录页:说清楚,不把网页存成图片", async () => {
+ const http = await listen((_req, res) => res.writeHead(200, { "content-type": "text/html" }).end("<html>"));
+ cleanups.push(http.close);
+ const t = new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url });
+ await expect((t as any).download(http.url + "/f")).rejects.toThrow("files:read");
+ });
+
+ it("上传文件分三步:要地址、传上去、发到会话", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-slack-"));
+ const f = path.join(dir, "a.txt");
+ fs.writeFileSync(f, "hello");
+ const up = await listen((req, res) => {
+ void req.resume();
+ res.writeHead(200).end("OK");
+ });
+ cleanups.push(up.close);
+ const { http, calls } = await slackApi("ws://unused", { "files.getUploadURLExternal": { ok: true, upload_url: up.url + "/u", file_id: "F1" } });
+ await new SlackTransport("xoxb-1", "xapp-1", { baseUrl: http.url }).sendFile("D1", f, "a.txt");
+ expect(calls.map((c) => c.method)).toEqual(["files.getUploadURLExternal", "files.completeUploadExternal"]);
+ expect(calls[0].body).toBe("filename=a.txt&length=5");
+ expect(JSON.parse(calls[1].body)).toEqual({ files: [{ id: "F1", title: "a.txt" }], channel_id: "D1" });
+ });
+});
+
+describe("Discord 传输层", () => {
+ const hello = (s: WebSocket, ms = 60_000) => s.send(JSON.stringify({ op: 10, d: { heartbeat_interval: ms } }));
+ const message = (n: number, d: Record<string, unknown> = {}) => ({ op: 0, s: n, t: "MESSAGE_CREATE", d: { id: String(n), channel_id: "C1", author: { id: "U1", username: "ann" }, content: `消息${n}`, ...d } });
+
+ it("登录:只要单聊的 intent;READY 算在线;消息交出去", async () => {
+ const sent: any[] = [];
+ const srv = await wsServer((s) => {
+ s.on("message", (raw) => {
+ const p = JSON.parse(raw.toString());
+ sent.push(p);
+ if (p.op === 2) {
+ s.send(JSON.stringify({ op: 0, s: 1, t: "READY", d: { session_id: "S", resume_gateway_url: "ws://unused" } }));
+ s.send(JSON.stringify(message(2)));
+ }
+ });
+ hello(s);
+ });
+ cleanups.push(srv.close);
+ const t = new DiscordTransport("TOK", { gatewayUrl: srv.url });
+ const got: MessengerMessage[] = [];
+ const states: string[] = [];
+ await t.start((m) => got.push(m), (s) => states.push(s));
+ await until(() => got.length === 1);
+ expect(got[0]).toMatchObject({ text: "消息2", dm: true });
+ expect(sent[0]).toMatchObject({ op: 2, d: { token: "TOK", intents: 4096 } });
+ expect(states).toContain("connected");
+ await t.stop();
+ });
+
+ it("平台要换连接(op 7):重连后带着会话和序号 RESUME,不重新登录", async () => {
+ const seen: any[] = [];
+ let url = "";
+ const srv = await wsServer((s, nth) => {
+ s.on("message", (raw) => {
+ const p = JSON.parse(raw.toString());
+ seen.push(p);
+ if (p.op === 2) {
+ s.send(JSON.stringify({ op: 0, s: 5, t: "READY", d: { session_id: "S", resume_gateway_url: url } }));
+ s.send(JSON.stringify({ op: 7, d: null }));
+ }
+ if (p.op === 6) s.send(JSON.stringify({ op: 0, s: 6, t: "RESUMED", d: null }));
+ });
+ hello(s);
+ void nth;
+ });
+ url = srv.url;
+ cleanups.push(srv.close);
+ const t = new DiscordTransport("TOK", { gatewayUrl: srv.url, reconnectMs: [1] });
+ await t.start(() => {}, () => {});
+ await until(() => seen.some((p) => p.op === 6));
+ expect(seen.find((p) => p.op === 6).d).toEqual({ token: "TOK", session_id: "S", seq: 5 });
+ expect(seen.filter((p) => p.op === 2)).toHaveLength(1);
+ await t.stop();
+ });
+
+ it("会话失效(op 9,不能接上):重新登录", async () => {
+ const ops: number[] = [];
+ let n = 0;
+ const srv = await wsServer((s) => {
+ s.on("message", (raw) => {
+ const p = JSON.parse(raw.toString());
+ ops.push(p.op);
+ if (p.op === 2 && ++n === 1) s.send(JSON.stringify({ op: 9, d: false }));
+ });
+ hello(s);
+ });
+ cleanups.push(srv.close);
+ const t = new DiscordTransport("TOK", { gatewayUrl: srv.url, reconnectMs: [1] });
+ await t.start(() => {}, () => {});
+ await until(() => ops.filter((o) => o === 2).length === 2);
+ await t.stop();
+ });
+
+ it("心跳没有回应:断开重连", async () => {
+ let conns = 0;
+ const srv = await wsServer((s) => {
+ conns++;
+ hello(s, 5);
+ });
+ cleanups.push(srv.close);
+ const t = new DiscordTransport("TOK", { gatewayUrl: srv.url, reconnectMs: [1] });
+ await t.start(() => {}, () => {});
+ await until(() => conns >= 2);
+ await t.stop();
+ });
+
+ it("token 不对(关闭码 4004):提示一次,不再重连", async () => {
+ let conns = 0;
+ const srv = await wsServer((s) => {
+ conns++;
+ s.close(4004, "Authentication failed");
+ });
+ cleanups.push(srv.close);
+ const t = new DiscordTransport("BAD", { gatewayUrl: srv.url, reconnectMs: [1] });
+ const seen: Array<[string, boolean | undefined]> = [];
+ await t.start(() => {}, (s, _d, f) => seen.push([s, f]));
+ await until(() => seen.some(([, f]) => f));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(conns).toBe(1);
+ await t.stop();
+ });
+
+ it("发消息:带 nonce 防重复,不让 @ 提醒到人;表格放进代码块;错误分得开", async () => {
+ const calls: Array<{ method: string; url: string; body: any }> = [];
+ let status = 200;
+ const http = await listen(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ calls.push({ method: req.method!, url: req.url!, body: JSON.parse(Buffer.concat(chunks).toString() || "{}") });
+ res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify({ id: "M1", message: "nope" }));
+ });
+ cleanups.push(http.close);
+ const t = new DiscordTransport("TOK", { baseUrl: http.url });
+ expect(await t.sendText("C1", "| a |\n|---|\n@everyone", "k".repeat(40))).toBe("M1");
+ expect(calls[0]).toMatchObject({ method: "POST", url: "/channels/C1/messages", body: { nonce: "k".repeat(25), enforce_nonce: true, allowed_mentions: { parse: [] } } });
+ expect(calls[0].body.content.startsWith("```\n| a |")).toBe(true);
+ await t.editText("C1", "M1", "改");
+ expect(calls[1]).toMatchObject({ method: "PATCH", url: "/channels/C1/messages/M1" });
+ status = 403;
+ await expect(t.sendText("C1", "x")).rejects.toMatchObject({ rejected: true });
+ status = 429;
+ await expect(t.sendText("C1", "x")).rejects.toMatchObject({ rejected: false });
+ });
+
+ it("文件超过 10 MB:直接报太大,不去传", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-dc-"));
+ const f = path.join(dir, "big.bin");
+ fs.writeFileSync(f, Buffer.alloc(10 * 1024 * 1024 + 1));
+ await expect(new DiscordTransport("TOK", { baseUrl: "http://127.0.0.1:1" }).sendFile("C1", f, "big.bin")).rejects.toThrow(/过大|too large/i);
+ });
+});
diff --git a/ui/locales/en/access.js b/ui/locales/en/access.js
index a3196a9..844814f 100644
--- a/ui/locales/en/access.js
+++ b/ui/locales/en/access.js
@@ -1,6 +1,6 @@
// access · en
export default {
- channel: { web: "Web", feishu: "Feishu", weixin: "WeChat" },
+ channel: { web: "Web", feishu: "Feishu", weixin: "WeChat", telegram: "Telegram", slack: "Slack", discord: "Discord" },
source: {
request: "Allowed by you",
migration: "Already using it before the upgrade",
diff --git a/ui/locales/en/chat.js b/ui/locales/en/chat.js
index c4aa347..0637cc6 100644
--- a/ui/locales/en/chat.js
+++ b/ui/locales/en/chat.js
@@ -75,7 +75,7 @@ export default {
guideTitle: "Hi, I'm {name}",
guideBody: "Take 5 minutes and walk through the checklist to see what I can do.",
title: "Start chatting with {name}",
- body: "Test your bot right here. Set up Feishu and WeChat channels in the info panel.",
+ body: "Test your bot right here. Connect WeChat, Feishu, Telegram, Slack or Discord in the info panel.",
sample: "What can you help me with?",
helpChip: "/help for commands",
},
diff --git a/ui/locales/en/guide.js b/ui/locales/en/guide.js
index 40cf021..9c349b0 100644
--- a/ui/locales/en/guide.js
+++ b/ui/locales/en/guide.js
@@ -56,7 +56,7 @@ export default {
title: "Connect {name} to WeChat",
desc: "Scan a QR code, then message it directly in WeChat. No new app to install, and it's online whenever your computer is on.",
how: ["Click the bot's name at the top to open the info panel", "Under “Channels”, click “WeChat” → “Scan to log in”", "Scan the code with WeChat and confirm on your phone"],
- note: "WeChat's rule: for each message you send, it can reply up to 10 times within 24 hours. For Feishu, enter your Feishu app's App ID and App Secret in the same place.",
+ note: "WeChat's rule: for each message you send, it can reply up to 10 times within 24 hours. For Feishu, Telegram, Slack or Discord, enter its credentials in the same place.",
doneText: "Send it a message in WeChat: same bot, same memory.",
},
hands: {
diff --git a/ui/locales/en/info.js b/ui/locales/en/info.js
index 9329ba9..e2061c2 100644
--- a/ui/locales/en/info.js
+++ b/ui/locales/en/info.js
@@ -16,6 +16,9 @@ export default {
web: "Web",
feishu: "Feishu",
weixin: "WeChat",
+ telegram: "Telegram",
+ slack: "Slack",
+ discord: "Discord",
},
feishu: {
bindHint: "Send the bot a message from your own Feishu account to finish binding.",
@@ -27,6 +30,30 @@ export default {
disconnectBody: "This removes the bot's Feishu App ID and App Secret.",
setupHint: "In the Feishu Open Platform, enable the Bot capability, set event subscription to “Receive events through long connection”, and subscribe to {event}. Permissions: {p1}, {p2}, {p3}, {p4}.",
},
+ messenger: {
+ bindHint: "Send the bot a message from your own account to finish binding.",
+ secretSaved: "Saved {masked}. Leave blank to keep it",
+ saveConnect: "Save & connect",
+ disconnect: "Disconnect",
+ disconnectTitle: "Disconnect {channel}?",
+ disconnectBody: "This removes the bot's {channel} credentials. After you reconnect, the first person to message it becomes the owner.",
+ telegram: {
+ sub: "Receives messages over long polling",
+ token: "Bot token",
+ setupHint: "In Telegram, message {bot}, send {cmd} to create a bot, and paste the token it gives you. Direct messages only for now. Messages sent while the app is closed are picked up for up to 24 hours.",
+ },
+ slack: {
+ sub: "Receives messages over Socket Mode",
+ botToken: "Bot token",
+ appToken: "App-level token",
+ setupHint: "At api.slack.com/apps, create an app, turn on Socket Mode and generate an app-level token with {conn}. Add the bot scopes {s1}, {s2}, {s3} and {s4}, subscribe to {event}, allow messages in App Home, then install it to your workspace. Direct messages only for now. Messages sent while the app is closed aren't received.",
+ },
+ discord: {
+ sub: "Receives messages over the Gateway",
+ token: "Bot token",
+ setupHint: "In the Discord Developer Portal, create an application, add a bot and copy its token. Under OAuth2 → URL Generator, tick bot and add it to a server you're in, then send it a direct message. Direct messages only for now. Messages sent while the app is closed aren't received.",
+ },
+ },
weixin: {
sub: "Official iLink channel",
linked: "Linked: {id}",
diff --git a/ui/locales/en/rules.js b/ui/locales/en/rules.js
index b4c430a..cb1198e 100644
--- a/ui/locales/en/rules.js
+++ b/ui/locales/en/rules.js
@@ -50,7 +50,7 @@ export default {
minutes: "minutes",
days: "Days",
to: "Send to",
- noConvs: "Message the bot on WeChat, Feishu or the web first",
+ noConvs: "Message the bot in a chat app or on the web first",
weixinNote: "WeChat lets the bot message you only within 24 hours of your last message. Otherwise it arrives with your next message and shows on the desktop.",
create: "Create",
gone: "This rule was deleted",
diff --git a/ui/locales/en/settings.js b/ui/locales/en/settings.js
index d8748e7..a1dc364 100644
--- a/ui/locales/en/settings.js
+++ b/ui/locales/en/settings.js
@@ -189,9 +189,9 @@ export default {
none: "Off",
},
lowBalancePush: {
- name: "Also send alerts to WeChat / Feishu",
- sub: "Sent by your bot: on WeChat to whoever scanned the login QR code (they need to have messaged recently), on Feishu to the most recent direct chat",
- keys: "push alert wechat feishu lark",
+ name: "Also send alerts to your chat apps",
+ sub: "Sent by your bot: on WeChat to whoever scanned the login QR code (they need to have messaged recently), on Feishu to the most recent direct chat, on Telegram, Slack and Discord to the owner",
+ keys: "push alert wechat feishu lark telegram slack discord",
},
usage: {
name: "Usage",
diff --git a/ui/locales/zh-CN/access.js b/ui/locales/zh-CN/access.js
index d9e4c5f..a2b340b 100644
--- a/ui/locales/zh-CN/access.js
+++ b/ui/locales/zh-CN/access.js
@@ -1,6 +1,6 @@
// access · zh-CN
export default {
- channel: { web: "网页", feishu: "飞书", weixin: "微信" },
+ channel: { web: "网页", feishu: "飞书", weixin: "微信", telegram: "Telegram", slack: "Slack", discord: "Discord" },
source: {
request: "你允许的",
migration: "升级前已在使用",
diff --git a/ui/locales/zh-CN/chat.js b/ui/locales/zh-CN/chat.js
index 3311278..ca53a91 100644
--- a/ui/locales/zh-CN/chat.js
+++ b/ui/locales/zh-CN/chat.js
@@ -76,7 +76,7 @@ export default {
guideTitle: "嗨,我是{name}",
guideBody: "花 5 分钟,跟着清单认识一下我能做什么。",
title: "和 {name} 开始对话",
- body: "在这里直接测试机器人;飞书和微信渠道在信息面板里配置。",
+ body: "在这里直接测试机器人;微信、飞书、Telegram、Slack、Discord 在信息面板里接入。",
/** 点一下就发给机器人的示例问题 */
sample: "你能帮我做什么?",
helpChip: "/help 查看命令",
diff --git a/ui/locales/zh-CN/guide.js b/ui/locales/zh-CN/guide.js
index 78da220..18af723 100644
--- a/ui/locales/zh-CN/guide.js
+++ b/ui/locales/zh-CN/guide.js
@@ -60,7 +60,7 @@ export default {
title: "把{name}接到微信",
desc: "扫码后,在微信里直接私聊它,不用装新 App。电脑开着,它就在线。",
how: ["点顶部的机器人名字,打开信息面板", "在「渠道」里点「微信」→「扫码登录」", "用微信扫码,在手机上确认"],
- note: "微信的规定:你每发一条消息,它 24 小时内最多回 10 条。用飞书的话,在同一处填飞书应用的 App ID 和 App Secret。",
+ note: "微信的规定:你每发一条消息,它 24 小时内最多回 10 条。用飞书、Telegram、Slack、Discord 的话,在同一处填对应的凭据。",
doneText: "在微信里给它发条消息试试:同一个机器人,同一份记忆。",
},
hands: {
diff --git a/ui/locales/zh-CN/info.js b/ui/locales/zh-CN/info.js
index cd8a162..485d800 100644
--- a/ui/locales/zh-CN/info.js
+++ b/ui/locales/zh-CN/info.js
@@ -18,6 +18,9 @@ export default {
web: "网页",
feishu: "飞书",
weixin: "微信",
+ telegram: "Telegram",
+ slack: "Slack",
+ discord: "Discord",
},
feishu: {
bindHint: "用你自己的飞书给机器人发一句话,就完成绑定。",
@@ -30,6 +33,32 @@ export default {
/** {event} {p1} {p2} {p3} 是 <code> 包着的事件名 / 权限名 */
setupHint: "在飞书开放平台启用「机器人」,事件订阅选「使用长连接接收事件」并订阅 {event};权限:{p1}、{p2}、{p3}、{p4}。",
},
+ messenger: {
+ bindHint: "用你自己的账号给机器人发一句话,就完成绑定。",
+ secretSaved: "已保存 {masked},留空则不修改",
+ saveConnect: "保存并连接",
+ disconnect: "断开",
+ disconnectTitle: "断开 {channel}?",
+ disconnectBody: "会清除这个机器人的 {channel} 凭据,之后连上时第一个发消息的人成为主人。",
+ telegram: {
+ sub: "长轮询接收消息",
+ token: "Bot Token",
+ /** {bot} {cmd} 是 <code> 包着的账号名 / 命令 */
+ setupHint: "在 Telegram 里找 {bot},发 {cmd} 创建机器人,把它给的 token 填到这里。目前只处理单聊;应用没开时发来的消息,24 小时内都能补上。",
+ },
+ slack: {
+ sub: "Socket Mode 接收消息",
+ botToken: "Bot Token",
+ appToken: "App-Level Token",
+ /** {conn} {s1}…{s4} 是权限名,{event} 是事件名 */
+ setupHint: "在 api.slack.com/apps 创建应用,打开 Socket Mode,生成带 {conn} 的 App-Level Token;给 Bot Token 加 {s1}、{s2}、{s3}、{s4},事件订阅 {event},在 App Home 允许发消息,再安装到工作区。目前只处理单聊;应用没开时发来的消息收不到。",
+ },
+ discord: {
+ sub: "Gateway 长连接接收消息",
+ token: "Bot Token",
+ setupHint: "在 Discord Developer Portal 创建应用并添加 Bot,复制 token;用 OAuth2 的 URL Generator 勾选 bot,把它加到你所在的服务器,然后私聊它。目前只处理单聊;应用没开时发来的消息收不到。",
+ },
+ },
weixin: {
sub: "iLink 官方通道",
linked: "已绑定 {id}",
diff --git a/ui/locales/zh-CN/rules.js b/ui/locales/zh-CN/rules.js
index 7877b72..5599c0c 100644
--- a/ui/locales/zh-CN/rules.js
+++ b/ui/locales/zh-CN/rules.js
@@ -50,7 +50,7 @@ export default {
minutes: "分钟",
days: "星期",
to: "发到",
- noConvs: "先在微信、飞书或网页里和机器人说句话",
+ noConvs: "先在聊天软件或网页里和机器人说句话",
weixinNote: "微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。",
create: "建好",
gone: "规则已经删了",
diff --git a/ui/locales/zh-CN/settings.js b/ui/locales/zh-CN/settings.js
index f7b07b1..6a0c59f 100644
--- a/ui/locales/zh-CN/settings.js
+++ b/ui/locales/zh-CN/settings.js
@@ -189,9 +189,9 @@ export default {
none: "不提醒",
},
lowBalancePush: {
- name: "提醒也发到微信 / 飞书",
- sub: "由机器人发给你:微信发给扫码登录的人(需要他最近发过消息),飞书发到最近的单聊",
- keys: "推送 提醒 微信 飞书",
+ name: "提醒也发到聊天软件",
+ sub: "由机器人发给你:微信发给扫码登录的人(需要他最近发过消息),飞书发到最近的单聊,Telegram、Slack、Discord 发给主人",
+ keys: "推送 提醒 微信 飞书 telegram slack discord",
},
usage: {
name: "用量",
diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.js
index d36feb7..cdc436e 100644
--- a/ui/screens/bot-settings.js
+++ b/ui/screens/bot-settings.js
@@ -133,8 +133,7 @@ function AccessRows({ botId }) {
return html`<div class="list-head">${t("botSettings.access.head")}</div>
<div class="list">
<${Row} id="access" name=${t("botSettings.access.policy")} />
- ${owner("weixin")}
- ${owner("feishu")}
+ ${["weixin", "feishu", "telegram", "slack", "discord"].map((ch) => owner(ch))}
</div>
${allowed.length > 0 && html`<div class="list-head">${t("botSettings.access.allowed")}<span class="badge count">${allowed.length}</span></div>
<div class="list">
diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.js
index 445c627..c5a3348 100644
--- a/ui/screens/info-panel.js
+++ b/ui/screens/info-panel.js
@@ -26,7 +26,69 @@ export function usePoll(fn, ms, deps = []) {
}
/** 渠道名(渲染时取,跟着界面语言);不认识的渠道原样显示 id */
-const channelName = (c) => ({ web: t("info.channel.web"), feishu: t("info.channel.feishu"), weixin: t("info.channel.weixin") })[c];
+const channelName = (c) => ({ web: t("info.channel.web"), feishu: t("info.channel.feishu"), weixin: t("info.channel.weixin"), telegram: t("info.channel.telegram"), slack: t("info.channel.slack"), discord: t("info.channel.discord") })[c];
+
+/** Telegram、Slack、Discord:填 token 连上。key 和后端 MESSENGER_FIELDS 对应 */
+const MESSENGER_FIELDS = {
+ telegram: [{ key: "token", placeholder: "123456789:AA…" }],
+ slack: [{ key: "botToken", placeholder: "xoxb-…" }, { key: "appToken", placeholder: "xapp-…" }],
+ discord: [{ key: "token", placeholder: "" }],
+};
+/** 接入说明里 <code> 包着的权限名、事件名 */
+const code = (s) => html`<code>${s}</code>`;
+const MESSENGER_HINT = {
+ telegram: () => ({ bot: code("@BotFather"), cmd: code("/newbot") }),
+ slack: () => ({ conn: code("connections:write"), s1: code("chat:write"), s2: code("im:history"), s3: code("files:read"), s4: code("files:write"), event: code("message.im") }),
+ discord: () => ({}),
+};
+
+function MessengerRow({ bot, id, st, owner, reload }) {
+ const [open, setOpen] = useState(false);
+ const [values, setValues] = useState({});
+ const [busy, setBusy] = useState(false);
+ const fields = MESSENGER_FIELDS[id];
+ const account = st.account;
+ const name = channelName(id);
+ // 第一次连接要填全;已保存的留空表示不改
+ const ready = account ? fields.some((f) => (values[f.key] || "").trim()) : fields.every((f) => (values[f.key] || "").trim());
+ const save = async () => {
+ setBusy(true);
+ try {
+ await api(`/bots/${bot.id}/${id}`, { method: "PUT", body: values });
+ setValues({});
+ saved();
+ reload();
+ } catch (e) {
+ failed(e);
+ }
+ setBusy(false);
+ };
+ const clear = async () => {
+ if (!(await confirmSheet({ title: t("info.messenger.disconnectTitle", { channel: name }), body: t("info.messenger.disconnectBody", { channel: name }), confirmLabel: t("info.messenger.disconnect"), danger: true }))) return;
+ try {
+ await api(`/bots/${bot.id}/${id}`, { method: "DELETE" });
+ setValues({});
+ reload();
+ } catch (e) {
+ failed(e);
+ }
+ };
+ return html`<div class="row clickable" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}
+ onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), setOpen((v) => !v))}>
+ <div class="who"><div class="name">${name}</div><div class="sub">${st.detail || (account && account.name) || t(`info.messenger.${id}.sub`)}</div></div>
+ <${Badge} s=${st.state} />
+ </div>
+ ${open && html`<div class="row-edit">
+ ${fields.map((f) => html`<label key=${f.key}>${t(`info.messenger.${id}.${f.key}`)}${account && account.saved[f.key] && html`<span class="hint">${t("info.messenger.secretSaved", { masked: account.saved[f.key] })}</span>`}
+ <input class="field mono" type="password" autocomplete="off" placeholder=${f.placeholder} value=${values[f.key] || ""} onInput=${(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))} /></label>`)}
+ <div class="actions">
+ <button type="button" class="btn primary" disabled=${!ready || busy} onClick=${save}>${busy ? html`<${Spinner} />` : t("info.messenger.saveConnect")}</button>
+ ${account && html`<button type="button" class="text danger" onClick=${clear}>${t("info.messenger.disconnect")}</button>`}
+ </div>
+ ${account && owner === null && html`<p class="hint">${t("info.messenger.bindHint")}</p>`}
+ <p class="hint">${t(`info.messenger.${id}.setupHint`, MESSENGER_HINT[id]())}</p>
+ </div>`}`;
+}
function FeishuRow({ bot, st, owner, reload }) {
const [open, setOpen] = useState(false);
@@ -231,10 +293,10 @@ export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChat
// 任务来自的会话:网页的就是这里的对话,微信、飞书的在会话记录里看
const openConv = (task) => (task.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === task.conversationId) || null));
const pending = (appr && appr.approvals) || [];
- // 上手清单:微信扫码绑定了,或飞书连上了,就算接好了渠道
+ // 上手清单:微信扫码绑定了,或飞书、Telegram、Slack、Discord 连上了,就算接好了渠道
useEffect(() => {
const ch = detail && detail.channels;
- if (ch && (ch.weixin.account || ch.feishu.state === "connected")) markDone("weixin");
+ if (ch && (ch.weixin.account || ["feishu", "telegram", "slack", "discord"].some((c) => ch[c] && ch[c].state === "connected"))) markDone("weixin");
}, [detail]);
// leaving:关上后还在播滑出的那一小会儿(main.js 的 usePresence),不再接收操作
return html`<aside class=${`panel${leaving ? " leaving" : ""}`} aria-label=${t("info.aria")} inert=${leaving || undefined}>
@@ -248,7 +310,7 @@ export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChat
<div class="list-head">${t("info.channels")}</div>
<div class="list">
${detail && detail.bot
- ? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} owner=${access ? access.owners.feishu : undefined} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} reload=${reloadDetail} />`
+ ? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} owner=${access ? access.owners.feishu : undefined} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} reload=${reloadDetail} />${["telegram", "slack", "discord"].map((id) => html`<${MessengerRow} key=${id} bot=${detail.bot} id=${id} st=${detail.channels[id]} owner=${access ? access.owners[id] : undefined} reload=${reloadDetail} />`)}`
: html`<div class="row"><${Skeleton} w="50%" /></div><div class="row"><${Skeleton} w="40%" /></div>`}
</div>