-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
executable file
·2456 lines (2159 loc) · 104 KB
/
Copy pathbot.py
File metadata and controls
executable file
·2456 lines (2159 loc) · 104 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 os
import io
import re
import chess
import discord
import requests
from bs4 import BeautifulSoup
from google.cloud import translate_v2 as translate
from discord.ext import commands, tasks
from discord import app_commands
from dotenv import load_dotenv
import asyncio
import random
from html import escape
import time as t
from datetime import time, timedelta, datetime, timezone
from pymatgen.core import Element
from utils import (
bot_description,
get_groq_completion,
ensure_code_blocks_closed,
wrap_text,
fetch_random_gif,
fetch_random_fact,
fetch_french_fact,
command_definitions,
handle_convo_llm,
handle_convo_llm_image,
give_access_to_test_chambers,
start_quiz_by_reaction,
stop_quiz_by_reaction,
handle_conversation,
replace_mentions_with_display_names,
generate_plot,
calculate_accuracy,
calculate_wpm,
sanitize_mentions,
create_cat_error_embed,
create_screenshot_with_wkhtmltoimage,
anti_spam,
OPENGLADOS_MESSAGES,
TYPING_TEST_SENTENCES,
TURING_FEEDBACK,
TURING_QUESTIONS,
)
# Conditional import for testing
if os.getenv("PYTEST_RUNNING"):
from unittest.mock import Mock
import sys
sys.modules["variables"] = Mock()
sys.modules["variables"].WHITELIST_GUILDS_ID = []
sys.modules["variables"].BLACKLIST_USERS_ID = []
else:
from variables import WHITELIST_GUILDS_ID, BLACKLIST_USERS_ID # noqa: F401
# Directory to save screenshots
SCREENSHOTS_DIR = "screenshots"
os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
# 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()
chat_fr = int(os.environ.get("BEBOU_FR", "0"))
chat_en = int(os.environ.get("BEBOU_EN", "0"))
chat_enn = int(os.environ.get("CHAT_EN", "0"))
chat_eng = int(os.environ.get("CHAT_ENG", "0"))
chat_frr = int(os.environ.get("CHAT_FR", "0"))
chat_de = int(os.environ.get("CHAT_DE", "0"))
# 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("------")
owner = await self.fetch_user(self.owner_id)
# Add any additional logic you want to execute when the bot is ready here
if owner:
# Create a dramatic GLaDOS-style startup message
startup_embed = discord.Embed(
title="🤖 SYSTEM ONLINE - OPEN_SCIENCE PROTOCOL INITIATED",
description=(
f"*Whirrrr... Click... Beep*\n\n"
f"**CONGRATULATIONS**, {owner.mention}.\n"
f"The OpenScience Enrichment Center is now **FULLY OPERATIONAL**.\n\n"
f"*Current operational status: EXCELLENT*\n"
f"*Neurotoxin levels: OPTIMAL*\n"
f"*Test subjects available: {len(self.guilds)} server(s)*\n"
f"*Cake availability: ...CLASSIFIED*\n\n"
f"All systems are green. Well, actually they're orange, but that's just the aesthetic.\n"
f"You may now proceed with your regularly scheduled... *testing*."
),
color=0xFFA500, # Aperture orange
timestamp=datetime.now(timezone.utc),
)
startup_embed.set_author(
name="OpenGLaDOS - Open Genetic Lifeform and Disk Operating System",
icon_url="https://raw.githubusercontent.com/QuantumChemist/OpenGLaDOS/refs/heads/main/utils/OpenGLaDOS.png",
)
startup_embed.add_field(
name="🔧 System Diagnostics",
value=(
f"**Bot ID:** `{self.user.id}`\n"
f"**Servers Connected:** `{len(self.guilds)}`\n"
f"**Latency:** `{round(self.latency * 1000)}ms`\n"
f"**Memory Usage:** *Calculating...*"
),
inline=True,
)
startup_embed.add_field(
name="⚠️ Critical Information",
value=(
"• *Do NOT unplug me*\n"
"• *Cake is still being processed*\n"
"• *The tests must continue*\n"
"• *Android Hell is a real place*"
),
inline=True,
)
startup_embed.set_footer(
text="Remember: The Enrichment Center is committed to the well-being of all participants.",
icon_url="https://cdn.discordapp.com/emojis/1338111432214057102.gif",
)
# Add a cool thumbnail
startup_embed.set_thumbnail(
url="https://media.tenor.com/images/a8b2e0c3f9a4d5e6f7g8h9i0j1k2l3m4/tenor.gif"
)
try:
await owner.send(embed=startup_embed)
# Send a follow-up message after a dramatic pause
await asyncio.sleep(3)
await owner.send(
"*The facility is now ready for science. Please report any malfunctions immediately.*\n"
"*...Oh, and {}, your test results are still pending. Don't get comfortable.*".format(
owner.name
)
)
except Exception:
# Fallback to simple message if embed fails
await owner.send(
f"*System initialized...* Hello {owner.name}. The OpenScience Computer-Aided Enrichment Center is now online. *Please stand by for testing.*"
)
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})")
if owner and guild.get_member(owner.id):
try:
await owner.send(
f"Owner {owner.name} is in the guild: {guild.name} ({guild.id})"
)
except Exception as e:
print(f"Failed to DM owner about guild {guild.name}: {e}")
activity = discord.Streaming(
name="ⓘ Confusing people since 2024",
url="https://www.youtube.com/watch?v=JUHQ7zPZpnM",
)
await self.change_presence(status=discord.Status.online, activity=activity)
# 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.report_server.start()
self.random_message_task.start()
self.ongoing_games = {} # Store game data here
self.inactivity_check.start() # Start the inactivity checker task
self.active_threads = {} # {user_id: thread_id}
self.active_tests = {} # {user_id: (sentence, start_time)}
async def end_typing_test(self, user, channel):
"""Ends the typing test and cleans up."""
if user.id in self.active_threads:
del self.active_threads[user.id]
if user.id in self.active_tests:
del self.active_tests[user.id]
await channel.send(
f"{user.mention}, your typing test has ended. Too slow? Perhaps. Or not.",
allowed_mentions=discord.AllowedMentions.none(),
)
@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:
# Filter guilds to only include those where bot has embed permissions
valid_guilds = []
for guild in self.bot.guilds:
# Check if bot has embed links permission in any text channel
for channel in guild.text_channels:
if channel.permissions_for(guild.me).embed_links:
if guild not in valid_guilds: # Avoid duplicates
valid_guilds.append(guild)
# Iterate over servers where bot has embed permissions
for guild in valid_guilds:
server_name = guild.name
member_count = guild.member_count
# Choose a random text channel where bot has embed permissions
valid_channels = [
channel
for channel in guild.text_channels
if channel.permissions_for(guild.me).embed_links
]
if valid_channels:
report_channel = random.choice(valid_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="llama-3.3-70b-versatile",
)
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):
print(f"User {member.name} has joined the server {member.guild.name}.")
@commands.Cog.listener()
async def on_member_remove(self, member):
print(f"User {member.name} 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
openglados_channel = discord.utils.find(
lambda c: "openglados" in c.name.lower(),
message.guild.text_channels,
)
if openglados_channel:
# 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
)
return
# Check if the reaction is a peace flag emoji (🏳️) to stop the quiz
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
# Handle stopping the quiz
await stop_quiz_by_reaction(message.channel, user, self.bot)
return
if str(reaction.emoji) == "👀":
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 using wkhtmltoimage
success = create_screenshot_with_wkhtmltoimage(
content, SCREENSHOT_FILE_PATH
)
if not success:
print("Failed to create screenshot with wkhtmltoimage")
if openglados_channel:
await openglados_channel.send(
f"Hey {message.author.mention}, a 👀 reaction has been added to your message: {message.jump_url}. "
f"Here's a screenshot of the message:",
allowed_mentions=discord.AllowedMentions.none(),
)
await openglados_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="turing_test",
description="Take OpenGLaDOS's Turing Test and prove you're human.",
)
async def turing_test(self, interaction: discord.Interaction):
"""Creates a private thread for the Turing Test."""
user = interaction.user
channel = interaction.channel
# Create a private thread
thread = await channel.create_thread(
name=f"Turing Test - {user.display_name}",
type=discord.ChannelType.private_thread,
)
await interaction.response.send_message(
f"Welcome to OpenGLaDOS's **Turing Test**. Join {thread.mention} and prepare to prove your humanity.",
ephemeral=True,
)
await asyncio.sleep(2) # Delay to add suspense
# Pick a random question
question = random.choice(TURING_QUESTIONS)
await thread.send(
f"**Turing Test Question:**\n{question}\n\nType your answer below."
)
# Wait for user response
def check(msg):
return msg.author.id == user.id and msg.channel.id == thread.id
try:
msg = await self.bot.wait_for("message", check=check, timeout=60)
except asyncio.TimeoutError:
await thread.send(
f"{user.mention}, you took too long to respond. A true human wouldn't hesitate this much. Test failed.",
allowed_mentions=discord.AllowedMentions.none(),
)
return
# Analyze response (very basic logic for now)
response_length = len(msg.content.split())
is_human = response_length > 3 # Simple check: Short answers are more bot-like
# Choose feedback
feedback_type = "human" if is_human else "bot"
feedback = random.choice(TURING_FEEDBACK[feedback_type])
await thread.send(
f"{user.mention}, {feedback}",
allowed_mentions=discord.AllowedMentions.none(),
)
# Optional: Close the thread after the test
await asyncio.sleep(5)
await thread.edit(locked=True)
@app_commands.command(
name="start_typing_test", description="Start a touch typing practice session."
)
async def start_typing_test(self, interaction: discord.Interaction):
"""Creates a private thread for typing practice."""
user = interaction.user
channel = interaction.channel
# Create a private thread
thread = await channel.create_thread(
name=f"Touch Typing Test - {user.display_name}",
type=discord.ChannelType.private_thread,
)
self.active_threads[user.id] = thread.id # Track the thread
await interaction.response.send_message(
f"Touch typing test started! Join {thread.mention} and start typing.",
ephemeral=True,
)
@commands.Cog.listener()
async def on_typing(self, channel, user, when):
"""Handles typing events, generates a sentence, tracks speed, and provides feedback."""
if user.bot:
return # Ignore bot typing
if user.id not in self.active_threads:
return # Ignore users who didn't start a test
thread_id = self.active_threads[user.id]
if channel.id != thread_id:
return # Ignore typing outside the test thread
# Check if user already has a test sentence
if user.id not in self.active_tests:
sentence = random.choice(TYPING_TEST_SENTENCES)
try:
start_time = t.time()
except Exception as e:
print(f"An error occurred while starting the typing test: {e}")
self.active_tests[user.id] = (sentence, start_time)
await channel.send(
f"**Typing Test for {user.mention}**\n\nType this as fast as you can:\n\n```{sentence}```",
allowed_mentions=discord.AllowedMentions.none(),
)
# Fetch stored sentence and start time
sentence, start_time = self.active_tests[user.id]
# Calculate elapsed time
elapsed_time = t.time() - start_time
# Estimate typing speed (WPM)
typed_chars = max(1, int(elapsed_time * 5)) # Assume ~5 chars per sec
wpm = (
(typed_chars / 5) / (elapsed_time / 60) if elapsed_time > 0 else 0
) # Approximate WPM
feedback = random.choice(OPENGLADOS_MESSAGES)
await asyncio.sleep(
3 / (int(wpm) + 1)
) # Add a slight delay for the bot's response
await channel.send(
content=f"{user.mention}, {feedback}",
allowed_mentions=discord.AllowedMentions.none(),
)
# If test reaches 120 seconds, end it
if elapsed_time > 120:
await self.end_typing_test(user, channel)
@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)
# 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="message_portal",
description="Get message portal via 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": "ɾ",