To create a Cloudflare Worker that acts as a bidirectional proxy between your domain and Telegram, follow these steps:
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 });
}
}
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.
- Deploy the worker to Cloudflare.
- Note the worker's URL (e.g., your-worker.your-subdomain.workers.dev).
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.
- Outgoing to Telegram: Send requests to https://your-worker.your-subdomain.workers.dev/bot/ (e.g., /bot/sendMessage).
- Incoming from Telegram: Telegram sends updates to the worker's /webhook endpoint, which forwards them to your backend.
- 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>.
- 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
- 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.
https://masihgh.ir/posts/bypass-telegram-endpoint-with-cloudflare-workers/