开发日记 | 用cloudflare worker实现telegram bot
840 字
4 分钟
开发日记 | 用cloudflare worker实现telegram bot
这段时间闲着没事,想做一个 Telegram Bot 来玩玩。了解了一下,可实施的开发方案还挺多的,Java/Python 等等都有相对应的库。但是奈何我没有服务器,无法进行传统的前后端开发。
于是乎,我想到了另一种开发思路:利用 Cloudflare 提供的 Serverless 无状态 JavaScript Worker 以及 Telegram Bot 官方支持的 Webhook 功能来实现无服务器聊天机器人。
实现原理
我们在聊天机器人的界面发送命令:
/chat 聊天内容通过设置 Webhook 地址指向 Worker,Worker 中写好处理指令的代码,截取 /开始 后面的文字,然后转发给 Cloudflare 官方提供的免费的大语言模型后端,然后再处理返回的信息,最后再通过 Telegram Bot API 再返回消息到客户端。
这样便实现了无服务器的聊天 AI Bot,但是这有个缺点:用户的每一次聊天都是单独的一次请求,bot没有上下文记忆,因为 Worker 本身是个无状态的js执行器,所以这个 Bot 其实相当于是一个图形化的终端命令请求器。
但是 Cloudflare 有提供免费的额外的 KV 数据库,于是我们再改动一下代码:
- 用户发来的文字不直接请求大语言模型后端
- 而是先存入 KV 数据库
- 最后将 KV 数据库里的数据一起再发给大语言模型后端
- 处理返回的信息
- 返回 Telegram 客户端
于是Worker通过外挂KV数据库,最终便实现了带有记忆的无服务器聊天 AI 机器人。
实现源代码
const TELEGRAM_BOT_TOKEN = "";const CF_API_TOKEN = "";
async function run(model, input) { const response = await fetch( `https://api.cloudflare.com/client/v4/accounts/1f5b3d5417456835c8191a2ec42f449e/ai/run/${model}`, { headers: { Authorization: `Bearer ${CF_API_TOKEN}` }, method: "POST", body: JSON.stringify(input), } ); return await response.json();}
async function sendTelegramMessage(chat_id, text) { try { await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ chat_id, text, parse_mode: "MarkdownV2", }), }); } catch (err) { console.error("发送 Telegram 消息失败:", err); }}
export default { async fetch(request, env, ctx) { if (request.method !== "POST") return new Response("ok", { status: 200 });
try { const data = await request.json(); console.log("Telegram Update:", JSON.stringify(data));
const message = data.message; if (!message?.text) return new Response("ok", { status: 200 });
const text = message.text; const match = text.match(/^\/chat(?:@\w+)?(?:\s+([\s\S]+))?$/); const arg = match ? (match[1] || "").trim() : "";
console.log("完整消息文本:", text); console.log("命令参数:", arg);
if (!arg) { await sendTelegramMessage(message.chat.id, "请在 /chat 后输入要生成的内容,例如:/chat 写一个小故事"); } else {
let history = await env.bot.get(message.chat.id); history = history ? JSON.parse(history) : []; history.push({ role: "user", content: arg }); await env.bot.put(message.chat.id, JSON.stringify(history));
const aiResponse = await run("@cf/openai/gpt-oss-120b", { instructions: '你是liaoke的私人中文AI助手,简洁地回答用户的问题。', reasoning: { "effort": "medium" }, input: history, });
console.log("AI 原始响应:", JSON.stringify(aiResponse));
const reasonText = aiResponse?.result?.output ?.filter(o => o.type === "reasoning") ?.map(o => o.content?.map(c => c.text).join("\n")) .filter(Boolean) .join("\n\n") || "AI 无法生成内容";
const outputText = aiResponse?.result?.output ?.filter(o => o.type === "message") ?.map(o => o.content?.map(c => c.text).join("\n")) .filter(Boolean) .join("\n\n") || "AI 无法生成内容";
const escapeMD = (text) => { if (!text) return ""; return text .replace(/\\/g, "\\\\") .replace(/`/g, "\\`") .replace(/_/g, "\\_") .replace(/\*/g, "\\*") .replace(/\[/g, "\\[") .replace(/\]/g, "\\]") .replace(/~/g, "\\~") .replace(/>/g, "\\>") .replace(/#/g, "\\#") .replace(/\+/g, "\\+") .replace(/-/g, "\\-") .replace(/=/g, "\\=") .replace(/\|/g, "\\|") .replace(/\{/g, "\\{") .replace(/\}/g, "\\}") .replace(/\./g, "\\.") .replace(/!/g, "\\!"); };
const messageMD = `🧠 推理过程:\`\`\`${escapeMD(reasonText)}\`\`\`
💬 最终回答:${escapeMD(outputText)} `;
await sendTelegramMessage(message.chat.id, messageMD); history.push({ role: "assistant", content: outputText }); await env.bot.put(message.chat.id, JSON.stringify(history)); console.log("AI 输出发送给用户:", messageMD); }
return new Response("ok", { status: 200 }); } catch (err) { console.error("解析 JSON 或处理失败:", err); return new Response("error", { status: 400 }); } },};文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
开发日记 | 用cloudflare worker实现telegram bot
https://blog.liao-ke.com/posts/cloudflare-worker-telegram-bot/相关文章智能推荐
1
学习笔记 | 利用cloudflare邮件路由功能实现自己域名的无限马甲邮箱
学习笔记利用 Cloudflare 邮件路由和自定义域名创建无限马甲邮箱,介绍全收件规则、子地址功能及邮件转发到 Worker 的扩展用法。
2
学习笔记 | 用OBS和mediamtx搭建本地直播推流
学习笔记在 Windows 上用 OBS 作为推流源、mediamtx 搭建本地 RTMP 服务器,通过 HLS 或 WebRTC 在浏览器中直接观看更高码率、更流畅的画面,并说明端口映射与内网穿透的对外访问方式。
3
学习笔记 | 最简单的绕过校园网多设备热点检测方案(改良版)
学习笔记通过 TUN 虚拟网卡和 MyPublicWiFi 创建共享热点,绕过校园网多设备检测,并提升不同设备和驱动的兼容性。
4
学习笔记 | openwrt25.12设置vlan实现单线复用
学习笔记通过在光猫、主路由与房间子路由三端统一配置vlanid,实现桥接模式下的单线复用,让光猫其他网口/房间网口也能正常获取主路由DHCP下发的IP,并给出openwrt25.10的配置步骤与注意事项。
5
随笔杂谈 | 谷歌0成本卡两年AI pro和油管会员
随笔杂谈分析 Google AI Pro 两年免费订阅项目的实现思路,包括结账请求修改、优惠叠加和自动化流程。
随机文章随机推荐

