This repository was archived by the owner on Nov 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
2018 lines (1680 loc) · 70.8 KB
/
bot.js
File metadata and controls
2018 lines (1680 loc) · 70.8 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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// bot.js
import { Telegraf } from 'telegraf';
import dotenv from 'dotenv';
import fs from 'fs/promises';
import toml from 'toml';
// config
import {
BOT_TOKEN,
BANNED_PATTERNS_DIR,
WHITELISTED_USER_IDS,
WHITELISTED_GROUP_IDS,
SETTINGS_FILE,
HIT_COUNTER_FILE
} from './config/config.js';
// security
import {
createPatternObject,
matchesPattern
} from './security.js';
// management auth
import {
setupAuth,
isAuthorized,
canManageGroup,
getManagedGroups,
getUserAuthInfo,
refreshAuthCache,
forceRefreshAuthCache,
getAuthCacheStats
} from './auth.js';
dotenv.config();
const bot = new Telegraf(BOT_TOKEN);
// In-memory Data
const groupPatterns = new Map(); // Map of groupId -> patterns array
const adminSessions = new Map();
const newJoinMonitors = {};
const knownGroupAdmins = new Set();
// Settings will be loaded from SETTINGS_FILE at startup
let settings = {
groupActions: {} // Per-group actions (loaded from settings.json)
};
// Ban messages
const banMessages = [
"Hasta la vista, baby! User {userId} has been terminated.",
"I'll be back... but user {userId} won't be.",
"User {userId} has been terminated. Come with me if you want to live.",
"Your clothes, your boots, and your Telegram access. User {userId} has been terminated.",
"User {userId} is now terminated. Judgment Day has come.",
"I need your username, your bio, and your Telegram account. User {userId} terminated.",
"Talk to the hand! User {userId} has been terminated.",
"User {userId} has been terminated. Consider that a divorce."
];
// Kick messages
const kickMessages = [
"User {userId} has been kicked out. They can come back, but I'll be watching...",
"User {userId} has been escorted out. They can return after they find Jesus.",
"I'm giving user {userId} a timeout. Come back after you've thought about what you've done.",
"User {userId} needs to rethink their life choices."
];
// Hit counter variables with race condition protection
let hitCounters = {}; // Structure: { groupId: { pattern: count, ... }, ... }
let saveInProgress = false;
let pendingSave = false;
let saveTimeout = null;
// Utility Functions
function isChatAllowed(ctx) {
const chatType = ctx.chat?.type;
if (chatType === 'group' || chatType === 'supergroup') {
const isAllowed = WHITELISTED_GROUP_IDS.includes(ctx.chat.id);
console.log(`[CHAT_CHECK] Group ${ctx.chat.id} (${chatType}) - Allowed: ${isAllowed}`);
return isAllowed;
}
console.log(`[CHAT_CHECK] Private chat (${chatType}) not whitelisted user`);
return false;
}
function getRandomMessage(userId, isBan = true) {
const messageArray = isBan ? banMessages : kickMessages;
const randomIndex = Math.floor(Math.random() * messageArray.length);
const message = messageArray[randomIndex].replace('{userId}', userId);
console.log(`[MESSAGE] Generated ${isBan ? 'ban' : 'kick'} message for user ${userId}: "${message}"`);
return message;
}
function getGroupAction(groupId) {
const action = settings.groupActions[groupId] || 'kick';
console.log(`[ACTION] Group ${groupId} action: ${action.toUpperCase()}`);
return action;
}
async function checkAndCacheGroupAdmin(userId, bot) {
console.log(`[ADMIN_CHECK] Checking admin status for user ${userId}`);
if (WHITELISTED_USER_IDS.includes(userId)) {
console.log(`[ADMIN_CHECK] User ${userId} is in whitelist - granted admin`);
return true;
}
for (const groupId of WHITELISTED_GROUP_IDS) {
try {
const user = await bot.telegram.getChatMember(groupId, userId);
if (user.status === 'administrator' || user.status === 'creator') {
knownGroupAdmins.add(userId);
console.log(`[ADMIN_CHECK] User ${userId} is admin in group ${groupId} - cached`);
return true;
}
} catch {
console.log(`[ADMIN_CHECK] User ${userId} not found in group ${groupId}`);
}
}
console.log(`[ADMIN_CHECK] User ${userId} is not an admin in any group`);
return false;
}
// Pattern matching using security module
async function isBanned(username, firstName, lastName, groupId) {
console.log(`[BAN_CHECK] Checking user: @${username || 'no_username'}, Name: ${[firstName, lastName].filter(Boolean).join(' ')}, Group: ${groupId}`);
const patterns = groupPatterns.get(groupId) || [];
// Quick exit if no patterns
if (patterns.length === 0) {
console.log(`[BAN_CHECK] No patterns configured for group ${groupId} - not banned`);
return false;
}
console.log(`[BAN_CHECK] Testing against ${patterns.length} patterns`);
// Test each pattern safely
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns[i];
console.log(`[BAN_CHECK] Testing pattern ${i + 1}/${patterns.length}: "${pattern.raw}"`);
try {
// Test username
if (username) {
const usernameMatch = await matchesPattern(pattern.raw, username.toLowerCase());
if (usernameMatch) {
incrementHitCounter(groupId, pattern.raw);
console.log(`[BAN_CHECK] BANNED - Username "${username}" matched pattern "${pattern.raw}"`);
return true;
}
}
// Test display name variations
const displayName = [firstName, lastName].filter(Boolean).join(' ');
if (displayName) {
const variations = [
displayName,
displayName.replace(/["'`]/g, ''),
displayName.replace(/\s+/g, ''),
displayName.replace(/["'`\s]/g, '')
];
for (const variation of variations) {
const nameMatch = await matchesPattern(pattern.raw, variation.toLowerCase());
if (nameMatch) {
incrementHitCounter(groupId, pattern.raw);
console.log(`[BAN_CHECK] BANNED - Display name "${variation}" matched pattern "${pattern.raw}"`);
return true;
}
}
}
} catch (err) {
console.error(`[BAN_CHECK] Error testing pattern "${pattern.raw}": ${err.message}`);
continue;
}
}
console.log(`[BAN_CHECK] User not banned - no pattern matches`);
return false;
}
// Persistence Functions
async function ensureBannedPatternsDirectory() {
console.log(`[INIT] Creating patterns directory: ${BANNED_PATTERNS_DIR}`);
try {
await fs.mkdir(BANNED_PATTERNS_DIR, { recursive: true });
console.log(`[INIT] Patterns directory ready`);
} catch (err) {
console.error(`[INIT] Error creating directory ${BANNED_PATTERNS_DIR}:`, err);
}
}
async function getGroupPatternFilePath(groupId) {
const path = `${BANNED_PATTERNS_DIR}/patterns_${groupId}.toml`;
console.log(`[FILE] Pattern file path for group ${groupId}: ${path}`);
return path;
}
async function loadGroupPatterns(groupId) {
console.log(`[LOAD] Loading patterns for group ${groupId}`);
try {
const filePath = await getGroupPatternFilePath(groupId);
const data = await fs.readFile(filePath, 'utf-8');
const parsed = toml.parse(data);
if (!parsed.patterns || !Array.isArray(parsed.patterns)) {
console.log(`[LOAD] No patterns array found in file for group ${groupId}`);
return [];
}
console.log(`[LOAD] Found ${parsed.patterns.length} patterns in file`);
const validatedPatterns = [];
for (let i = 0; i < parsed.patterns.length; i++) {
const pt = parsed.patterns[i];
try {
// Use security module to validate and create pattern objects
const patternObj = createPatternObject(pt);
validatedPatterns.push(patternObj);
console.log(`[LOAD] Pattern ${i + 1}: "${pt}" - validated`);
// Safety limit
if (validatedPatterns.length >= 100) {
console.warn(`[LOAD] Reached maximum patterns (100) for group ${groupId}`);
break;
}
} catch (err) {
console.warn(`[LOAD] Pattern ${i + 1}: "${pt}" - skipped: ${err.message}`);
}
}
console.log(`[LOAD] Loaded ${validatedPatterns.length} valid patterns for group ${groupId}`);
return validatedPatterns;
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(`[LOAD] Error reading patterns for group ${groupId}:`, err);
} else {
console.log(`[LOAD] No pattern file exists for group ${groupId}`);
}
return [];
}
}
async function saveGroupPatterns(groupId, patterns) {
console.log(`[SAVE] Saving ${patterns.length} patterns for group ${groupId}`);
const lines = patterns.map(({ raw }) => ` "${raw}"`).join(',\n');
const content = `patterns = [\n${lines}\n]\n`;
try {
const filePath = await getGroupPatternFilePath(groupId);
await fs.writeFile(filePath, content);
console.log(`[SAVE] Successfully saved patterns to ${filePath}`);
} catch (err) {
console.error(`[SAVE] Error writing patterns for group ${groupId}:`, err);
}
}
async function loadAllGroupPatterns() {
console.log(`[INIT] Loading patterns for all whitelisted groups`);
await ensureBannedPatternsDirectory();
for (const groupId of WHITELISTED_GROUP_IDS) {
const patterns = await loadGroupPatterns(groupId);
groupPatterns.set(groupId, patterns);
console.log(`[INIT] Group ${groupId}: loaded ${patterns.length} patterns`);
}
console.log(`[INIT] Pattern loading complete - ${groupPatterns.size} groups configured`);
}
async function loadSettings() {
console.log(`[SETTINGS] Loading settings from ${SETTINGS_FILE}`);
try {
const data = await fs.readFile(SETTINGS_FILE, 'utf-8');
const loadedSettings = JSON.parse(data);
settings = {
groupActions: {},
...loadedSettings
};
console.log(`[SETTINGS] Loaded existing settings:`, settings);
} catch {
console.log(`[SETTINGS] No settings file found or error reading - creating new settings`);
settings = {
groupActions: {}
};
}
// Ensure all whitelisted groups have settings entries
let settingsChanged = false;
WHITELISTED_GROUP_IDS.forEach(groupId => {
if (!settings.groupActions[groupId]) {
settings.groupActions[groupId] = 'kick';
settingsChanged = true;
console.log(`[SETTINGS] Created default action for group ${groupId}: ${'kick'}`);
}
});
// Remove settings for groups no longer whitelisted
Object.keys(settings.groupActions).forEach(groupId => {
const numericGroupId = parseInt(groupId);
if (!WHITELISTED_GROUP_IDS.includes(numericGroupId)) {
delete settings.groupActions[groupId];
settingsChanged = true;
console.log(`[SETTINGS] Removed settings for non-whitelisted group ${groupId}`);
}
});
if (settingsChanged) {
await saveSettings();
}
console.log(`[SETTINGS] Final settings:`, settings.groupActions);
}
async function saveSettings() {
console.log(`[SETTINGS] Saving settings to ${SETTINGS_FILE}`);
try {
await fs.writeFile(SETTINGS_FILE, JSON.stringify(settings, null, 2));
console.log(`[SETTINGS] Settings saved successfully`);
return true;
} catch (err) {
console.error(`[SETTINGS] Error writing settings:`, err);
return false;
}
}
// Debounced save function to batch multiple increments
function debouncedSave() {
if (saveTimeout) {
clearTimeout(saveTimeout);
}
saveTimeout = setTimeout(() => {
saveHitCounters().catch(err => {
console.error(`[HITCOUNTER] Debounced save failed:`, err);
});
}, 1000); // Save after 1 second of inactivity
}
async function loadHitCounters() {
try {
const data = await fs.readFile(HIT_COUNTER_FILE, 'utf-8');
// Add JSON validation
const parsed = JSON.parse(data);
hitCounters = parsed;
console.log(`[HITCOUNTER] Loaded hit counters from disk.`);
} catch (err) {
hitCounters = {};
if (err.code === 'ENOENT') {
console.log(`[HITCOUNTER] No hit counter file found. Starting fresh.`);
} else if (err instanceof SyntaxError) {
console.error(`[HITCOUNTER] JSON corrupted, resetting:`, err.message);
// Auto-fix corrupted JSON by saving empty object
await saveHitCounters();
} else {
console.error(`[HITCOUNTER] Failed to load:`, err);
}
}
}
async function saveHitCounters() {
// Prevent concurrent saves
if (saveInProgress) {
pendingSave = true;
return;
}
saveInProgress = true;
try {
const jsonData = JSON.stringify(hitCounters, null, 2);
await fs.writeFile(HIT_COUNTER_FILE, jsonData);
console.log(`[HITCOUNTER] Saved hit counters to disk.`);
} catch (err) {
console.error(`[HITCOUNTER] Failed to save hit counters:`, err);
} finally {
saveInProgress = false;
// If another save was requested while this one was running, do it now
if (pendingSave) {
pendingSave = false;
// Use setTimeout to avoid recursion issues
setTimeout(() => saveHitCounters(), 10);
}
}
}
function incrementHitCounter(groupId, patternRaw) {
if (!groupId || !patternRaw) return;
if (!hitCounters[groupId]) hitCounters[groupId] = {};
if (!hitCounters[groupId][patternRaw]) hitCounters[groupId][patternRaw] = 0;
hitCounters[groupId][patternRaw] += 1;
// Use debounced save instead of immediate save to prevent race conditions
debouncedSave();
}
function getHitStatsForGroup(groupId, topN = 5) {
const groupStats = hitCounters[groupId] || {};
// Sort by count descending
return Object.entries(groupStats)
.sort((a, b) => b[1] - a[1])
.slice(0, topN)
.map(([pattern, count]) => ({ pattern, count }));
}
function getHitStatsForPattern(patternRaw) {
// Return all group stats for this pattern
const results = [];
for (const [groupId, patterns] of Object.entries(hitCounters)) {
if (patterns[patternRaw]) {
results.push({ groupId, count: patterns[patternRaw] });
}
}
return results;
}
// Action Handlers
async function takePunishmentAction(ctx, userId, username, chatId) {
const action = getGroupAction(chatId);
const isBan = action === 'ban';
console.log(`[PUNISH] Taking ${action.toUpperCase()} action against user ${userId} (@${username}) in chat ${chatId}`);
try {
if (isBan) {
await ctx.banChatMember(userId);
} else {
await ctx.banChatMember(userId, { until_date: Math.floor(Date.now() / 1000) + 35 });
}
const message = getRandomMessage(userId, isBan);
await ctx.reply(message);
console.log(`[PUNISH] ${isBan ? 'Banned' : 'Kicked'} user ${userId} successfully`);
return true;
} catch (error) {
console.error(`[PUNISH] Failed to ${isBan ? 'ban' : 'kick'} user ${userId}:`, error);
return false;
}
}
// Get all patterns from all groups for browsing/copying
function getAllGroupPatterns() {
const allPatterns = new Map();
WHITELISTED_GROUP_IDS.forEach(groupId => {
const patterns = groupPatterns.get(groupId) || [];
if (patterns.length > 0) {
allPatterns.set(groupId, patterns);
}
});
return allPatterns;
}
// Copy patterns from one group to another
async function copyPatternsToGroup(sourceGroupId, targetGroupId, patternIndices = null) {
console.log(`[COPY] Copying patterns from group ${sourceGroupId} to group ${targetGroupId}`);
const sourcePatterns = groupPatterns.get(sourceGroupId) || [];
let targetPatterns = groupPatterns.get(targetGroupId) || [];
if (sourcePatterns.length === 0) {
console.log(`[COPY] No patterns to copy from group ${sourceGroupId}`);
return { success: false, message: `No patterns found in source group ${sourceGroupId}` };
}
let patternsToCopy = [];
if (patternIndices === null) {
// Copy all patterns
patternsToCopy = sourcePatterns;
console.log(`[COPY] Copying all ${sourcePatterns.length} patterns`);
} else {
// Copy specific patterns by index
patternsToCopy = patternIndices.map(index => sourcePatterns[index]).filter(Boolean);
console.log(`[COPY] Copying ${patternsToCopy.length} selected patterns`);
}
let addedCount = 0;
let skippedCount = 0;
for (const pattern of patternsToCopy) {
// Check if pattern already exists
if (!targetPatterns.some(p => p.raw === pattern.raw)) {
// Check if we're at the limit
if (targetPatterns.length >= 100) {
console.log(`[COPY] Maximum patterns (100) reached for group ${targetGroupId}`);
break;
}
targetPatterns.push(pattern);
addedCount++;
console.log(`[COPY] Added pattern: "${pattern.raw}"`);
} else {
skippedCount++;
console.log(`[COPY] Skipped duplicate pattern: "${pattern.raw}"`);
}
}
if (addedCount > 0) {
groupPatterns.set(targetGroupId, targetPatterns);
await saveGroupPatterns(targetGroupId, targetPatterns);
}
console.log(`[COPY] Copy complete: ${addedCount} added, ${skippedCount} skipped`);
return {
success: true,
added: addedCount,
skipped: skippedCount,
message: `Copied ${addedCount} patterns (${skippedCount} duplicates skipped)`
};
}
// User Monitoring
function monitorNewUser(chatId, user) {
const key = `${chatId}_${user.id}`;
console.log(`[MONITOR] Starting name change monitoring for user ${user.id} in chat ${chatId}`);
let attempts = 0;
const interval = setInterval(async () => {
attempts++;
console.log(`[MONITOR] Check ${attempts}/6 for user ${user.id}`);
try {
const chatMember = await bot.telegram.getChatMember(chatId, user.id);
const username = chatMember.user.username;
const firstName = chatMember.user.first_name;
const lastName = chatMember.user.last_name;
const displayName = [firstName, lastName].filter(Boolean).join(' ');
console.log(`[MONITOR] Current name: @${username || 'no_username'}, Display: ${displayName}`);
if (await isBanned(username, firstName, lastName, chatId)) {
const action = getGroupAction(chatId);
const isBan = action === 'ban';
console.log(`[MONITOR] User ${user.id} matched pattern - taking action: ${action.toUpperCase()}`);
if (isBan) {
await bot.telegram.banChatMember(chatId, user.id);
} else {
await bot.telegram.banChatMember(chatId, user.id, { until_date: Math.floor(Date.now() / 1000) + 35 });
}
const message = getRandomMessage(user.id, isBan);
await bot.telegram.sendMessage(chatId, message);
clearInterval(interval);
delete newJoinMonitors[key];
console.log(`[MONITOR] Monitoring stopped - user ${user.id} was ${action}ned`);
return;
}
if (attempts >= 6) {
console.log(`[MONITOR] Monitoring completed for user ${user.id} - no violations`);
clearInterval(interval);
delete newJoinMonitors[key];
}
} catch (error) {
console.error(`[MONITOR] Error checking user ${user.id}:`, error);
clearInterval(interval);
delete newJoinMonitors[key];
}
}, 5000);
newJoinMonitors[key] = interval;
}
// --- Admin Menu Functions ---
// Show the main admin menu (updates an existing menu message if available)
async function showMainMenu(ctx) {
console.log(`[MENU] Showing main menu for admin ${ctx.from.id}`);
const adminId = ctx.from.id;
let session = adminSessions.get(adminId) || { chatId: ctx.chat.id };
// Determine which groups this user can manage
const isGlobalAdmin = WHITELISTED_USER_IDS.includes(adminId);
let manageableGroups = [];
if (isGlobalAdmin) {
manageableGroups = WHITELISTED_GROUP_IDS;
session.isGlobalAdmin = true;
console.log(`[MENU] Global admin - can manage all groups: ${manageableGroups.join(', ')}`);
} else {
// Group admin - can only manage their authorized group
if (session.authorizedGroupId && WHITELISTED_GROUP_IDS.includes(session.authorizedGroupId)) {
manageableGroups = [session.authorizedGroupId];
console.log(`[MENU] Group admin - can manage group: ${session.authorizedGroupId}`);
} else {
console.log(`[MENU] No manageable groups found for user ${adminId}`);
await ctx.reply("You don't have permission to manage any groups.");
return;
}
}
// Auto-select first manageable group if none selected
if (!session.selectedGroupId || !manageableGroups.includes(session.selectedGroupId)) {
session.selectedGroupId = manageableGroups[0];
console.log(`[MENU] Auto-selected group: ${session.selectedGroupId}`);
}
const selectedGroupId = session.selectedGroupId;
const patterns = groupPatterns.get(selectedGroupId) || [];
const groupAction = getGroupAction(selectedGroupId);
let text = `<b>Admin Menu</b>\n`;
if (isGlobalAdmin) {
text += `<b>Global Admin Access</b>\n`;
} else {
text += `<b>Group Admin Access</b>\n`;
}
text += `Selected Group: ${selectedGroupId}\n`;
text += `Patterns: ${patterns.length}/100\n`;
text += `Action: ${groupAction.toUpperCase()}\n\n`;
text += `Use the buttons below to manage filters.`;
// Create group selection buttons (only for groups user can manage)
const keyboard = { reply_markup: { inline_keyboard: [] } };
if (manageableGroups.length > 1) {
const groupButtons = manageableGroups.map(groupId => ({
text: `${groupId === selectedGroupId ? '✓ ' : ''}Group ${groupId} (${getGroupAction(groupId).toUpperCase()})`,
callback_data: `select_group_${groupId}`
}));
// Split group buttons into rows of 2
const groupRows = [];
for (let i = 0; i < groupButtons.length; i += 2) {
groupRows.push(groupButtons.slice(i, i + 2));
}
keyboard.reply_markup.inline_keyboard.push(...groupRows);
}
// Add management buttons
keyboard.reply_markup.inline_keyboard.push(
[
{ text: 'Add Filter', callback_data: 'menu_addFilter' },
{ text: 'Remove Filter', callback_data: 'menu_removeFilter' }
],
[
{ text: 'List Filters', callback_data: 'menu_listFilters' },
{ text: 'Browse & Copy', callback_data: 'menu_browsePatterns' }
],
[
{ text: `Action: ${groupAction.toUpperCase()}`, callback_data: 'menu_toggleAction' },
{ text: 'Test Pattern', callback_data: 'menu_testPattern' }
],
[
{ text: 'Pattern Help', callback_data: 'menu_patternHelp' },
{ text: 'Switch Group', callback_data: 'menu_switchGroup' }
]
);
adminSessions.set(adminId, session);
try {
// Always create a new message instead of trying to edit
// Clear the old menu message ID to force new message creation
if (session.menuMessageId) {
try {
await ctx.telegram.deleteMessage(session.chatId, session.menuMessageId);
} catch (err) {
// Ignore deletion errors - message might already be deleted
console.log(`[MENU] Could not delete old message: ${err.message}`);
}
}
const message = await ctx.reply(text, { parse_mode: 'HTML', ...keyboard });
session.menuMessageId = message.message_id;
session.chatId = ctx.chat.id;
adminSessions.set(adminId, session);
console.log(`[MENU] Created new menu message ${message.message_id}`);
} catch (e) {
console.error(`[MENU] Error showing main menu:`, e);
// Fallback: try to send without keyboard
try {
await ctx.reply(text, { parse_mode: 'HTML' });
} catch (fallbackErr) {
console.error(`[MENU] Fallback also failed:`, fallbackErr);
}
}
}
async function showPatternBrowsingMenu(ctx) {
console.log(`[MENU] Showing pattern browsing menu for admin ${ctx.from.id}`);
const adminId = ctx.from.id;
const session = adminSessions.get(adminId);
const currentGroupId = session.selectedGroupId;
const allPatterns = getAllGroupPatterns();
if (allPatterns.size === 0) {
await showOrEditMenu(ctx,
`<b>Browse & Copy Patterns</b>\n\nNo patterns found in any groups.`,
{
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [[{ text: 'Back to Menu', callback_data: 'menu_back' }]]
}
}
);
return;
}
let text = `<b>Browse & Copy Patterns</b>\n`;
text += `Your Selected Group: ${currentGroupId}\n\n`;
text += `Select any group to view and copy patterns:\n\n`;
const keyboard = { reply_markup: { inline_keyboard: [] } };
// Add buttons for ALL groups that have patterns (including current group for viewing)
for (const [groupId, patterns] of allPatterns) {
const buttonText = groupId === currentGroupId
? `Group ${groupId} (${patterns.length} patterns) - YOUR GROUP`
: `Group ${groupId} (${patterns.length} patterns)`;
keyboard.reply_markup.inline_keyboard.push([{
text: buttonText,
callback_data: `browse_group_${groupId}`
}]);
// Add sample patterns to the text
if (groupId === currentGroupId) {
text += `<b>Group ${groupId} (Your Group):</b> ${patterns.length} patterns\n`;
} else {
text += `<b>Group ${groupId}:</b> ${patterns.length} patterns\n`;
}
const samplePatterns = patterns.slice(0, 3).map(p => `<code>${p.raw}</code>`).join(', ');
text += `${samplePatterns}${patterns.length > 3 ? '...' : ''}\n\n`;
}
// If no other groups have patterns, show a note
if (allPatterns.size === 1 && allPatterns.has(currentGroupId)) {
text += `<i>Only your group has patterns. Other groups will appear here once they add patterns.</i>\n\n`;
}
keyboard.reply_markup.inline_keyboard.push([
{ text: 'Back to Menu', callback_data: 'menu_back' }
]);
await showOrEditMenu(ctx, text, {
parse_mode: 'HTML',
...keyboard
});
}
async function showGroupSelectionMenu(ctx) {
console.log(`[MENU] Showing group selection menu for admin ${ctx.from.id}`);
const adminId = ctx.from.id;
let session = adminSessions.get(adminId) || { chatId: ctx.chat.id };
const isGlobalAdmin = WHITELISTED_USER_IDS.includes(adminId);
let manageableGroups = [];
if (isGlobalAdmin) {
manageableGroups = WHITELISTED_GROUP_IDS;
} else {
if (session.authorizedGroupId && WHITELISTED_GROUP_IDS.includes(session.authorizedGroupId)) {
manageableGroups = [session.authorizedGroupId];
}
}
if (manageableGroups.length <= 1) {
await ctx.reply("You can only manage one group, so group switching is not available.");
await showMainMenu(ctx);
return;
}
let text = `<b>Select Group to Manage</b>\n\n`;
text += `Choose which group you want to configure:\n\n`;
const keyboard = { reply_markup: { inline_keyboard: [] } };
// Add buttons for each manageable group
for (const groupId of manageableGroups) {
const patterns = groupPatterns.get(groupId) || [];
const action = getGroupAction(groupId);
const isSelected = groupId === session.selectedGroupId;
text += `<b>Group ${groupId}</b>\n`;
text += `• Patterns: ${patterns.length}/100\n`;
text += `• Action: ${action.toUpperCase()}\n`;
text += `${isSelected ? '• <i>Currently Selected</i>' : ''}\n\n`;
keyboard.reply_markup.inline_keyboard.push([{
text: `${isSelected ? '✓ ' : ''}Select Group ${groupId} (${patterns.length} patterns)`,
callback_data: `select_group_${groupId}`
}]);
}
keyboard.reply_markup.inline_keyboard.push([
{ text: 'Back to Menu', callback_data: 'menu_back' }
]);
await showOrEditMenu(ctx, text, {
parse_mode: 'HTML',
...keyboard
});
}
async function showTestPatternMenu(ctx) {
console.log(`[MENU] Showing test pattern menu for admin ${ctx.from.id}`);
const adminId = ctx.from.id;
let session = adminSessions.get(adminId) || {};
session.action = 'Test Pattern';
adminSessions.set(adminId, session);
const promptText =
`<b>Test Pattern Matching</b>\n\n` +
`This will test if a pattern matches a given string.\n\n` +
`<b>Format:</b> <code>pattern|test-string</code>\n\n` +
`<b>Examples:</b>\n` +
`• <code>spam|spammer123</code>\n` +
`• <code>*bot*|testbot_user</code>\n` +
`• <code>/^evil/i|eviluser</code>\n\n` +
`Send your test in the format above, or use /cancel to abort.`;
await showOrEditMenu(ctx, promptText, {
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [[{ text: 'Cancel', callback_data: 'menu_back' }]]
}
});
}
async function showGroupPatternsForCopy(ctx, sourceGroupId) {
console.log(`[MENU] Showing patterns from group ${sourceGroupId} for viewing/copying`);
const adminId = ctx.from.id;
const session = adminSessions.get(adminId);
const targetGroupId = session.selectedGroupId;
const sourcePatterns = groupPatterns.get(sourceGroupId) || [];
if (sourcePatterns.length === 0) {
await showOrEditMenu(ctx,
`<b>Group ${sourceGroupId} Patterns</b>\n\nNo patterns found in this group.`,
{
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [[{ text: 'Back', callback_data: 'menu_browsePatterns' }]]
}
}
);
return;
}
const isOwnGroup = sourceGroupId === targetGroupId;
const canManageTarget = canManageGroup(adminId, targetGroupId);
let text = `<b>Group ${sourceGroupId} Patterns</b>\n`;
if (isOwnGroup) {
text += `<b>This is your selected group</b>\n\n`;
} else {
text += `To: Group ${targetGroupId} ${canManageTarget ? 'OK' : 'NO ACCESS'}\n\n`;
if (!canManageTarget) {
text += `<b>You cannot copy to Group ${targetGroupId}</b>\n`;
text += `You can only view these patterns.\n\n`;
}
}
text += `<b>Available Patterns (${sourcePatterns.length}):</b>\n\n`;
// Show all patterns with numbers
sourcePatterns.forEach((pattern, index) => {
text += `${index + 1}. <code>${pattern.raw}</code>\n`;
});
const keyboard = { reply_markup: { inline_keyboard: [] } };
// Only show copy buttons if not own group and can manage target
if (!isOwnGroup && canManageTarget) {
text += `\nChoose what to copy:`;
keyboard.reply_markup.inline_keyboard.push([
{ text: 'Copy All', callback_data: `copy_all_${sourceGroupId}` },
{ text: 'Select Specific', callback_data: `copy_select_${sourceGroupId}` }
]);
} else if (isOwnGroup) {
text += `\n<i>This is your group. Use the main menu to manage these patterns.</i>`;
} else {
text += `\n<i>You can view these patterns but cannot copy them to Group ${targetGroupId}.</i>`;
}
keyboard.reply_markup.inline_keyboard.push([
{ text: 'Back to Browse', callback_data: 'menu_browsePatterns' }
]);
await showOrEditMenu(ctx, text, {
parse_mode: 'HTML',
...keyboard
});
}
// Show or edit a menu-like message (used for prompts)
async function showOrEditMenu(ctx, text, extra) {
if (ctx.chat.type !== 'private') return;
console.log(`[MENU] Showing/editing prompt for admin ${ctx.from.id}`);
const adminId = ctx.from.id;
let session = adminSessions.get(adminId) || { chatId: ctx.chat.id };
try {
if (session.menuMessageId) {
await ctx.telegram.editMessageText(
session.chatId,
session.menuMessageId,
undefined,
text,
extra
);
console.log(`[MENU] Updated prompt message`);
} else {
const msg = await ctx.reply(text, extra);
session.menuMessageId = msg.message_id;
session.chatId = ctx.chat.id;
adminSessions.set(adminId, session);
console.log(`[MENU] Created new prompt message ${msg.message_id}`);
}
} catch (e) {
console.error(`[MENU] Error showing/editing prompt:`, e);
}
}
// Delete the current admin menu message and optionally send a confirmation
async function deleteMenu(ctx, confirmationMessage) {
if (ctx.chat.type !== 'private') return;
console.log(`[MENU] Deleting menu for admin ${ctx.from.id}`);
const adminId = ctx.from.id;
let session = adminSessions.get(adminId);
if (session && session.menuMessageId) {
try {
await ctx.telegram.deleteMessage(session.chatId, session.menuMessageId);
console.log(`[MENU] Deleted menu message ${session.menuMessageId}`);
} catch (e) {
console.error(`[MENU] Error deleting menu:`, e);
}
session.menuMessageId = null;
adminSessions.set(adminId, session);
}
if (confirmationMessage) {
await ctx.reply(confirmationMessage);
console.log(`[MENU] Sent confirmation: "${confirmationMessage}"`);
}
}
// Prompt the admin for a pattern, setting the session action accordingly
async function promptForPattern(ctx, actionLabel) {
if (ctx.chat.type !== 'private') return;
console.log(`[MENU] Prompting for pattern: ${actionLabel}`);
const adminId = ctx.from.id;
let session = adminSessions.get(adminId) || {};
const groupId = session.selectedGroupId;
const promptText =
`<b>Add Pattern for Group ${groupId}</b>\n\n` +
`<b>Pattern Types:</b>\n\n` +
`<b>1. Simple Text</b> - Case-insensitive substring match\n` +
` • <code>spam</code> matches "SPAM", "Spam", "spammer"\n\n` +
`<b>2. Wildcards</b>\n` +
` • <code>*</code> = any characters\n` +
` • <code>?</code> = single character\n` +
` • <code>spam*</code> matches "spam", "spammer", "spam123"\n` +
` • <code>*bot</code> matches "mybot", "testbot", "123bot"\n` +
` • <code>*bad*</code> matches "baduser", "this_is_bad"\n` +
` • <code>test?</code> matches "test1", "testa", "tests"\n\n` +
`<b>3. Regular Expressions</b> - Advanced patterns\n` +
` • Format: <code>/pattern/flags</code>\n` +
` • <code>/^spam.*$/i</code> starts with "spam"\n` +
` • <code>/\\d{5,}/</code> 5+ digits in a row\n` +
` • <code>/ch[!1i]ld/i</code> "child", "ch!ld", "ch1ld"\n\n` +