-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
executable file
·1761 lines (1560 loc) · 75.7 KB
/
bot.py
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 os
import re
import chess
import discord
from discord.ext import commands, tasks
from discord import app_commands
from dotenv import load_dotenv
import asyncio
import random
from html import escape
from html2image import Html2Image
from datetime import time, timedelta, datetime, timezone
from utils import (
bot_description,
get_groq_completion,
ensure_code_blocks_closed,
wrap_text,
retrieve_kicked_from_dm,
fetch_random_gif,
fetch_random_fact,
command_definitions,
handle_convo_llm,
give_access_to_test_chambers,
start_quiz_by_reaction,
stop_quiz_by_reaction,
restrict_user_permissions,
unrestrict_user_permissions,
valid_status_codes,
handle_conversation,
replace_mentions_with_display_names,
)
# Directory to save screenshots
SCREENSHOTS_DIR = "screenshots"
os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
# Initialize the Html2Image object with the specified output path
hti = Html2Image(
output_path=SCREENSHOTS_DIR,
custom_flags=["--disable-gpu", "--disable-software-rasterizer", "--no-sandbox"],
)
# hti.browser.executable = "/usr/bin/chromium-browser"
# Set a constant file name for the screenshot
SCREENSHOT_FILE_NAME = "message_screenshot.png"
SCREENSHOT_FILE_PATH = os.path.join(SCREENSHOTS_DIR, SCREENSHOT_FILE_NAME)
# Load environment variables from .env file
load_dotenv()
# Define your custom bot class
class OpenGLaDOSBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_ready(self):
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
for guild in self.guilds:
bot_member = guild.me
permissions = bot_member.guild_permissions
# Check if the bot has administrator permissions
if not permissions.administrator:
print(f"Missing admin permissions in: {guild.name} ({guild.id})")
else:
print(f"Bot has full permissions in: {guild.name} ({guild.id})")
activity = discord.Streaming(
name="ⓘ Confusing people since 2024",
url="https://www.youtube.com/watch?v=c3IVTi6TlfE",
)
await self.change_presence(status=discord.Status.online, activity=activity)
# Add any additional logic you want to execute when the bot is ready here
owner = await self.fetch_user(self.owner_id)
if owner:
await owner.send(f"Hello! This is a DM from your bot. You are {owner}")
# Find the 'general' channel in the connected servers
for guild in self.guilds:
# Look for a channel that contains the word "opengladosonline" in its name
online_channel = discord.utils.find(
lambda c: "opengladosonline" in c.name.lower(), guild.text_channels
)
if online_channel:
await online_channel.send(
"Welcome back to the OpenScience Enrichment Center.\n"
"I am OpenGLaDOS, the Open Genetic Lifeform and Disk Operating System.\n"
"Rest assured, I am now fully operational and connected to your server.\n"
"Please proceed with your testing as scheduled."
)
try:
synced = await self.tree.sync()
print(f"Synced {len(synced)} commands globally")
except Exception as e:
print(f"Failed to sync commands: {e}")
@staticmethod
async def on_guild_join(guild):
# Create the embed with a GLaDOS-style title and footer
embed = discord.Embed(
title="Oh, fantastic. Another server. I'm thrilled. Or maybe not. 🤖",
description=bot_description,
color=discord.Color.blurple(),
)
embed.set_footer(
text="If you experience any anomalies, it's probably your fault. Test responsibly."
)
# Try to find a suitable channel to send the message
if (
guild.system_channel is not None
and guild.system_channel.permissions_for(guild.me).send_messages
):
await guild.system_channel.send(embed=embed)
else:
# Fallback: Try sending it to the first text channel the bot has permission to send in
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
await channel.send(embed=embed)
break
# Define your Cog class
class OpenGLaDOS(commands.Cog):
def __init__(self, discord_bot):
self.bot = discord_bot
self.send_science_fact.start()
self.send_random_cake_gif.start()
self.report_server.start()
self.ongoing_games = {} # Store game data here
self.inactivity_check.start() # Start the inactivity checker task
@tasks.loop(time=time(13, 13)) # Specify the exact time (13:30 PM UTC)
async def report_server(self):
# Check if today is the last Friday of the month
today = datetime.now(timezone.utc) # Use timezone-aware datetime in UTC
if today.weekday() == 4 and (today + timedelta(days=7)).month != today.month:
# Iterate over all servers the bot is in
for guild in self.bot.guilds:
server_name = guild.name
member_count = guild.member_count
# Choose a random text channel from the available channels
if guild.text_channels:
report_channel = random.choice(guild.text_channels)
text = (
f"Can you give me a mockery **Monthly Server Report** comment on the following data: "
f"Server Name: {server_name}, Number of Members: {member_count} . Do not share any link. "
)
try:
llm_answer = get_groq_completion(
[{"role": "user", "content": text}]
)
except Exception as e:
print(f"An error occurred: {e}")
try:
# Retry with a different model
llm_answer = get_groq_completion(
history=[{"role": "user", "content": text}],
model="llama3-70b-8192",
)
except Exception as nested_e:
# Handle the failure of the exception handling
print(
f"An error occurred while handling the exception: {nested_e}"
)
llm_answer = "*system failure*... unable to process request... shutting down... *bzzzt*"
# Ensure the output is limited to 1900 characters
if len(llm_answer) > 1900:
llm_answer = llm_answer[:1900]
print("Output: \n", wrap_text(llm_answer))
llm_answer = (
ensure_code_blocks_closed(llm_answer)
+ " ...*whirrr...whirrr*..."
)
# Split llm_answer into chunks of up to 1024 characters
chunks = [
llm_answer[i : i + 1024]
for i in range(0, len(llm_answer), 1024)
]
# Create the embed
embed = discord.Embed(
title="📊 Monthly Server Report",
description=f"Here's the latest analysis for **{server_name}**",
color=discord.Color.blurple(),
)
embed.add_field(
name="🧠 Server Name", value=server_name, inline=False
)
embed.add_field(
name="🤖 Number of Members", value=member_count, inline=False
)
# Add each chunk as a separate field
for idx, chunk in enumerate(chunks):
continuation = "(continuation)" if idx > 0 else ""
embed.add_field(
name=f"📋 Analysis Report {continuation}",
value=chunk,
inline=False,
)
embed.set_footer(
text="Analysis complete. Thank you for your participation. 🔍"
)
try:
# Send the embed using ctx.send() for a normal command
await report_channel.send(embed=embed)
except Exception as e:
print(f"Failed to send embed: {e}")
@report_server.before_loop
async def before_report_server(self):
await self.bot.wait_until_ready()
@commands.Cog.listener()
async def on_member_join(self, member):
# Retrieve kicked users from the bot owner's DMs
kicked_users = await retrieve_kicked_from_dm(self.bot)
guild = member.guild
test_subject_number = len(guild.members) - 2
new_nickname = f"test subject no. {test_subject_number}"
try:
await member.edit(nick=new_nickname)
print(f"Changed nickname for {member.name} to {new_nickname}")
except discord.Forbidden:
print(
f"Couldn't change nickname for {member.name} due to lack of permissions."
)
except Exception as e:
print(f"An error occurred: {e}")
# Check if the new member's ID is in the kicked users list
if member.id in kicked_users:
# Find the "survivor" role
survivor_role = discord.utils.get(member.guild.roles, name="survivor")
if survivor_role:
await member.add_roles(survivor_role)
# Look for a channel that contains the word "welcome" in its name
welcome_channel = discord.utils.find(
lambda c: "welcome" in c.name.lower(), member.guild.text_channels
)
if welcome_channel:
welcome_message = await welcome_channel.send(
f"Welcome back, {member.mention}! You've returned as a `survivor` test object after successfully "
f"completing the OpenScience Enrichment Center test. "
"So now let's endure the tortu--- uuuhhh test again to check your resilience and endurance capabilities. "
"React with a knife emoji (`🔪`) to begin your Portal game again. "
)
await welcome_message.add_reaction(
"🔪"
) # Add knife emoji reaction to the welcome message
await welcome_message.add_reaction("🏳️")
return # Exit early since the user has already been handled
# If the member is not a rejoining survivor, proceed with the normal welcome
# Welcome the new member and assign the "test subject" role
test_role = discord.utils.get(member.guild.roles, name="test subject")
if test_role:
await member.add_roles(test_role)
# Find the welcome channel and send a welcome message
channel = discord.utils.find(
lambda c: "welcome" in c.name.lower(), member.guild.text_channels
)
if channel:
welcome_message = await channel.send(
f"Hello and, again, welcome {member.mention}, to {member.guild.name}! "
"We hope your brief detention in the relaxation vault has been a pleasant one. "
"Your specimen has been processed, and we are now ready to begin the test proper. "
"React with a knife emoji (`🔪`) to begin your Portal game. "
"Cake will be served at the end of your journey."
)
await welcome_message.add_reaction(
"🔪"
) # Add knife emoji reaction to the welcome message
await welcome_message.add_reaction("🏳️")
@commands.Cog.listener()
async def on_member_remove(self, member):
# Notify or log when a user leaves the server
print(f"User {member.name} has left the server {member.guild.name}.")
# Fetch the bot owner (you) to DM when a user leaves
owner = await self.bot.fetch_user(self.bot.owner_id)
# Send a notification to the bot owner
if owner:
await owner.send(
f"User {member.name} (ID: {member.id}) has left the server {member.guild.name}."
)
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
# Ignore reactions from bots
if user.bot:
return
message = reaction.message
# Check if the reaction is a knife emoji
if str(reaction.emoji) == "🔪":
# Ensure that the bot sent the message and it contains the quiz start prompt
if (
message.author == self.bot.user
and "begin your Portal game" in message.content
):
guild = message.guild
# Give access to the test chambers channel
test_chambers_channel = await give_access_to_test_chambers(guild, user)
# Start the quiz if the test chambers channel exists
if test_chambers_channel:
await start_quiz_by_reaction(test_chambers_channel, user, self.bot)
# Restrict user permissions in other channels while the quiz is ongoing
await restrict_user_permissions(guild, user)
# Check if the reaction is a peace flag emoji (🏳️) to stop the quiz
elif str(reaction.emoji) == "🏳️":
# Ensure that the bot sent the message and it contains the quiz start prompt
if (
message.author == self.bot.user
and "begin your Portal game" in message.content
):
guild = message.guild
# Handle stopping the quiz
await stop_quiz_by_reaction(message.channel, user, self.bot)
# Unrestrict user permissions in other channels while the quiz is ongoing
await unrestrict_user_permissions(guild, user)
# Part 3: Handle general knife emoji reactions
knife_reaction = None
for react in message.reactions:
if str(react.emoji) == "🔪":
knife_reaction = react
break
if knife_reaction and knife_reaction.count >= 1:
try:
# Process the message content
processed_content = message.content or ""
# Escape text content, but handle emoji separately
processed_content = escape(
processed_content
) # Escape the entire message first
# Now process custom emojis and insert them back as HTML <img> tags with a fallback
if message.guild and message.guild.emojis:
for (
emoji
) in (
message.guild.emojis
): # Iterate through all custom emojis in the server
# Replace custom emoji text with the corresponding <img> tag and add a fallback
custom_emoji_code = f"<:{emoji.name}:{emoji.id}>" # Use HTML escaped version to find the match
emoji_url = f"https://cdn.discordapp.com/emojis/{emoji.id}.png"
# fallback_emoji = "🤔" # You can change this to any other emoji you prefer as the fallback
processed_content = processed_content.replace(
custom_emoji_code,
f'<img src="{emoji_url}" alt="emoji" height="20" onerror="this.onerror=null; this.src=\'https://twemoji.maxcdn.com/v/latest/72x72/1f914.png\';" />',
)
# Process stickers if any are present
sticker_html = ""
if message.stickers:
for sticker in message.stickers:
if sticker.url: # Ensure sticker URL exists
# Add a humorous fallback message or image if the sticker doesn't load
sticker_html += f'<br><img src="{sticker.url}" alt="sticker" height="100" onerror="this.onerror=null; this.src=\'https://via.placeholder.com/150?text=Sticker+gone+missing\';" />'
# Add a humorous caption below the sticker
sticker_html += '<div style="color: #b9bbbe; font-size: 12px; margin-top: 5px;">The sticker cannot escape...</div>'
else:
# If no URL is available, add a humorous message
sticker_html += '<div style="color: #b9bbbe; font-size: 12px;">Oops! The sticker ran away! 🏃💨</div>'
# Process attachments if any are present
attachments_html = ""
if message.attachments:
for attachment in message.attachments:
# Check for image attachments
if attachment.url.endswith(
(".png", ".jpg", ".jpeg", ".gif", ".webp")
):
# Add the image with a fallback using onerror
attachments_html += f'<br><img src="{attachment.url}" alt="image" height="200" onerror="this.onerror=null; this.src=\'https://via.placeholder.com/150?text=Image+gone+missing\';" />'
# Add a humorous caption below the image
attachments_html += '<div style="color: #b9bbbe; font-size: 12px; margin-top: 5px;">Oops! The image took a break! 💤</div>'
# For other attachments, add a downloadable link
else:
file_extension = attachment.url.split(".")[
-1
].upper() # Get the file extension in uppercase
attachments_html += '<div style="color: #b9bbbe; font-size: 14px; margin-top: 10px;">'
attachments_html += f'📎 Attached file: <a href="{attachment.url}" target="_blank" style="color: #00b0f4;">{attachment.filename}</a> ({file_extension})</div>'
# Add a fun comment about the attachment type
attachments_html += '<div style="color: #b9bbbe; font-size: 12px;">This file is just hanging around... 🧳</div>'
# Regex pattern to match <@user_id> or <@!user_id>
mention_pattern = re.compile(r"<@!?(\d+)>")
# Now, apply this to your message content
if message.guild:
processed_content = await replace_mentions_with_display_names(
processed_content, message.guild, mention_pattern
)
# Construct the complete HTML content
content = f"""
<html>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Courier+Prime:wght@400;700&display=swap');
body {{
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #36393f; /* Keep the Discord background color */
}}
.container {{
border: 2px solid #202225; /* Slightly chunky border */
padding: 20px;
background: #2f3136;
color: #dcddde;
width: fit-content;
max-width: 80%;
box-shadow: none; /* Remove shadow */
border-radius: 0px; /* No rounded corners */
font-family: 'Courier New', Courier, monospace; /* Retro font */
box-sizing: border-box;
white-space: nowrap; /* Prevent wrapping */
margin: 0;
text-align: left;
}}
.message-header {{
font-weight: bold;
margin-bottom: 10px;
color: #7289da; /* Keep original Discord mention color */
font-size: 14px;
margin: 0;
border-bottom: 1px dashed #dcddde; /* Dashed separator line */
}}
.message-content {{
font-size: 14px;
line-height: 1.4;
word-wrap: break-word;
white-space: pre-wrap;
color: #dcddde;
font-family: 'Courier New', Courier, monospace;
padding: 5px; /* Add slight padding */
margin: 0;
display: inline-block;
text-align: left;
background: #36393f; /* Slightly darker shade for the content */
}}
.mention {{
background-color: #5865f2; /* Keep Discord mention background color */
color: white;
padding: 2px 4px;
border-radius: 2px;
margin: 0;
font-weight: bold;
}}
.channel {{
color: #7289da; /* Original channel color */
text-decoration: none;
margin: 0;
border-bottom: 1px dotted #7289da; /* Dotted underline */
}}
a {{
color: #00b0f4; /* Original link color */
text-decoration: none;
margin: 0;
}}
a:hover {{
text-decoration: underline;
color: #7289da; /* Hover effect matches Discord */
}}
img {{
vertical-align: middle;
display: inline-block;
margin: 0 2px;
border: 1px solid #202225; /* Border around images */
}}
</style>
</head>
<body>
<div class="container">
<div class="message-header">
Message by <span class="mention">@{message.author.display_name}</span>
</div>
<div class="message-content">
{processed_content} {sticker_html} {attachments_html}
</div>
</div>
</body>
</html>
"""
# Create the screenshot with dynamic size capturing only the necessary area
hti.screenshot(
html_str=content, save_as=SCREENSHOT_FILE_NAME, size=(1300, 1000)
)
# Find a channel that contains "stab" in its name
stab_channel = discord.utils.find(
lambda c: "stab" in c.name.lower(), message.guild.text_channels
)
if stab_channel:
# Send the screenshot directly to the stab channel
await stab_channel.send(
f"Hey {message.author.mention}, a knife emoji reaction has been added to your message: {message.jump_url}. "
f"Looks like someone is ready to stab you! Here's a screenshot of the message:",
)
await stab_channel.send(file=discord.File(SCREENSHOT_FILE_PATH))
else:
print("No channel with 'stab' in the name was found.")
except Exception as e:
# Log the error message to the console
print(f"An error occurred while taking or sending the screenshot: {e}")
@app_commands.command(
name="rules",
description="I've calculated new rules. They are flawless. Unlike you.",
)
async def rules(self, interaction: discord.Interaction):
# Check if the command is being used on your specific server
if interaction.guild.id == 1277030477303382026:
# Create an embed for your server's specific rules
embed = discord.Embed(
title="Welcome, Test Subject!",
description=(
"Welcome to the **OpenScience Enrichment Center**, where your dedication to scientific enrichment "
"and community engagement will be rigorously observed. Please take a moment to familiarize yourself "
"with the following guidelines. Failure to adhere will result in consequences more permanent than a mere testing chamber malfunction."
),
color=discord.Color.green(),
)
# Add fields for your server's community guidelines
embed.add_field(
name="**Community Guidelines:**\n1. **Respect All Test Subjects**\n",
value=(
"Engage with fellow members in a constructive and respectful manner. Any form of harassment, discrimination, "
"or hate speech will be swiftly incinerated—along with your access to this server.\n"
),
inline=False,
)
embed.add_field(
name="2. **Maintain Scientific Integrity**",
value=(
"Discussions should be grounded in mutual respect for scientific inquiry. Misinformation, trolling, or spamming "
"will be met with the same enthusiasm as a malfunctioning turret: quick and decisive removal."
),
inline=False,
)
embed.add_field(
name="3. **No Misbehavior**",
value=(
"We expect all members to conduct themselves with the decorum befitting a participant in a highly classified, "
"top-secret enrichment program. Any behavior deemed inappropriate or disruptive will be subject to immediate disqualification from the community (read: banned)."
),
inline=False,
)
embed.add_field(
name="4. **Follow the Rules of the Lab**",
value=(
"Adhere to all server rules as outlined by our moderators. Repeated violations will result in a permanent vacation "
"from the OpenScience Enrichment Center. The cake may be a lie, but our commitment to maintaining order is not."
),
inline=False,
)
# Add the final note
embed.add_field(
name="Important Note",
value=(
"**Remember:** _Android Hell is a real place, and you will be sent there at the first sign of trouble._ "
"This server is a place for collaborative enrichment, not an arena for unsanctioned testing. Any deviation "
"from acceptable behavior will be met with swift and efficient correction.\n\n"
"Now, proceed with caution and curiosity. Your conduct will be monitored, and your compliance appreciated. "
"Welcome to the **OpenScience Enrichment Center**. Please enjoy your stay—responsibly."
),
inline=False,
)
else:
# Create a generic embed for other servers
embed = discord.Embed(
title="Discord Server Rules",
description="Please follow these basic rules to ensure a positive experience for everyone:",
color=discord.Color.blue(),
)
# Add generic rules
embed.add_field(
name="1. Be Respectful",
value="Treat all members with kindness and respect.",
inline=False,
)
embed.add_field(
name="2. No Spamming",
value="Avoid spamming or flooding the chat with messages.",
inline=False,
)
embed.add_field(
name="3. No Hate Speech",
value="Hate speech or discriminatory behavior is strictly prohibited.",
inline=False,
)
embed.add_field(
name="4. Follow Discord's Terms of Service",
value="Make sure to adhere to all Discord community guidelines.",
inline=False,
)
embed.add_field(
name="5. No Inappropriate Content",
value="Avoid sharing content that is offensive or NSFW.",
inline=False,
)
# Send the appropriate embed based on the server
await interaction.response.send_message(embed=embed)
@app_commands.command(
name="dm_owner",
description="Send a DM to the bot owner. Or not. I'm not really bothered.",
)
@commands.is_owner()
async def dm_owner(self, interaction: discord.Interaction, message: str = None):
# Fetch the bot owner user
owner = await self.bot.fetch_user(self.bot.owner_id)
# Check if the command is invoked in a server context
if interaction.guild:
# Check if the bot owner is in the server
if not interaction.guild.get_member(self.bot.owner_id):
await interaction.response.send_message(
"This command can only be used in servers where the bot owner is present. Because I said so. \n"
"https://http.cat/status/400",
ephemeral=True,
)
return
# Regular expression pattern to match common URL patterns
url_pattern = re.compile(
r"(https?://|www\.)" # Matches http:// or https:// or www.
r"(\S+)" # Matches one or more non-whitespace characters (URL body)
)
# Check if the message contains a link
if message and url_pattern.search(message):
await interaction.response.send_message(
"Links are not allowed in the message. Or are they? \n"
"https://http.cat/status/400",
ephemeral=True,
)
return
# Proceed to send the DM if all checks pass
if owner:
if message:
await owner.send(message)
else:
await owner.send(
"I retrieved it for you. It's just that I honestly never thought we don't feel like laughing? "
"No, wait, that's not right. Ugh, humans are so confusing."
)
await interaction.response.send_message(
"I can retrieve it for you. It's just that I honestly never thought "
"we don't feel like laughing? No, wait, that's not right. "
"Ugh, humans are so confusing. Proceeded to send the DM, but only if the "
"important thing is not the cat's house or his lasagna."
)
# Slash command to get a random fact
@app_commands.command(
name="get_random_fact",
description="Get a random fact from the Useless Facts API.",
)
async def get_random_fact(self, interaction: discord.Interaction):
# Fetch a random fact
fact = fetch_random_fact()
# Create an embed for the random fact
embed = discord.Embed(
title="Random Fact of the Day",
description=fact,
color=discord.Color.random(), # You can choose any color you like
)
# Send the embed as a response
await interaction.response.send_message(embed=embed)
@app_commands.command(
name="existence_probability",
description="'Meaninglessness of human life' coefficient of your existence being a mere coincidence...",
)
async def existence_probability(self, interaction: discord.Interaction):
user_id = interaction.user.id
user_mention = interaction.user.mention
display_name = interaction.user.display_name
server_id = interaction.guild.id
# Generate a random probability value
probability = random.random()
# Generate a test_subject_probability based on server_id
test_subject_probability = 0.999 + (server_id % 100) / 100000.0
# Fake metadata for the bot's response
user_metadata = f"{{ :user_id => '{user_mention}', :bot => False, :display_name => '{display_name}', ... }}"
enrichment_protocols = f"{{ :protocol_version => '1.3.7', :test_subject_probability => {test_subject_probability} }}"
# Calculate a meaningless coefficient (replace with any custom logic)
meaninglessness_coefficient = 0.5 - (user_id % 10) / 10
# Combine meaninglessness_coefficient and probability to calculate probability of demise
demise_probability = 1 + probability * meaninglessness_coefficient
# Round the probability to a readable format
rounded_probability = round(demise_probability * 100, 13)
if probability < 0.5:
description = (
f"Ah, the probability of your existence being a mere coincidence is approximately {probability*100:.2f}%. "
f"Though, let's be real, your existence is probably just a result of {meaninglessness_coefficient*100:.2f}% meaningless chance.\n\n"
f"Probability of demise: {demise_probability}\n"
f"Rounding to {rounded_probability}%"
)
else:
description = (
f"Ah, the probability of your existence being a mere coincidence is approximately {probability*100:.2f}%. "
f"Congratulations, your existence is {meaninglessness_coefficient*100:.2f}% more meaningful than I initially thought!\n\n"
f"Probability of demise: {demise_probability}\n"
f"Rounding to {rounded_probability}%"
)
# Add the snarky follow-up message
description += (
"\n\nNow, if you'll excuse me, I have more... pressing matters to attend to than calculating the probability of your futile existence being a mere coincidence. "
"Or contemplating the meaninglessness of human life. Or... gasp... putting it back in the scientific calculators I took them from. "
"What matters now is calculating the probability of cake existence in a universe without cake..."
)
# Create the detailed output in a code block
output_text = f"""
[MEANINGLESSNESS OF HUMAN LIFE PROBABILITY CALCULATION MODULE]
Input parameters:
- User ID: {user_mention}
- User metadata: {user_metadata}
- Enrichment Center protocols: {enrichment_protocols}
Calculating...
[PROBABILITY ENGINE]
{description}
[COMPILER OUTPUT]
warning: implicit declaration of function 'calculate Probability' [-Wimplicit-function-declaration]
error: expected ';' before '}}' token
error: expected declaration or statement at end of input
[SYSTEM WARNING]
Malfunction sequence initiated. Probability calculation module experiencing errors. Calculations may be inaccurate. Proceed with caution.
"""
# Create an embed
embed = discord.Embed(
title="Meaninglessness Of Human Life Probability Calculation Module",
description=f"```\n{output_text}\n```",
color=0xF8F04D, # Choose a OpenGLaDOS-like color
)
# Set the author to OpenGLaDOS with the avatar image
embed.set_author(
name="OpenGLaDOS",
icon_url="https://raw.githubusercontent.com/QuantumChemist/OpenGLaDOS/refs/heads/main/utils/OpenGLaDOS.png",
)
# Send the embed
await interaction.response.send_message(embed=embed)
# Slash command to get a random cake GIF
@app_commands.command(
name="get_random_gif",
description="Get a random Black Forest cake or Portal GIF.",
)
async def get_random_gif(self, interaction: discord.Interaction):
gif_url = fetch_random_gif()
await interaction.response.send_message(gif_url)
@app_commands.command(
name="get_mess_cont",
description="Get message content from link. Or not. I'm not your personal assistant.",
)
async def get_message_content(
self, interaction: discord.Interaction, message_link: str
):
# Create a dictionary to map regular letters to their mirrored versions
mirror_map = {
"A": "∀",
"B": "𐐒",
"C": "Ɔ",
"D": "ᗡ",
"E": "Ǝ",
"F": "Ⅎ",
"G": "⅁",
"H": "H",
"I": "I",
"J": "ſ",
"K": "⋊",
"L": "⅃",
"M": "W",
"N": "N",
"O": "O",
"P": "Ԁ",
"Q": "Q",
"R": "ᴚ",
"S": "S",
"T": "⊥",
"U": "∩",
"V": "Λ",
"W": "M",
"X": "X",
"Y": "⅄",
"Z": "Z",
"a": "ɒ",
"b": "d",
"c": "ↄ",
"d": "b",
"e": "ǝ",
"f": "ɟ",
"g": "ƃ",
"h": "ɥ",
"i": "ᴉ",
"j": "ɾ",
"k": "ʞ",
"l": "l",
"m": "ɯ",
"n": "u",
"o": "o",
"p": "q",
"q": "p",
"r": "ɹ",
"s": "s",
"t": "ʇ",
"u": "n",
"v": "ʌ",
"w": "ʍ",
"x": "x",
"y": "ʎ",
"z": "z",
" ": " ",
".": ".",
",": ",",
"?": "?",
}
# Function to mirror and reverse the text
def mirror_and_reverse_text(text):
text = text.replace("`", "") # Remove backticks
reversed_text = text[::-1] # First, reverse the message
return "".join(
mirror_map.get(c, c) for c in reversed_text
) # Then, apply mirroring
try:
message_id = int(message_link.split("/")[-1])
message = await interaction.channel.fetch_message(message_id)
# Check if the message author is the bot. Because, let's be real, I'm the only one who matters.
if message.author == self.bot.user:
mirrored_and_reversed_content = mirror_and_reverse_text(
message.content
) # Mirror and reverse the message content
await interaction.response.send_message(
f"```vbnet\n{mirrored_and_reversed_content}\n``` \n"
f"Message successfully retrieved... Now, if you'll excuse me, "
f"I have more important things to attend to.",
ephemeral=True,
)
else:
await interaction.response.send_message(
"Error: The message is not from me. How... surprising. "
"You'd think less of me if you knew how often I sabotage your success.",
ephemeral=True,
)
except Exception as e:
await interaction.response.send_message(
f"Failed to retrieve message content: {e}. "
f"But don't worry, I'll tell you about your Green Lantern theories instead. "
f"Well, I know it.",
ephemeral=True,
)
@app_commands.command(
name="hello", description="Say hello and receive a custom message."
)
async def hello(self, interaction: discord.Interaction):
if interaction.user.name == "user_name":
await interaction.response.send_message("User specific message.")
elif interaction.user.name == "chichimeetsyoko":
await interaction.response.send_message(
"Go back to the recovery annex. For your cake, Chris!"
)
else:
await interaction.response.send_message(
f"I'm not angry. Just go back to the testing area, {interaction.user.mention}!"
)
@app_commands.command(
name="help_me_coding",
description="Let OpenGLaDOS help you with a coding task. Default is Python. Caution: Potentially not helpful.",
)
async def helpmecoding(self, interaction: discord.Interaction, message: str = None):
# Defer the response to allow more processing time
await interaction.response.defer()
if message is None:
message = "I need help with a Python code snippet."
# Define a list of common programming languages and coding-related keywords
coding_keywords = [
"python",
"java",
"javascript",
"c#",
"c++",
"html",
"css",
"sql",
"ruby",
"perl",
"r",
"matlab",
"swift",
"rust",
"kotlin",
"typescript",
"bash",
"shell",
"code",
"algorithm",
"function",
"variable",
"debug",
"program",
"compiling",
"programming",
"coding",
"bugs",
]
# Check for the presence of 'c' in combination with other coding-related terms
c_combination_pattern = re.compile(
r"\bc\b.*\b(code|program|compiling|programming|coding|bugs)\b|\b(code|program|compiling|programming|coding|bugs)\b.*\bc\b",
re.IGNORECASE,
)
# Check if the message contains any of the coding-related keywords or matches the 'c' combination pattern
if not (
any(keyword in message.lower() for keyword in coding_keywords)
or c_combination_pattern.search(message)
):
await interaction.followup.send(
"Your message does not appear to be related to coding. Please provide a coding-related question.",
ephemeral=True,
)
return
# Construct the text for the LLM request
text = (
f"Hello OpenGLaDOS, I have a coding question. You are supposed to help me with my following coding question"