Spaces:
Sleeping
Sleeping
File size: 1,809 Bytes
44ee7fe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | // 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' },
});
}
},
};
|