-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
executable file
·1540 lines (1318 loc) · 73.3 KB
/
bot.py
File metadata and controls
executable file
·1540 lines (1318 loc) · 73.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
import discord
import logging
import asyncio
import httpx
import random
import subprocess
import config
# Constants
PHRASES_DEFAULT = config.PHRASES_DEFAULT
PHRASES_THINK = config.PHRASES_THINK
PHRASES_SEARCH = config.PHRASES_SEARCH
PHRASES_HYBRID = config.PHRASES_HYBRID
PHRASES_ACTION = config.PHRASES_ACTION
PHRASES_PARSING = config.PHRASES_PARSING
PHRASES_QUEUE = config.PHRASES_QUEUE
# Error Mapping for LLM Responses
LLM_ERROR_MAPPING = {
400: ("Invalid Argument", "Double check your request, something seems invalid!"),
401: ("Unauthenticated", "Authentication failed. My API key might be invalid."),
403: ("Permission Denied", "Permission denied. I don't have access to this resource."),
404: ("Not Found", "Model not found. It might be deprecated or non-existent."),
429: ("Resource Exhausted", "I'm a bit overwhelmed right now, please try again in a minute!"),
500: ("Internal Error", "Internal server error. Google's AI is having a moment."),
503: ("Service Unavailable", "Service unavailable. The AI is likely down or overloaded."),
504: ("Gateway Timeout", "Gateway timeout. The request took way too long."),
}
from context_builder import clean_mention, build_context
from llm_client import ask_llm
from gemini_client import get_client
from guardrails import is_safe_prompt
from database import (
init_db, add_reminder, get_due_reminders, delete_reminder, save_memory,
get_memories, increment_stats, get_stats, save_user_variation,
get_user_settings, get_message_variation, save_message_variation,
save_system_state, get_system_state, save_keyword_memory, get_keyword_memories
)
import time
import urllib.parse
import json
import re
import os
# ---------------------------------------------------------------------------
# File attachment security policy
# ---------------------------------------------------------------------------
# Only these plain-text extensions are allowed. Everything else is blocked.
# Hard block list – binaries, compiled code, or containers.
# This ensures the bot doesn't attempt to read non-text data.
BLOCKED_EXTENSIONS: set[str] = {
".pyc", ".pyo", ".class", ".jar", ".war", ".ear",
".exe", ".dll", ".so", ".dylib", ".elf", ".bin", ".out", ".run",
".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar",
".iso", ".img", ".dmg",
}
async def read_attachments(attachments: list[discord.Attachment]) -> tuple[list[dict], str | None]:
"""
Download and validate all attachments from a Discord message.
Returns:
(list_of_media_dicts, error_message)
"""
import mimetypes
if not attachments:
return [], None
# Respect the per-message file cap
attachments = attachments[:config.MAX_ATTACHMENT_COUNT]
results: list[dict] = []
for att in attachments:
ext = os.path.splitext(att.filename)[1].lower()
# Block executables / binaries first (deny always wins)
if ext in BLOCKED_EXTENSIONS:
return [], (
f"🚫 **Blocked:** `{att.filename}` has a potentially executable extension (`{ext}`). "
"I cannot read files that could be executed for security reasons."
)
# Size guard
if att.size > config.MAX_MEDIA_BYTES:
size_mb = att.size / 1_000_000
return [], (
f"❌ **File too large:** `{att.filename}` is {size_mb:.1f} MB. "
f"Maximum size per file is {config.MAX_MEDIA_BYTES // 1_000_000} MB."
)
# Download the file content
try:
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.get(att.url)
resp.raise_for_status()
data = resp.content
mime_type, _ = mimetypes.guess_type(att.filename)
if getattr(att, "is_voice_message", lambda: False)():
mime_type = "audio/ogg"
# Expand guessing for Gemini-friendly types and avoid application/octet-stream
if not mime_type or mime_type == "application/octet-stream":
# Text/Code fallbacks
if ext in [
".py", ".js", ".ts", ".tsx", ".jsx", ".c", ".cpp", ".cc", ".h", ".hpp",
".cs", ".go", ".rs", ".md", ".markdown", ".json", ".yaml", ".yml",
".toml", ".sql", ".sh", ".bash", ".zsh", ".env", ".log", ".txt"
]:
mime_type = "text/plain"
elif ext == ".pdf":
mime_type = "application/pdf"
else:
# Gemini rejects application/octet-stream for inline data.
# Defaulting to text/plain is safer; if it's actually binary,
# the model will just see it as encoded characters.
mime_type = "text/plain"
results.append({
"filename": att.filename,
"mime_type": mime_type,
"data": data,
"size": att.size
})
except Exception as e:
return [], f"❌ **Failed to download** `{att.filename}`: {e}"
return results, None
# Set up logging for the bot
logger = logging.getLogger(__name__)
async def rotate_status(loading_msg: discord.Message | None, phrases: list, prefix: str = "> ⏳ ***", original_msg: discord.Message = None):
"""
Background task to rotate loading phrases if generation takes a while.
When config.SHOW_LOADING_MESSAGES is disabled, uses typing indicator on original_msg instead.
"""
if not config.SHOW_LOADING_MESSAGES:
try:
if original_msg:
async with original_msg.channel.typing():
while True:
await asyncio.sleep(3600)
else:
while True:
await asyncio.sleep(3600)
except asyncio.CancelledError:
pass
return
used_phrases = set()
try:
while True:
# Wait before changing the message (wait less if we have many many phrases)
sleep_time = random.uniform(5, 8) if len(phrases) < 10 else random.uniform(4, 6)
await asyncio.sleep(sleep_time)
# Pick a new phrase not just used
available = [p for p in phrases if p not in used_phrases]
if not available:
used_phrases.clear()
available = phrases
phrase = random.choice(available)
used_phrases.add(phrase)
# CRITICAL: Do not edit if we were cancelled during the sleep
# This prevents "zombie" edits from overwriting the final answer.
try:
await loading_msg.edit(content=f"{prefix}{phrase}***")
except discord.NotFound:
break # Message deleted, stop rotating
except Exception:
pass # Ignore transient edit errors
except asyncio.CancelledError:
# Task was cancelled, exit quietly
pass
except Exception as e:
logger.error(f"Error in status rotation: {e}")
async def safe_cancel_status(task: asyncio.Task | None):
"""Safely cancels and awaits a status rotation task to prevent race conditions."""
if task and not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
async def status_loop(bot: discord.Client):
"""
Background task to continuously update the bot's Rich Presence with global stats.
"""
await bot.wait_until_ready()
while not bot.is_closed():
try:
stats = get_stats()
servers = len(bot.guilds)
msgs = stats['messages_answered']
tokens = stats['tokens_used']
# Format nicely, e.g., 25.5k, 1.25M
if tokens >= 1_000_000:
tok_str = f"{tokens/1_000_000:.2f}M"
elif tokens >= 1000:
tok_str = f"{tokens/1000:.1f}k"
else:
tok_str = str(tokens)
# Send raw protocol-level Presence update to force-render the icon
# This bypasses library filtering that strips assets from user accounts
payload = {
"op": 3, # PRESENCE_UPDATE
"d": {
"since": 0,
"activities": [{
"name": "Answering questions",
"type": 5, # Playing (0) or Competing (5)
"details": f"🧠 Connected to {servers} Servers",
"state": f"💬 {msgs} Answered | 🔋 {tok_str} Tokens",
"application_id": str(1250551199862624349),
"assets": {
"large_image": "1490776461685162104",
},
"timestamps": {
"start": int(bot.start_time)
}
}],
"status": "online",
"afk": False
}
}
await bot.ws.send_as_json(payload)
except Exception as e:
logger.error(f"Failed to update rich presence: {e}")
await asyncio.sleep(60)
class PromptQueue:
def __init__(self, bot):
self.bot = bot
self.queue = asyncio.Queue()
self.active_user_ids = set() # Tracks users currently in queue or being processed
self._current_user_id = None
self.worker_task = None
def start(self):
if self.worker_task is not None and not self.worker_task.done():
logger.info("PromptQueue worker already running.")
return
logger.info("Starting PromptQueue worker...")
self.worker_task = asyncio.create_task(self._worker())
async def put(self, user_id, message, loading_msg, user_prompt, reply_content, is_reply_to_self, history=None, user_info=None, other_users_info=None, attachments_text=None, media_data=None, status_data=None):
if user_id in self.active_user_ids:
logger.warning(f"User {user_id} already has an active task. Put rejected.")
return False, 0
self.active_user_ids.add(user_id)
pos = self.queue.qsize() + (1 if self._current_user_id is not None else 0)
logger.info(f"Adding task to queue for user {user_id} (Calculated Pos: {pos})")
task_data = {
"message": message,
"loading_msg": loading_msg,
"user_prompt": user_prompt,
"reply_content": reply_content,
"is_reply_to_self": is_reply_to_self,
"history": history or [],
"user_info": user_info or {},
"other_users_info": other_users_info,
"attachments_text": attachments_text,
"media_data": media_data,
"status_data": status_data, # This is a dict/ref: {"task": <asyncio.Task>}
}
await self.queue.put((user_id, task_data))
return True, pos
async def _worker(self):
logger.info("PromptQueue worker thread entered _worker loop.")
while True:
# Re-initialize these for every iteration to prevent scoping leak issues
current_user_id = None
current_task = None
try:
# Wait for next task
user_id, task_data = await self.queue.get()
current_user_id = user_id
current_task = task_data
self._current_user_id = user_id
logger.info(f"PromptQueue: Processing task for user {user_id}")
# Actual prompt processing happens here
await self.bot.process_queued_prompt(
task_data["message"],
task_data["loading_msg"],
task_data["user_prompt"],
task_data["reply_content"],
task_data["is_reply_to_self"],
task_data["history"],
task_data["user_info"],
task_data.get("other_users_info"),
task_data.get("attachments_text"),
task_data.get("media_data"),
task_data.get("status_data")
)
logger.info(f"PromptQueue: Successfully processed user {user_id}'s task.")
except Exception as e:
logger.error(f"PromptQueue: ERROR for user {current_user_id}: {e}", exc_info=True)
finally:
if current_user_id:
if current_user_id in self.active_user_ids:
self.active_user_ids.remove(current_user_id)
self._current_user_id = None
self.queue.task_done()
logger.info(f"PromptQueue: Finished cleanup for user {current_user_id}.")
else:
logger.warning("PromptQueue: Worker iteration finished without a valid user_id.")
async def extract_user_metadata(user: discord.User | discord.Member, guild: discord.Guild | None) -> dict:
"""
Extract as much publicly available metadata as possible for a Discord user/member.
Handles both discord.User (DMs / minimal info) and discord.Member (full guild context).
"""
# ── Base identity ────────────────────────────────────────────────────────
user_info: dict = {
"display_name": getattr(user, "display_name", str(user)),
"username": str(user),
"global_name": getattr(user, "global_name", None),
"id": user.id,
"bot": user.bot,
"system": getattr(user, "system", False),
"created_at": user.created_at.strftime("%Y-%m-%d %H:%M UTC"),
"avatar_url": str(user.display_avatar.url) if user.display_avatar else None,
}
# ── Online presence ──────────────────────────────────────────────────────
raw_status = getattr(user, "status", None)
if raw_status is not None:
user_info["online_status"] = str(raw_status) # online / idle / dnd / offline
raw_mobile = getattr(user, "mobile_status", None)
if raw_mobile is not None:
user_info["mobile_status"] = str(raw_mobile)
raw_desktop = getattr(user, "desktop_status", None)
if raw_desktop is not None:
user_info["desktop_status"] = str(raw_desktop)
raw_web = getattr(user, "web_status", None)
if raw_web is not None:
user_info["web_status"] = str(raw_web)
# ── Guild-member specific ────────────────────────────────────────────────
user_info["server_name"] = guild.name if guild else "Direct Message"
if isinstance(user, discord.Member):
user_info["server_nickname"] = user.nick # May be None
user_info["joined_server_at"] = (
user.joined_at.strftime("%Y-%m-%d %H:%M UTC") if user.joined_at else None
)
user_info["server_roles"] = [r.name for r in user.roles if r.name != "@everyone"]
user_info["top_role"] = user.top_role.name if user.top_role else None
user_info["server_booster_since"] = (
user.premium_since.strftime("%Y-%m-%d") if user.premium_since else None
)
user_info["pending_membership_screening"] = user.pending
timed_out = getattr(user, "timed_out_until", None)
user_info["timed_out_until"] = timed_out.strftime("%Y-%m-%d %H:%M UTC") if timed_out else None
# Guild avatar (separate from global avatar)
guild_av = getattr(user, "guild_avatar", None)
user_info["server_avatar_url"] = str(guild_av.url) if guild_av else None
# Colour from top coloured role
colour = user.colour
if colour != discord.Colour.default():
user_info["role_colour"] = str(colour)
# Key guild permissions (non-exhaustive but informative)
try:
perms = user.guild_permissions
user_info["guild_permissions"] = {
"administrator": perms.administrator,
"manage_guild": perms.manage_guild,
"manage_channels": perms.manage_channels,
"manage_roles": perms.manage_roles,
"manage_messages": perms.manage_messages,
"kick_members": perms.kick_members,
"ban_members": perms.ban_members,
"moderate_members": perms.moderate_members,
"mention_everyone": perms.mention_everyone,
}
except Exception:
pass
else:
user_info["server_roles"] = []
user_info["top_role"] = None
# ── Activities / Rich Presence ───────────────────────────────────────────
status_list: list[str] = []
if hasattr(user, "activities"):
for activity in user.activities:
try:
atype = activity.type
name = getattr(activity, "name", "Unknown")
if atype == discord.ActivityType.listening:
# Spotify and generic listening
title = getattr(activity, "title", None) or name
artist = getattr(activity, "artist", None) or "Unknown Artist"
album = getattr(activity, "album", None)
track_url = getattr(activity, "track_url", None)
entry = f"Listening to: {title} by {artist}"
if album:
entry += f" (Album: {album})"
if track_url:
entry += f" — {track_url}"
status_list.append(entry)
elif atype == discord.ActivityType.playing:
details = getattr(activity, "details", None)
state = getattr(activity, "state", None)
ts = getattr(activity, "timestamps", None)
start = getattr(ts, "start", None) if ts else None
entry = f"Playing: {name}"
if details:
entry += f" ({details}"
if state:
entry += f" — {state}"
entry += ")"
if start:
entry += f" [since {start.strftime('%H:%M UTC')}]"
status_list.append(entry)
elif atype == discord.ActivityType.streaming:
platform = getattr(activity, "platform", "Unknown Platform")
url = getattr(activity, "url", None)
entry = f"Streaming: {name} on {platform}"
if url:
entry += f" — {url}"
status_list.append(entry)
elif atype == discord.ActivityType.watching:
status_list.append(f"Watching: {name}")
elif atype == discord.ActivityType.competing:
status_list.append(f"Competing in: {name}")
elif atype == discord.ActivityType.custom:
# Custom status has emoji + state text
emoji = getattr(activity, "emoji", None)
state = getattr(activity, "state", None)
parts = []
if emoji:
parts.append(str(emoji))
if state:
parts.append(state)
elif name and name != "Custom Status":
parts.append(name)
if parts:
status_list.append("Custom status: " + " ".join(parts))
except Exception:
continue
user_info["activities"] = status_list
# ── User Profile (requires an API call; may fail for non-friends/privacy) ──
try:
profile = await user.profile()
user_info["bio"] = getattr(profile, "bio", None)
user_info["pronouns"] = getattr(profile, "pronouns", None)
prof_premium = getattr(profile, "premium_since", None)
user_info["nitro_since"] = prof_premium.strftime("%Y-%m-%d") if prof_premium else None
# Nitro type (0=none, 1=classic, 2=full, 3=basic)
nitro_type = getattr(profile, "premium_type", None)
if nitro_type is not None:
_nitro_labels = {0: "None", 1: "Nitro Classic", 2: "Nitro", 3: "Nitro Basic"}
user_info["nitro_type"] = _nitro_labels.get(int(nitro_type), str(nitro_type))
# Banner
banner = getattr(profile, "banner", None) or getattr(user, "banner", None)
user_info["banner_url"] = str(banner.url) if banner else None
# Accent colour
accent = getattr(profile, "accent_colour", None) or getattr(user, "accent_colour", None)
user_info["accent_colour"] = str(accent) if accent else None
# Connected accounts
connected = getattr(profile, "connected_accounts", [])
user_info["connections"] = [f"{c.type}: {c.name}" for c in connected] if connected else []
# Mutual guilds / friends (available when fetching someone else's profile)
mutual_guilds = getattr(profile, "mutual_guilds", None)
if mutual_guilds is not None:
user_info["mutual_guild_count"] = len(mutual_guilds)
mutual_friends = getattr(profile, "mutual_friends", None)
if mutual_friends is not None:
user_info["mutual_friend_count"] = len(mutual_friends)
# Recent activity & leaderboards
recent = getattr(profile, "user_recent_activity", None)
user_info["recent_activity"] = str(recent) if recent else None
leaderboards = getattr(profile, "leaderboards", None)
user_info["game_leaderboard"] = str(leaderboards) if leaderboards else None
except Exception as e:
logger.debug(f"Could not fetch profile for {user}: {e}")
user_info.setdefault("bio", None)
user_info.setdefault("connections", [])
user_info.setdefault("recent_activity", None)
return user_info
class GeminiSelfBot(discord.Client):
def __init__(self, ollama_http_client: httpx.AsyncClient, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ollama_http_client = ollama_http_client
self.start_time = int(time.time() * 1000)
self.prompt_queue = PromptQueue(self)
self.reminder_loop_started = False
async def on_ready(self):
# Set online status
await self.change_presence(status=discord.Status.online)
init_db()
logger.info(f"Logged in as {self.user} (ID: {self.user.id})")
# Check for pending restart notification
restart_channel_id = get_system_state("pending_restart_channel")
restart_message_id = get_system_state("pending_restart_message_id")
if restart_channel_id:
try:
save_system_state("pending_restart_channel", None)
save_system_state("pending_restart_message_id", None)
channel = self.get_channel(int(restart_channel_id)) or await self.fetch_channel(int(restart_channel_id))
if channel:
success = False
if restart_message_id:
try:
msg = await channel.fetch_message(int(restart_message_id))
await msg.edit(content="> ✅ **Restarted and Online.**")
success = True
except:
pass # Fallback to sending new message
if not success:
await channel.send("> ✅ **Restarted and Online.**")
except Exception as e:
logger.error(f"Failed to send/edit restart notification: {e}")
logger.info("Self-bot is ready and listening for mentions/replies (Status: Online).")
self.loop.create_task(status_loop(self))
if not self.reminder_loop_started:
self.loop.create_task(self.reminder_loop())
self.reminder_loop_started = True
self.prompt_queue.start()
async def reminder_loop(self):
await self.wait_until_ready()
while not self.is_closed():
try:
due = get_due_reminders()
for r in due:
try:
channel = self.get_channel(r['channel_id']) or await self.fetch_channel(r['channel_id'])
if channel:
try:
msg = await channel.fetch_message(r['message_id'])
await msg.reply(f"> ⏰ **Reminder:** {r['topic']}")
delete_reminder(r['id'])
except discord.NotFound:
# Message was deleted - can't reply, so just send a normal message if possible
logger.warning(f"Reminder {r['id']}: Original message {r['message_id']} not found. Sending to channel instead.")
await channel.send(f"> ⏰ **Reminder:** {r['topic']}\n*(Note: The message I was supposed to reply to was deleted)*")
delete_reminder(r['id'])
except discord.Forbidden:
logger.error(f"Reminder {r['id']}: Forbidden from replying to message in channel {r['channel_id']}.")
# Depending on policy, we might want to delete it or leave it.
# Let's delete it so it doesn't spam the log.
delete_reminder(r['id'])
else:
logger.error(f"Reminder {r['id']}: Could not find channel {r['channel_id']}.")
# If we can't find the channel at all, it's likely gone or we lost access.
# Delete it to avoid infinite looping.
delete_reminder(r['id'])
except Exception as e:
logger.error(f"Failed to process reminder {r['id']}: {e}")
except Exception as e:
logger.error(f"Error in reminder_loop: {e}")
await asyncio.sleep(10)
async def on_message(self, message: discord.Message):
# 0. Admin Commands (Owner Only: tx24)
if message.content.startswith(";gem"):
is_owner = message.author.id == 504541573636161546
is_self_admin = (message.author.id == self.user.id and message.guild and message.guild.id == 1490733173246660658)
if is_owner or is_self_admin:
parts = message.content.split()
sub = parts[1].lower() if len(parts) > 1 else "help"
# Helper for toggle commands
def get_toggle_val(p):
return "true" if p.lower() in ("on", "true", "yes") else "false"
if sub == "restart":
init_msg = await message.reply("> 🔄 **Initiating PM2 restart...**")
save_system_state("pending_restart_channel", str(message.channel.id))
save_system_state("pending_restart_message_id", str(init_msg.id))
subprocess.run(["pm2", "restart", "gemini-bot"])
return
elif sub == "model":
if len(parts) < 3:
await message.reply("> ❌ **Usage:** `;gem model <model_id>`")
return
new_model = parts[2].strip()
# Active Model Validation
validate_msg = await message.reply(f"> 🔍 **Validating model:** `{new_model}`...")
try:
genai_client = get_client()
await genai_client.aio.models.get(model=new_model)
config.update_config("GEMINI_MODEL", new_model)
await validate_msg.edit(content=f"> ✅ **Model validated and changed to:** `{new_model}`")
except Exception as e:
await validate_msg.edit(content=f"> ❌ **Invalid Model:** `{new_model}` is not accessible or does not exist.\n> *Error: {str(e)[:300]}*")
return
elif sub == "autothink":
if len(parts) < 3:
await message.reply("> ❌ **Usage:** `;gem autothink <on/off>`")
return
val = get_toggle_val(parts[2])
config.update_config("AUTO_THINKING", val)
await message.reply(f"> ✅ **Auto-Thinking set to:** `{val == 'true'}`")
return
elif sub == "vertex":
if len(parts) < 3:
await message.reply("> ❌ **Usage:** `;gem vertex <on/off>`")
return
is_on = parts[2].lower() in ("on", "true", "yes")
config.update_config("USE_VERTEX_AI", "true" if is_on else "false")
await message.reply(f"> ✅ **Vertex AI set to:** `{is_on}`")
return
elif sub == "pause":
config.update_config("IS_PAUSED", "true")
await message.reply("> ⏸️ **Bot Paused.**")
return
elif sub == "resume":
config.update_config("IS_PAUSED", "false")
await message.reply("> ▶️ **Bot Resumed.**")
return
elif sub == "statusmsg" or sub == "loading":
if len(parts) < 3:
await message.reply("> ❌ **Usage:** `;gem statusmsg <on/off>`")
return
val = get_toggle_val(parts[2])
config.update_config("SHOW_LOADING_MESSAGES", val)
await message.reply(f"> ✅ **Status Messages set to:** `{val == 'true'}`")
return
elif sub == "queue":
if len(parts) < 3:
await message.reply(f"> ⏳ **Queue Status:** `{'Enabled' if config.ENABLE_QUEUE else 'Disabled'}`\n> **Usage:** `;gem queue <on/off>`")
return
val = get_toggle_val(parts[2])
config.update_config("ENABLE_QUEUE", val)
await message.reply(f"> ✅ **Queue System set to:** `{val == 'true'}`")
return
elif sub == "join":
if len(parts) < 3:
await message.reply("> ❌ **Usage:** `;gem join <invite_link_or_code>`")
return
invite_input = parts[2].strip()
try:
# discord.py-self method to accept invites
invite = await self.accept_invite(invite_input)
await message.reply(f"> ✅ **Joined Server:** `{invite.guild.name}` ({invite.guild.id})")
except Exception as e:
logger.error(f"Failed to join server: {e}")
await message.reply(f"> ❌ **Failed to join:** `{str(e)}`")
return
elif sub == "help":
# Full admin help for the owner
help_text = (
"> 🛠️ **Admin Commands**\n"
"- `;gem model <id>`: Switch Gemini model.\n"
"- `;gem autothink <on/off>`: Toggle native reasoning.\n"
"- `;gem statusmsg <on/off>`: Toggle loading messages.\n"
"- `;gem vertex <on/off>`: Toggle Vertex AI mode.\n"
"- `;gem queue <on/off>`: Toggle prompt queue.\n"
"- `;gem pause/resume`: Control bot processing.\n"
"- `;gem join <invite>`: Join a Discord server.\n"
"- `;gem restart`: Force PM2 process restart.\n\n"
"> 🎭 **Persona Commands**\n"
"- `;gem prompt <name> [user]`: Switch user personality.\n"
"- `;gem prompts`: List all variations with descriptions.\n"
"- `;gem status`: Show current personality and system status.\n"
"- `;gem help`: Show this list."
)
await message.reply(help_text)
return
# 1. Ignore messages from yourself (to prevent infinite loops)
# Exception: Allow self-messages in server 1490733173246660658 if they start with ;gem
if message.author.id == self.user.id:
if message.guild and message.guild.id == 1490733173246660658 and message.content.startswith(";gem"):
logger.info("Self-message detected in target server with prefix ;gem - processing.")
else:
return
# 2. Ignore messages from other bots
if message.author.bot:
return
# 3. Check for triggers: Direct Mention or Reply to self
is_mentioned = False
# Exception: Self-messages starting with ;gem count as mentioned in target server
if message.author.id == self.user.id and message.guild and message.guild.id == 1490733173246660658 and message.content.startswith(";gem"):
is_mentioned = True
if any(mention.id == self.user.id for mention in message.mentions):
is_mentioned = True
# Also trigger if they explicitly type @gemini
if "@gemini" in message.content.lower():
is_mentioned = True
is_reply_to_self = False
reply_content = None
other_users_info = []
relevant_users_scanned = set()
if message.reference:
try:
# Resolve the referenced message
ref_msg = message.reference.cached_message or await message.channel.fetch_message(message.reference.message_id)
if ref_msg:
if ref_msg.author.id == self.user.id:
is_reply_to_self = True
reply_content = ref_msg.content
else:
reply_content = f"{ref_msg.author.name} said: {ref_msg.content}"
other_users_info.append(await extract_user_metadata(ref_msg.author, message.guild))
relevant_users_scanned.add(ref_msg.author.id)
except discord.HTTPException:
pass
# 0.5 Public Persona Commands
if message.content.startswith(";gem"):
parts = message.content.split()
sub = parts[1].lower() if len(parts) > 1 else "help"
if sub == "prompts" or (sub == "prompt" and len(parts) < 3):
settings = get_user_settings(message.author.id)
current_var = settings.get('variation', 'default')
desc_lines = []
for k, v in config.PROMPT_DESCRIPTIONS.items():
active_marker = " 🟢" if k == current_var else ""
desc_lines.append(f"- **{k.capitalize()}**: {v}{active_marker}")
final_msg = "> 📜 **Available Prompt Variations**\n\n" + "\n".join(desc_lines) + "\n\n> **Usage:** `;gem prompt <name>`"
if len(final_msg) > 1950:
parts_msg = [final_msg[i:i+1900] for i in range(0, len(final_msg), 1900)]
for p in parts_msg: await message.reply(p)
else: await message.reply(final_msg)
return
elif sub == "prompt":
if len(parts) < 3:
await message.reply("> ❌ **Missing variation name.** Use `;gem prompts` to see the list.")
return
target = parts[2].lower()
if target in config.PROMPT_MODIFIERS:
target_user = message.author
is_owner = message.author.id == 504541573636161546
if len(parts) > 3 and is_owner:
try:
# Mentions format is <@id> or <@!id>
user_str = parts[3].strip('<@!>')
if not user_str.isdigit():
raise ValueError()
target_user_id = int(user_str)
target_user = self.get_user(target_user_id) or await self.fetch_user(target_user_id)
except Exception:
await message.reply("> ❌ **Invalid user ID or mention.**")
return
save_user_variation(target_user.id, target)
if target_user.id == message.author.id:
await message.reply(f"> ✅ **Personality shifted to:** `{target.capitalize()}`")
else:
await message.reply(f"> ✅ **Personality for {target_user.name} shifted to:** `{target.capitalize()}`")
else:
await message.reply(f"> ❌ **Unknown variation:** `{target}`. Use `;gem prompts` to see the list.")
return
elif sub == "help" and message.author.id != 504541573636161546:
# Public restricted help
help_text = (
"> 🎭 **Gemini Persona Commands**\n"
"- `;gem prompt <name>`: Switch the bot's personality for yourself.\n"
"- `;gem prompts`: List all available personalities.\n"
"- `;gem status`: Show current personality and system status.\n"
"- `;gem help`: Show this message."
)
await message.reply(help_text)
return
elif sub == "status":
mode = "Vertex AI" if config.USE_VERTEX_AI else "AI Studio"
paused_status = "⏸️ PAUSED" if config.IS_PAUSED else "▶️ RUNNING"
think_status = "🧠 ON" if config.AUTO_THINKING else "⚪ OFF"
queue_status = "⏳ ON" if config.ENABLE_QUEUE else "⚪ OFF"
# Fetch user-specific settings
user_settings = get_user_settings(message.author.id)
variation = user_settings.get('variation', 'default').capitalize()
await message.reply(
f"> 📊 **System Status**\n"
f"- **Model:** `{config.GEMINI_MODEL}`\n"
f"- **Variation:** `{variation}`\n"
f"- **Mode:** `{mode}`\n"
f"- **Thinking:** `{think_status}`\n"
f"- **Queue:** `{queue_status}`\n"
f"- **State:** `{paused_status}`"
)
return
if not (is_mentioned or is_reply_to_self):
return
# 4. Check for Pause State (Owner Exception)
if config.IS_PAUSED and message.author.id != 504541573636161546:
return # Silent ignore when paused
# 5. Process the message
logger.info(f"Triggered by {message.author}: '{message.content}'")
# Clean the input
user_prompt = clean_mention(message.content, self.user.id)
# Handle file attachments (before we decide whether to proceed)
# Core Safety Guardrail
# Deny obvious malicious patterns immediately to save compute
is_safe, refusal_reason = is_safe_prompt(user_prompt)
if not is_safe:
logger.warning(f"Guardrail blocked request from {message.author}: {refusal_reason}")
await message.reply(f"> 🛡️ **Guardrail Triggered:** {refusal_reason}\nI cannot fulfill this request.")
return
# Initialize context containers
attachments_text = None
loading_msg = None
# 1. Identify all attachments (Current Message)
all_attachments = list(message.attachments)
# 2. Identify all attachments (Replied Message)
ref_msg = None
if message.reference:
try:
ref_msg = message.reference.cached_message or await message.channel.fetch_message(message.reference.message_id)
if ref_msg and ref_msg.attachments:
all_attachments.extend(ref_msg.attachments)
except discord.HTTPException:
pass
# 3. Handle All Attachments
attachments_text = ""
media_data = []
if all_attachments:
results, att_err = await read_attachments(all_attachments)
if att_err:
await message.reply(f"> {att_err}")
return
for item in results:
# If it's small and potentially text-based, embed it directly in the prompt
is_embedded = False
if item["size"] < config.MAX_TEXT_EMBED_BYTES:
try:
text_content = item["data"].decode("utf-8")
attachments_text += f"### Attached file: `{item['filename']}`\n```\n{text_content}\n```\n\n"
is_embedded = True
logger.info(f"Embedded text file: {item['filename']}")
except UnicodeDecodeError:
pass # Not text, treat as media part
# Always pass images, videos, and large/binary files as media parts
if not is_embedded or item["mime_type"].startswith(("image/", "video/", "audio/")):
media_data.append(item)
logger.info(f"Prepared media part: {item['filename']} ({item['mime_type']})")
# 5. Early exit if no content to process
is_reply = message.reference is not None
if not user_prompt and not is_reply and not attachments_text and not media_data:
return
# 6. Display final loading state if not already set by image processing
status_task = None
if loading_msg is None and config.SHOW_LOADING_MESSAGES:
loading_msg = await message.reply(f"> ⏳ ***{random.choice(PHRASES_PARSING)}***")
status_task = asyncio.create_task(rotate_status(loading_msg, PHRASES_PARSING, original_msg=message))
elif loading_msg and config.SHOW_LOADING_MESSAGES:
# If image analysis was already running, start rotating parsing phrases
status_task = asyncio.create_task(rotate_status(loading_msg, PHRASES_PARSING, original_msg=message))
elif not config.SHOW_LOADING_MESSAGES:
status_task = asyncio.create_task(rotate_status(None, [], original_msg=message))
status_data = {"task": status_task}
# 5. Fetch Channel History (Context awareness)
history = []
recent_users_map = {}
async for msg in message.channel.history(limit=config.CHANNEL_HISTORY_LIMIT):
if msg.id == message.id: continue # Skip the current trigger message
history.append({"author": str(msg.author), "content": msg.content})
if msg.author.id not in recent_users_map and msg.author.id != self.user.id and msg.author.id != message.author.id:
recent_users_map[msg.author.id] = msg.author
# Reverse history so it's chronologically ordered (Oldest -> Newest) for the LLM
history.reverse()
# Extract extra context if users mention others or refer to them by name
if len(other_users_info) < 3:
# 1. Direct Mentions
for m in message.mentions:
if m.id != self.user.id and m.id != message.author.id and m.id not in relevant_users_scanned:
try:
other_users_info.append(await extract_user_metadata(m, message.guild))
relevant_users_scanned.add(m.id)
except: pass
if len(other_users_info) >= 3: break
# 2. Aggressive Name Matching (Recent Users & Guild Members)
prompt_lower = user_prompt.lower()
if len(prompt_lower) > 2 and len(other_users_info) < 3:
# Combine recent users and guild members for a wider search
search_pool = list(recent_users_map.values())
if message.guild:
# Only add a few extra guild members to avoid massive loops,
# prioritizing those with distinctive names mentioned
search_pool.extend([m for m in message.guild.members if m.id not in recent_users_map])
for u in search_pool:
if u.id == self.user.id or u.id == message.author.id or u.id in relevant_users_scanned:
continue
# Safely handle attributes that might be None
names = [
(u.name or "").lower(),
(getattr(u, 'display_name', '') or "").lower(),
(getattr(u, 'global_name', '') or "").lower()
]
# Check for whole word match to avoid false positives (e.g. "hi" matching "Hillary")
matched = False
for n in names:
if n and len(n) > 2:
# Use regex for word boundary matching
if re.search(rf'\b{re.escape(n)}\b', prompt_lower):
matched = True
break