forked from PonyPlaceDevelopment/Trixie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
derpy.py
1208 lines (1051 loc) · 43.5 KB
/
derpy.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
from typing import Optional, Union
from discord import app_commands
from discord.ext import commands
import discord
import asyncio
import os
from dotenv import load_dotenv
import json
import re
import requests
import random
from pytz import timezone
from io import BytesIO
import time
from PIL import Image, ImageDraw, ImageFont
load_dotenv()
# .env file
# discord_token = "TOKEN"
# guild_id = the guild id where the bot should work (guild id for r/place bronies is: 1086048263620276254)
BOT_TOKEN = os.getenv("place")
def is_suspicious_username(username):
suspicious_patterns = [
# For Cloud: Add keywords here if you want
r"\b(?:spam|bot|nudes|18\+|nsfw|admin|dick|tits|dik|hitler|adolf)\b",
]
# random signs check
random_letters_pattern = r"^(?!.*(.).*\1)[a-z0-9]{4,}$"
for pattern in suspicious_patterns:
if re.search(pattern, username, re.IGNORECASE):
return True
if re.match(random_letters_pattern, username):
return True
return False
class TicketMessageView(discord.ui.View):
def __init__(self):
super().__init__()
async def interaction_close_callback(
self, interaction: discord.Interaction, channelus: discord.TextChannel
):
message_content = f"Welcome {interaction.user.mention}! Please stand by until a Moderator has time for your request"
message = await channelus.send(message_content)
return message
@discord.ui.button(label="Delete ticket", style=discord.ButtonStyle.red)
async def ticket_close_callback(self, interaction, button):
data = load("setup_data.json")
if data and str(interaction.guild_id) in data:
mod_role_id = data.get(str(interaction.guild_id), {}).get("mod_role_id")
mod_role = discord.utils.get(interaction.guild.roles, id=mod_role_id)
if mod_role in interaction.user.roles:
await interaction.response.send_message("Deleting ticket...")
await interaction.channel.delete()
else:
await interaction.response.send_message(
"You dont have permission to do that!", ephemeral=True
)
class TicketView(discord.ui.View):
def __init__(
self,
interaction: discord.Interaction,
textchannel: discord.TextChannel,
button_message: str,
button_color: str,
ticket_name: str,
):
super().__init__()
self.channel = textchannel
self.guild_id = interaction.guild_id
self.button_message = button_message
self.button_color = button_color
self.ticket_name = ticket_name
async def interaction_callback(self, interaction: discord.Interaction):
message_content = f"{self.button_message}"
message = await self.channel.send(message_content)
await interaction.response.send_message("Ticket button(s) created")
return message
button_styless = {
"primary": discord.ButtonStyle.primary,
"grey": discord.ButtonStyle.grey,
"green": discord.ButtonStyle.green,
"red": discord.ButtonStyle.red,
}
def button_label(self):
return f" Create {self.ticket_name} ticket"
def set_button_color(self):
button_styless = {
"primary": discord.ButtonStyle.primary,
"grey": discord.ButtonStyle.grey,
"green": discord.ButtonStyle.green,
"red": discord.ButtonStyle.red,
}
return button_styless[self.button_color]
@discord.ui.button(label=button_label, style=set_button_color)
async def ticket_callback(self, interaction, button):
guild = interaction.guild
username = interaction.user.name
user = interaction.user
data = load("setup_data.json")
if data and str(interaction.guild_id) in data:
ticket_role_id = data.get(str(interaction.guild_id), {}).get("ticket_role")
ticket_role = discord.utils.get(guild.roles, id=ticket_role_id)
ticket_category_id = data.get(str(interaction.guild_id), {}).get(
"ticket_category"
)
print(ticket_category_id)
category = discord.utils.get(guild.categories, id=ticket_category_id)
print(category)
overwrites = {
guild.default_role: discord.PermissionOverwrite(
view_channel=False, read_messages=False
),
guild.me: discord.PermissionOverwrite(
read_messages=True, send_messages=True
),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True),
}
channel = await category.create_text_channel(
f"{self.ticket_name}-ticket-{interaction.user.name}", overwrites=overwrites
)
await interaction.user.add_roles(ticket_role)
welcomeView = (
TicketMessageView()
) # No error since i still have to make this view puplic
message = await welcomeView.interaction_close_callback(interaction, channel)
await interaction.response.send_message(
f"Ticket created! {channel.mention}", ephemeral=True
)
return message
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
intents.message_content = True
super().__init__(command_prefix="!", intents=intents)
self.setup_data = {}
self.mod_role_data = {}
self.load_data()
self.load_mod()
async def on_command_error(self, ctx, error):
await ctx.reply(error, ephemeral=True)
def save_data(self):
with open("setup_data.json", "w") as file:
json.dump(self.setup_data, file)
def save_mod(self):
with open("mod_role_data.json", "w") as file:
json.dump(self.mod_role_data, file)
def load_mod(self):
try:
with open("mod_role_data.json", "r") as file:
self.mod_role_data = json.load(file)
except FileNotFoundError:
pass
def load_data(self):
try:
with open("setup_data.json", "r") as file:
self.setup_data = json.load(file)
except FileNotFoundError:
pass
bot = Bot()
emote = None
category_name = None
class BanFlags(commands.FlagConverter):
member: discord.Member
days: int = 1
class KickFlags(commands.FlagConverter):
member: discord.Member
reason: str
class TimeoutFlags(commands.FlagConverter):
member: discord.member
reason: str
duration: int
def load(file):
try:
with open(file, "r", encoding="UTF-8") as f:
config = json.load(f)
return config
except Exception as e:
print(e)
return None
def save(config, file):
try:
with open(file, "w", encoding="UTF-8") as f:
json.dump(config, f)
return
except Exception as e:
print(e)
return None
@bot.tree.context_menu(name="ban")
async def ban(
interaction: discord.Interaction,
member: discord.User,
):
try:
await member.ban(delete_message_days=7)
await interaction.response.send_message(
f"{member.mention} got banned!", ephemeral=True
)
except discord.Forbidden:
await interaction.response.send_message(
"I don't have permission to ban members.", ephemeral=True
)
except discord.HTTPException:
await interaction.response.send_message(
"An error occurred while trying to ban the member. Please try again later.",
ephemeral=True,
)
@bot.tree.context_menu(name="kick")
async def ban(interaction: discord.Interaction, member: discord.User):
try:
await member.kick()
await interaction.response.send_message(
f"{member.mention} has been kicked", ephemeral=True
)
except discord.Forbidden:
await interaction.response.send_message(
"I don't have permission to kick members.", ephemeral=True
)
except discord.HTTPException:
await interaction.response.send_message(
"An error occurred while trying to kick the member. Please try again later.",
ephemeral=True,
)
@bot.tree.context_menu(name="whothis")
async def whothis(interaction: discord.Interaction, member: discord.Member):
embed = discord.Embed(title=f"{member.name}", description=f" {member.id}")
embed.add_field(
name="Joined Discord",
value=member.created_at.strftime("%d/%m/%Y/%H:%M:%S"),
inline=False,
)
embed.add_field(
name="Roles",
value=", ".join([role.mention for role in member.roles]),
inline=False,
)
embed.add_field(
name="Badges",
value=", ".join([badge.name for badge in member.public_flags.all()]),
inline=False,
)
embed.add_field(name="Activity", value=member.activity, inline=False)
embed.set_thumbnail(url=member.avatar.url)
await interaction.response.send_message(embed=embed, ephemeral=True)
@bot.tree.command(name="rps", description="Play Rock, Paper, Scissors against others")
@app_commands.describe(username="@username")
@app_commands.choices(
user_choice=[
discord.app_commands.Choice(name="Scissors", value="1"),
discord.app_commands.Choice(name="Rock", value="2"),
discord.app_commands.Choice(name="Paper", value="3"),
]
)
async def rps_user(
interaction: discord.Interaction, username: discord.User, user_choice: str
):
challenger = interaction.user
opponent = username
class SSPMultiplayerView(discord.ui.View):
def __init__(self, challenger, opponent):
super().__init__()
self.challenger = challenger
self.opponent = opponent
async def interaction_callback(self, interaction: discord.Interaction):
if self.challenger == self.opponent:
await interaction.response.send_message(
"You can't play against yourself", ephemeral=True
)
return
message_content = f"### {opponent.mention}, yout got challenged by {self.challenger.mention} to play some Rock Paper Scissors"
print(user_choice)
message = await interaction.response.send_message(
message_content, view=self
)
return message
async def disable_buttons(self, interaction):
for child in self.children:
child.disabled = True
await interaction.message.edit(content="Game started", view=self)
@discord.ui.button(label="Scissors", style=discord.ButtonStyle.grey)
async def schere_callback(self, interaction, button):
if (
self.opponent != interaction.user
): # Only allow the challenged user to click
await interaction.response.send_message(
"Only your opponent can use this!", ephemeral=True
)
return
await interaction.response.send_message(f"Success", ephemeral=True)
await self.disable_buttons(interaction)
await game_logic(user_choice, "1")
print("Schere")
@discord.ui.button(label="Stone", style=discord.ButtonStyle.grey)
async def stein_callback(self, interaction, button):
if (
self.opponent != interaction.user
): # Only allow the challenged user to click
await interaction.response.send_message(
"Only your opponent can use this!", ephemeral=True
)
return
await interaction.response.send_message(f"Success", ephemeral=True)
await self.disable_buttons(interaction)
await game_logic(user_choice, "2")
print("Stein")
@discord.ui.button(label="Paper", style=discord.ButtonStyle.grey)
async def papier_callback(self, interaction, button):
if (
self.opponent != interaction.user
): # Only allow the challenged user to click
await interaction.response.send_message(
"Only your opponent can use this!", ephemeral=True
)
return
await interaction.response.send_message(f"Success", ephemeral=True)
await self.disable_buttons(interaction)
await game_logic(user_choice, "3")
print("Papier")
async def game_logic(view, user_choice):
win_conditions = {"3": "1", "2": "3", "1": "2"}
user_options = ["1", "2", "3"]
bot_choice = random.choice(user_options)
emojis = {"1": "✂️", "2": "🪨", "3": "📜"}
await asyncio.sleep(1)
if user_choice == view:
before = await interaction.original_response()
await before.edit(
content=f"### Tie! {opponent.mention} also choose {emojis[user_choice]}"
)
else:
if win_conditions[user_choice] == view:
before = await interaction.original_response()
await before.edit(
content=f"### {challenger.mention} won! {emojis[view]} beats {emojis[user_choice]}!"
)
else:
before = await interaction.original_response()
await before.edit(
content=f"### {challenger.mention} lost! {emojis[user_choice]} beats {emojis[view]}!"
)
view = SSPMultiplayerView(challenger, opponent)
message = await view.interaction_callback(interaction)
return message
@bot.tree.context_menu(name="voicekick")
async def kick(interaction: discord.Interaction, member: discord.Member):
voice_channel = member.voice.channel
await member.move_to(None)
await interaction.response.send_message(
f"{member.mention} got kicked out of {voice_channel.mention}", ephemeral=True
)
@bot.tree.command(name="purge", description="Delete messages from a channel")
async def delete_messages(
interaction: discord.Interaction, channel: discord.TextChannel, limit: int
):
messages = []
async for message in channel.history(limit=limit):
messages.append(message)
await channel.delete_messages(messages)
await asyncio.sleep(4)
await interaction.response.send_message(
f"{limit} messages got deleted in {channel.mention}.", ephemeral=True
)
@bot.tree.command(name="setup", description="Setup cmd")
@commands.has_permissions(kick_members=True)
async def setup(
interaction: discord.Interaction,
mod_role: discord.Role,
mod_channel: discord.TextChannel,
log_channel: discord.TextChannel,
member_role: discord.Role,
):
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
print(setup_data)
if setup_data is None:
setup_data = {}
if str(interaction.guild_id) not in setup_data:
setup_data[str(interaction.guild_id)] = {}
setup_data[str(interaction.guild_id)].update(
{
"mod_role_id": mod_role.id,
"mod_channel_id": mod_channel.id,
"member_role_id": member_role.id,
"log_channel_id": log_channel.id,
}
)
save(setup_data, "setup_data.json")
await interaction.response.send_message(
"Setup complete! Now the bot is ready to use with the provided configurations."
)
@bot.tree.command(name="ticket_setup", description="Setup tickets cmd")
@commands.has_permissions(kick_members=True)
async def setup(
interaction: discord.Interaction,
create_channels_auto: bool,
ticket_role: discord.Role = None,
ticket_category: discord.CategoryChannel = None,
):
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
if not setup_data:
await interaction.response.send_message("Run /setup first", ephemeral=True)
return
if str(interaction.guild_id) not in setup_data:
await interaction.response.send_message("Run /setup first!", ephemeral=True)
return
if create_channels_auto is True and ticket_role is None and ticket_category is None:
category = discord.utils.get(
interaction.guild.categories, name="Pending Tickets"
)
if category is None:
category = await interaction.guild.create_category("Pending Tickets")
cooldown_role = discord.utils.get(
interaction.guild.roles, name="Ticket Cooldown"
)
if cooldown_role is None:
cooldown_role = await interaction.guild.create_role("Ticket Cooldown")
else:
if ticket_role is None or ticket_category is None:
interaction.response.send_message(
"Pleaso provide both ticket_role and ticket_category!", ephemeral=True
)
return
category = ticket_category
cooldown_role = ticket_role
ticket_data = {"ticket_role": cooldown_role.id, "ticket_category": category.id}
setup_data[str(interaction.guild_id)].update(ticket_data)
save(setup_data, "setup_data.json")
await interaction.response.send_message(
"Setup complete! Now the bot is ready to use with the provided configurations."
)
@bot.event
async def on_member_join(member):
server_id = member.guild.id
print("New Member!")
username = member.name
if is_suspicious_username(username):
print("Sus name")
else:
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
if setup_data:
member_role_id = setup_data.get(str(server_id), {}).get(
"member_role_id"
)
member_role = discord.utils.get(member.guild.roles, id=member_role_id)
await member.add_roles(member_role)
print("[Main INFO]: Member Role given")
else:
print(
"[Main ERROR]: No Setup Data available! No role was handed out! (Run /setup)"
)
@bot.event
async def on_message_edit(before, after):
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
server_id = after.author.guild.id
if before.content == after.content:
return
if setup_data:
channel_id = setup_data.get(str(server_id), {}).get("log_channel_id")
channel = bot.get_channel(channel_id)
if after.author.bot:
return
embed = discord.Embed(color=discord.Color.blue())
embed.add_field(
name=f"Message Edited in {after.channel.mention}",
value=f"[Jump to Message](https://discordapp.com/channels/{server_id}/{after.channel.id}/{after.id})",
inline=False,
)
embed.add_field(name="User", value=after.author.mention, inline=False)
embed.set_author(name=before.author.name, icon_url=before.author.avatar.url)
embed.add_field(name="Before", value=before.content, inline=False)
embed.add_field(name="After", value=after.content, inline=False)
embed.set_footer(text=f"User ID: {after.author.id}")
await channel.send(embed=embed)
else:
return
@bot.event
async def on_member_join(member):
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
server_id = member.guild.id
if setup_data:
channel_id = setup_data.get(str(server_id), {}).get("log_channel_id")
mod_channel_id = setup_data.get(str(server_id), {}).get("mod_channel_id")
mod_channel = bot.get_channel(mod_channel_id)
channel = bot.get_channel(channel_id)
if is_suspicious_username(member.name):
await mod_channel.send(
f"{member.mention} got detected by the sus name detection"
)
if member.bot:
return
embed = discord.Embed(
description=f"{member.mention} {member.name}",
color=discord.Color.green(),
)
embed.set_author(name="Member Joined", icon_url=member.avatar.url)
embed.add_field(name="Created at", value=member.created_at, inline=False)
embed.set_footer(text=f"User ID: {member.id}")
await channel.send(embed=embed)
@bot.event
async def on_member_remove(member):
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
server_id = member.guild.id
if setup_data:
channel_id = setup_data.get(str(server_id), {}).get("log_channel_id")
channel = bot.get_channel(channel_id)
if member.bot:
return
embed = discord.Embed(
description=f"{member.mention} {member.name}",
color=discord.Color.green(),
)
embed.set_author(name="Member Left", icon_url=member.avatar.url)
embed.set_footer(text=f"User ID: {member.id}")
await channel.send(embed=embed)
# @bot.event
# async def on_member_update(before, after):
# with open('setup_data.json', 'r') as file:
# setup_data = json.load(file)
# server_id = before.guild.id
# setup_data:
# channel_id = setup_data.get(str(server_id), {}).get("log_channel_id")
# channel = bot.get_channel(channel_id)
# if before.bot:
# return
# embed=discord.Embed(description = f"{after.mention} {after.name}", color=discord.Color.orange())
# embed.set_author(name="User updated", icon_url=after.avatar.url)
# embed.add_field(name="Before", value=before.global_name)
# embed.add_field(name="After", value=after.global_name)
# embed.set_footer(text=f"User ID: {after.id}")
# await channel.send(embed=embed)
@bot.event
async def on_message_delete(message):
with open("setup_data.json", "r") as file:
setup_data = json.load(file)
server_id = message.guild.id # Using message.guild.id directly
if setup_data:
channel_id = setup_data.get(str(server_id), {}).get("log_channel_id")
channel = bot.get_channel(channel_id)
if message.author.bot:
return
if not message.attachments:
embed = discord.Embed(color=discord.Color.red())
embed.set_author(
name=message.author.name, icon_url=message.author.avatar.url
)
embed.add_field(
name=f"Message deleted in {message.channel.mention}",
value=message.content,
inline=False,
)
embed.add_field(
name="Author", value=message.author.mention, inline=False
)
embed.set_footer(text=f"Message ID: {message.id}")
# Check for attachments (images) in the deleted message
if message.attachments:
image_urls = message.attachments[0].url
print(image_urls)
embed = discord.Embed(color=discord.Color.red())
embed.set_author(
name=message.author.name, icon_url=message.author.avatar.url
)
embed.add_field(
name=f"Attachment deleted in {message.channel.mention}",
value=message.content,
inline=False,
)
embed.add_field(
name="Author", value=message.author.mention, inline=False
)
embed.set_footer(text=f"Message ID: {message.id}")
if image_urls:
embed.set_image(
url=image_urls
) # Only adding the first image URL if multiple images are attached
await channel.send(embed=embed)
async def process_booru_command(
interaction: discord.Interaction, url, images, incomplete_url
):
# main body of booru commands in separate func to avoid code repetition
if url == None:
await interaction.response.send_message(f"Missing argument search query")
else:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if images in data and len(data[images]) > 0:
image = random.choice(data[images])
image_url = incomplete_url + image["representations"]["full"]
if "uploader" in image:
author = image["uploader"]
else:
author = "anonymous"
embed = discord.Embed(color=discord.Color.pink())
embed.add_field(name="Author", value=author)
embed.set_image(url=image_url)
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message("No picture was found")
else:
await interaction.response.send_message(
"Error occured while searching for pictures"
)
async def create_transcript(channel):
messages = channel.history(limit=None)
html_content = "<html>\n<body>\n"
file = "transcript.html"
async for message in messages:
html_content += (
f"<p>{message.author.name} - {message.created_at}: {message.content}</p>\n"
)
html_content += "</body>\n</html>"
with open(file, "w", encoding="UTF-8") as f:
f.write(html_content)
try:
with open(file, "rb") as html:
msg = await channel.send(
file=discord.File(html, filename="transcript.html")
)
except Exception as e:
print(f"Error sending file: {e}")
else:
# Ensure the file is sent before attempting deletion
try:
await msg.publish()
except Exception as e:
print(f"Error publishing message: {e}")
finally:
os.remove(file) # Delete the file after it's sent
@bot.tree.command(name="close_request", description="Request to close a ticket")
async def close_request(interaction: discord.Interaction, reason: str):
text_channel = interaction.channel
guild_id = interaction.guild_id
if "ticket" not in text_channel.name:
await interaction.response.send_message(
"Current channel is not a ticket channel", ephemeral=True
)
class TicketMessageView(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Delete ticket", style=discord.ButtonStyle.red)
async def ticket_close_callback(self, interaction, button):
data = load("setup_data.json")
if data and str(interaction.guild_id) in data:
mod_role_id = data.get(str(interaction.guild_id), {}).get("mod_role_id")
mod_role = discord.utils.get(interaction.guild.roles, id=mod_role_id)
if mod_role in interaction.user.roles:
await interaction.response.send_message(
"Closing ticket...", ephemeral=True
)
await interaction.channel.delete()
else:
await interaction.response.send_message(
"You don't have the permission to run this command!",
ephemeral=True,
)
else:
await interaction.response.send_message(
"Bot needs some config! Please run /setup first", ephemeral=True
)
@discord.ui.button(label="Create transcript", style=discord.ButtonStyle.grey)
async def transcript_callback(self, interaction, button):
data = load("setup_data.json")
if data and str(interaction.guild_id) in data:
mod_role_id = data.get(str(interaction.guild_id), {}).get("mod_role_id")
mod_role = discord.utils.get(interaction.guild.roles, id=mod_role_id)
if mod_role in interaction.user.roles:
await interaction.response.send_message("Creating transcript...")
await create_transcript(interaction.channel)
await interaction.channel.send(
f"Ticket transcript created by {interaction.user.mention}."
)
# Disable button
button.disabled = True
else:
await interaction.response.send_message(
"You don't have permission to run this command", ephemeral=True
)
else:
await interaction.response.send_message(
"Bot needs some config! Please run /setup first", ephemeral=True
)
class close_view(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.textchannel = text_channel
self.guild_id = guild_id
async def disable_buttons(self, interaction):
for child in self.children:
child.disabled = True
@discord.ui.button(label="Close", style=discord.ButtonStyle.red)
async def close_callback(self, interaction, button):
guild = interaction.guild
setup_data = load("setup_data.json")
timeout_role_id = setup_data.get(str(interaction.guild_id), {}).get(
"ticket_role"
)
timeout_role = discord.utils.get(
interaction.guild.roles, id=timeout_role_id
)
await interaction.response.send_message(
"Ticket will be closed in 3 seconds."
)
await interaction.channel.edit(name=f"closed-{interaction.channel.name}")
await interaction.user.remove_roles(timeout_role)
await interaction.channel.send(
f"Ticket closed by {interaction.user.mention}. Reason: {reason}"
)
await self.disable_buttons(interaction)
user_id = 1014344645020495942
await interaction.channel.set_permissions(
interaction.user,
read_messages=False,
send_messages=False,
view_channel=False,
)
user = await interaction.guild.fetch_member(user_id)
await interaction.channel.set_permissions(
user, read_messages=True, send_messages=True
)
data = load("setup_data.json")
if data and str(interaction.guild_id) in data:
mod_role_id = data.get(str(interaction.guild_id), {}).get("mod_role_id")
mod_role = discord.utils.get(interaction.guild.roles, id=mod_role_id)
await interaction.channel.set_permissions(
mod_role, read_messages=True, send_messages=True
)
embed = discord.Embed(
description=f"Ticket closed by {interaction.user.mention}",
color=discord.Color.yellow(),
)
adminEmbed = discord.Embed(title="```Support team ticket controls```")
await interaction.channel.send(embed=embed)
await interaction.channel.send(embed=adminEmbed, view=TicketMessageView())
await interaction.message.delete(delay=1)
@discord.ui.button(label="Deny", style=discord.ButtonStyle.gray)
async def deny_callback(self, interaction, button):
await interaction.response.send_message(
"User has declined the close request."
)
button.disabled = True
await self.disable_buttons(interaction)
await interaction.message.delete(delay=1)
await interaction.response.send_message(
f"{interaction.user.mention} requested to close the ticket!", view=close_view()
)
user_role = None
async def refresh_buttons(view, channel, original_message_id, content):
while True:
print("Refreshing...")
# Fetch the original message using its ID
try:
message = await channel.fetch_message(original_message_id)
# Update the message with fresh buttons
await message.edit(content="TEST", view=view)
except discord.NotFound:
print("YAY")
pass
# Wait for a certain interval before refreshing again
await asyncio.sleep(20) # 300 seconds (5 minutes) interval
@bot.tree.command(name="ticket", description="setup ticket system")
@app_commands.choices(
button_color=[
discord.app_commands.Choice(name="Blue", value="primary"),
discord.app_commands.Choice(name="Grey", value="grey"),
discord.app_commands.Choice(name="Green", value="green"),
discord.app_commands.Choice(name="Red", value="red"),
]
)
async def ticket_system(
interaction: discord.Interaction,
channel: discord.TextChannel,
button_message: str,
ticket_name: str,
button_color: str,
):
setup_check = load("setup_data.json")
if setup_check:
if interaction.guild_id in setup_check:
ticket_role_id = setup_check.get(
str(interaction.guild_id), {}.get("ticket_role")
)
ticket_category_id = setup_check.get(
str(interaction.guild_id), {}.get("ticket_category")
)
if ticket_category_id is None or ticket_role_id is None:
interaction.response.send_message(
"Please set up ticket roles first! (/ticket_setup)", ephemeral=True
)
return
else:
interaction.response.send_message(
"Please set up ticket roles first! (/ticket_setup)", ephemeral=True
)
view = TicketView(
interaction=interaction,
textchannel=interaction.channel,
button_message=button_message,
button_color=button_color,
ticket_name=ticket_name,
)
await view.interaction_callback(interaction)
message_content = f"{button_message}"
message = await channel.send(message_content, view=TicketView(interaction=interaction, textchannel=interaction.channel, button_message=button_message, button_color=button_color, ticket_name=ticket_name))
await interaction.response.send_message("Ticket button(s) created")
@bot.tree.command(
name="create_channel", description="Admins are to lazy so this exists"
)
async def c_channel(
interaction: discord.Interaction,
channel_name: str,
category: discord.CategoryChannel = None,
category_name: str = None,
):
guild = interaction.guild
user = interaction.user
if category is not None:
overwrites = {
guild.default_role: discord.PermissionOverwrite(
view_channel=False, read_messages=False
),
guild.me: discord.PermissionOverwrite(
read_messages=True, send_messages=True
),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True),
}
await category.create_text_channel(f"{channel_name}", overwrites=overwrites)
await interaction.response.send_message("Channel created", ephemeral=True)
else:
if category_name is not None:
overwrites = {
guild.default_role: discord.PermissionOverwrite(
view_channel=False, read_messages=False
),
guild.me: discord.PermissionOverwrite(
read_messages=True, send_messages=True
),
user: discord.PermissionOverwrite(
read_messages=True, send_messages=True
),
}
categoryname = await interaction.guild.create_category(name=category_name)
await categoryname.create_text_channel(f"{channel_name}", overwrites=overwrites)
await interaction.response.send_message("Channel created", ephemeral=True)
@bot.tree.command(name="unsync", description="Unsync unused commands")
async def test(interaction: discord.Interaction):
guild = interaction.guild_id
await interaction.response.send_message("Unsynced Commands")
await bot.tree.sync(guild=discord.Object(id=guild))
# level system
@bot.tree.command(name="rank", description="Display your current chat level")
async def levelcard(interaction: discord.Interaction, user: discord.User = None):
if user is None:
user = interaction.user
guild_id = str(interaction.guild_id)
user_id = str(user.id)
levels = load("levels.json")
if levels is not None and guild_id in levels and user_id in levels[guild_id]:
username = user.name
level = (
levels.get(str(interaction.guild_id), {}).get(str(user_id), {}).get("level")
)
current_xp = (
levels.get(str(interaction.guild_id), {}).get(str(user_id), {}).get("xp")
)
next_level = 5 * level**2 + 50 * level + 100