利用cloudflare workers监听tg群组消息并保存到kv中

1/23/2025

# 步骤 1:创建 Telegram 机器人

  1. 打开 Telegram,搜索 @BotFather
  2. 使用 /newbot 命令创建一个新机器人,获取 API Token

# 步骤 2:创建 Cloudflare Worker

  1. 登录 Cloudflare

  2. 创建 Worker

    • 点击“创建 worker”,输入名称,点击部署。
  3. 自定义域名

    • 设置 -> 域和路由 -> 添加 -> 自定义域 -> 输入托管域名的二级域名,会自动绑定dns
  4. 创建kv命名空间

    • 存储和数据库 -> kv -> 创建 -> 输入命名空间
  5. worker绑定kv命名空间

    • 设置 -> 绑定 -> 添加 -> kv命名空间 -> 输入变量名称和选择刚刚创建的命名空间 -> 部署

# 步骤 3:设置 Webhook

Telegram Bot API 支持通过 Webhook 接收消息。你需要将 Webhook 设置为 Cloudflare Worker 的 URL。

  1. 获取 Cloudflare Worker 的 URL

    • 部署一个简单的 Worker(见上一步),获取其 URL(如 https://your-worker.your-subdomain.workers.dev或者自定义的域名)。
  2. 设置 Webhook

    • 使用以下 URL 设置 Webhook(将 YOUR_BOT_TOKENYOUR_WORKER_URL 替换为实际值):
      https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook?url=YOUR_WORKER_URL
      
    • 例如:
      https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/setWebhook?url=https://your-worker.your-subdomain.workers.dev
      
  3. 验证 Webhook

    • 访问以下 URL 检查 Webhook 是否设置成功:
      https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo
      

# 步骤 4:调整 Worker代码

export default {
  async fetch(request, env, ctx) {
    if (request.method === 'POST') {
      try {
        // 解析请求体
        const data = await request.json();
        const message = data.message;

        if (message) {
          const chatId = message.chat.id;
          const timestamp = new Date().toISOString();
          // 提取消息内容
          let content = {};
          if (message.text) {
            // 纯文本消息
            content = { type: "text", data: message.text };
          } else if (message.photo) {
            // 图片消息(可能包含 caption)
            content = {
              type: "photo",
              data: message.photo,
              caption: message.caption || null // 如果有 caption 则提取
            };
          } else if (message.video) {
            // 视频消息(可能包含 caption)
            content = {
              type: "video",
              data: message.video,
              caption: message.caption || null
            };
          } else if (message.document) {
            // 文档消息(可能包含 caption)
            content = {
              type: "document",
              data: message.document,
              caption: message.caption || null
            };
          } else if (message.audio) {
            // 音频消息(通常没有 caption)
            content = { type: "audio", data: message.audio };
          } else if (message.location) {
            // 位置消息
            content = { type: "location", data: message.location };
          } else {
            // 未知消息类型
            content = { type: "unknown", data: message };
          }

          // 将消息存储到 KV,这个MESSAGE_STORE就是你绑定kv设置的变量名称
          await env.MESSAGE_STORE.put(`msg_${timestamp}`, JSON.stringify({
            chatId,
            content,
            timestamp
          }));

          // 返回成功响应
          return new Response('Message stored in KV', { status: 200 });
        }

        // 如果没有消息内容,返回错误
        return new Response('No message found', { status: 400 });
      } catch (error) {
        // 返回错误响应
        return new Response(`Error: ${error.message}`, { status: 500 });
      }
    }

    // 如果不是 POST 请求,返回 404
    return new Response('Not Found2', { status: 404 });
  }
};

# 步骤 5:测试 Worker

需要是公开群组,并且添加你创建的bot到群组中

  1. 发送消息到群组

    • 在群组中发送一条消息,机器人会通过 Webhook 接收到消息。
  2. 查看kv中是否有保存一条记录

    • 如果一切正常,kv中会增加一条记录

# 注意事项

  1. 安全性

    • 确保你的 Worker URL 和 Bot Token 不会泄露。
    • 可以在 Worker 中验证请求来源(通过 Telegram 的 secret_token 参数)。
  2. 速率限制

    • Telegram Bot API 有速率限制(默认每秒最多 30 条消息),避免频繁请求。
  3. Webhook 设置

    • Webhook URL 必须是 HTTPS,Cloudflare Workers 默认支持 HTTPS。