-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
3934 lines (3707 loc) · 146 KB
/
main.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
# Holy shit, that's a lot of imports
import contextlib
import io
import ipaddress
import os
import subprocess
import sys
import difflib
import textwrap
import traceback
import re
from base64 import urlsafe_b64encode
import uuid
from urllib import parse, request
from urllib.parse import parse_qsl
from millify import prettify
import uuid as uuid
from PIL import Image
from requests import PreparedRequest
from decouple import config
import aiohttp
import discord.ext
import discord
from discord import Webhook, AsyncWebhookAdapter, http, DMChannel
from discord.ext.commands import (
CommandNotFound,
is_owner,
check,
Context,
has_permissions,
)
from discord.ext import commands, tasks
from discord_slash import SlashCommand, SlashContext, ComponentContext, MenuContext
from discord_slash.utils.manage_commands import create_option
from discord_slash.utils.manage_components import (
create_button,
create_actionrow,
create_select_option,
create_select,
wait_for_component,
)
from discord_slash.model import ButtonStyle, ContextMenuType
from slash_help import SlashHelp
import requests
import json
from durations import Duration
import time
import datetime
import dateutil.relativedelta
import logging
import random
import sentry_sdk
import inflect
p = inflect.engine()
if config("DEBUG"):
environment = "development"
else:
environment = "production"
sentry_sdk.init(config("SENTRY"), environment=environment, traces_sample_rate=1.0)
# Setup the logger
class CustomFormatter(logging.Formatter):
grey = "\x1b[38;21m"
yellow = "\x1b[33;21m"
red = "\x1b[31;21m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
format = (
"%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
)
FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: grey + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset,
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
logger = logging.getLogger("discord")
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(CustomFormatter())
logger.addHandler(ch)
# Setup the bot
intents = discord.Intents.default()
intents.members = True
intents.presences = True
bot = commands.Bot(
command_prefix=["$", "pls", "prism"],
intents=intents,
case_insensitive=True,
help_command=None,
strip_after_prefix=True,
)
toe_ken = config("TOKEN")
slash = SlashCommand(bot, sync_commands=True)
help_slash = SlashHelp(
bot,
slash,
toe_ken,
dpy_command=True,
no_category_name="All commands",
no_category_description=" ",
extended_buttons=True,
prefix="$",
)
bot.completion_date = "soon"
# Much easier than remembering numbers
option_type = {
"sub_command": 1,
"sub_command_group": 2,
"string": 3,
"integer": 4,
"boolean": 5,
"user": 6,
"channel": 7,
"role": 8,
"mentionable": 9,
"float": 10,
}
bot_name = "Prism Bot"
filename = "roles.json"
status = ""
async def has_perms(ctx): # Check that a user has one of the roles to manage the bot
for b in ctx.author.roles:
if b.id in RJD["perms"]:
return True
# Slash commands don't have a message object
try:
name = ctx.message.author.display_name
except:
name = ctx.author.display_name
try:
icon = ctx.message.author.avatar_url
except:
icon = ctx.author.avatar_url
embed = discord.Embed(
title="We ran into an error",
description="You don't have permissions to manage this bot's functions",
color=discord.Color.red(),
)
embed.set_footer(text=f"Caused by {name}", icon_url=icon)
await ctx.send(embed=embed)
return False
bot.guild_ids = [
858547359804555264
] # Bypass stupid hour+ waiting time for global commands
@bot.event
async def on_ready():
channel = bot.get_channel(897765157940396052)
message = await channel.fetch_message(920460790354567258)
with open("old.txt", "w", encoding="utf8") as text_file:
print(message.content, file=text_file)
if config("DEBUG") == "False":
await discord.utils.get(bot.get_all_members(), id=bot.user.id).edit(
nick="prism bot peace be upon him"
)
bot.debug_status = "normal"
else:
await discord.utils.get(bot.get_all_members(), id=bot.user.id).edit(
nick="prism bot testing be his job"
)
bot.debug_status = "debug"
print(f"╔═══════════════════════════════════════════════════")
print(f"╠Bot is ready")
print(f"╠{bot.user.name} running in {bot.debug_status} mode")
print(f"╠Discord API Version: {discord.__version__}")
print(f"╠═Guilds:")
for guild in bot.guilds: # Print list of current guildsPreparedRequest
print(f"╠════{guild.name} ({guild.id})")
print(f"╚═══════════════════════════════════════════════════")
prismian.start()
changelog.start()
website_loop.start()
global RJD, roles_json
testing_zone = bot.get_guild(int(config("guild_id")))
try:
roles_json = open(filename, "r+")
except:
roles_json = open(filename, "w+")
json.dump({"perms": [], "roles": []}, roles_json)
roles_json.seek(0)
RJD = json.load(roles_json)
roles_json.seek(0)
for role in RJD["roles"]:
for member in RJD[role[0]]:
if member[1] <= time.time():
try:
await testing_zone.get_member(member[0]).remove_roles(
testing_zone.get_role(int(role[0])), reason="expired"
)
except:
pass
RJD[role[0]].remove(member)
else:
break
jsondump(RJD)
current_time = time.time()
for role in RJD["roles"]:
for member in RJD[role[0]]:
member[1] -= current_time
# task to check who is president, vice president and who has the other important website roles
@tasks.loop(seconds=600)
async def website_loop():
print("Website Loop")
prism_guild = bot.get_guild(int(config("guild_id")))
interview_guild = bot.get_guild(861018927752151071)
new_member_role = discord.utils.get(prism_guild.roles, name="New Member")
application_channel = discord.utils.get(interview_guild.channels, id=1008883079076659400)
def get_sorted_role(role_id: int) -> str:
return ", ".join(sorted([member.display_name for member in (prism_guild.get_role(role_id)).members], key=str.casefold))
data = {
"president": get_sorted_role(858548175711240192),
"vice_president": get_sorted_role(858548322158247947),
"adjudicators": get_sorted_role(883556570703740988),
"head_admin": get_sorted_role(933465436266323989),
"admins": get_sorted_role(858547762080776192),
"mods": get_sorted_role(858547638719086613),
"training_mods": get_sorted_role(931458136584359966),
"member_count": int(prism_guild.member_count),
"new_members": len(new_member_role.members),
"application_status": str(application_channel.name)
}
with open("transcripts/website.json", "w+") as text_file:
json.dump(data, text_file)
@bot.command()
async def dm(ctx):
user = discord.utils.get(ctx.guild.members, id="510748531926106113")
await user.remove_roles(883556570703740988)
#for member in ctx.guild.members:
# await member.send(
# "Hey there! This is just a reminder to vote in the current Prismian Presidential Election if you haven't already! You can do so in the election-votes."
# )
# print(f"Sent a DM to {member.display_name}")
@bot.command()
async def prismian(ctx):
for member in bot.get_guild(858547359804555264).members:
prismian_role = discord.utils.get(ctx.guild.roles, name="Prismian")
new_role = discord.utils.get(ctx.guild.roles, name="New Member")
general = bot.get_channel(858547359804555267)
if prismian_role not in member.roles and new_role in member.roles:
duration = datetime.datetime.now() - member.joined_at
hours, remainder = divmod(int(duration.total_seconds()), 3600)
days, hours = divmod(hours, 24)
if days >= 14:
mod_log = bot.get_channel(897765157940396052)
await mod_log.send(
f"{member.display_name} has been a new member for {days} days and upgraded to Prismian today!"
)
await member.remove_roles(new_role)
await member.add_roles(prismian_role)
await general.send(
"https://cdn.discordapp.com/attachments/861289278374150164/934758089075355708/party-popper-joypixels.gif"
)
await general.send(
f"{member.mention} congrats on upgrading from New Member to Prismian today!"
)
logger.info(f"{member.display_name} has been upgraded to Prismian")
@tasks.loop(hours=2)
async def prismian():
logger.info("Checking for Prismian upgrades")
guild = bot.get_guild(858547359804555264)
for member in bot.get_guild(858547359804555264).members:
prismian_role = discord.utils.get(guild.roles, name="Prismian")
new_role = discord.utils.get(guild.roles, name="New Member")
general = bot.get_channel(858547359804555267)
if prismian_role not in member.roles and new_role in member.roles:
duration = datetime.datetime.now() - member.joined_at
hours, remainder = divmod(int(duration.total_seconds()), 3600)
days, hours = divmod(hours, 24)
if days >= 14:
mod_log = bot.get_channel(897765157940396052)
await mod_log.send(
f"{member.display_name} has been a new member for {days} days and upgraded to Prismian today!"
)
await member.remove_roles(new_role)
await member.add_roles(prismian_role)
await general.send(
"https://cdn.discordapp.com/attachments/861289278374150164/934758089075355708/party-popper-joypixels.gif"
)
await general.send(
f"{member.mention} congrats on upgrading from New Member to Prismian today!"
)
logger.info(f"{member.display_name} has been upgraded to Prismian")
logger.info("Done checking for Prismian upgrades")
@tasks.loop(minutes=2)
async def changelog():
channel = bot.get_channel(897765157940396052)
message = await channel.fetch_message(920460790354567258)
with open("old.txt", "w", encoding="utf8") as text_file:
print(message.content, file=text_file)
@tasks.loop(seconds=10)
async def updating_embed():
channel = bot.get_channel(861289278374150164)
message = await channel.fetch_message(932900240019828756)
user = bot.get_user(324504908013240330)
IP = config("GAME_IP")
url = f"http://{IP}/players/{user.display_name}/stats"
# print(f"http://{IP}/players/{user.display_name}/stats")
page = requests.get(url)
stats = json.loads(page.text)
try:
if stats["error"]:
embed = discord.Embed(
color=discord.colour.Color.red(),
title=f"No one is currently in game",
description=f"Last updated at {datetime.datetime.now()}",
)
await message.edit(embed=embed)
return
except:
# Game time
sec = int(stats["time"])
sec_value = sec % (24 * 3600)
hour_value = sec_value // 3600
sec_value %= 3600
min_value = sec_value // 60
sec_value %= 60
if hour_value != 0:
game_time = f"{hour_value} hours, {min_value} minutes"
else:
game_time = f"{min_value} minutes"
# Death time
sec = int(stats["death"])
sec_value = sec % (24 * 3600)
hour_value = sec_value // 3600
sec_value %= 3600
min_value = sec_value // 60
sec_value %= 60
time = stats["lastJoined"]
time = int(str(time)[:-3])
if hour_value != 0:
death_time = f"{hour_value} hours, {min_value} minutes"
else:
death_time = f"{min_value} minutes"
embed = discord.Embed(
color=discord.colour.Color.red(),
title=f"{user.display_name}'s current game stats",
)
embed.add_field(name="Time spent in game:", value=game_time, inline=True)
embed.add_field(name="Time since last death:", value=death_time, inline=True)
embed.add_field(name="Last quit:", value=f"<t:{time}:R>", inline=True)
embed.add_field(name="Kills:", value=stats["kills"], inline=True)
embed.add_field(name="Deaths:", value=stats["deaths"], inline=True)
embed.add_field(name="XP level:", value=stats["level"], inline=True)
embed.add_field(name="Health:", value=stats["health"], inline=True)
embed.add_field(name="Hunger:", value=stats["food"], inline=True)
embed.add_field(name="Times jumped:", value=stats["jumps"], inline=True)
embed.add_field(name="World:", value=stats["world"], inline=True)
embed.set_thumbnail(
url=f"https://heads.discordsrv.com/head.png?name={user.display_name}&overlay#{random.randint(1, 2000)}"
)
await message.edit(embed=embed)
@bot.command()
async def dothesupportthing(ctx):
try:
support_category: discord.CategoryChannel = discord.utils.get(ctx.guild.categories, name="SUPPORT")
channel = discord.utils.get(support_category.channels, name="support")
await channel.purge(limit=10000)
except AttributeError: # the category doesn't exist, so make it exist
support_category = await ctx.guild.create_category(name="SUPPORT")
channel = await support_category.create_text_channel(name="support")
button = [
create_button(
style=ButtonStyle.green,
label="Report a player/social issue",
custom_id="ticket|mod contact"
), create_button(
style=ButtonStyle.blurple,
label="I just have a question",
custom_id="ticket|question"
), create_button(
style=ButtonStyle.danger,
label="Report a technical issue",
custom_id="ticket|issue report"
), create_button(
style=ButtonStyle.gray,
label="Something else",
custom_id="ticket|who really knows"
)
]
action_row = create_actionrow(*button)
embed = discord.Embed(
title="Need help from a mod? Have a question? Want to report something odd?",
description="Simply press a button below and a channel will be made for you"
)
await channel.send(embed=embed, components=[action_row])
@bot.event
async def on_component(ctx: ComponentContext):
if "ticket" in ctx.custom_id:
support_category: discord.CategoryChannel = discord.utils.get(ctx.guild.categories, name="SUPPORT")
staff = discord.utils.get(ctx.guild.roles, name="Staff")
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
ctx.guild.me: discord.PermissionOverwrite(read_messages=True),
ctx.author: discord.PermissionOverwrite(read_messages=True),
staff: discord.PermissionOverwrite(read_messages=True),
}
channel = await support_category.create_text_channel(name=ctx.author.name, overwrites=overwrites)
await ctx.reply(channel.mention, hidden=True)
button = [
create_button(
style=ButtonStyle.danger,
label="Close",
custom_id="close"
)
]
action_row = create_actionrow(*button)
await channel.send(f"{ctx.author.mention} your channel has been created\n"
f"Use the button below to close", components=[action_row])
if "mod" in ctx.custom_id:
await channel.send("<@&858547638719086613>")
if "issue" in ctx.custom_id:
await channel.send("<@&895186163265056778>")
if ctx.custom_id == "close":
await ctx.edit_origin(content="Released.", components=None)
css = """
body {
background-color: #36393e;
color: #dcddde;
}
a {
color: #0096cf;
}
.info {
display: flex;
max-width: 100%;
margin: 0 5px 10px;
}
.guild-icon-container {
flex: 0;
}
.guild-icon {
max-width: 88px;
max-height: 88px;
}
.metadata {
flex: 1;
margin-left: 10px;
}
.guild-name {
font-size: 1.4em;
}
.channel-name {
font-size: 1.2em;
}
.channel-topic {
margin-top: 2px;
}
.channel-message-count {
margin-top: 2px;
}
.chatlog {
max-width: 100%;
margin-bottom: 24px;
}
.message-group {
display: flex;
margin: 0 10px;
padding: 15px 0;
border-top: 1px solid;
}
.author-avatar-container {
flex: 0;
width: 40px;
height: 40px;
}
.author-avatar {
border-radius: 50%;
height: 40px;
width: 40px;
}
.messages {
flex: 1;
min-width: 50%;
margin-left: 20px;
}
.author-name {
font-size: 1em;
font-weight: 500;
}
.timestamp {
margin-left: 5px;
font-size: 0.75em;
}
.message {
padding: 2px 5px;
margin-right: -5px;
margin-left: -5px;
background-color: transparent;
transition: background-color 1s ease;
}
.content {
font-size: 0.9375em;
word-wrap: break-word;
}
.mention {
color: #7289da;
}
.botTag {
height: 0.9375rem;
padding: 0px 0.275rem;
margin-top: 0.075em;
border-radius: 0.1875rem;
background: #5961ec;
font-size: 0.625rem;
text-transform: uppercase;
vertical-align: top;
display: inline-flex;
align-items: center;
flex-shrink: 0;
text-indent: 0px;
position: relative;
top: 0.1rem;
margin-left: 0.25rem;
line-height: 1.375rem;
white-space: break-spaces;
overflow-wrap: break-word;
}
.botText {
position: relative;
font-size: 10px;
line-height: 15px;
text-transform: uppercase;
text-indent: 0px;
color: rgb(255, 255, 255);
font-weight: 500;
}
"""
def check_message_mention(msgs: discord.Message):
user_mentions: list = msgs.mentions
role_mentions: list = msgs.role_mentions
channel_mentions: list = msgs.channel_mentions
total_mentions: list = user_mentions + role_mentions + channel_mentions
m: str = msgs.content
for mentions in total_mentions:
if mentions in user_mentions:
for mention in user_mentions:
m = m.replace(
str(f"<@{mention.id}>"),
f'<span class="mention">@{mention.name}</span>',
)
m = m.replace(
str(f"<@!{mention.id}>"),
f'<span class="mention">@{mention.name}</span>',
)
elif mentions in role_mentions:
for mention in role_mentions:
m = m.replace(
str(f"<@&{mention.id}>"),
f'<span class="mention">@{mention.name}</span>',
)
elif mentions in channel_mentions:
for mention in channel_mentions:
m = m.replace(
str(f"<#{mention.id}>"),
f'<span class="mention">#{mention.name}</span>',
)
else:
pass
return m
messages: discord.TextChannel.history = await ctx.channel.history(
limit=None, oldest_first=True
).flatten()
title = str(
f"Transcript of {str(ctx.channel.name).encode('ascii', 'ignore')}'s channel"
)
description = str(f"Saved by {ctx.author.display_name}")
f = f"""
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset=utf-8>
<meta name=viewport content="width=device-width">
<meta content="Transcript saved" property="og:title" />
<meta content="{str(title).replace("b'", "").replace("'", "")}
{description}" property="og:description"/>
<meta content="https://transcripts.boredman.net" property="og:url" />
<meta content="https://paste.boredman.net/transcripts.png" property="og:image" />
<meta content="#14adc4" data-react-helmet="true" name="theme-color" />
<style>
{css}
</style>
</head>
<body>
<div class=info>
<div class=guild-icon-container><img class=guild-icon src={ctx.guild.icon_url}></div>
<div class=metadata>
<div class=guild-name>{ctx.guild.name}</div>
<div class=channel-name>{ctx.channel.name}'s arrest</div>
<div class=channel-message-count>{len(messages)} messages</div>
</div>
</div>
"""
for message in messages:
if message.embeds:
content = f"""Embed:
Title: {message.embeds[0].title}
Description: {message.embeds[0].description}
"""
elif message.attachments:
# IS AN IMAGE:
if message.attachments[0].url.endswith(("jpg", "png", "gif", "bmp")):
if message.content:
content = (
check_message_mention(message)
+ "<br>"
+ f'<a href="{message.attachments[0].url}" target="_blank"><img src="{message.attachments[0].url}" width="200" alt="Attachment" \\></a>'
)
else:
content = f'<a href="{message.attachments[0].url}" target="_blank"><img src="{message.attachments[0].url}" width="200" alt="Attachment" \\></a>'
# IS A VIDEO
elif message.attachments[0].url.endswith(
("mp4", "ogg", "flv", "mov", "avi")
):
if message.content:
content = (
check_message_mention(message)
+ "<br>"
+ f"""
<video width="320" height="240" controls>
<source src="{message.attachments[0].url}" type="video/{message.attachments[0].url[-3:]}">
Your browser does not support the video.
</video>
"""
)
else:
content = f"""
<video width="320" height="240" controls>
<source src="{message.attachments[0].url}" type="video/{message.attachments[0].url[-3:]}">
Your browser does not support the video.
</video>
"""
elif message.attachments[0].url.endswith(("mp3", "boh")):
if message.content:
content = (
check_message_mention(message)
+ "<br>"
+ f"""
<audio controls>
<source src="{message.attachments[0].url}" type="audio/{message.attachments[0].url[-3:]}">
Your browser does not support the audio element.
</audio>
"""
)
else:
content = f"""
<audio controls>
<source src="{message.attachments[0].url}" type="audio/{message.attachments[0].url[-3:]}">
Your browser does not support the audio element.
</audio>
"""
# OTHER TYPE OF FILES
else:
# add things
pass
else:
content = check_message_mention(message)
if message.author.bot:
isBot = """<span class="botTag">
<svg aria-label="Verified bot" class="botTagVerified" aria-hidden="false" width="16" height="16" viewBox="0 0 16 15.2">
<path d="M7.4,11.17,4,8.62,5,7.26l2,1.53L10.64,4l1.36,1Z" fill="currentColor"></path>
</svg>
<span class="botText">BOT</span>
</span>"""
else:
isBot = ""
f += f"""
<div class="message-group">
<div class="author-avatar-container"><img class=author-avatar src={message.author.avatar_url}></div>
<div class="messages">
<span class="author-name" >{message.author.name}</span>{isBot}<span class="timestamp">{message.created_at.strftime("%b %d, %Y %H:%M")}</span>
<div class="message">
<div class="content"><span class="markdown">{content}</span></div>
</div>
</div>
</div>
"""
f += """
</div>
</body>
</html>
"""
id = uuid.uuid4()
with open(f"transcripts/{str(id)}.html", mode="w+", encoding="utf-8") as file:
print(io.StringIO(f).read(), file=file)
await ctx.author.send(
f"Hi there, I've taken the liberty of sending you a copy of your transcript\n"
f"http://transcripts.boredman.net/{str(id)}.html")
await ctx.origin_message.channel.delete()
mod_log = bot.get_channel(897765157940396052)
await mod_log.send(f"{ctx.origin_message.channel.name}'s transcript:\n"
f"http://transcripts.boredman.net/{str(id)}.html")
if "release" in ctx.custom_id:
await ctx.edit_origin(components=None)
css = """
body {
background-color: #36393e;
color: #dcddde;
}
a {
color: #0096cf;
}
.info {
display: flex;
max-width: 100%;
margin: 0 5px 10px;
}
.guild-icon-container {
flex: 0;
}
.guild-icon {
max-width: 88px;
max-height: 88px;
}
.metadata {
flex: 1;
margin-left: 10px;
}
.guild-name {
font-size: 1.4em;
}
.channel-name {
font-size: 1.2em;
}
.channel-topic {
margin-top: 2px;
}
.channel-message-count {
margin-top: 2px;
}
.chatlog {
max-width: 100%;
margin-bottom: 24px;
}
.message-group {
display: flex;
margin: 0 10px;
padding: 15px 0;
border-top: 1px solid;
}
.author-avatar-container {
flex: 0;
width: 40px;
height: 40px;
}
.author-avatar {
border-radius: 50%;
height: 40px;
width: 40px;
}
.messages {
flex: 1;
min-width: 50%;
margin-left: 20px;
}
.author-name {
font-size: 1em;
font-weight: 500;
}
.timestamp {
margin-left: 5px;
font-size: 0.75em;
}
.message {
padding: 2px 5px;
margin-right: -5px;
margin-left: -5px;
background-color: transparent;
transition: background-color 1s ease;
}
.content {
font-size: 0.9375em;
word-wrap: break-word;
}
.mention {
color: #7289da;
}
.botTag {
height: 0.9375rem;
padding: 0px 0.275rem;
margin-top: 0.075em;
border-radius: 0.1875rem;
background: #5961ec;
font-size: 0.625rem;
text-transform: uppercase;
vertical-align: top;
display: inline-flex;
align-items: center;
flex-shrink: 0;
text-indent: 0px;
position: relative;
top: 0.1rem;
margin-left: 0.25rem;
line-height: 1.375rem;
white-space: break-spaces;
overflow-wrap: break-word;
}
.botText {
position: relative;
font-size: 10px;
line-height: 15px;
text-transform: uppercase;
text-indent: 0px;
color: rgb(255, 255, 255);
font-weight: 500;
}
"""
user = "boop"
def check_message_mention(msgs: discord.Message):
user_mentions: list = msgs.mentions
role_mentions: list = msgs.role_mentions
channel_mentions: list = msgs.channel_mentions
total_mentions: list = user_mentions + role_mentions + channel_mentions
m: str = msgs.content
for mentions in total_mentions:
if mentions in user_mentions:
for mention in user_mentions:
m = m.replace(
str(f"<@{mention.id}>"),
f'<span class="mention">@{mention.name}</span>',
)
m = m.replace(
str(f"<@!{mention.id}>"),
f'<span class="mention">@{mention.name}</span>',
)
elif mentions in role_mentions:
for mention in role_mentions:
m = m.replace(
str(f"<@&{mention.id}>"),
f'<span class="mention">@{mention.name}</span>',
)
elif mentions in channel_mentions:
for mention in channel_mentions:
m = m.replace(
str(f"<#{mention.id}>"),
f'<span class="mention">#{mention.name}</span>',
)
else:
pass
return m
messages: discord.TextChannel.history = await ctx.channel.history(
limit=None, oldest_first=True
).flatten()
title = str(
f"Transcript of {str(ctx.channel.name).encode('ascii', 'ignore')}'s channel"
)
description = str(f"Saved by {ctx.author.display_name}")
f = f"""
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset=utf-8>
<meta name=viewport content="width=device-width">
<meta content="Transcript saved" property="og:title" />
<meta content="{str(title).replace("b'", "").replace("'", "")}
{description}" property="og:description"/>
<meta content="https://transcripts.boredman.net" property="og:url" />
<meta content="https://paste.boredman.net/transcripts.png" property="og:image" />
<meta content="#14adc4" data-react-helmet="true" name="theme-color" />
<style>
{css}
</style>
</head>
<body>
<div class=info>
<div class=guild-icon-container><img class=guild-icon src={ctx.guild.icon_url}></div>
<div class=metadata>
<div class=guild-name>{ctx.guild.name}</div>
<div class=channel-name>{ctx.channel.name}'s arrest</div>
<div class=channel-message-count>{len(messages)} messages</div>
</div>
</div>
"""
for message in messages:
if message.embeds:
content = f"""Embed:
Title: {message.embeds[0].title}
Description: {message.embeds[0].description}
"""
elif message.attachments:
# IS AN IMAGE:
if message.attachments[0].url.endswith(("jpg", "png", "gif", "bmp")):
if message.content:
content = (
check_message_mention(message)
+ "<br>"
+ f'<a href="{message.attachments[0].url}" target="_blank"><img src="{message.attachments[0].url}" width="200" alt="Attachment" \\></a>'
)
else:
content = f'<a href="{message.attachments[0].url}" target="_blank"><img src="{message.attachments[0].url}" width="200" alt="Attachment" \\></a>'
# IS A VIDEO
elif message.attachments[0].url.endswith(
("mp4", "ogg", "flv", "mov", "avi")
):
if message.content:
content = (
check_message_mention(message)
+ "<br>"
+ f"""
<video width="320" height="240" controls>
<source src="{message.attachments[0].url}" type="video/{message.attachments[0].url[-3:]}">
Your browser does not support the video.
</video>
"""
)
else:
content = f"""
<video width="320" height="240" controls>
<source src="{message.attachments[0].url}" type="video/{message.attachments[0].url[-3:]}">
Your browser does not support the video.
</video>
"""
elif message.attachments[0].url.endswith(("mp3", "boh")):
if message.content:
content = (
check_message_mention(message)
+ "<br>"
+ f"""
<audio controls>
<source src="{message.attachments[0].url}" type="audio/{message.attachments[0].url[-3:]}">
Your browser does not support the audio element.
</audio>
"""
)
else:
content = f"""
<audio controls>
<source src="{message.attachments[0].url}" type="audio/{message.attachments[0].url[-3:]}">
Your browser does not support the audio element.
</audio>
"""
# OTHER TYPE OF FILES
else:
# add things
pass
else:
content = check_message_mention(message)