Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
119 lines (112 loc) · 5.08 KB
/
Copy pathindex.js
File metadata and controls
119 lines (112 loc) · 5.08 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const messages = {
'/start': 'Welcome! Try /services, /resources or /contact.',
'/services': 'I build websites and automation tools. See examples: https://example.com/services',
'/resources': 'Your free deployment checklist: https://example.com/resources',
'/contact': 'Send an enquiry here: https://example.com/contact',
};
/**
* Respond to a supported Telegram command from an incoming update.
*
* @param {object} update Telegram update payload received from the Bot API.
* @param {string} token Bot token used to authenticate the sendMessage request.
* @param {Function} send HTTP implementation used to call Telegram; injectable for tests.
* @returns {Promise<void>} Resolves when the message is sent or no reply is needed.
* @throws {Error} If Telegram rejects the outgoing message.
*/
export async function handleUpdate(update, token, send = fetch) {
// Telegram adds "@BotName" to commands used in groups; remove it before lookup.
const message = update?.message;
if (!message?.chat?.id || typeof message.text !== 'string') return;
const command = message.text.trim().split(/\s+/)[0].split('@')[0].toLowerCase();
const text = messages[command];
if (!text) return;
const response = await send(`https://api.telegram.org/bot${token}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: message.chat.id, text }),
});
if (!response.ok || !(await response.json()).ok) throw new Error('Telegram could not send the message');
}
/**
* Continuously retrieve updates from Telegram using long polling and handle them.
*
* Before polling, this verifies that the bot does not currently have a webhook,
* because Telegram does not allow long polling and webhooks to run together.
*
* @param {string} token Bot token used to authenticate Telegram API requests.
* @param {Function} request HTTP implementation used for API calls; injectable for tests.
* @returns {Promise<never>} Does not resolve during normal operation.
* @throws {Error} If the token is missing, a webhook is active, or Telegram reports an error.
*/
export async function pollTelegram(token, request = fetch) {
if (!token) throw new Error('TELEGRAM_BOT_TOKEN is required');
// Keep the common Telegram request setup in one helper so every API call uses
// the same authentication, method, headers, and JSON encoding.
const api = (method, body) => request(`https://api.telegram.org/bot${token}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const webhookResponse = await api('getWebhookInfo', {});
const webhookInfo = await webhookResponse.json();
if (!webhookResponse.ok || !webhookInfo.ok) {
throw new Error(`Telegram getWebhookInfo failed: ${webhookInfo.description || webhookResponse.status}`);
}
if (webhookInfo.result.url) {
throw new Error(`A webhook is enabled at ${webhookInfo.result.url}; remove it before using long polling.`);
}
// Confirm each processed update on the next request by asking Telegram only
// for update IDs greater than the last one handled.
let offset = 0;
console.log('Long polling started. Press Ctrl+C to stop.');
while (true) {
const response = await api('getUpdates', {
offset,
timeout: 30,
allowed_updates: ['message'],
});
const result = await response.json();
if (!response.ok || !result.ok) {
throw new Error(`Telegram getUpdates failed: ${result.description || response.status}`);
}
for (const update of result.result) {
offset = update.update_id + 1;
await handleUpdate(update, token, request);
}
}
}
export default {
/**
* Handle health checks and authenticated Telegram webhook requests.
*
* @param {Request} request Incoming Cloudflare Worker request.
* @param {object} env Worker bindings containing TELEGRAM_BOT_TOKEN and WEBHOOK_SECRET.
* @returns {Promise<Response>} HTTP response describing the request result.
*/
async fetch(request, env) {
const path = new URL(request.url).pathname;
if ((path === '/' || path === '/health') && request.method === 'GET') {
return new Response('Telegram bot is running');
}
if (path !== '/telegram/webhook' && path !== '/webhook') return new Response('Not found', { status: 404 });
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
if (!env.TELEGRAM_BOT_TOKEN || !env.WEBHOOK_SECRET) return new Response('Missing configuration', { status: 503 });
// Telegram includes the secret configured by setup-webhook.js with every update.
if (request.headers.get('X-Telegram-Bot-Api-Secret-Token') !== env.WEBHOOK_SECRET) {
return new Response('Forbidden', { status: 403 });
}
let update;
try {
update = await request.json();
} catch {
return new Response('Invalid JSON', { status: 400 });
}
try {
await handleUpdate(update, env.TELEGRAM_BOT_TOKEN);
return new Response('OK');
} catch (error) {
console.error(error.message);
return new Response('Reply failed', { status: 502 });
}
}
};