-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
1647 lines (1393 loc) · 65.3 KB
/
Copy pathbot.py
File metadata and controls
1647 lines (1393 loc) · 65.3 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
"""Main Telegram Bot - handles all user interactions"""
import asyncio
from pathlib import Path
from loguru import logger
from telegram import (
InlineKeyboardButton,
InlineKeyboardMarkup,
KeyboardButton,
ReplyKeyboardMarkup,
Update,
WebAppInfo,
)
from telegram.constants import ParseMode
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
MessageHandler,
PersistenceInput,
PicklePersistence,
filters,
)
import config
from aggregator import ResultAggregator
from database import Database
from utils import is_valid_url, normalize_url, setup_logging, truncate_text
from log_server import start_log_server
from batch_scanner import BatchScanner, DeepScanner, ScanQueue
from export_handler import ExportHandler
from visual_enhancer import VisualEnhancer
class APIBot:
"""Telegram Bot for API Resource Availability Testing"""
def __init__(self):
"""Initialize bot"""
self.aggregator = ResultAggregator()
self.db = Database() # Only for bot-wide stats
self.active_scans = {} # Track active scans per user
self.start_time = None # Track bot start time
self.is_running = False # Track bot status
self.last_status_update = None # Track last status update time
self.update_task = None # Background task for periodic status updates
# New features
self.batch_scanner = BatchScanner(self.aggregator, max_parallel=3)
self.deep_scanner = DeepScanner(self.aggregator, max_depth=2, max_pages=10)
self.scan_queue = ScanQueue(max_concurrent=2)
self.visual = VisualEnhancer()
self.cancel_flags = {} # Track cancel requests per user
# Setup logging
setup_logging(config.LOG_LEVEL, config.LOG_FILE)
# Ensure user data directory exists
self.user_data_dir = Path("telegram_user_data")
self.user_data_dir.mkdir(exist_ok=True)
def _get_main_menu_keyboard(self) -> ReplyKeyboardMarkup:
"""Get persistent reply keyboard for main menu"""
# Web App hosted on same Render instance
webapp_url = "https://api-bot-in6q.onrender.com/webapp"
keyboard = [
[KeyboardButton("🌐 Open Web Scanner", web_app=WebAppInfo(url=webapp_url))],
[KeyboardButton("📚 Bookmarks"), KeyboardButton("📊 Stats")],
[KeyboardButton("📦 Batch Scan"), KeyboardButton("🔬 Deep Scan")],
[KeyboardButton("📤 Export"), KeyboardButton("🔴 Status")],
[KeyboardButton("❓ Help")]
]
return ReplyKeyboardMarkup(
keyboard,
resize_keyboard=True,
one_time_keyboard=False
)
async def _update_bot_status(self, bot, force=False):
"""Update bot's Telegram status/description"""
try:
from datetime import datetime, timedelta
# Rate limit: only update every 30 seconds (unless forced)
if not force and self.last_status_update:
time_since_update = datetime.now() - self.last_status_update
if time_since_update < timedelta(seconds=30):
logger.debug("Skipping status update (rate limited)")
return
if self.is_running and self.start_time:
uptime = datetime.now() - self.start_time
days = uptime.days
hours, remainder = divmod(uptime.seconds, 3600)
minutes, _ = divmod(remainder, 60)
# Format uptime for status
if days > 0:
uptime_str = f"{days}d {hours}h"
elif hours > 0:
uptime_str = f"{hours}h {minutes}m"
else:
uptime_str = f"{minutes}m"
status_text = f"🟢 Active | Uptime: {uptime_str} | 21 Scanners Running"
status_emoji = "🟢"
else:
status_text = "🔴 Initializing..."
status_emoji = "🔴"
# Update bot's display name with status indicator (visible everywhere)
try:
await bot.set_my_name(
name=f"{status_emoji} API URL Bot"
)
except Exception as e:
logger.warning(f"Could not update bot name: {e}")
# Set bot's short description (visible in bot info)
await bot.set_my_short_description(
short_description=status_text
)
# Set bot's description (visible when starting chat)
full_description = (
"🤖 API & Resource Testing Bot\n\n"
f"Status: {status_text}\n\n"
"✅ 19 Advanced Scanners\n"
"⚡ Parallel Processing\n"
"🔍 Comprehensive Analysis\n\n"
"Send any URL to start scanning!"
)
await bot.set_my_description(
description=full_description
)
self.last_status_update = datetime.now()
logger.info(f"Bot status updated: {status_text}")
except Exception as e:
logger.error(f"Failed to update bot status: {e}")
async def _periodic_status_update(self, bot):
"""Background task to update bot status every 5 minutes"""
import httpx
try:
while self.is_running:
await asyncio.sleep(300) # Wait 5 minutes
if self.is_running: # Check again after sleep
logger.info("Periodic status update triggered")
await self._update_bot_status(bot, force=False)
# Keep-alive: ping own log server to prevent Render sleep
try:
async with httpx.AsyncClient(timeout=10) as client:
await client.get("http://localhost:10000/")
logger.info("✓ Keep-alive ping sent")
except Exception as ping_error:
logger.debug(f"Keep-alive ping failed (non-critical): {ping_error}")
except asyncio.CancelledError:
logger.info("Periodic status update task cancelled")
except Exception as e:
logger.error(f"Error in periodic status update: {e}")
async def post_init(self, application: Application):
"""Post initialization - setup database"""
from datetime import datetime
from performance import warm_up, clear_old_cache
await self.db.initialize()
self.is_running = True
self.start_time = datetime.now()
# Start log server FIRST (Render needs open port immediately)
logger.info("Starting web log server...")
await start_log_server()
# Warm up for Render performance
logger.info("Warming up services...")
await warm_up()
# Start cache cleanup task
asyncio.create_task(self._periodic_cache_cleanup())
# Initialize bot-wide data if not exists
if 'total_users' not in application.bot_data:
application.bot_data['total_users'] = 0
# Set bot status in Telegram
await self._update_bot_status(application.bot, force=True)
# Start periodic status update task
self.update_task = asyncio.create_task(
self._periodic_status_update(application.bot)
)
logger.info("Periodic status update task started")
logger.info("Bot initialized successfully")
async def _periodic_cache_cleanup(self):
"""Background task to clean expired cache every 10 minutes"""
from performance import clear_old_cache
try:
while self.is_running:
await asyncio.sleep(600) # 10 minutes
clear_old_cache()
logger.debug("Cache cleanup completed")
except asyncio.CancelledError:
pass
async def post_shutdown(self, application: Application):
"""Post shutdown - update status to offline with delay"""
import asyncio
try:
logger.info("Starting shutdown sequence...")
self.is_running = False
# Cancel periodic update task
if self.update_task and not self.update_task.done():
self.update_task.cancel()
try:
await self.update_task
except asyncio.CancelledError:
pass
logger.info("Periodic update task cancelled")
# Update bot status to offline (with retry and delay)
update_success = False
try:
logger.info("Updating bot status to offline...")
# Try to update bot name in chat/profile
try:
await application.bot.set_my_name(
name="🔴 API URL Bot"
)
logger.info("✓ Bot name updated to offline")
except Exception as e:
logger.warning(f"Could not update bot name: {e}")
# Update short description (visible in bot info)
try:
await application.bot.set_my_short_description(
short_description="🔴 Offline"
)
logger.info("✓ Short description updated")
except Exception as e:
logger.warning(f"Could not update short description: {e}")
# Update full description (visible when starting chat)
try:
await application.bot.set_my_description(
description=(
"🤖 API & Resource Testing Bot\n\n"
"Status: 🔴 Offline\n\n"
"✅ 19 Advanced Scanners\n"
"⚡ Parallel Processing\n"
"🔍 Comprehensive Analysis\n\n"
"Bot is currently not running."
)
)
logger.info("✓ Full description updated")
except Exception as e:
logger.warning(f"Could not update description: {e}")
update_success = True
logger.info("Bot status successfully updated to offline")
# Add delay to ensure updates are sent
logger.info("Waiting 2 seconds for status updates to propagate...")
await asyncio.sleep(2)
except Exception as e:
logger.warning(f"Could not update Telegram status: {e}")
except Exception as e:
logger.error(f"Error during shutdown: {e}")
finally:
# Close database
try:
await self.db.close()
except Exception as e:
logger.error(f"Error closing database: {e}")
logger.info("Bot shutdown complete")
async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /start command"""
from datetime import datetime
# Initialize user data if first time
if 'initialized' not in context.user_data:
context.user_data['initialized'] = True
context.user_data['bookmarks'] = []
context.user_data['scan_history'] = []
context.user_data['preferences'] = {
'show_detailed': True,
'auto_bookmark': False,
'notification_enabled': True
}
context.user_data['first_seen'] = datetime.now().isoformat()
# Increment total users count
context.bot_data['total_users'] = context.bot_data.get('total_users', 0) + 1
logger.info(f"New user registered: {update.effective_user.id}")
# Update last seen
context.user_data['last_seen'] = datetime.now().isoformat()
# Get total user count from bot_data
total_users = context.bot_data.get('total_users', 0)
# Calculate real-time uptime
if self.is_running and self.start_time:
uptime = datetime.now() - self.start_time
days = uptime.days
hours, remainder = divmod(uptime.seconds, 3600)
minutes, _ = divmod(remainder, 60)
# Format uptime
uptime_parts = []
if days > 0:
uptime_parts.append(f"{days}d")
if hours > 0:
uptime_parts.append(f"{hours}h")
if minutes > 0:
uptime_parts.append(f"{minutes}m")
uptime_str = " ".join(uptime_parts) if uptime_parts else "< 1m"
status_text = f"🟢 *Active* | Uptime: `{uptime_str}` | 👥 {total_users} Users | 21 Scanners"
else:
status_text = f"🔴 *Initializing...* | 👥 {total_users} Users"
# Dynamic welcome message with real-time status
welcome_message = (
f"🤖 *API Resource Availability Bot*\n\n"
f"*Status:* {status_text}\n\n"
f"🔍 *21 Advanced Scanners - Comprehensive Website Analysis*\n\n"
f"*Core Scanners:*\n"
f"• 🌐 Availability & Latency Detection\n"
f"• 🔍 DNS & IP Information Lookup\n"
f"• 🔒 Protocol & Security Analysis\n"
f"• 💰 Paywall & Authentication Detection\n"
f"• ⚠️ Security Breach Status Check\n\n"
f"*Performance & SEO:*\n"
f"• ⚡ Performance Metrics (Load Time, TTFB)\n"
f"• 📊 SEO Analysis (Meta Tags, Sitemap)\n"
f"• 📱 Mobile Optimization Check\n\n"
f"*Security & Privacy:*\n"
f"• 🔐 Authentication Methods (OAuth, SSO)\n"
f"• 🍪 Privacy & Cookie Compliance\n"
f"• 🌍 CORS Configuration\n"
f"• 🔓 Insecure Content Detection\n\n"
f"*Advanced Analysis:*\n"
f"• 🛠️ Tech Stack Detection (CMS, Frameworks, Hidden Tech)\n"
f"• 💾 Database Detection\n"
f"• 💳 Payment Provider Detection\n"
f"• 🔄 Redirect Chain Analysis\n"
f"• 🌍 Geolocation & Network Detection\n"
f"• 📡 CDN & Hosting Provider Detection\n"
f"• 🤖 Robots.txt & Sitemap Checker\n"
f"• 📜 Certificate & SSL Analysis\n\n"
f"⚡ *Parallel Processing* - All scanners run simultaneously!\n"
f"📊 Get detailed reports in seconds!\n"
f"🌐 *NEW:* WebApp interface available!\n\n"
f"Send me any URL to start comprehensive scanning!"
)
# WebApp button - Uncomment and update URL after deploying webapp/index.html
# from telegram import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
#
# Deploy webapp/index.html to GitHub Pages, Netlify, or Vercel first, then:
# keyboard = [
# [InlineKeyboardButton(
# "🌐 Open Web Scanner",
# web_app=WebAppInfo(url="https://YOUR-USERNAME.github.io/bot-webapp/index.html")
# )],
# [InlineKeyboardButton("📖 Help", callback_data="show_help")],
# ]
# reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
welcome_message,
parse_mode=ParseMode.MARKDOWN,
reply_markup=self._get_main_menu_keyboard()
)
async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /help command"""
help_text = (
"*Available Commands:*\n\n"
"/start - Start the bot\n"
"/start - Start the bot\n"
"/help - Show this help message\n"
"/bookmarks - View your bookmarks\n"
"/stats - View your statistics\n"
"/status - Check bot status\n"
"/batch - Scan multiple URLs at once\n"
"/deepscan - Deep scan with link crawling\n"
"/export - Export last scan results\n"
"/cancel - Cancel current mode\n"
"/cleardata - Clear all your data\n\n"
"*New Features:*\n"
"📦 **Batch Scan** - Scan up to 10 URLs simultaneously\n"
"🔬 **Deep Scan** - Crawl and scan linked pages (up to 2 levels)\n"
"📤 **Export** - Export results in JSON, CSV, Markdown, HTML, or Text\n"
"✨ **Enhanced Visuals** - Beautiful progress bars and animations\n\n"
"*Usage:*\n"
"Simply send me any URL to scan!"
)
await update.message.reply_text(
help_text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=self._get_main_menu_keyboard()
)
async def status_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /status command - show bot status"""
from datetime import datetime
# Update bot's Telegram status
await self._update_bot_status(context.bot)
if not self.is_running or not self.start_time:
status_text = "🔴 *Bot Status: Unknown*\n\nCannot determine bot status."
else:
# Calculate uptime
uptime = datetime.now() - self.start_time
days = uptime.days
hours, remainder = divmod(uptime.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# Format uptime
uptime_parts = []
if days > 0:
uptime_parts.append(f"{days}d")
if hours > 0:
uptime_parts.append(f"{hours}h")
if minutes > 0:
uptime_parts.append(f"{minutes}m")
uptime_parts.append(f"{seconds}s")
uptime_str = " ".join(uptime_parts)
# Get stats
user_id = update.effective_user.id
# Get stats from context.user_data
total_scans = len(context.user_data.get('scan_history', []))
bookmarks_count = len(context.user_data.get('bookmarks', []))
# Check active scans
active_scan_count = len(self.active_scans)
# Get performance stats
from performance import get_performance_stats
perf_stats = get_performance_stats()
cache_entries = perf_stats['cache']['total_entries']
cache_mb = perf_stats['cache']['memory_mb']
status_text = (
f"🟢 *Bot Status: Active*\n\n"
f"⏱️ Uptime: `{uptime_str}`\n"
f"📅 Started: `{self.start_time.strftime('%Y-%m-%d %H:%M:%S')}`\n"
f"🔄 Active Scans: {active_scan_count}\n\n"
f"*Your Activity:*\n"
f"📊 Total Scans: {total_scans}\n"
f"📚 Bookmarks: {bookmarks_count}\n\n"
f"*Performance:*\n"
f"💾 Cache: {cache_entries} entries ({cache_mb:.2f} MB)\n"
f"⚡ Fast mode: {'ON' if config.ENABLE_CACHING else 'OFF'}\n\n"
f"*Scanner Modules:*\n"
f"✅ 21 scanners active\n"
f"⚡ Parallel execution enabled\n"
f"🔍 Comprehensive analysis"
)
await update.message.reply_text(
status_text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=self._get_main_menu_keyboard()
)
async def handle_keyboard_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle keyboard button presses"""
text = update.message.text
if text == "📚 Bookmarks":
await self.bookmarks_command(update, context)
elif text == "📊 Stats":
await self.stats_command(update, context)
elif text == "📦 Batch Scan":
await self.batch_scan_command(update, context)
elif text == "🔬 Deep Scan":
await self.deep_scan_command(update, context)
elif text == "📤 Export":
await self.export_command(update, context)
elif text == "🔴 Status":
await self.status_command(update, context)
elif text == "❓ Help":
await self.help_command(update, context)
async def bookmarks_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /bookmarks command"""
bookmarks = context.user_data.get('bookmarks', [])
if not bookmarks:
await update.message.reply_text(
config.MESSAGES['no_bookmarks'],
reply_markup=self._get_main_menu_keyboard()
)
return
# Create keyboard with bookmarks
keyboard = []
for bookmark in bookmarks[:20]: # Limit to 20
# Get status emoji
status_emoji = '🟢' if bookmark.get('last_status') == 'AVAILABLE' else '🔴'
button_text = f"{status_emoji} {truncate_text(bookmark.get('title', bookmark['url']), 30)}"
keyboard.append([
InlineKeyboardButton(
button_text,
callback_data=f"scan:{bookmark['url']}"
)
])
# Add refresh all button
keyboard.append([
InlineKeyboardButton("🔄 Refresh All", callback_data="refresh_bookmarks")
])
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
f"📚 *Your Bookmarks* ({len(bookmarks)})\n"
"Click to scan again:",
parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup
)
async def stats_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /stats command"""
bookmarks = context.user_data.get('bookmarks', [])
scan_history = context.user_data.get('scan_history', [])
# Calculate most scanned URL
from collections import Counter
if scan_history:
url_counter = Counter([scan['url'] for scan in scan_history if 'url' in scan])
most_common = url_counter.most_common(1)
most_scanned_url = most_common[0][0] if most_common else None
most_scanned_count = most_common[0][1] if most_common else 0
else:
most_scanned_url = None
most_scanned_count = 0
stats_text = (
"*📊 Your Statistics*\n\n"
f"📚 Total Bookmarks: {len(bookmarks)}\n"
f"🔍 Total Scans: {len(scan_history)}\n"
)
if most_scanned_url:
stats_text += f"\n🎯 Most Scanned: {truncate_text(most_scanned_url, 40)}\n"
stats_text += f" ({most_scanned_count} times)"
await update.message.reply_text(
stats_text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=self._get_main_menu_keyboard()
)
async def settings_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /settings command"""
prefs = context.user_data.get('preferences', {
'show_detailed': True,
'auto_bookmark': False,
'notification_enabled': True
})
keyboard = [
[InlineKeyboardButton(
f"{'✅' if prefs.get('show_detailed') else '❌'} Detailed Reports",
callback_data="toggle:show_detailed"
)],
[InlineKeyboardButton(
f"{'✅' if prefs.get('auto_bookmark') else '❌'} Auto Bookmark",
callback_data="toggle:auto_bookmark"
)],
[InlineKeyboardButton(
f"{'✅' if prefs.get('notification_enabled') else '❌'} Notifications",
callback_data="toggle:notification_enabled"
)],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"*⚙️ Settings*\n\nClick to toggle options:",
parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup
)
async def cleardata_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /cleardata command - clear all user data"""
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
# Ask for confirmation
keyboard = [
[
InlineKeyboardButton("✅ Yes, Clear All Data", callback_data="confirm_cleardata"),
InlineKeyboardButton("❌ Cancel", callback_data="cancel_cleardata")
]
]
await update.message.reply_text(
"⚠️ *Warning*\n\n"
"This will permanently delete:\n"
"• All your bookmarks\n"
"• All scan history\n"
"• All your preferences\n\n"
"This action cannot be undone. Are you sure?",
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(keyboard)
)
async def handle_url(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle URL messages with security validation"""
user_id = update.effective_user.id
text = update.message.text.strip()
# Check if it's a keyboard button (fallback if handler didn't catch it)
if text in ['📚 Bookmarks', '📊 Stats', '📦 Batch Scan', '🔬 Deep Scan', '📤 Export', '🔴 Status', '❓ Help']:
await self.handle_keyboard_button(update, context)
return
# Check for batch mode
if context.user_data.get('expecting_batch_urls'):
urls = [line.strip() for line in text.split('\n') if line.strip()]
urls = [u for u in urls if is_valid_url(u)]
if not urls:
await update.message.reply_text(
f"{self.visual.EMOJIS['error']} No valid URLs found!\n\n"
f"Please send URLs, one per line.",
reply_markup=self._get_main_menu_keyboard()
)
return
if len(urls) > 10:
await update.message.reply_text(
f"{self.visual.EMOJIS['warning']} Too many URLs! Maximum is 10.\n\n"
f"Please send fewer URLs.",
reply_markup=self._get_main_menu_keyboard()
)
return
# Clear batch mode
context.user_data.pop('expecting_batch_urls', None)
# Process batch
await self.process_batch_scan(update, urls)
return
# Check for deep scan mode
if context.user_data.get('expecting_deep_scan_url'):
if not is_valid_url(text):
await update.message.reply_text(
f"{self.visual.EMOJIS['error']} Invalid URL!\n\n"
f"Please send a valid URL.",
reply_markup=self._get_main_menu_keyboard()
)
return
# Clear deep scan mode
context.user_data.pop('expecting_deep_scan_url', None)
# Process deep scan
await self.process_deep_scan(update, text, context)
return
# Regular URL handling
url = text
# SECURITY: Rate limiting check
from security_utils import check_rate_limit, validate_url as secure_validate_url, sanitize_url
is_allowed, error_msg = check_rate_limit(user_id)
if not is_allowed:
await update.message.reply_text(
f"⚠️ {error_msg}",
reply_markup=self._get_main_menu_keyboard()
)
return
# SECURITY: Validate URL with advanced checks
is_valid, error_msg = secure_validate_url(url)
if not is_valid:
await update.message.reply_text(
f"❌ {error_msg}",
reply_markup=self._get_main_menu_keyboard()
)
logger.warning(f"Invalid URL from user {user_id}: {url}")
return
# Fallback to legacy validation
if not is_valid_url(url):
await update.message.reply_text(
config.MESSAGES['invalid_url'],
reply_markup=self._get_main_menu_keyboard()
)
return
# SECURITY: Sanitize URL
url = sanitize_url(url)
# Normalize URL
url = normalize_url(url)
# Check if already scanning
if user_id in self.active_scans:
await update.message.reply_text(
"⏳ Please wait for the current scan to complete.",
reply_markup=self._get_main_menu_keyboard()
)
return
# Start scan
self.active_scans[user_id] = True
# Show animated scanning message
status_message = await update.message.reply_text(
f"{self.visual.EMOJIS['loading'][0]} **Initializing scan...**\n\n"
f"URL: {url[:50]}{'...' if len(url) > 50 else ''}",
parse_mode=ParseMode.MARKDOWN,
reply_markup=self._get_main_menu_keyboard()
)
# Start animation task
animation_task = asyncio.create_task(
self.visual.animate_scanning(status_message, url[:40])
)
try:
from datetime import datetime
# Check for cancel before scanning
if self.cancel_flags.get(user_id):
self.cancel_flags.pop(user_id, None) # Clear flag
animation_task.cancel()
try:
await animation_task
except asyncio.CancelledError:
pass
await status_message.edit_text(
f"{self.visual.EMOJIS['cross']} Scan cancelled by user.",
reply_markup=self._get_main_menu_keyboard()
)
self.active_scans.pop(user_id, None)
return
# Perform scan with timeout (60 seconds max)
try:
results = await asyncio.wait_for(
self.aggregator.scan_url(url),
timeout=60.0
)
except asyncio.TimeoutError:
animation_task.cancel()
try:
await animation_task
except asyncio.CancelledError:
pass
await status_message.edit_text(
f"{self.visual.EMOJIS['cross']} Scan timeout! The URL took too long to respond.\n\n"
f"Try again later.",
reply_markup=self._get_main_menu_keyboard()
)
self.active_scans.pop(user_id, None)
return
# Cancel animation
animation_task.cancel()
try:
await animation_task
except asyncio.CancelledError:
pass
# Save to user's scan history in context.user_data
if 'scan_history' not in context.user_data:
context.user_data['scan_history'] = []
context.user_data['scan_history'].append({
'url': url,
'results': results,
'timestamp': datetime.now().isoformat()
})
# Save last scan result for export
context.user_data['last_scan_result'] = results
# Keep only last 100 scans to avoid memory issues
if len(context.user_data['scan_history']) > 100:
context.user_data['scan_history'] = context.user_data['scan_history'][-100:]
# Check if bookmarked and update status
bookmarks = context.user_data.get('bookmarks', [])
for bookmark in bookmarks:
if bookmark['url'] == url:
bookmark['last_status'] = results.get('summary', {}).get('status', 'UNKNOWN')
bookmark['last_scan'] = datetime.now().isoformat()
break
# Format results with enhanced visuals
result_text = self.visual.format_scan_result(results)
# Add detailed report section
prefs = context.user_data.get('preferences', {'show_detailed': True})
if prefs.get('show_detailed', True):
result_text += "\n\n" + self.aggregator.format_detailed_report(results)
else:
result_text += "\n\n" + self.aggregator.format_as_table(results)
# Delete status message
await status_message.delete()
# Send results with action buttons AND persistent menu
keyboard = self._get_result_keyboard_with_bookmark(url, bookmarks)
await update.message.reply_text(
result_text,
parse_mode=None, # Disable markdown to prevent parse errors
reply_markup=keyboard
)
# Send persistent menu in separate message to keep it visible
await update.message.reply_text(
"Use buttons below for quick actions:",
reply_markup=self._get_main_menu_keyboard()
)
except Exception as e:
logger.error(f"Error scanning {url}: {e}")
await status_message.edit_text(
config.MESSAGES['error'].format(str(e))
)
finally:
# Remove from active scans
self.active_scans.pop(user_id, None)
async def handle_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle callback queries from inline buttons"""
from telegram.error import BadRequest
query = update.callback_query
# Try to answer the callback query
try:
await query.answer()
except BadRequest as e:
if "Query is too old" in str(e) or "query id is invalid" in str(e):
logger.warning(f"Ignoring expired callback query: {e}")
return
raise
user_id = update.effective_user.id
data = query.data
try:
if data.startswith('scan:'):
# Rescan URL
url = data.split(':', 1)[1]
await self._rescan_url(query, user_id, url, context)
elif data.startswith('bookmark:'):
# Add to bookmarks
url = data.split(':', 1)[1]
await self._add_bookmark(query, user_id, url, context)
elif data.startswith('unbookmark:'):
# Remove from bookmarks
url = data.split(':', 1)[1]
await self._remove_bookmark(query, user_id, url, context)
elif data.startswith('logs:'):
# Show logs
url = data.split(':', 1)[1]
await self._show_logs(query, user_id, url, context)
elif data.startswith('toggle:'):
# Toggle setting
setting = data.split(':', 1)[1]
await self._toggle_setting(query, user_id, setting, context)
elif data == 'refresh_bookmarks':
await self._refresh_bookmarks(query, user_id, context)
elif data.startswith('export_'):
# Export results
export_format = data.split('_', 1)[1]
await self._export_results(query, user_id, export_format, context)
elif data == 'confirm_cleardata':
# Clear all user data
context.user_data.clear()
context.user_data['initialized'] = True
context.user_data['bookmarks'] = []
context.user_data['scan_history'] = []
context.user_data['preferences'] = {
'show_detailed': True,
'auto_bookmark': False,
'notification_enabled': True
}
from datetime import datetime
context.user_data['first_seen'] = datetime.now().isoformat()
await query.message.edit_text(
"✅ *Data Cleared*\n\n"
"All your data has been permanently deleted.",
parse_mode=ParseMode.MARKDOWN
)
elif data == 'cancel_cleardata':
await query.message.edit_text(
"❌ Cancelled. Your data is safe.",
parse_mode=ParseMode.MARKDOWN
)
except Exception as e:
logger.error(f"Error handling callback {data}: {e}")
await query.message.reply_text(
config.MESSAGES['error'].format(str(e))
)
async def _rescan_url(self, query, user_id: int, url: str, context: ContextTypes.DEFAULT_TYPE):
"""Rescan a URL"""
await query.message.edit_text(config.MESSAGES['scanning'])
try:
from datetime import datetime
results = await self.aggregator.scan_url(url)
# Save to scan history
if 'scan_history' not in context.user_data:
context.user_data['scan_history'] = []
context.user_data['scan_history'].append({
'url': url,
'results': results,
'timestamp': datetime.now().isoformat()
})
# Keep only last 100 scans
if len(context.user_data['scan_history']) > 100:
context.user_data['scan_history'] = context.user_data['scan_history'][-100:]
# Update bookmark status if bookmarked
bookmarks = context.user_data.get('bookmarks', [])
for bookmark in bookmarks:
if bookmark['url'] == url:
bookmark['last_status'] = results.get('summary', {}).get('status', 'UNKNOWN')
bookmark['last_scan'] = datetime.now().isoformat()
break
prefs = context.user_data.get('preferences', {'show_detailed': True})
if prefs.get('show_detailed', True):
result_text = self.aggregator.format_detailed_report(results)
else:
result_text = self.aggregator.format_as_table(results)
keyboard = self._get_result_keyboard_with_bookmark(url, bookmarks)
await query.message.edit_text(
result_text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=keyboard
)
except Exception as e:
logger.error(f"Error rescanning {url}: {e}")
await query.message.edit_text(
config.MESSAGES['error'].format(str(e))
)
async def _add_bookmark(self, query, user_id: int, url: str, context: ContextTypes.DEFAULT_TYPE):
"""Add URL to bookmarks"""
from datetime import datetime
bookmarks = context.user_data.get('bookmarks', [])
# Check if already bookmarked
is_bookmarked = any(b['url'] == url for b in bookmarks)
if is_bookmarked:
await query.answer("ℹ️ Already bookmarked!", show_alert=False)
return
# Add bookmark
bookmarks.append({