Skip to content

Instantly share code, notes, and snippets.

@sadegh19b
Last active April 19, 2025 12:00
Show Gist options
  • Save sadegh19b/c1d83b8acdfa8bf9f8a372f5bafaa0aa to your computer and use it in GitHub Desktop.
Save sadegh19b/c1d83b8acdfa8bf9f8a372f5bafaa0aa to your computer and use it in GitHub Desktop.
How to Use Cloudflare Workers to Bypass Telegram

To create a Cloudflare Worker that acts as a bidirectional proxy between your domain and Telegram, follow these steps:

Step 1: Create the Cloudflare Worker Script

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);
  const path = url.pathname;

  // Route outgoing requests to Telegram API
  if (path.startsWith('/bot')) {
    return handleTelegramAPIRequest(request);
  }

  // Route incoming webhook updates to your backend
  if (path.startsWith('/webhook')) {
    return handleWebhookRequest(request);
  }

  return new Response('Not Found', { status: 404 });
}

async function handleTelegramAPIRequest(request) {
  // Ensure the request is authorized (optional)
  const apiKey = request.headers.get('X-API-Key');
  if (API_KEY && apiKey !== API_KEY) {
    return new Response('Unauthorized', { status: 401 });
  }

  const url = new URL(request.url);
  const method = url.pathname.split('/')[2]; // Extract method (e.g., "sendMessage")
  const telegramUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/${method}${url.search}`;

  try {
    const newRequest = new Request(telegramUrl, {
      method: request.method,
      headers: request.headers,
      body: request.body,
    });
    const response = await fetch(newRequest);
    return response;
  } catch (error) {
    return new Response('Telegram API Error', { status: 500 });
  }
}

async function handleWebhookRequest(request) {
  const backendUrl = USER_BACKEND_URL;

  try {
    const newRequest = new Request(backendUrl, {
      method: request.method,
      headers: request.headers,
      body: request.body,
    });
    const response = await fetch(newRequest);
    return response;
  } catch (error) {
    return new Response('Backend Error', { status: 500 });
  }
}

Step 2: Configure Environment Variables

Set these in your Cloudflare Worker settings:

  • TELEGRAM_BOT_TOKEN: Your Telegram bot token (from BotFather).
  • USER_BACKEND_URL: Your domain's endpoint to handle webhooks (e.g., https://yourdomain.com/webhook).
  • API_KEY (optional): A secret key to secure the /bot endpoint.

Step 3: Deploy the Worker

  1. Deploy the worker to Cloudflare.
  2. Note the worker's URL (e.g., your-worker.your-subdomain.workers.dev).

Step 4: Set Up Telegram Webhook

Use the Telegram API to set your worker's /webhook endpoint as the webhook URL:

curl "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook?url=https://your-worker.your-subdomain.workers.dev/webhook&secret_token=<SECRET_TOKEN>"

Replace <SECRET_TOKEN> with a secret string. Your backend must validate the X-Telegram-Bot-Api-Secret-Token header against this token.

Step 5: Route Requests Through the Worker

Security Notes

  • API Key Protection: If you set API_KEY, include the X-API-Key header in requests to /bot.
  • Webhook Security: Your backend should validate the X-Telegram-Bot-Api-Secret-Token header against your <SECRET_TOKEN>.

Testing

  1. Send a Message via the Worker:
      curl -X POST -H "X-API-Key: your_api_key" \
        -d "chat_id=123456&text=Hello" \
        https://your-worker.your-subdomain.workers.dev/bot/sendMessage
  1. Trigger a Webhook Update: Send a message to your bot; verify it reaches your backend.

This setup securely proxies requests between your domain and Telegram, handling both directions through a single Cloudflare Worker.

@sadegh19b
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment