34.3 通道集成
34.3.1 实现 Telegram Bot 通道适配器
前置准备
使用 grammY 框架
// src/channels/telegram.ts
import { Bot } from "grammy";
import { WebSocket } from "ws";
export class TelegramChannel {
private bot: Bot;
private gatewayWs: WebSocket;
constructor(params: {
botToken: string;
gatewayUrl: string;
}) {
this.bot = new Bot(params.botToken);
this.gatewayWs = new WebSocket(params.gatewayUrl);
}
start() {
// 等待 Gateway 连接就绪
this.gatewayWs.on("open", () => {
console.log("Telegram channel connected to Gateway");
});
// 处理 Gateway 返回的事件
this.gatewayWs.on("message", (raw) => {
const frame = JSON.parse(raw.toString());
if (frame.type === "event" && frame.event === "chat") {
this.handleChatEvent(frame.payload);
}
});
// 监听 Telegram 消息
this.bot.on("message:text", async (ctx) => {
const chatId = ctx.chat.id;
const senderId = ctx.from?.id;
const text = ctx.message.text;
// 构造会话键(每个 Telegram 用户一个会话)
const sessionKey = `telegram:${senderId}`;
// 发送到 Gateway
this.sendToGateway("chat.send", {
sessionKey,
message: text,
channel: "telegram",
accountId: String(senderId),
to: String(chatId),
});
});
this.bot.start();
console.log("Telegram Bot started");
}
private handleChatEvent(payload: {
sessionKey: string;
state: string;
message?: { content: string };
}) {
if (payload.state !== "final") return;
if (!payload.sessionKey.startsWith("telegram:")) return;
// 从 sessionKey 反查 chatId
// (实际项目中应维护 sessionKey → chatId 的映射)
const content = payload.message?.content;
if (content) {
// 通过 Gateway 路由回复到正确的 chat
this.bot.api.sendMessage(/* chatId */, content);
}
}
private sendToGateway(method: string, params: unknown) {
const frame = {
type: "req",
id: crypto.randomUUID(),
method,
params,
};
this.gatewayWs.send(JSON.stringify(frame));
}
}通道-会话映射
34.3.2 实现 Discord Bot 通道适配器
特性
Telegram
Discord
34.3.3 实现 WebChat 通道
前端(HTML + JavaScript)
静态文件服务
流式输出增强
通道统一入口
本节小结
Last updated