-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
428 lines (351 loc) · 12.8 KB
/
worker.js
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// ---------- Configuration ---------- //
const BOT_TOKEN = '1234567890:ABCDEfghijklmno-PQrstuvwxYZ'; // Your Bot's Token (from BotFather)
const BOT_WEBHOOK = '/endpoint'; // Path for Telegram updates
const BOT_SECRET = 'akkil123456'; // Secret for webhook verification
const LOG_CHANNEL = '-1234567890'; // Channel ID for logs
const OWNER_ID = 1428968542; // Your Telegram User ID (Admin)
// ---------- Constants & Helpers ---------- //
const IF_TEXT = "Reference ID: {}\nFrom: {}\n\n{}";
const IF_CONTENT = "Reference ID: {}\nFrom: {}";
const HEADERS_JSON = { 'Content-Type': 'application/json' };
// ---------- Database (using KV Store) ---------- //
/**
* @param {string} userId
*/
async function isUserExist(userId) {
// Replace 'FEEDBACK' with your KV namespace binding name
return await FEEDBACK.get(`user:${userId}`) !== null;
}
/**
* @param {string} userId
*/
async function addUser(userId) {
// Replace 'FEEDBACK' with your KV namespace binding name
await FEEDBACK.put(`user:${userId}`, JSON.stringify({ created_at: Date.now() }));
}
/**
* @param {string} userId
*/
async function getBanStatus(userId) {
// Replace 'FEEDBACK' with your KV namespace binding name
const data = await FEEDBACK.get(`ban:${userId}`);
if (data) {
return JSON.parse(data);
}
return { is_banned: false, ban_duration: 0, ban_reason: '' };
}
/**
* @param {string} userId
* @param {number} banDuration
* @param {string} banReason
*/
async function setBanStatus(userId, banDuration, banReason) {
// Replace 'FEEDBACK' with your KV namespace binding name
await FEEDBACK.put(`ban:${userId}`, JSON.stringify({
is_banned: true,
ban_duration: banDuration,
ban_reason: banReason
}));
}
// ---------- Telegram API Functions ---------- //
/**
* @param {string} method
* @param {object} [params]
*/
async function api(method, params) {
const url = `https://api.telegram.org/bot${BOT_TOKEN}/${method}`;
const response = await fetch(params ? `${url}?${new URLSearchParams(params)}` : url, {
method: params ? 'POST' : 'GET',
headers: params ? { 'Content-Type': 'application/json' } : undefined,
body: params ? JSON.stringify(params) : undefined
});
return response.json();
}
async function getMe() {
return api('getMe');
}
async function sendMessage(chat_id, text, reply_to_message_id = null) {
return api('sendMessage', { chat_id, text, reply_to_message_id, parse_mode: 'Markdown' });
}
async function copyMessage(chat_id, from_chat_id, message_id, caption = null) {
return api('copyMessage', { chat_id, from_chat_id, message_id, caption, parse_mode: 'Markdown' });
}
async function copyMediaGroup(chat_id, from_chat_id, message_id) {
return api('copyMessage', { chat_id, from_chat_id, message_id });
}
async function sendPhoto(chatId, photo, caption = null, replyToMessageId = null) {
return api("sendPhoto", {
chat_id: chatId,
photo: photo,
caption: caption,
parse_mode: "Markdown",
reply_to_message_id: replyToMessageId,
});
}
async function sendVideo(chatId, video, caption = null, replyToMessageId = null) {
return api("sendVideo", {
chat_id: chatId,
video: video,
caption: caption,
parse_mode: "Markdown",
reply_to_message_id: replyToMessageId,
});
}
async function sendAudio(chatId, audio, caption = null, replyToMessageId = null) {
return api("sendAudio", {
chat_id: chatId,
audio: audio,
caption: caption,
parse_mode: "Markdown",
reply_to_message_id: replyToMessageId,
});
}
async function sendDocument(chatId, document, caption = null, replyToMessageId = null) {
return api("sendDocument", {
chat_id: chatId,
document: document,
caption: caption,
parse_mode: "Markdown",
reply_to_message_id: replyToMessageId,
});
}
async function sendSticker(chatId, sticker, replyToMessageId = null) {
return api("sendSticker", {
chat_id: chatId,
sticker: sticker,
reply_to_message_id: replyToMessageId,
});
}
async function getUsers(user_ids) {
const response = await api("getChat", { chat_id: user_ids });
if (response.ok) {
return response.result;
} else {
console.error("Error getting user info:", response);
return null;
}
}
// ---------- Webhook Handling ---------- //
async function handleWebhook(request) {
if (request.headers.get('X-Telegram-Bot-Api-Secret-Token') !== BOT_SECRET) {
return new Response('Unauthorized', { status: 403 });
}
const update = await request.json();
await onUpdate(update);
return new Response('OK');
}
async function registerWebhook(request) {
const url = new URL(request.url);
const webhookUrl = `${url.protocol}//${url.hostname}${BOT_WEBHOOK}`;
const response = await api('setWebhook', {
url: webhookUrl,
secret_token: BOT_SECRET
});
return new Response(JSON.stringify(response), { headers: HEADERS_JSON });
}
async function unregisterWebhook() {
const response = await api('setWebhook', { url: '' });
return new Response(JSON.stringify(response), { headers: HEADERS_JSON });
}
// ---------- Update Handler ---------- //
async function onUpdate(update) {
if (update.message) {
await onMessage(update.message);
}
}
// ---------- Message Handler ---------- //
async function onMessage(message) {
const chatId = message.from.id;
const isGroup = message.chat.type === 'group' || message.chat.type === 'supergroup';
// Database Check and User Add
if (!(await isUserExist(chatId))) {
const botInfo = await getMe();
await addUser(chatId);
await sendMessage(LOG_CHANNEL, `#NEWUSER: \n\nNew User [${message.from.first_name}](tg://user?id=${chatId}) started @${botInfo.username} !!`);
}
// Ban Check
const banStatus = await getBanStatus(chatId);
if (banStatus.is_banned) {
await sendMessage(chatId, `You are Banned 🚫 to use this bot for **${banStatus.ban_duration}** day(s) for the reason _${banStatus.ban_reason}_ \n\n**Message from the admin 🤠**`);
return;
}
if (message.text) {
await handleTextMessage(message, isGroup);
} else if (message.media_group_id && message.photo) {
await handleMediaGroupMessage(message, isGroup);
} else if (message.photo) {
await handlePhotoMessage(message, isGroup);
} else if (message.video) {
await handleVideoMessage(message, isGroup);
} else if (message.audio) {
await handleAudioMessage(message, isGroup);
} else if (message.document) {
await handleDocumentMessage(message, isGroup);
} else if (message.sticker) {
await handleStickerMessage(message, isGroup);
}
}
// ---------- Text Message Handler ---------- //
async function handleTextMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replyText(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
await sendMessage(OWNER_ID, IF_TEXT.replace("{}", referenceId).replace("{}", info.first_name).replace("{}", message.text));
}
// ---------- Media Group Message Handler ---------- //
async function handleMediaGroupMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const referenceId = message.chat.id;
await copyMediaGroup(OWNER_ID, referenceId, message.message_id);
}
// ---------- Media Message Handlers ---------- //
async function handleMediaMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
let caption = IF_CONTENT.replace("{}", referenceId).replace("{}", info.first_name);
if (message.caption) {
caption += `\n\n${message.caption}`;
}
if (message.photo) {
const fileId = message.photo[message.photo.length - 1].file_id;
await sendPhoto(OWNER_ID, fileId, caption);
} else if (message.video) {
await sendVideo(OWNER_ID, message.video.file_id, caption);
} else if (message.audio) {
await sendAudio(OWNER_ID, message.audio.file_id, caption);
} else if (message.document) {
await sendDocument(OWNER_ID, message.document.file_id, caption);
} else if (message.sticker) {
await sendSticker(OWNER_ID, message.sticker.file_id);
}
}
async function handlePhotoMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
let caption = IF_CONTENT.replace("{}", referenceId).replace("{}", info.first_name);
if (message.caption) {
caption += `\n\n${message.caption}`;
}
const fileId = message.photo[message.photo.length - 1].file_id;
await sendPhoto(OWNER_ID, fileId, caption);
}
async function handleVideoMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
let caption = IF_CONTENT.replace("{}", referenceId).replace("{}", info.first_name);
if (message.caption) {
caption += `\n\n${message.caption}`;
}
await sendVideo(OWNER_ID, message.video.file_id, caption);
}
async function handleAudioMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
let caption = IF_CONTENT.replace("{}", referenceId).replace("{}", info.first_name);
if (message.caption) {
caption += `\n\n${message.caption}`;
}
await sendAudio(OWNER_ID, message.audio.file_id, caption);
}
async function handleDocumentMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
let caption = IF_CONTENT.replace("{}", referenceId).replace("{}", info.first_name);
if (message.caption) {
caption += `\n\n${message.caption}`;
}
await sendDocument(OWNER_ID, message.document.file_id, caption);
}
async function handleStickerMessage(message, isGroup) {
if (message.from.id === OWNER_ID) {
await replayMedia(message);
return;
}
const info = await getUsers(message.from.id);
const referenceId = message.chat.id;
const caption = IF_CONTENT.replace("{}", referenceId).replace("{}", info.first_name);
await sendSticker(OWNER_ID, message.sticker.file_id, caption);
}
// ---------- Reply Handlers (for Owner) ---------- //
async function replyText(message) {
if (!message.reply_to_message) return;
const referenceId = getReferenceIdFromReply(message.reply_to_message);
if (!referenceId) return;
await sendMessage(referenceId, message.text);
}
async function replayMedia(message) {
if (!message.reply_to_message) return;
const referenceId = getReferenceIdFromReply(message.reply_to_message);
if (!referenceId) return;
if (message.media_group_id) {
// Handle media group
await copyMediaGroup(referenceId, message.chat.id, message.message_id);
} else if (message.photo) {
const fileId = message.photo[message.photo.length - 1].file_id;
await sendPhoto(referenceId, fileId, message.caption, message.message_id);
} else if (message.video) {
await sendVideo(referenceId, message.video.file_id, message.caption, message.message_id);
} else if (message.audio) {
await sendAudio(referenceId, message.audio.file_id, message.caption, message.message_id);
} else if (message.document) {
await sendDocument(referenceId, message.document.file_id, message.caption, message.message_id);
} else if (message.sticker) {
await sendSticker(referenceId, message.sticker.file_id, message.message_id);
}
}
// ---------- Helper Function for Replies ---------- //
function getReferenceIdFromReply(replyToMessage) {
let referenceId = null;
if (replyToMessage.text) {
const match = replyToMessage.text.match(/Reference ID: (\d+)/);
if (match) {
referenceId = parseInt(match[1]);
}
} else if (replyToMessage.caption) {
const match = replyToMessage.caption.match(/Reference ID: (\d+)/);
if (match) {
referenceId = parseInt(match[1]);
}
}
return referenceId;
}
// ---------- Event Listener ---------- //
addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);
if (url.pathname === BOT_WEBHOOK) {
event.respondWith(handleWebhook(request));
} else if (url.pathname === '/register') {
event.respondWith(registerWebhook(request));
} else if (url.pathname === '/unregister') {
event.respondWith(unregisterWebhook());
} else {
event.respondWith(new Response('Not Found', { status: 404 }));
}
});