使用自己的域名,利用Cloudflare Worker代理Telegram Bot API

1、 创建部署Cloudflare Worker写入以下代码

var URL_PATH_REGEX = /^\/bot(?<bot_token>[^/]+)\/(?<api_method>[a-z]+)/i;

var src_default = {
  async fetch(request) {
    const { pathname: path, search } = new URL(request.url);

    let matchResult;
    let apiUrl;

    try {
      matchResult = path.match(URL_PATH_REGEX);
    } catch (e) {
      return new Response("Invalid URL", {
        status: 400,
        headers: { "content-type": "text/plain" }
      });
    }

    if (matchResult && matchResult.groups) {
      const { bot_token, api_method } = matchResult.groups;
      apiUrl = "https://api.telegram.org/bot" + bot_token + "/" + api_method + search;
    } else {
      return new Response("Invalid URL", {
        status: 400,
        headers: { "content-type": "text/plain" }
      });
    }

    if (request.method === "GET") {
      const response = await fetch(apiUrl, {
        method: "GET",
        headers: request.headers
      });
      const responseBody = await response.text();

      return new Response(responseBody, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers
      });
    } else if (request.method === "POST") {
      const response = await fetch(apiUrl, {
        method: request.method,
        headers: request.headers,
        body: request.body
      });
      const responseBody = await response.text();
      
      return new Response(responseBody, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers
      });
    } else {
      return new Response("Unsupported Request Method", {
        status: 400,
        headers: { "content-type": "text/plain" }
      });
    }
  }
};
export {
  src_default as default
};

2、 使用自己的域名反代

Cloudflare Workers的默认域名已经被404,所以需要使用自己的域名,并通过Workers Route调用刚刚创建的Worker。
(1)添加DNS记录
打开想使用的托管到Cloudflare的域名,添加DNS“A"记录。可以使用二级域名,名称随意,IP随意,只要合规即可。黄云处于打开状态。
(2) 创建Workers Route
点击边栏的"Worker Routes"。点击"Add route","Route"填写刚刚添加的DNS记录中的你的域名,"Worker"选择你刚刚创建的Worker。

3、用法

Telegram Bot API代码中填写替换相应内容即可,参考格式:

TG_BOT_TOKEN = 'TG_BOT_TOKEN'
TG_USER_ID = 'TG_USER_ID'
TG_API_HOST = 'DNS记录中的的域名'