Automations / worker.js
sivakumar330's picture
Upload 3 files
44ee7fe verified
Raw History Blame Contribute Delete
1.81 kB
// Cloudflare Worker: Telegram Bot API proxy
// Deploy: Cloudflare Dashboard > Workers & Pages > Create > Hello World > Edit code > paste > Deploy
// Then in n8n Telegram credential set Base URL = https://<your-worker>.workers.dev (no trailing slash)
const TELEGRAM_API = 'https://api.telegram.org';
export default {
async fetch(request) {
const url = new URL(request.url);
// Health check: open the worker URL in a browser, you should see this text
if (url.pathname === '/' || url.pathname === '/health') {
return new Response('Telegram proxy OK', {
status: 200,
headers: { 'content-type': 'text/plain' },
});
}
// Only allow real Telegram Bot API paths: /bot<TOKEN>/method and /file/bot<TOKEN>/path
if (!/^\/(file\/)?bot[^/]+\//.test(url.pathname)) {
return new Response('Not allowed', { status: 403 });
}
const target = new URL(TELEGRAM_API + url.pathname + url.search);
// Rebuild the request so Host/CF headers don't leak to Telegram
const headers = new Headers(request.headers);
headers.delete('host');
headers.delete('cf-connecting-ip');
headers.delete('x-forwarded-for');
headers.delete('x-real-ip');
try {
const upstream = await fetch(target.toString(), {
method: request.method,
headers,
body: ['GET', 'HEAD'].includes(request.method) ? undefined : request.body,
redirect: 'follow',
});
return new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers: upstream.headers,
});
} catch (err) {
return new Response(JSON.stringify({ ok: false, error: String(err) }), {
status: 502,
headers: { 'content-type': 'application/json' },
});
}
},
};