-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
2314 lines (1892 loc) · 91.5 KB
/
main.py
File metadata and controls
2314 lines (1892 loc) · 91.5 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
import json
import logging
import logging.handlers
import os
import platform
import queue
import re
import shutil
import sys
from datetime import datetime
from datetime import timedelta
import discord
import psutil
from cachetools import TTLCache
from discord.ext import commands, tasks
from dotenv import load_dotenv
from utils.cache_utils import get_cache_stats, load_bad_words
from utils.command_utils import setup_command_execution, handle_cancel_request, apply_cooldown, save_scan_results
from utils.search_utils import process_search_channels, update_search_status, update_search_stats
# --- Environment check ---
def check_environment():
"""Check the runtime environment and return any warnings."""
warnings = []
# Check Python version
python_version = tuple(map(int, platform.python_version_tuple()))
if python_version < (3, 8):
raise Exception("DeepSearch requires Python 3.8 or higher to work because it uses the Discord.py library. Please update your Python version.")
# Check if running in IDE first (takes precedence over venv detection)
in_ide = any(ide in os.environ.get('PYTHONPATH', '').lower() for ide in ['pycharm', 'vscode', 'eclipse', 'intellij', 'idle']) or \
'PYCHARM_HOSTED' in os.environ or 'VSCODE_CLI' in os.environ or 'VSCODE_CWD' in os.environ or \
'SPYDER' in os.environ or 'JUPYTER' in os.environ or 'IDLE' in os.environ
# Define environments to check with custom messages
env_checks = {
"Docker": (os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"),
"Running in Docker container"),
"Pterodactyl": (os.environ.get("P_SERVER_LOCATION") is not None or
os.path.exists("/etc/pterodactyl") or
"pterodactyl" in os.environ.get("HOSTNAME", "").lower(),
"Running in Pterodactyl environment"),
"Virtual Environment": (not in_ide and # Only report venv if not in IDE
(hasattr(sys, 'real_prefix') or
(hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)),
"Running in a virtual environment"),
"IDE": (in_ide, "Running in an IDE environment"),
"Raspberry Pi": (platform.system() == 'Linux' and 'arm' in platform.machine().lower(),
"Running on Raspberry Pi. Performance may be limited"),
"Low Memory": (psutil.virtual_memory().total < 2 * 1024 * 1024 * 1024,
"Less than 2GB of RAM detected. Performance may be affected"),
"Headless System": (os.environ.get('DISPLAY', '') == '', None) # Don't warn about headless
}
# Add warnings for detected environments that need caution
for env_type, (detected, message) in env_checks.items():
if detected and message: # Only add warning if there's a message to display
warnings.append(message)
# Check internet connection (only on posix systems)
if os.name == 'posix':
try:
import subprocess
subprocess.run(
["ping", "-c", "1", "8.8.8.8"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2 # Add timeout to prevent hanging
)
except (subprocess.SubprocessError, FileNotFoundError):
warnings.append("No internet connection detected. DeepSearch cannot connect to Discord.")
exit() # Exit if no internet connection
return warnings
# Display environment warnings
print("🔍 Environment Check:")
warnings = check_environment()
if warnings:
print("⚠️ Notices:")
for warning in warnings:
print(f" • {warning}")
else:
print("✅ All environment checks passed")
# --- Load env and config ---
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
CONFIG_FILE = "config.json"
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
CONFIG = json.load(f)
# --- Setup logs ---
LOGS_DIR = "logs"
os.makedirs(LOGS_DIR, exist_ok=True)
msg_log_path = os.path.join(LOGS_DIR, "message_logs.log")
user_log_path = os.path.join(LOGS_DIR, "user_logs.log")
def setup_logging():
# Create date-based directory structure
current_datetime = datetime.now()
date_hour_dir = os.path.join(LOGS_DIR, current_datetime.strftime('%Y-%m-%d_%H'))
os.makedirs(date_hour_dir, exist_ok=True)
# Define log paths with date-based directory
msg_log_path = os.path.join(date_hour_dir, "message_logs.log")
user_log_path = os.path.join(date_hour_dir, "user_logs.log")
# Set up logging with queue handlers for thread safety
log_queue = queue.Queue(-1) # No limit on queue size
queue_handler = logging.handlers.QueueHandler(log_queue)
# Configure root logger to use the queue
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
for handler in root_logger.handlers[:]: # Remove any existing handlers
root_logger.removeHandler(handler)
root_logger.addHandler(queue_handler)
# Configure file handlers for the listener
msg_handler = logging.FileHandler(msg_log_path, mode='a', encoding='utf-8')
user_handler = logging.FileHandler(user_log_path, mode='a', encoding='utf-8')
formatter = logging.Formatter('%(asctime)s - %(message)s')
msg_handler.setFormatter(formatter)
user_handler.setFormatter(formatter)
# Create and configure loggers
msg_logger = logging.getLogger('message_log')
user_logger = logging.getLogger('user_log')
msg_logger.setLevel(logging.INFO)
user_logger.setLevel(logging.INFO)
msg_logger.propagate = False
user_logger.propagate = False
msg_logger.addHandler(msg_handler)
user_logger.addHandler(user_handler)
# Set up the queue listener
listener = logging.handlers.QueueListener(log_queue, msg_handler, user_handler)
listener.start()
return msg_logger, user_logger, msg_log_path, user_log_path, listener
# --- Init bot ---
intents = discord.Intents.all()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
msg_logger, user_logger, msg_log_path, user_log_path, log_listener = setup_logging()
BAD_WORDS = load_bad_words()
# --- Caches ---
member_cache = TTLCache(maxsize=500, ttl=3600) # Cache for 1 hour, store up to 500 guilds
message_cache = TTLCache(maxsize=1000, ttl=300) # Cache for 5 minutes, store up to 1000 channel histories
user_cache = TTLCache(maxsize=2000, ttl=3600) # Cache for 1 hour, store up to 2000 users
keyword_match_cache = TTLCache(maxsize=10000, ttl=3600) # Cache for 1 hour
# --- Utils ---
def save_config():
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(CONFIG, f, indent=2)
except Exception as e:
print(f"Error saving config: {e}")
def log_to_file(path, content):
try:
with open(path, "a", encoding="utf-8") as f:
f.write(content)
except Exception as e:
print(f"Error writing to log {path}: {e}")
def is_admin(ctx):
return ctx.author.guild_permissions.administrator
def format_time_interval(minutes):
"""Format time interval in appropriate units"""
if minutes < 1:
# Less than a minute, show seconds
seconds = int(minutes * 60)
return f"{seconds} seconds"
elif minutes < 60:
# Less than an hour, show minutes
return f"{minutes} minutes"
elif minutes < 1440: # 24 hours
# Less than a day, show hours and minutes
hours = int(minutes // 60)
mins = int(minutes % 60)
if mins == 0:
return f"{hours} hours"
else:
return f"{hours} hours, {mins} minutes"
elif minutes < 10080: # 7 days
# Less than a week, show days and hours
days = int(minutes // 1440)
hours = int((minutes % 1440) // 60)
if hours == 0:
return f"{days} days"
else:
return f"{days} days, {hours} hours"
else:
# More than a week, show weeks and days
weeks = int(minutes // 10080)
days = int((minutes % 10080) // 1440)
if days == 0:
return f"{weeks} weeks"
else:
return f"{weeks} weeks, {days} days"
def update_scheduled_tasks():
"""Update scheduled tasks based on current config"""
if CONFIG.get("auto_scan_enabled", False):
interval = CONFIG.get("auto_scan_interval_minutes", 60)
# Convert to seconds for more precision
seconds = int(interval * 60)
# Need to restart the task to change interval
if auto_scan.is_running():
auto_scan.cancel()
# Update interval and restart
auto_scan.change_interval(seconds=seconds)
auto_scan.start()
print(f"🔄 Auto-scan enabled (every {format_time_interval(interval)})")
else:
if auto_scan.is_running():
auto_scan.cancel()
print("🛑 Auto-scan disabled")
def get_cached_members(guild_id):
"""Get or create cached member list for a guild"""
if guild_id not in member_cache:
guild = bot.get_guild(guild_id)
if guild:
member_cache[guild_id] = list(guild.members)
return member_cache.get(guild_id, [])
async def get_cached_messages(channel_id, limit=100, force_refresh=False):
"""Get or create cached message history for a channel"""
cache_key = f"{channel_id}_{limit}"
if force_refresh or cache_key not in message_cache:
channel = bot.get_channel(channel_id)
if channel:
messages = []
async for msg in channel.history(limit=limit):
messages.append(msg)
message_cache[cache_key] = messages
return message_cache.get(cache_key, [])
async def get_cached_user(user_id):
"""Get or create cached user information"""
if user_id not in user_cache:
try:
user = await bot.fetch_user(int(user_id))
user_cache[user_id] = user
except Exception:
return None
return user_cache.get(user_id)
# Create a set of lowercase keywords for faster matching
KEYWORD_SET = {k.lower() for k in CONFIG["search_keywords"]}
def keyword_match(text):
"""Check if text contains any keywords with caching"""
# Use a short hash of the text as a cache key
cache_key = hash(text) % 10000000
if cache_key in keyword_match_cache:
return keyword_match_cache[cache_key]
# Convert text to lowercase once
text_lower = text.lower()
# Check for any keyword in the set
result = any(k in text_lower for k in KEYWORD_SET)
# Cache the result
keyword_match_cache[cache_key] = result
return result
def parse_query_limit(limit_str):
"""Parse query limit with support for k/m suffixes (e.g., 5k = 5000)"""
limit_str = limit_str.lower()
try:
if limit_str.endswith('k'):
return int(float(limit_str[:-1]) * 1000)
elif limit_str.endswith('m'):
return int(float(limit_str[:-1]) * 1000000)
else:
return int(limit_str)
except ValueError:
return None
# Unified argument parsing function
def parse_command_args(args):
"""Parse command arguments and separate flags from positional arguments"""
processed_args = []
flags = {}
i = 0
while i < len(args):
arg = args[i].lower()
# Handle flags that take a value
if i + 1 < len(args) and arg in ("--q", "--query"):
limit = parse_query_limit(args[i + 1])
if limit is not None:
flags["query_limit"] = limit
i += 1 # Skip the value
else:
flags["error"] = "Invalid query limit. Must be a number (e.g., 100, 5k, 1m)."
elif i + 1 < len(args) and arg in ("--in", "--channel"):
flags["include_channels"] = [c.strip() for c in args[i + 1].split(",")]
i += 1 # Skip the value
elif i + 1 < len(args) and arg in ("--exclude", "--not"):
flags["exclude_channels"] = [c.strip() for c in args[i + 1].split(",")]
i += 1 # Skip the value
# Handle boolean flags
elif arg in ("--all", "-a"):
flags["deep_search"] = True
if "--debug" in args or "-d" in args:
flags["debug"] = True
elif arg in ("--users", "-u"):
flags["scan_users"] = True
elif arg in ("--messages", "-m"):
flags["scan_messages"] = True
else:
processed_args.append(args[i])
i += 1
return processed_args, flags
def debug_print(message, debug_enabled=False):
"""Print debug messages if debug mode is enabled"""
if debug_enabled:
timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
print(f"[DEBUG {timestamp}] {message}")
# --- Events ---
@bot.event
async def on_ready():
print(f"✅ Logged in as {bot.user}")
print("🔍 Keywords:", ', '.join(CONFIG["search_keywords"]))
print(f"📁 Logs at {os.path.dirname(msg_log_path)}")
update_scheduled_tasks()
# Track message matches for initial scan
initial_message_matches = 0
initial_member_matches = 0
total_members_scanned = 0
total_messages_scanned = 0
guild_count = len(bot.guilds)
print(f"\n🔎 Starting initial scan across {guild_count} guilds...")
for guild in bot.guilds:
# Chunk only if necessary
if not guild.chunked:
await guild.chunk(cache=True)
# Scan members
member_count = len(guild.members)
total_members_scanned += member_count
member_matches = 0
for member in get_cached_members(guild.id):
name_fields = f"{member.name} {member.display_name}"
if keyword_match(name_fields):
initial_member_matches += 1
member_matches += 1
entry = f"[AUTO] {member} ({member.id}) in {guild.name}"
user_logger.info(entry)
if CONFIG["print_user_matches"]:
print(entry)
# Initial scan of messages
message_scan_count = 0
channels = [c for c in guild.text_channels if c.permissions_for(guild.me).read_messages]
if channels:
# Calculate messages per channel to reach approximately 5000 total
messages_per_channel = max(1, 5000 // len(channels))
for channel in channels:
try:
async for msg in channel.history(limit=messages_per_channel):
message_scan_count += 1
if keyword_match(msg.content):
initial_message_matches += 1
entry = f"[INIT] {msg.author} in #{channel.name} ({guild.name}) > {msg.content}"
msg_logger.info(entry)
if CONFIG["print_message_matches"]:
print(entry)
except (discord.Forbidden, Exception):
continue
total_messages_scanned += message_scan_count
print(f" • {guild.name}: {member_matches}/{member_count} members, {message_scan_count} messages scanned")
print(f"\n✅ Initial scan complete! Found {initial_member_matches}/{total_members_scanned} matching members and {initial_message_matches}/{total_messages_scanned} matching messages.")
@bot.event
async def on_message(msg):
if msg.author.bot or not msg.guild:
return
if keyword_match(msg.content):
entry = f"[AUTO] {msg.author} in #{msg.channel} ({msg.guild.name}) > {msg.content}"
msg_logger.info(entry)
if CONFIG["print_message_matches"]:
print(entry)
await bot.process_commands(msg)
# --- Commands Section---
@bot.command(name="setkeywords")
async def set_keywords(ctx, *, words):
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
new_words = [w.strip() for w in words.split(",") if w.strip()]
CONFIG["search_keywords"] = new_words
save_config()
await ctx.send(f"✅ Keywords updated: {', '.join(new_words)}")
@bot.command(name="toggleprints")
async def toggle_prints(ctx, category: str):
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
if category not in ["user", "message"]:
return await ctx.send("⚠️ Use `user` or `message`.")
key = f"print_{category}_matches"
CONFIG[key] = not CONFIG[key]
save_config()
await ctx.send(f"✅ {category.capitalize()} print set to {CONFIG[key]}")
@bot.command(name="showkeywords")
async def show_keywords(ctx):
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
await ctx.send("🔍 Current keywords:\n" + ", ".join(CONFIG["search_keywords"]))
@bot.command(name="scan")
async def scan_members(ctx, *args):
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
global search_cancelled
# Handle cancel request
if len(args) == 1 and args[0].lower() == "cancel":
if hasattr(scan_members, "is_running") and scan_members.is_running:
search_cancelled = True
return await ctx.send("⚠️ Scan cancelled.")
else:
return await ctx.send("⚠️ No scan is currently running.")
if not hasattr(scan_members, "is_running"):
scan_members.is_running = False
if scan_members.is_running:
return await ctx.send("⚠️ A scan is already running. Please wait for it to complete or use `!scan cancel` to stop it.")
search_cancelled = False
# Use the unified argument parsing function
processed_args, flags = parse_command_args(args)
# Extract flags with default values
deep_search = flags.get("deep_search", False)
query_limit = flags.get("query_limit", 500) # Default limit
custom_query = "query_limit" in flags
include_channels = flags.get("include_channels", [])
exclude_channels = flags.get("exclude_channels", [])
scan_users = flags.get("scan_users", False)
scan_messages = flags.get("scan_messages", False)
# If no specific scan type is selected, inform the user
if not scan_users and not scan_messages:
if "deep_search" in flags or "query_limit" in flags:
# User specified search options but not what to scan
scan_messages = True # Default to messages if options were provided
else:
return await ctx.send("⚠️ Usage: `!scan [--users/-u] [--messages/-m] [--all/-a] [--q limit]`")
# If deep_search is enabled, consider both users and messages
if deep_search and not (scan_users or scan_messages):
scan_users = True
scan_messages = True
# Create a description of what's being scanned
scan_targets = []
if scan_users:
scan_targets.append("members")
if scan_messages:
scan_targets.append("messages")
scan_description = " and ".join(scan_targets)
# Fix: Capitalize first letter when not deep searching
scanning_text = "Scanning" if not deep_search else "Deep scanning"
status_msg = await ctx.send(f"🔍 {scanning_text} {scan_description}...")
scan_members.is_running = True
try:
user_count = 0
message_count = 0
start_time = datetime.now()
last_update_time = start_time
# Scan members if requested
if scan_users:
# Ensure guild is chunked for complete member list
if not ctx.guild.chunked:
await ctx.guild.chunk(cache=True)
total_members = len(ctx.guild.members)
members_scanned = 0
for member in ctx.guild.members:
members_scanned += 1
# Update status periodically
current_time = datetime.now()
if (current_time - last_update_time).total_seconds() > 5:
progress = members_scanned / total_members * 100
time_elapsed = (current_time - start_time).total_seconds()
await status_msg.edit(content=f"🔍 {scanning_text} members... ({members_scanned}/{total_members}, {progress:.1f}%, {time_elapsed:.1f}s)")
last_update_time = current_time
# Check for cancellation
if search_cancelled:
await status_msg.edit(content=f"⚠️ Scan cancelled after checking {members_scanned} members.")
return
name_fields = f"{member.name} {member.display_name}"
if keyword_match(name_fields):
user_count += 1
entry = f"[SCAN] {member.name} ({member.id}) in {ctx.guild.name}"
user_logger.info(entry)
if CONFIG["print_user_matches"]:
print(entry)
# Scan messages if requested
if scan_messages:
# Prepare search channels
search_channels = []
if include_channels:
for ch_name in include_channels:
ch_name = ch_name.strip('#')
channel = discord.utils.get(ctx.guild.text_channels, name=ch_name)
if channel:
search_channels.append(channel)
else:
if exclude_channels:
exclude_ch_names = [ch.strip('#') for ch in exclude_channels]
search_channels = [ch for ch in ctx.guild.text_channels
if ch.name not in exclude_ch_names]
else:
search_channels = ctx.guild.text_channels
total_channels = len(search_channels)
channels_scanned = 0
total_messages_scanned = 0
for channel in search_channels:
channels_scanned += 1
# Check for cancellation
if search_cancelled:
await status_msg.edit(content=f"⚠️ Scan cancelled after scanning {channels_scanned}/{total_channels} channels.")
return
# Update status periodically
current_time = datetime.now()
if (current_time - last_update_time).total_seconds() > 5:
progress = channels_scanned / total_channels * 100
time_elapsed = (current_time - start_time).total_seconds()
await status_msg.edit(content=f"🔍 {scanning_text} messages... ({channels_scanned}/{total_channels} channels, {total_messages_scanned} msgs, {progress:.1f}%, {time_elapsed:.1f}s)")
last_update_time = current_time
try:
# Use different limits based on deep search setting
limit = query_limit if deep_search or custom_query else 100
async for msg in channel.history(limit=limit):
total_messages_scanned += 1
if keyword_match(msg.content):
message_count += 1
entry = f"[SCAN] {msg.author} in #{channel.name} ({ctx.guild.name}) > {msg.content}"
msg_logger.info(entry)
if CONFIG["print_message_matches"]:
print(entry)
except discord.Forbidden:
continue
# Calculate scan time
scan_time = (datetime.now() - start_time).total_seconds()
# Format the result message
result_parts = []
if scan_users:
result_parts.append(f"{user_count} matching members")
if scan_messages:
result_parts.append(f"{message_count} matching messages (from {total_messages_scanned} messages)")
result_text = " and ".join(result_parts)
await status_msg.edit(content=f"✅ Scan complete! Found {result_text} in {scan_time:.1f}s.")
except Exception as e:
await ctx.send(f"⚠️ Error during scan: {e}")
finally:
scan_members.is_running = False
search_cancelled = False
# Define search cooldowns dictionary
search_cooldowns = {}
# Global search cancellation flag
search_cancelled = False
@bot.command(name="search")
async def search_messages(ctx, *args):
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
global search_cancelled, search_cooldowns
# Handle cancel request
cancel_result = handle_cancel_request(search_messages, args)
if cancel_result is not None:
if cancel_result:
search_cancelled = True
return await ctx.send("⚠️ Search cancelled.")
else:
return await ctx.send("⚠️ No search is currently running.")
# Setup command execution
if not setup_command_execution(search_messages):
return await ctx.send("⚠️ A search is already running. Please wait for it to complete or use `!search cancel` to stop it.")
search_cancelled = False
# Use the unified argument parsing function
processed_args, flags = parse_command_args(args)
# Extract flags with default values
deep_search = flags.get("deep_search", False)
query_limit = flags.get("query_limit", 500) # Default limit
custom_query = "query_limit" in flags
include_channels = flags.get("include_channels", [])
exclude_channels = flags.get("exclude_channels", [])
# Check if there was an error in parsing arguments
if "error" in flags:
search_messages.is_running = False
return await ctx.send(f"⚠️ {flags['error']}")
# Check for required user and keyword arguments
if len(processed_args) < 2:
search_messages.is_running = False
return await ctx.send("⚠️ Usage: `!search @user keyword [--a/--all] [--q limit] [--in #channel1,#channel2] [--exclude #channel3]`")
# Extract user from the first processed argument
try:
user_arg = processed_args[0]
if user_arg.startswith("<@") and user_arg.endswith(">"):
user_id = user_arg[2:-1].strip()
if user_id.startswith('!'):
user_id = user_id[1:]
else:
user_id = user_arg
user_id = int(user_id)
user = await get_cached_user(user_id)
if not user:
search_messages.is_running = False
return await ctx.send("⚠️ User not found. Please make sure you've provided a valid user ID or @mention.")
# Extract keyword from remaining processed arguments
keyword = " ".join(processed_args[1:])
except Exception:
search_messages.is_running = False
return await ctx.send("⚠️ Invalid user format. Use @mention or user ID.")
# Apply cooldown check for deep searches
cooldown_ok, remaining = apply_cooldown(search_cooldowns, ctx, deep_search, custom_query)
if not cooldown_ok:
search_messages.is_running = False
return await ctx.send(f"⚠️ Please wait {remaining:.1f} minutes before performing another deep search in this server.")
# Prepare search channels
search_channels = await process_search_channels(ctx, include_channels, exclude_channels)
if not search_channels:
search_messages.is_running = False
return
# Status message based on search type
search_msg_prefix = ""
if include_channels:
channel_names = ", ".join([f"#{ch.name}" for ch in search_channels])
search_msg_prefix = f" in channels: {channel_names}"
elif exclude_channels:
channel_names = ", ".join(exclude_channels)
search_msg_prefix = f" (excluding channels: {channel_names})"
# Fix: Capitalize first letter when not deep searching
searching_text = "Searching" if not deep_search else "Deep searching"
status_msg = await ctx.send(
f"🔍 {searching_text} for messages from {user.name} containing '{keyword}'{search_msg_prefix}..."
)
try:
total_channels = len(search_channels)
found_messages = []
total_searched = 0
start_time = datetime.now()
last_update_time = start_time
channels_searched = 0
for channel in search_channels:
channels_searched += 1
# Check for cancellation
if search_cancelled:
await status_msg.edit(content=f"⚠️ Search cancelled after checking {channels_searched}/{total_channels} channels.")
return
try:
# Use different limits based on deep search setting
limit = query_limit if deep_search or custom_query else 100
messages_checked = 0
async for msg in channel.history(limit=limit):
messages_checked += 1
total_searched += 1
# Update status message periodically
last_update_time = await update_search_status(
status_msg,
channels_searched,
total_channels,
total_searched,
len(found_messages),
start_time,
last_update_time,
search_cancelled
)
# Check for cancellation
if search_cancelled:
break
# Check if message is from target user and contains keyword
if msg.author.id == user.id and keyword.lower() in msg.content.lower():
found_messages.append(msg)
except discord.Forbidden:
continue
except Exception as e:
await ctx.send(f"⚠️ Error searching channel {channel.name}: {e}")
continue
# Calculate search time
search_time = (datetime.now() - start_time).total_seconds()
if not found_messages:
await status_msg.edit(content=f"✅ Search complete! No messages found from {user.name} containing '{keyword}' (searched {total_searched:,} messages in {search_time:.1f}s)")
else:
# Format results
result_text = f"✅ Found {len(found_messages)} messages from {user.name} containing '{keyword}' (searched {total_searched:,} messages in {search_time:.1f}s)"
# List first few results
result_text += "\nLatest messages:"
count = 0
for msg in sorted(found_messages, key=lambda m: m.created_at, reverse=True):
if count < 5: # Show at most 5 messages
channel_name = msg.channel.name
date = msg.created_at.strftime('%Y-%m-%d %H:%M:%S')
result_text += f"\n- {date} #{channel_name}: {msg.content[:100]}{'...' if len(msg.content) > 100 else ''}"
count += 1
else:
break
result_text += f"\n\nUse `!export {user.id} {keyword}` to export all messages."
await status_msg.edit(content=result_text[:2000]) # Discord message limit
# Update search statistics
update_search_stats(search_stats, ctx, total_searched, found_messages, search_time)
save_search_stats()
finally:
search_messages.is_running = False
search_cancelled = False
# Handle cooldown error
@search_messages.error
async def search_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
remaining = int(error.retry_after)
minutes = remaining // 60
seconds = remaining % 60
await ctx.send(f"⚠️ Command on cooldown! Try again in {minutes}m {seconds}s.")
STATS_FILE = "search_stats.json"
def load_search_stats():
"""Load search statistics from file if it exists"""
try:
if os.path.exists(STATS_FILE):
with open(STATS_FILE, 'r', encoding='utf-8') as f:
loaded_stats = json.load(f)
return loaded_stats
else:
# Return default stats structure if file doesn't exist
return {
"total_searches": 0,
"total_messages_searched": 0,
"total_matches_found": 0,
"cancelled_searches": 0,
"deep_searches": 0,
"search_time_total": 0,
"searches_by_guild": {},
"searches_by_user": {},
"last_search": None,
"largest_search": {"messages": 0, "time": 0, "keyword": "", "guild": ""}
}
except Exception as e:
print(f"Error loading search stats: {e}")
# Return default stats structure on error
return {
"total_searches": 0,
"total_messages_searched": 0,
"total_matches_found": 0,
"cancelled_searches": 0,
"deep_searches": 0,
"search_time_total": 0,
"searches_by_guild": {},
"searches_by_user": {},
"last_search": None,
"largest_search": {"messages": 0, "time": 0, "keyword": "", "guild": ""}
}
# Global dictionaries for tracking search stats
search_stats = load_search_stats()
def save_search_stats():
"""Save current search statistics to file"""
try:
with open(STATS_FILE, 'w', encoding='utf-8') as f:
json.dump(search_stats, f, indent=2)
except Exception as e:
print(f"Error saving search stats: {e}")
@bot.command(name="searchstats")
async def search_stats_command(ctx):
"""Show statistics about searches performed"""
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
global search_stats
# No stats available
if search_stats["total_searches"] == 0:
return await ctx.send("ℹ️ No search statistics available yet.")
# Calculate average time and messages
avg_time = search_stats["search_time_total"] / search_stats["total_searches"]
avg_messages = search_stats["total_messages_searched"] / search_stats["total_searches"]
# Create embed with stats
embed = discord.Embed(
title="🔍 Search Statistics",
color=0x3498db,
description="Statistics about searches performed with this bot"
)
# General stats
embed.add_field(
name="General Stats",
value=f"• Total searches: **{search_stats['total_searches']}**\n"
f"• Messages searched: **{search_stats['total_messages_searched']:,}**\n"
f"• Matches found: **{search_stats['total_matches_found']}**\n"
f"• Deep searches: **{search_stats['deep_searches']}**\n"
f"• Cancelled searches: **{search_stats['cancelled_searches']}**",
inline=False
)
# Performance stats
embed.add_field(
name="Performance",
value=f"• Average messages per search: **{avg_messages:,.1f}**\n"
f"• Average search time: **{avg_time:.2f}s**\n"
f"• Total search time: **{search_stats['search_time_total']:.2f}s**",
inline=False
)
# Last search info
if search_stats["last_search"]:
last = search_stats["last_search"]
embed.add_field(
name="Last Search",
value=f"• User: **{last['user']}**\n"
f"• Keyword: **{last['keyword']}**\n"
f"• Messages: **{last['messages']:,}**\n"
f"• Time: **{last['time']:.2f}s**\n"
f"• Matches: **{last['matches']}**\n"
f"• Guild: **{last['guild']}**",
inline=False
)
# Largest search info
if search_stats["largest_search"]["messages"] > 0:
largest = search_stats["largest_search"]
embed.add_field(
name="Largest Search",
value=f"• Messages: **{largest['messages']:,}**\n"
f"• Time: **{largest['time']:.2f}s**\n"
f"• Keyword: **{largest['keyword']}**\n"
f"• Guild: **{largest['guild']}**",
inline=False
)
# Most frequent searchers
if search_stats["searches_by_user"]:
top_users = sorted(search_stats["searches_by_user"].items(), key=lambda x: x[1], reverse=True)[:5]
users_text = "\n".join([f"• **{user}**: {count} searches" for user, count in top_users])
embed.add_field(name="Top Searchers", value=users_text, inline=False)
# Most searched servers
if search_stats["searches_by_guild"]:
top_guilds = sorted(search_stats["searches_by_guild"].items(), key=lambda x: x[1], reverse=True)[:5]
guilds_text = "\n".join([f"• **{guild}**: {count} searches" for guild, count in top_guilds])
embed.add_field(name="Most Searched Servers", value=guilds_text, inline=False)
# Footer - update to show stats are persistent
embed.set_footer(text="Stats persist across bot restarts")
await ctx.send(embed=embed)
# Save stats to ensure they're synced with file
save_search_stats()
@bot.command(name="context")
async def get_context(ctx, message_id: int = None, lines: int = 5):
"""Get context around a specific message"""
if not is_admin(ctx):
return await ctx.send("❌ You must be a server admin to use this.")
# Check for required message ID
if message_id is None:
return await ctx.send("⚠️ Usage: `!context message_id [lines=5]`\nYou must provide a message ID to get context.")
# Validate lines parameter
if lines < 1:
lines = 1
elif lines > 15: # Limit to reasonable number
lines = 15