-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
2321 lines (1939 loc) · 95.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
__author__ = "Strawberry Software"
__copyright__ = "Copyright 2019-2025"
__credits__ = [
"Strawberry",
"Vim - An old Friend of Strawberry's",
"italy2003 (https://www.pixiv.net/en/users/66835722)"
]
__license__ = "MIT"
__version__ = "2.3.27"
__maintainer__ = "Strawberry"
__status__ = "Development"
__support_discord__ = "https://discord.gg/9EAGVZUt2Y" # EDIT THIS
__invite_link__ = "https://discord.com/api/oauth2/authorize?client_id=883082974252384277&permissions=8&scope=bot" # EDIT THIS
# bot.py
#
# Note to self: DO NOT ADD COGS, they break EVERYTHING! It is NOT worth it, no matter what people say!
#
import asyncio
import json
import math
import time
import tkinter
import aiohttp
if __name__ == "__main__":
pass
import random
import os
import sys
import discord
from discord import app_commands
import discord.ext
import discord.utils
from oracle import oracle as oraclewords
from oracle_german import oracle_de as oracle_de_words
import functools
from discord.ext import commands
from botToken import botToken
import eyed3
import datetime
from bs4 import BeautifulSoup
from discord.ext.commands import Context, Greedy
from typing import Optional, Literal
from datetime import datetime
import re
from pathlib import Path
import yt_dlp
from datetime import date
from importlib.metadata import version
import logging
import requests
from datetime import timedelta
import json
import subprocess
from datetime import timedelta
import defusedxml.ElementTree as ET
import settings
# Settings
is_phone = settings.is_phone
ping_delay = settings.ping_delay
enable_ascii = settings.enable_ascii
print_guilds_connected = settings.print_guilds_connected
is_debugging = settings.is_debugging
DISCORD_FILE_LIMIT = settings.file_size_limit
waifugame_enabled = settings.enable_waifugame
if is_debugging:
logging.basicConfig(level=logging.DEBUG)
else:
# User will still want good warnings.
logging.basicConfig(level=logging.ERROR)
time_now = datetime.now().strftime("%H:%M:%S")
print(f"Bot Started at {time_now}")
client = commands.Bot(
command_prefix="n!",
description="A bot of the best character in DDLC!",
status=discord.Status.online,
case_insensitive=True,
intents=discord.Intents.all()
)
mp3_path = list(Path("D:\\Alles\\Alle Musik und Videos\\RR\\").rglob("*.mp3")) # <-- EDIT this to whatever folder your RR music is in.
folders = [
"D:\\Alles\\Alle Musik und Videos\\RR under 8MB\\", # <-- EDIT this to your RR music. RR = Real Rock.
""
]
# For on_ready, so it only creates one single task.
has_started = False
@client.command()
@commands.guild_only()
@commands.is_owner()
@app_commands.default_permissions(manage_messages=True)
async def sync(
interaction: discord.Interaction,
ctx: Context,
guilds: Greedy[discord.Object],
spec: Optional[Literal["~", "*", "^"]] = None) -> None:
"""
Manually sync the bot (True Natsukian only command)
"""
if not check_user_is_true_natsukian(interaction.user.id, load_longterm_lists()):
interaction.channel.send(
content = "Cannot use command, you are not a Bot Admin.",
delete_after = 5
)
return
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
def shorten(string):
"""
Replace spaces with underscores
"""
return string.replace(" ", "_")
### Music
activity_json_file_path = "./activity_texts.json" # <-- EDIT this to your own path!
with open(activity_json_file_path, encoding = "utf8") as file:
activity_text_data = json.load(file)
ffmpeg_options = {
"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
'options': '-vn ',
}
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0', # bind to ipv4 since ipv6 addresses cause issues sometimes
}
ytdl = yt_dlp.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
@classmethod
async def from_url(cls, url, *, loop=None, stream=True):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
def endSong(guild, path):
os.remove(path)
def search(query):
with yt_dlp.YoutubeDL({'format': 'bestaudio', 'noplaylist':'True'}) as ydl:
try: requests.get(query)
except: info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
else: info = ydl.extract_info(query, download=False)
return (info, info['url'], info['title'], info['duration'], info['thumbnail'])
### End of Music
print("Initializing...")
# Load blacklist data from a JSON file
def load_longterm_lists(filename="./longterm_lists.json"):
'''Load data from a file.'''
with open(filename, 'r') as file:
return json.load(file)
# Check if user is in blacklist and return details
def check_user_in_blacklist(user_id, blacklist_data) -> str | bool:
'''Returns user ID if found. Else returns a bool "False".'''
for entry in blacklist_data['blacklist']:
if entry['uid'] == user_id:
return entry['uid'], entry['reason']
return False
# Check if True Natsukian
def check_user_is_true_natsukian(userid : int, natsukian_data : json) -> str | bool:
'''Returns user ID if found. Else returns a bool "False"'''
for entry in natsukian_data['true_natsukians']:
if str(entry) == str(userid):
return str(entry)
return False
# Save data to JSON file
def save_data(data, filename="./longterm_lists.json"):
'''Save data to a JSON file.'''
with open(filename, 'w') as file:
json.dump(data, file, indent=4)
# For activity-related things. Discord shows "status" to users, despite it being Activities.
class NatsukiActivity:
'''Represents a collection of activity-related things.'''
async def set_random_activity(activity_text_data : str):
'''Set a random activity, defaults to "Chilling" if "activity_text_data" is faulty.'''
try:
activity_text = random.choice(activity_text_data["default"])
activity = discord.CustomActivity(
type = discord.ActivityType.custom,
name = "Custom Status", # Does nothing, but is required.
state = activity_text,
)
await client.change_presence(
activity = activity
)
except:
activity = discord.CustomActivity(
type = discord.ActivityType.custom,
name = "Custom Status", # Does nothing, but is required.
state = "Chilling",
)
await client.change_presence(
activity = activity
)
async def set_voice_activity(activity_text_data : str):
'''Sets a random voice-related activity'''
try:
activity_text = random.choice(activity_text_data["voice"])
activity = discord.CustomActivity(
type = discord.ActivityType.custom,
name = "Custom Status", # Does nothing, but is required.
state = activity_text,
)
await client.change_presence(
activity = activity
)
except:
activity = discord.CustomActivity(
type = discord.ActivityType.custom,
name = "Custom Status", # Does nothing, but is required.
state = "Speaking",
)
await client.change_presence(
activity = activity
)
async def set_streaming_activity(activity_text_data : str):
'''Sets a random streaming-related (i.E. streaming music) activity'''
try:
activity_text = random.choice(activity_text_data["streaming"])
activity = discord.CustomActivity(
type = discord.ActivityType.custom,
name = "Custom Status", # Does nothing, but is required.
state = activity_text,
)
await client.change_presence(
activity = activity
)
except:
activity = discord.CustomActivity(
type = discord.ActivityType.custom,
name = "Custom Status", # Does nothing, but is required.
state = "Streaming",
)
await client.change_presence(
activity = activity
)
# Because I often accidentally write the wrong name.
NatsukiStatus = NatsukiActivity
@client.tree.command(name="cute") # n!you_are_cute
async def you_are_cute(interaction: discord.Interaction) -> None:
""" Tell me I'm cute """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
await interaction.response.send_message("I'm NOT cute!!!")
@client.tree.command(name="ping") # n!ping
async def ping(interaction: discord.Interaction) -> None:
""" Get my Ping """
await interaction.response.send_message(f"Pong! `{(client.latency * 100):.3f}ms`")
# These commands point to a local folder.
if not is_phone:
@client.tree.command(name="img") # Natsuki image from "Natsuki Worship" <-- Oh wow this is an old comment! Has to be from 2019! Thank God I don't store my images on Discord anymore :P.
async def img(interaction: discord.Interaction) -> None:
""" Send an image of Natsuki """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
imgimg = "D:\\Alles\\Alle Bilder\\DDLC\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\DDLC")) # <-- EDIT this to any path with images you like.
await interaction.response.send_message(file=discord.File(imgimg))
@client.tree.command(name="shdf") # Get image <-- Can ignore unless you find a meaning behind "shdf", I don't remember.
async def shdf(interaction: discord.Interaction):
""" Send an SHDF image """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
shdfimg = "D:\\Alles\\Alle Bilder\\Anime People doing Wholesome Thing\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Anime People doing Wholesome Thing")) # <-- EDIT this to any path with images you like.
await interaction.response.send_message(file=discord.File(shdfimg))
@client.tree.command(name="fate") # Fate image
async def fate(interaction: discord.Interaction):
""" Get an image of the anime \"Fate\" """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
fateimg = "D:Alles\\Alle Bilder\\Fate\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Fate")) # <-- EDIT this if you have a folder for Fate images.
await interaction.response.send_message(file=discord.File(fateimg))
@client.tree.command(name="tanya") # Tanya image from
async def tanya(interaction: discord.Interaction):
""" Get an image of Tanya von Degurechaff """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
tanyaimg = "D:\\Alles\\Alle Bilder\\Tanya Degurechaff\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Tanya Degurechaff")) # <-- EDIT this if you have a folder for images of anything called "tanya".
await interaction.response.send_message(file=discord.File(tanyaimg))
@client.tree.command(name="tomboy") # Get image
async def tomboy(interaction: discord.Interaction):
"""Mmm tomboy abs yummy licky """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
tomboyimg = "D:\\Alles\\Alle Bilder\\Anime Tomboys\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Anime Tomboys")) # <-- EDIT this to your Anime Tomboys folder. I know you have one.
await interaction.response.send_message(file=discord.File(tomboyimg))
@client.tree.command(name="rem")
async def rem(interaction: discord.Interaction):
""" Get an image of Rem """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
remimg = "D:\\Alles\\Alle Bilder\\Rem\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Rem\\")) # <-- EDIT this to images of Rem.
await interaction.response.send_message(file=discord.File(remimg))
@client.tree.command(name="klk")
async def klk(interaction: discord.Interaction):
""" Get an image of Kill la Kill """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
klkimg = "D:\\Alles\\Alle Bilder\\Kill la Kill\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Kill la Kill\\")) # <-- EDIT this to Kill La Kill images.
await interaction.response.send_message(file=discord.File(klkimg))
@client.tree.command(name="rmeme")
async def rmeme(interaction: discord.Interaction):
""" Get one of Strawb's memes """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
await interaction.response.defer()
try:
mp4 = "D:\\Alles\\Alle Musik und Videos\\" + random.choice(os.listdir("D:\\Alles\\Alle Musik und Videos\\")) # <-- EDIT this to a path with video memes.
await interaction.followup.send(file=discord.File(mp4))
except discord.errors.HTTPException:
await interaction.followup.send("File too large, try again.")
except PermissionError:
await interaction.followup.send("Permission denied; Folder was auto-blocked, please try again.")
@client.tree.command(name="rr") # EDIT this away if you don't have RR or NS music. RR here means Real Rock, and I forgot what NS stood for.
async def rr(interaction: discord.Interaction):
""" Get a NS song (Most likely German) """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
await interaction.response.defer()
try:
mp3 = random.choice(mp3_path)
try:
audiofile = eyed3.load(mp3)
try:
audTitle = audiofile.tag.title
except AttributeError:
audTitle = "Unknown Title"
try:
audArt = audiofile.tag.artist
except AttributeError:
audArt = "Unknown Artist"
try:
audAlbum = audiofile.tag.album
except AttributeError:
audAlbum = "Unknown Album"
await interaction.followup.send(f"Song: {audTitle} | Artist: {audArt} | Album: {audAlbum}", file=discord.File(mp3))
print(f"RR music -- {mp3}")
except discord.errors.HTTPException:
await interaction.followup.send("File too large, try again.")
except PermissionError:
await interaction.followup.send("Permission denied; Folder was probably auto-blocked.")
except OSError:
await interaction.followup.send("An error occoured, please try again.")
@client.tree.command(name="christ_chan")
async def christ_chan(interaction: discord.Interaction):
""" Get an image of Christ-Chan """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
chrImg = "D:\\Alles\\Alle Bilder\\Christ-chan\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Christ-chan\\")) # <-- EDIT this to a path with images of Christ Chan. Not to be confused with Chris Chan.
await interaction.response.send_message(file=discord.File(chrImg))
@client.tree.command(name="chan")
async def chan(interaction: discord.Interaction):
""" Get an image of another Chan """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
chanImg = "D:\\Alles\\Alle Bilder\\Other Chans\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Other Chans\\")) # <-- EDIT this to a path with images of other -chan characters.
await interaction.response.send_message(file=discord.File(chanImg))
@client.tree.command(name="megu")
async def megu(interaction: discord.Interaction):
""" Get an image of Megumin """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
chanImg = "D:\\Alles\\Alle Bilder\\Megumin\\" + random.choice(os.listdir("D:\\Alles\\Alle Bilder\\Megumin\\")) # <-- EDIT this to a path with Megumin images.
await interaction.response.send_message(file=discord.File(chanImg))
B = ":black_large_square:"
b = B
W = ":white_large_square:"
w = W
R = ":red_square:"
r = R
@client.tree.command(name="draw")
async def draw(
interaction: discord.Interaction,
drawmessage: str):
""" Draw something with B, W, R, and . """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
drawfinalmessage = []
for char in drawmessage:
if char == "B" or char == "b":
drawfinalmessage.append(str(B))
elif char == "W" or char == "w":
drawfinalmessage.append(str(W))
elif char == "R" or char == "r":
drawfinalmessage.append(str(R))
elif char == ".":
drawfinalmessage.append("\n")
finalmessage = ''.join(drawfinalmessage)
if len(finalmessage) <= 2000:
await interaction.response.send_message(finalmessage)
else:
await interaction.response.send_message("Message too long. It has to be ~100 characters or less.\nBecause Discord Emojis vary in string sizes, it may be more or less than 100.")
# Oracle
@client.tree.command(name="oracle")
async def oracle(
interaction: discord.Interaction,
amount_of_letters: int):
""" Terry A. Davis' Oracle """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
await interaction.response.send_message(functools.reduce(lambda line, word: line + f"{word} ", (random.choice(oraclewords) for _ in range(amount_of_letters)), str()))
# Oracle German
@client.tree.command(name="oracle_ger")
async def oracle_ger(
interaction: discord.Interaction,
amount_de: int):
""" Terry A. Davis' Oracle but in German """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
await interaction.response.send_message(functools.reduce(lambda line, word: line + f"{word} ", (random.choice(oracle_de_words) for _ in range(amount_de)), str()))
@client.tree.command(name="safe")
@app_commands.describe(tags = "Enter tags in a `tag 1, tag 2 (series name), -banned tag, *wildcard` format")
async def safe(
interaction: discord.Interaction,
tags: str):
""" Get an image from Safebooru """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
try:
ctxtags1 = tags.replace(", ", "+")
ctxtags = ctxtags1.replace(" ", "_")
urlSafePre = "https://safebooru.org/index.php?page=dapi&s=post&q=index&tags=" + ctxtags + "rating:s"
async with aiohttp.ClientSession() as session:
async with session.get(urlSafePre) as response:
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
file_urls = []
file_urls_length = 0
source = []
for post in soup.find_all('post'):
file_urls.append(post.get('file_url'))
file_urls_length += 1
source.append(post.get('id'))
the_url_num = random.randint(0, file_urls_length - 1)
the_url = file_urls[the_url_num]
await interaction.response.send_message(str(the_url) + f"\nTags recorded: `{ctxtags}`\nID: {source[the_url_num]} | Found `{file_urls_length - 1}` other entries.")
print(
f"Someone has searched for \"{tags}\"\nThis has resulted in the bot sending this link: [ {urlSafePre} ]")
except IndexError:
await interaction.response.send_message(f"No results found for {tags}.")
@client.tree.command(name="gelbooru")
@app_commands.describe(tags = "Enter tags in a `tag 1, tag 2 (series name), -banned tag, *wildcard` format")
@app_commands.describe(nsfw = "Filter ratings. Default: `Safe`")
@app_commands.describe(gendered = "Filter `Female Only`, `Male Only`, or `Any` images. Default: `Any`")
async def gel(
interaction: discord.Interaction,
tags: str,
nsfw: Literal['safe', 'safe and questionable', 'questionable', 'explicit only', 'all'] = 'safe',
gendered: Literal['Female Only', 'Male Only', 'Any'] = 'Any'):
""" Get an image from Gelbooru (SFW only) """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
return
elif not interaction.channel.nsfw and nsfw.lower() in ['questionable', 'explicit only', 'all']:
await interaction.response.send_message(f"Could not run command! This command is for channels marked NSFW only!")
return
else:
urlSafePre = ""
try:
print(tags)
await interaction.response.defer()
ctxtags3 = tags.replace(", ", "+")
ctxtags2 = ctxtags3.replace(" ", "_")
print(ctxtags2)
if nsfw == 'safe': # Safe only
urlSafePre = "https://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=" + ctxtags2 + "+-transgender+-transgender_flag+-transgender_colors+-transsexual+-rating:questionable+-rating:explicit"
elif nsfw == 'safe and questionable': # All except explicit
urlSafePre = "https://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=" + ctxtags2 + "+-transgender+-transgender_flag+-transgender_colors+-transsexual+-rating:explicit"
elif nsfw == 'all': # All
urlSafePre = "https://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=" + ctxtags2 + "+-transgender+-transgender_flag+-transgender_colors+-transsexual"
elif nsfw == 'explicit only': # Explicit only
urlSafePre = "https://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=" + ctxtags2 + "+-transgender+-transgender_flag+-transgender_colors+-transsexual+rating:explicit"
elif nsfw == 'questionable': # Questionable only
urlSafePre = "https://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=" + ctxtags2 + "+-transgender+-transgender_flag+-transgender_colors+-transsexual+rating:questionable"
if gendered == 'Female Only':
urlSafePre += "+-1boy+-2boys+-3boys+-4boys+-5boys+-6%2bboys+-penis+-multiple_penises+-muscular_male+-male_focus+-multiple_boys+-futanari+-futa_only+-yaoi"
elif gendered == 'Male Only':
urlSafePre += "+-1girl+-2girls+-3girls+-4girls+-5girls+-6%2bgirls+-vagina+-futanari"
else:
pass
async with aiohttp.ClientSession() as session:
async with session.get(urlSafePre) as response:
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
gel_file_urls = []
gel_file_ratings = []
source = []
gel_file_urls_length = 0
for post in soup.find('posts').find_all('post'):
# if post.find('rating').get_text().strip().lower() == "general":
gel_file_urls.append(post.find('file_url').get_text())
gel_file_ratings.append(post.find('rating').get_text())
source.append(post.find('id').get_text())
gel_file_urls_length += 1
the_url_num = random.randint(0, gel_file_urls_length - 1)
the_url = gel_file_urls[the_url_num]
if gel_file_ratings[the_url_num] == 'explicit' or gel_file_ratings[the_url_num] == 'questionable':
await interaction.followup.send("|| " + str(the_url) + f" ||\nTags recorded: `{ctxtags2}`\nUser searched for: `{nsfw}`\nID: `{source[the_url_num]}`\nFound `{gel_file_urls_length - 1}` other entries.")
else:
await interaction.followup.send(str(the_url) + f"\nTags recorded: `{ctxtags2}`\nUser searched for: `{nsfw}`\nID: `{source[the_url_num]}`\nFound `{gel_file_urls_length - 1}` other entries.")
print(
f"Someone has searched for \"{tags}\"\nThis has resulted in the bot sending this link: [ {urlSafePre} ]\nThe ID of the post is `{source[the_url_num]}`\n"
f"This is the link sent: -# {the_url} #-")
except IndexError or discord.app_commands.errors.CommandInvokeError:
await interaction.followup.send(f"No results found for `{tags}`.")
except ValueError:
await interaction.followup.send(f"Something went wrong. Please check the spelling of each tag and try again.\nPlease check Gelbooru if it s down or if it shows results at all.\nTags used: `{tags.replace('+', ', ')}`")
@client.tree.command(name="rule34xxx")
@app_commands.describe(tags = "Enter tags in a `tag 1, tag 2 (series name), -banned tag, *wildcard` format")
@app_commands.describe(gendered = "Filter `Female Only`, `Male Only`, or `Any` images. Default: `Any`")
@app_commands.describe(blacklists = "Preset Blacklists for various tags considered NSFL or disgusing. Default: Use All Presets")
@app_commands.describe(allow_ai = "Dis/Allow images generated by AI. Default: `False`")
@app_commands.describe(allow_3d = "Dis/Allow '3d' images. Default: `False`")
async def rule34xxx(
interaction: discord.Interaction,
tags: str,
gendered: Literal['Female Only', 'Male Only', 'Any'] = 'Any',
blacklists: Literal['Guro', 'Futa', 'Scat', 'Guro and Futa', 'Guro and Scat', 'Scat and Futa', 'Guro, Scat and Futa', 'None'] = 'Guro, Scat and Futa',
allow_lolis: bool = True,
allow_obesity: bool = False,
allow_ai: bool = False,
allow_3d: bool = False):
"""
Get an image from rule34.xxx (NSFW very likely)\n
`tags` defines tags. Follow this format: `tag_1, tag_2, -banned_tag, *wild_card`
"""
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
female_only = "+-1boy+-2boys+-3boys+-4boys+-5boys+-6%2bboys+-penis+-multiple_penises+-muscular_male+-male_focus+-multiple_boys+-yaoi"
male_only = "+-1girl+-2girls+-3girls+-4girls+-5girls+-6%2bgirls+-vagina"
guro = "+-guro+-gore+-death+-murder+-beaten+-decapitated_head+-decapitation+-female_death+-necrophilia+-ryona+-severed_head+-skullfuck+-skull_fucking+-snuff"
futa = "+-futa+-futadom+-dickgirl+-shemale+-newhalf+-gynomorph+-cuntboy+-hermaphrodite+-intersex+-futa_only"
scat = "+-scat+-shit+-scat_inflation+-poop+-pooping+-defecating+-shitting_self+-fart+-farting+-fart_cloud+-fart_fetish+-hyper_fart"
loli = "+-loli+-shota+-lolicon+-shotacon"
obesity = "+-huge_ass+-hyper_ass+-giant_ass+-gigantic_breasts+-enormous_breasts+-massive_breasts+-colossal_breasts+-astronomical_breasts+-obese+-fat+-fat_man+-fat_woman+-plump"
ai_tags = "+-ai_generated+-ai_*"
tags_3d = "+-3d+-3d_(artwork)+-3d_(gif)+-3d_(animation)+-3d_artwork+-3d_background+-3d_custom_girl"
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
return
elif not interaction.channel.nsfw:
await interaction.response.send_message(f"Could not run command! This command is for channels marked NSFW only!")
return
else:
pass
#try:
print(tags)
await interaction.response.defer()
ctxtags3 = tags.replace(", ", "+")
ctxtags2 = ctxtags3.replace(" ", "_")
print(ctxtags2)
r34xxx_url_pre = 'https://api.rule34.xxx/index.php?page=dapi&s=post&q=index&tags=' + ctxtags2
#Gender Tags
if gendered == 'Female Only':
r34xxx_url_pre = r34xxx_url_pre + female_only
elif gendered == 'Male Only':
r34xxx_url_pre = r34xxx_url_pre + male_only
# Disgusting Tags
if blacklists == 'Guro':
r34xxx_url_pre = r34xxx_url_pre + guro
elif blacklists == 'Futa':
r34xxx_url_pre = r34xxx_url_pre + futa
elif blacklists == 'Scat':
r34xxx_url_pre = r34xxx_url_pre + scat
elif blacklists == 'Guro and Futa':
r34xxx_url_pre = r34xxx_url_pre + guro + futa
elif blacklists == 'Guro and Scat':
r34xxx_url_pre = r34xxx_url_pre + guro + scat
elif blacklists == 'Scat and Futa':
r34xxx_url_pre = r34xxx_url_pre + scat + futa
elif blacklists == 'Guro, Scat and Futa':
r34xxx_url_pre = r34xxx_url_pre + guro + scat + futa
# Other tags
if not allow_lolis:
r34xxx_url_pre = r34xxx_url_pre + loli
if not allow_obesity:
r34xxx_url_pre = r34xxx_url_pre + obesity
if not allow_ai:
r34xxx_url_pre = r34xxx_url_pre + ai_tags
if not allow_3d:
r34xxx_url_pre = r34xxx_url_pre + tags_3d
async with aiohttp.ClientSession() as session:
async with session.get(r34xxx_url_pre) as response:
xml_data = await response.text()
r34xxx_file_urls = []
source = []
r34xxx_file_urls_length = 0
root = ET.fromstring(xml_data)
for post in root.findall('post'):
r34xxx_file_urls.append(post.get('file_url'))
source.append(post.get('id'))
r34xxx_file_urls_length += 1
the_url_num = random.randint(0, r34xxx_file_urls_length - 1)
the_url = r34xxx_file_urls[the_url_num]
await interaction.followup.send(str(the_url) + f"\nTags recorded: `{ctxtags2}`\nID: `{source[the_url_num]}`\nFound `{r34xxx_file_urls_length - 1}` other entries.")
print(
f"Someone has searched for \"{tags}\"\nThis has resulted in the bot sending this link: [ {r34xxx_url_pre} ]\nThe ID of the post is `{source[the_url_num]}`\n"
f"This is the link sent: -# {the_url} #-")
#except IndexError or discord.app_commands.errors.CommandInvokeError:
# await interaction.followup.send(f"No results found for `{tags}`.")
#except ValueError:
# await interaction.followup.send(f"Something went wrong. Please check the spelling of each tag and try again.\nPlease check Rule34.xxx if it s down or if it shows results at all.\nTags used: `{tags.replace('+', ', ')}`")
@client.tree.command(name="bleachbooru")
@app_commands.describe(tags = "Enter tags in a `tag 1, tag 2 (series name), -banned tag, *wildcard` format")
@app_commands.describe(nsfw = "Filter ratings. Default: `Safe`. **WARNING** Even `Safe` will often result in NSFW artwork! Fault: Website Moderation.")
async def bleach(interaction: discord.Interaction, tags: str, nsfw: Literal['safe', 'questionable and safe (high filter)', 'questionable and safe (low filter)', 'all', 'explicit only'] = 'safe'): # <-- This site sucks btw, horrid API, barely any documentation, not even filtered correctly. Be careful, even "safe" will often return porn.
""" Get an image from Bleachbooru (Severe NSFW warning) """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
return
elif not interaction.channel.nsfw:
await interaction.response.send_message(f"Could not run command! This command is for channels marked NSFW only!")
return
else:
urlSafePreBleach = ""
try:
print(tags)
await interaction.response.defer()
ctxtags6 = tags.replace(", ", "+")
ctxtags7 = ctxtags6.replace(" ", "_")
print(ctxtags7)
if nsfw == 'safe': # Safe only
urlSafePreBleach = "https://bleachbooru.org/post.xml?limit=100?tags=" + ctxtags7 + "+-sex+-nipples+-penis+-vaginal_penetration+rating%3As"
elif nsfw == 'questionable and safe (high filter)':
urlSafePreBleach = "https://bleachbooru.org/post.xml?limit=100?tags=" + ctxtags7 + "+-sex+-nipples+-penis+-vaginal_penetration+-rating%3Aexplicit"
elif nsfw == 'questionable and safe (high filter)':
urlSafePreBleach = "https://bleachbooru.org/post.xml?limit=100?tags=" + ctxtags7 + "+-rating%3Aexplicit"
elif nsfw == 'all':
urlSafePreBleach = "https://bleachbooru.org/post.xml?limit=100?tags=" + ctxtags7
elif nsfw == 'explicit only':
urlSafePreBleach = "https://bleachbooru.org/post.xml?limit=100?tags=" + ctxtags7 + "+rating%3Aexplicit"
async with aiohttp.ClientSession() as session:
async with session.get(urlSafePreBleach) as response:
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
bleach_file_urls = []
bleach_file_urls_length = 0
source = []
for post in soup.find('posts').find_all('post'):
bleach_file_urls.append(post.attrs["file_url"])
bleach_file_urls_length += 1
source.append(post.attrs["id"])
print("I arrived at line 363")
the_url_num = random.randint(0, bleach_file_urls_length - 1)
the_url = "https://bleachbooru.org" + bleach_file_urls[the_url_num]
await interaction.followup.send(the_url + f"\nTags recorded: `{tags}`\nUser searched for: `{nsfw}` | ID: `{source[the_url_num]}`\nFound {bleach_file_urls_length - 1} other entries (Max. 39 others).")
print("I arrived at line 367")
print(
f"Someone has searched for \"{tags}\"\nThis has resulted in the bot sending this link: [ {urlSafePreBleach} ]\nThe ID of the post is `{source[the_url_num]}`\n"
f"This is the link sent: -# {the_url} #-")
except IndexError or discord.app_commands.errors.CommandInvokeError:
await interaction.followup.send(f"No results found for `{tags}`.")
@client.tree.command(name="roll")
@app_commands.describe(sides = "How many sides your dice should have")
@app_commands.describe(rolls = "How many dices you want to roll")
@app_commands.describe(highlight_number = "Highlight the x-th roll (counts from 1 upwards)")
async def roll(interaction: discord.Interaction, sides: int, rolls: int = 1, highlight_number: int = None):
""" Roll a die """
blacklist_data = load_longterm_lists()
user_id = str(interaction.user.id) # Convert user ID to string
result = check_user_in_blacklist(user_id, blacklist_data)
if result:
uid, reason = result
await interaction.response.send_message(f"Could not run command! User <@{user_id}> is blacklisted.\nReason: {reason}.")
else:
result = []
response = ""
if sides <= 0:
await interaction.response.send_message("Please enter a positive, non-zero number when choosing sides.", ephemeral = True)
elif rolls <= 0:
await interaction.response.send_message("Please enter a positive, non-zero number when choosing how many rolls you want to make.", ephemeral = True)
elif sides >= sys.maxsize:
await interaction.response.send_message("Please enter a smaller number for how many sides your roll has.", ephemeral = True)
elif rolls >= sys.maxsize:
await interaction.response.send_message("Please enter a smaller number for how many roll you want to make.", ephemeral = True)
else:
try:
for roll in range(rolls):
result.append(random.randint(1, sides))
response = f"Input: `{rolls}d{sides}`\nResult: " + ", ".join(map(str, result))
if highlight_number:
if highlight_number <= 0:
await interaction.response.send_message("Please enter a positive, non-zero number when choosing the highlighted roll.", ephemeral = True)
if highlight_number >= rolls + 2:
await interaction.response.send_message("Please ensure that the number you want to highlight is not higher than the number of rolls.", ephemeral = True)
else:
response = response + f"\nHighlighted Roll: {result[highlight_number - 1]}"
await interaction.response.send_message(response)
except Exception as e:
await interaction.response.send_message(f"Error rolling die: {e}", ephemeral = True)
list_ = [
"cunny",
"kani",
"loli",
"lolicon",
"shota",
"shotacon",
"uoh", "uooh", "uoooh", "uooooh",
"correction",
"coney",
"coni",
"koney",
"koni",
"kuni",
"cnnuy"
]
@client.event
async def on_message(message: discord.Message):
if message.author == client.user:
try:
await message.add_reaction(trash_emoji)
except:
print("Couldn't add emoji to own message :/")
pass
return
# Load blacklist only if necessary
if check_user_in_blacklist(user_id=message.author.id, blacklist_data=load_longterm_lists()):
return
message_lowsplit = message.content.lower().split()
message_set = set(message_lowsplit) # Convert to set for fast lookup
if any(substring in message_set for substring in list_):
await message.add_reaction('😭')
return
for word in message_lowsplit:
if word.startswith('u') and word.endswith('h') and 'o' in word and not re.search('[a-gi-np-tv-z]', word):
await message.add_reaction('😭')
return # Exit immediately after adding reaction
### Link Renamer ###
# List of domains to exclude from processing