-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
55 lines (45 loc) · 1.65 KB
/
main.js
File metadata and controls
55 lines (45 loc) · 1.65 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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
try {
const data = await request.json();
if (!data.message || !data.message.chat || !data.message.chat.id) {
return new Response('Invalid data structure', { status: 400 });
}
const chatId = data.message.chat.id;
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
const responseMessage = JSON.stringify(data, null, 2);
const messageChunks = splitMessage(responseMessage, 4000);
for (const chunk of messageChunks) {
const url = `https://api.telegram.org/bot${token}/sendMessage`;
const body = {
chat_id: chatId,
text: `\`\`\`${chunk}\`\`\``,
parse_mode: 'Markdown'
};
const init = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
};
const response = await fetch(url, init);
if (!response.ok) {
throw new Error(`Telegram API error: ${response.statusText}`);
}
}
return new Response('Messages sent successfully');
} catch (error) {
console.error('Error handling request:', error);
return new Response('Internal Server Error', { status: 500 });
}
}
function splitMessage(message, maxLength) {
const chunks = [];
for (let i = 0; i < message.length; i += maxLength) {
chunks.push(message.slice(i, i + maxLength));
}
return chunks;
}