-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathmoderation.py
executable file
·2808 lines (2290 loc) · 134 KB
/
moderation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import.standard
import asyncio
import os
import re
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union
# import.thirdparty
import discord
from discord import user_command
from discord.ext import commands, menus, tasks
# import.local
from extra import utils
from extra.menu import MemberSnipeLooping, SnipeLooping, prompt_message_guild, prompt_number
from extra.moderation.fakeaccounts import ModerationFakeAccountsTable
from extra.moderation.firewall import (BypassFirewallTable,
ModerationFirewallTable)
from extra.moderation.moderatednicknames import ModeratedNicknamesTable
from extra.moderation.mutedmember import ModerationMutedMemberTable
from extra.moderation.user_muted_galaxies import UserMutedGalaxiesTable
from extra.moderation.userinfractions import ModerationUserInfractionsTable
from extra.moderation.watchlist import ModerationWatchlistTable
from extra.prompt.menu import Confirm
from extra.useful_variables import banned_links
from extra.view import WarnRulesView
from mysqldb import DatabaseCore
# variables.id
server_id = int(os.getenv('SERVER_ID', 123))
guild_ids: List[int] = [server_id]
# variables.role
sponsor_role_id = int(os.getenv('SPONSOR_ROLE_ID', 123))
mod_role_id = int(os.getenv('MOD_ROLE_ID', 123))
muted_role_id = int(os.getenv('MUTED_ROLE_ID', 123))
timedout_role_id = int(os.getenv('TIMEDOUT_ROLE_ID', 123))
preference_role_id = int(os.getenv('PREFERENCE_ROLE_ID', 123))
senior_mod_role_id: int = int(os.getenv('SENIOR_MOD_ROLE_ID', 123))
admin_role_id: int = int(os.getenv('ADMIN_ROLE_ID', 123))
analyst_debugger_role_id: int = int(os.getenv('ANALYST_DEBUGGER_ROLE_ID', 123))
lesson_manager_role_id: int = int(os.getenv('LESSON_MANAGEMENT_ROLE_ID', 123))
event_manager_role_id = int(os.getenv('EVENT_MANAGER_ROLE_ID', 123))
allowed_roles = [int(os.getenv('OWNER_ROLE_ID', 123)), admin_role_id, senior_mod_role_id, mod_role_id]
# variables.textchannel
mod_log_id = int(os.getenv('MOD_LOG_CHANNEL_ID', 123))
secret_agent_channel_id = int(os.getenv('SECRET_AGENTS_CHANNEL_ID', 123))
error_log_channel_id = int(os.getenv('ERROR_LOG_CHANNEL_ID', 123))
muted_chat_id = int(os.getenv('MUTED_CHANNEL_ID', 123))
watchlist_disallowed_channels = [int(os.getenv('MUTED_CHANNEL_ID', 123))]
frog_catchers_channel_id: int = int(os.getenv("FROG_CATCHERS_CHANNEL_ID", 123))
teacher_applicant_infraction_thread_id: int = int(os.getenv("TEACHER_APPLICANT_INFRACTION_THREAD_ID", 123))
host_applicant_infraction_thread_id: int = int(os.getenv("HOST_APPLICANT_INFRACTION_THREAD_ID", 123))
last_deleted_message = []
moderation_cogs: List[commands.Cog] = [
ModerationFirewallTable, BypassFirewallTable, ModerationMutedMemberTable,
ModerationUserInfractionsTable, ModerationWatchlistTable, ModerationFakeAccountsTable,
ModeratedNicknamesTable, UserMutedGalaxiesTable
]
class Moderation(*moderation_cogs):
""" Moderation related commands. """
INVITE_TYPES = [
"discord.gg/", "discord.com/invites/",
"discord.gg/events/", "discord.com/events/"
]
def __init__(self, client):
self.client = client
self.db = DatabaseCore()
@commands.Cog.listener()
async def on_ready(self):
self.look_for_expired_tempmutes.start()
self.check_timeouts_expirations.start()
self.guild = self.client.get_guild(server_id)
print('Moderation cog is ready!')
@commands.Cog.listener()
async def on_message(self, message):
if not message.guild:
return
if message.author.bot:
return
# Checks if someone pinged Staff
await self.check_if_pinged_staff(message)
# Banned links
await self.check_banned_links(message)
# Invite tracker
msg = str(message.content)
invite_root = self.get_invite_root(msg.lower().strip())
if invite_root and invite_root not in ("discord.gg/events/", "discord.com/events/"):
ctx = await self.client.get_context(message)
if not await utils.is_allowed([*allowed_roles, sponsor_role_id]).predicate(ctx):
is_from_guild = await self.check_invite_guild(msg, message.guild, invite_root)
if not is_from_guild:
return await self._mute_callback(ctx, member=message.author, reason="Invite Advertisement.")
@commands.Cog.listener()
async def on_member_update(self, before, after):
""" Checks whether a member is picking roles while muted. """
member = after # Alias for the member object that will be updated and used
# It's a bot
if member.bot:
return
# The user left the server
if not after.guild:
return
# Before and After roles
roles = before.roles
roles2 = after.roles
# User lost a role
if len(roles2) < len(roles):
return
new_role = None
# Gets the new role
for r2 in roles2:
if r2 not in roles:
new_role = r2
break
# Checks, just in case, if the new role was found
if not new_role:
return
# Checks whether the user has muted roles in the database
if await self.get_muted_roles(member.id):
keep_roles, _ = await self.get_remove_roles(member, keep_roles=allowed_roles)
muted_role = discord.utils.get(member.guild.roles, id=muted_role_id)
# If the user, for some reason, doesn't have the muted role, adds it
if muted_role not in keep_roles:
keep_roles.append(muted_role)
# Updates the user roles
await member.edit(roles=keep_roles)
def get_invite_root(self, message: str) -> str:
""" Gets the invite root from an invite link.
:param message: The message content. """
for invite_type in self.INVITE_TYPES:
if invite_type in message:
return invite_type
return ""
async def check_banned_links(self, message: discord.Message) -> None:
""" Checks if the message sent was or contains a banned link. """
videos = [v for v in message.attachments if v.content_type in ['video/mp4', 'video/webm']]
# Checks it in the message attachments
for video in videos:
if str(video) in banned_links:
ctx = await self.client.get_context(message)
if not await utils.is_allowed(allowed_roles).predicate(ctx):
return await self._mute_callback(ctx, member=message.author, reason="Banned Link")
# Checks it in the message content
for word in message.content.split():
if word in banned_links:
ctx = await self.client.get_context(message)
if not await utils.is_allowed(allowed_roles).predicate(ctx):
return await self._mute_callback(ctx, member=message.author, reason="Banned Link")
@tasks.loop(minutes=1)
async def look_for_expired_tempmutes(self) -> None:
""" Looks for expired tempmutes and unmutes the users. """
current_ts = await utils.get_timestamp()
tempmutes = await self.get_expired_tempmutes(current_ts)
guild = self.client.get_guild(server_id)
for tm in tempmutes:
member = discord.utils.get(guild.members, id=tm)
if not member:
continue
try:
role = discord.utils.get(guild.roles, id=muted_role_id)
if role:
if user_roles := await self.get_muted_roles(member.id):
bot = discord.utils.get(guild.members, id=self.client.user.id)
member_roles = list([
a_role for the_role in user_roles if (a_role := discord.utils.get(guild.roles, id=the_role[1]))
and a_role < bot.top_role
])
member_roles.extend(member.roles)
member_roles = list(set(member_roles))
if role in member_roles:
member_roles.remove(role)
try:
await self.remove_all_roles_from_system(member.id)
except Exception as e:
print(e)
pass
else:
# Update member roles
await member.edit(roles=member_roles)
current_time = await utils.get_time_now()
# Moderation log embed
moderation_log = discord.utils.get(guild.channels, id=mod_log_id)
embed = discord.Embed(title='__**Unmute**__', colour=discord.Colour.light_grey(), timestamp=current_time)
embed.add_field(name='User info:', value=f'```Name: {member.display_name}\nId: {member.id}```',
inline=False)
embed.set_thumbnail(url=member.display_avatar)
await moderation_log.send(embed=embed)
try:
await member.send(embed=embed)
except:
pass
except Exception as e:
print(e)
continue
async def check_invite_guild(self, msg, guild, invite_root: str):
""" Checks whether it's a guild invite or not. """
start_index = msg.index(invite_root)
end_index = start_index + len(invite_root)
invite_hash = ''
for c in msg[end_index:]:
if c == ' ':
break
invite_hash += c
for char in ['!', '@', '.', '(', ')', '[', ']', '#', '?', ':', ';', '`', '"', "'", ',', '{', '}']:
invite_hash = invite_hash.replace(char, '')
invite = invite_root + invite_hash
inv_code = discord.utils.resolve_invite(invite)
print(inv_code)
if inv_code == 'languages':
return True
if inv_code in ['TE6hPrn65a']:
return True
guild_inv = discord.utils.get(await guild.invites(), code=inv_code)
if guild_inv:
return True
else:
return False
async def check_if_pinged_staff(self, message: discord.Message) -> None:
""" Checks whether the member pinged the Staff in the message.
:param message: The message the member sent. """
guild = message.guild
member = message.author
# If it's Staff, don't check it
if await utils.is_allowed(allowed_roles).predicate(member=member, channel=message.channel): return
# Checks for mentioned roles in the message
if not (mentioned_roles := await utils.get_roles(message)): return
# Makes a set with the Staff roles
staff_mentions = set([
discord.utils.get(guild.roles, id=mod_role_id), # Mod
discord.utils.get(guild.roles, id=senior_mod_role_id), # Staff Manager
discord.utils.get(guild.roles, id=admin_role_id) # Admin
])
# Checks whether any of the Staff roles were in the list of roles pinged in the message
if staff_mentions.intersection(set(mentioned_roles)):
report_support_channel = discord.utils.get(guild.text_channels, id=int(os.getenv("REPORT_CHANNEL_ID")))
await message.channel.send(f"You should use {report_support_channel.mention} for help reports!")
@commands.Cog.listener(name="on_member_join")
async def on_member_join_check_muted_user(self, member):
if member.bot:
return
if await self.get_muted_roles(member.id):
muted_role = discord.utils.get(member.guild.roles, id=muted_role_id)
await member.add_roles(muted_role)
@commands.Cog.listener(name="on_member_join")
async def on_member_join_check_account_age_firewall(self, member):
if member.bot:
return
firewall_state = await self.get_firewall_state()
if not firewall_state:
return
if firewall_state[0]:
try:
bypass_check = await self.get_bypass_firewall_user(member.id)
if bypass_check:
return
firewall_type, firewall_minimum_age, firewall_reason = (
await self.get_firewall_type(),
await self.get_firewall_min_account_age(),
await self.get_firewall_reason(),
)
response_type = firewall_type[0] if firewall_type else "timeout"
minimum_age = firewall_minimum_age[0] if firewall_minimum_age else 43200
reason = firewall_reason[0] if firewall_reason else "Account is less than 12 hours old."
current_time, account_age = (
await utils.get_timestamp(),
member.created_at.timestamp(),
)
time_check = current_time - account_age
if time_check < minimum_age:
if response_type == "timeout":
from_time = current_time + time_check
timedout_until = datetime.fromtimestamp(from_time)
timedout_role = discord.utils.get(member.guild.roles, id=timedout_role_id)
if timedout_role not in member.roles:
await member.add_roles(timedout_role)
await member.timeout(until=timedout_until, reason=reason)
await member.send(f"**You have been automatically timed-out in the Language Sloth.**\n- **Reason:** {reason}")
elif response_type == "kick":
await member.kick(reason=reason)
await member.send(f"**You have been automatically kicked from the Language Sloth.**\n- **Reason:** {reason}")
else:
return
except Exception as e:
pass
@commands.Cog.listener()
async def on_message_delete(self, message):
if message.author.bot:
return
if len(last_deleted_message) >= 1000:
last_deleted_message[1:]
last_deleted_message.append({message.author.id : {"content" : message.content, "time" : (message.created_at).timestamp(), 'channel' : message.channel }})
async def search_user_deleted_messages(self, member) -> List[Dict]:
deleteds_messages = []
for message in last_deleted_message:
member_id = next(iter(message))
if member_id == member.id:
message = message[member_id]
deleteds_messages.append({"content" : message["content"], "time" : message["time"], "channel" : message["channel"]})
deleteds_messages = (sorted(deleteds_messages, key = lambda d: d['time']))
return deleteds_messages
@commands.command()
@utils.is_allowed([*allowed_roles, analyst_debugger_role_id], throw_exc=True)
async def snipe(self, ctx, *, message : str = None):
"""(MOD) Snipes deleted messages.
:param member: The @ or the ID of one or more users to snipe. (Optional) or
:param quantity: The quantity of messages to snipe (Optional) """
member, message_qtd = await utils.greedy_member_reason(ctx, message)
if not last_deleted_message:
#await ctx.message.delete()
return await ctx.send("**I couldn't snipe any message.**")
if not member:
if not message_qtd:
# Gets the last deleted message
messages: List[Dict] = [last_deleted_message[-1]]
else:
# Gets the requested amount of deleted messages
if int(message_qtd) <= 0:
return await ctx.send("**I couldn't snipe any message.**")
if int(message_qtd) > len(last_deleted_message):
message_qtd: int = len(last_deleted_message)
messages: List[Dict] = sorted(last_deleted_message, key = lambda d: d[next(iter(d))]['time'])
messages: List[Dict] = messages[- int(message_qtd): ]
menu = menus.MenuPages(SnipeLooping(messages))
#await ctx.message.delete()
await menu.start(ctx)
else:
# Gets all deleted messsages from the user
messages: List[Dict] = await self.search_user_deleted_messages(member[0])
if not messages:
return await ctx.send("**I couldn't snipe any messages from this member.**")
menu = menus.MenuPages(MemberSnipeLooping(messages, member[0]))
#await ctx.message.delete()
await menu.start(ctx)
# Purge command
@commands.command()
@commands.has_permissions(manage_messages=True)
async def purge(self, ctx, *, message : str = None):
""" (MOD) Purges messages.
:param member: The member from whom to purge the messages. (Optional)
:param amount: The amount of messages to purge. """
await ctx.message.delete()
members, amount = await utils.greedy_member_reason(ctx, message)
if not members and len(ctx.message.content.split()) > 2:
return await ctx.send(f"**Use z!purge Member[Optional] amount**", delete_after=5)
if not amount or not amount.isdigit() or int(amount) < 1:
return await ctx.send("**Please, insert a valid amount of messages to delete**", delete_after=5)
perms = ctx.channel.permissions_for(ctx.author)
if not perms.administrator and not ctx.author.get_role(senior_mod_role_id):
if int(amount) > 30:
return await ctx.send(f"**You cannot delete more than `30` messages at a time, {ctx.author.mention}!**")
# global deleted
deleted = 0
if members:
members_id = [member.id for member in members]
channel = ctx.channel
msgs = list(filter(
lambda m: m.author.id in members_id,
await channel.history(limit=200).flatten()
))
for _ in range(int(amount)):
await msgs.pop(0).delete()
deleted += 1
await ctx.send(f"**`{deleted}` messages deleted from `{' and '.join(member.name for member in members)}`**",
delete_after=5)
else:
await ctx.channel.purge(limit=int(amount))
@commands.command()
@utils.is_allowed(allowed_roles, throw_exc=True)
async def clear(self, ctx):
""" (MOD) Clears the whole channel. """
special_channels = {
int(os.getenv('MUTED_CHANNEL_ID', 123)): 'https://tenor.com/view/you-are-muted-jeremy-clarkson-gif-24026601',
int(os.getenv('QUESTION_CHANNEL_ID', 123)): '''**Have a question about the server? Ask it here!**\nThe chat will be cleared once questions are answered.'''
}
if ctx.channel.id not in special_channels.keys():
return await ctx.send("**You cannot do that here!**")
embed = discord.Embed(
title="Confirmation",
description="Clear the whole channel, **are you sure?**",
color=discord.Color.green(),
timestamp=ctx.message.created_at)
msg = await ctx.send(embed=embed)
await msg.add_reaction('✅')
await msg.add_reaction('❌')
def check(r, u):
return r.message.id == msg.id and u.id == ctx.author.id and str(r.emoji) in ['✅', '❌']
try:
r, _ = await self.client.wait_for('reaction_add', timeout=60, check=check)
r = str(r.emoji)
except asyncio.TimeoutError:
embed.description = '**Timeout!**'
return await msg.edit(embed=embed)
else:
if r == '❌':
embed.description = "Good, not doing it then! ❌"
return await msg.edit(embed=embed)
else:
embed.description = "Clearing whole channel..."
await msg.edit(embed=embed)
await asyncio.sleep(1)
while True:
msgs = await ctx.channel.history().flatten()
if (lenmsg := len(msgs)) > 0:
await ctx.channel.purge(limit=lenmsg)
else:
break
if smessage := special_channels.get(ctx.channel.id):
await ctx.send(smessage)
# Warns a member
@commands.command()
@commands.has_permissions(administrator=True)
async def fwarn(self, ctx, *, message: Optional[str] = None):
""" (ADM) Warns't a member in the server.
:param member: The @ or ID of the user to fwarn.
:param reason: The reason for fwarning the user. (Optional) """
await ctx.message.delete()
members, reason = await utils.greedy_member_reason(ctx, message)
if not members:
await ctx.send('**Member not found!**', delete_after=3)
else:
for member in members:
# General embed
general_embed = discord.Embed(description=f'**Reason:** {reason}', colour=discord.Colour.dark_gold())
general_embed.set_author(name=f'{member} has been warned', icon_url=member.display_avatar)
await ctx.send(embed=general_embed)
@commands.command(aliases=["lwarn", "lwarnado", "lwrn", "lw"])
@utils.is_allowed(allowed_roles, throw_exc=True)
async def light_warn(self, ctx, *, message: Optional[str] = None) -> None:
"""(MOD) Soft-Warns one or more members.
:param member: The @ or the ID of one or more users to soft warn.
:param reason: The reason for warning one or all users. (Optional)"""
if not message:
await self._easy_warn_callback(ctx=ctx, warn_type="lwarn")
else:
await self._warn_callback(ctx=ctx, message=message, warn_type="lwarn")
@commands.command(aliases=["warnado", "wrn", "w"])
@utils.is_allowed(allowed_roles, throw_exc=True)
async def warn(self, ctx, *, message: Optional[str] = None) -> None:
"""(MOD) Warns one or more members.
:param member: The @ or the ID of one or more users to warn.
:param reason: The reason for warning one or all users. (Optional)"""
if not message:
await self._easy_warn_callback(ctx=ctx, warn_type="warn")
else:
await self._warn_callback(ctx=ctx, message=message, warn_type="warn")
@commands.command(aliases=["hwarn", "hwarnado", "hwrn", "hw"])
@utils.is_allowed(allowed_roles, throw_exc=True)
async def heavy_warn(self, ctx, *, message: Optional[str] = None) -> None:
"""(MOD) Warns one or more members.
:param member: The @ or the ID of one or more users to warn.
:param reason: The reason for warning one or all users. (Optional)"""
if not message:
await self._easy_warn_callback(ctx=ctx, warn_type="hwarn")
else:
await self._warn_callback(ctx=ctx, message=message, warn_type="hwarn")
async def _easy_warn_callback(self, ctx, warn_type: str = "warn") -> None:
""" Callback for the easy warn.
:param warn_type: The warn type. [light/normal/heavy]"""
author = ctx.author
channel = ctx.channel
await ctx.send(f"**{author.mention}, type the ID of the user that will to get warned.\n- (Multiple ID's work as well.)**")
if not (ids := await prompt_message_guild(client=self.client, member=author, channel=channel, limit=180)):
return
rule_embed: discord.Embed = discord.Embed(
title="__Warn Rule Selection__",
color=author.color,
timestamp=ctx.message.created_at
)
rule_embed.set_author(name=author, icon_url=author.display_avatar)
rule_embed.set_thumbnail(url=author.display_avatar)
rule_embed.set_footer(text="3 minutes to select.", icon_url=ctx.guild.icon.url)
view: discord.ui.View = WarnRulesView(author)
msg = await ctx.send(embed=rule_embed, view=view)
await view.wait()
await utils.disable_buttons(view)
await msg.edit(view=view)
if view.selected_rule is None:
await ctx.send(f"- **Rule selection cancelled, warn aborted.**")
return
if not view.selected_rule:
await ctx.send(f"- **No rules have been selected, warn aborted.**")
return
await ctx.send(f"**- Rule selection successful!**")
await ctx.send(f"- **{author.mention}, specify the reason you're warning this/these member(s).**")
if not (personal_message := await prompt_message_guild(client=self.client, member=author, channel=channel, limit=860)):
return
reason_output = f"{view.selected_rule.label}: {view.selected_rule.description}"
output = f"{ids} {reason_output} {personal_message}"
confirm = await Confirm(f"**Are you sure about about this/these `{warn_type}(s)`?**\n- ID(s): `{ids}` \n- Selected rule: `{reason_output}`\n- Reason: `{personal_message}`").prompt(ctx)
if confirm:
await self._warn_callback(ctx=ctx, message=output, warn_type=warn_type)
async def _warn_callback(self, ctx, *, message: Optional[str] = None, warn_type: str = "warn") -> None:
""" Callback for the warn commands.
:param member: The @ or the ID of one or more users to warn.
:param reason: The reason for warning one or all users. (Optional)
:param warn_type: The warn type. [light/normal/heavy]"""
await ctx.message.delete()
icon = ctx.author.display_avatar
is_admin = ctx.author.guild_permissions.administrator
members, reason = await utils.greedy_member_reason(ctx, message)
ban_reason = "You have been banned from Language Sloth for exceeding the maximum warn limit within 6 months."
if not members:
await ctx.send("**Please, inform a member!**", delete_after=3)
else:
if not is_admin and (reason is not None and len(reason) > 960):
return await ctx.send(f"**Please, inform a reason that is lower than or equal to 960 characters, {ctx.author.mention}!**", delete_after=3)
elif not is_admin and (reason is None or len(reason) < 16):
return await ctx.send(f"**Please, inform a reason that is higher than 15 characters, {ctx.author.mention}!**", delete_after=3)
for member in members:
if ctx.guild.get_member(member.id):
# General embed
## Check warn type
warn_msg, infr = await self.get_warn_type(warn_type)
warn_desc = f'**Reason:** {reason}'
user_infractions = await self.get_user_infractions(member.id)
hours, days, weeks, ban = await self.get_timeout_time(ctx, member, await self.get_timeout_warns(infr, user_infractions))
if ban:
warn_desc += '\n**User has exceeded the maximum warn limit within 6 months and will be banned!**'
else:
if hours > 0:
warn_desc += f'\n**Timeout:** {hours}h'
elif days > 0:
warn_desc += f'\n**Timeout:** {days}d'
elif weeks > 0:
warn_desc += f'\n**Timeout:** {weeks}w'
general_embed = discord.Embed(description=warn_desc, colour=ctx.author.color)
general_embed.set_author(name=f'{member} has been {warn_msg}warned', icon_url=member.display_avatar)
await ctx.send(embed=general_embed)
# Moderation log embed
moderation_log = discord.utils.get(ctx.guild.channels, id=mod_log_id)
embed = discord.Embed(title=f'__**{warn_type.capitalize()} Warning**__', colour=discord.Colour.dark_gold(),
timestamp=ctx.message.created_at)
embed.add_field(name='User info:', value=f'```Name: {member.display_name}\nId: {member.id}```',
inline=False)
embed.add_field(name='Reason:', value=f'```{reason}```')
embed.set_author(name=member)
embed.set_thumbnail(url=member.display_avatar)
embed.set_footer(text=f"Warned by {ctx.author}", icon_url=ctx.author.display_avatar)
await moderation_log.send(embed=embed)
# Inserts a infraction into the database
current_ts = await utils.get_timestamp()
await self.insert_user_infraction(
user_id=member.id, infr_type=infr, reason=reason,
timestamp=current_ts, perpetrator=ctx.author.id)
try:
await member.send(embed=general_embed)
except:
pass
if ban:
# Ban log embed
ban_embed = discord.Embed(title='__**Banishment**__', colour=discord.Colour.dark_red(),
timestamp=ctx.message.created_at)
ban_embed.add_field(name='User info:', value=f'```Name: {member.display_name}\nId: {member.id}```',
inline=False)
ban_embed.add_field(name='Reason:', value=f'```{ban_reason}```')
ban_embed.set_author(name=member)
ban_embed.set_thumbnail(url=member.display_avatar)
ban_embed.set_footer(text=f"Banned by {ctx.author}", icon_url=icon)
await moderation_log.send(embed=ban_embed)
# Inserts a ban infraction into the database
current_ts = await utils.get_timestamp()
await self.insert_user_infraction(
user_id=member.id, infr_type="ban", reason=ban_reason,
timestamp=current_ts, perpetrator=ctx.author.id)
# General ban embed
general_ban_embed = discord.Embed(description=f"**Reason:** {ban_reason}", colour=discord.Colour.dark_red())
general_ban_embed.set_author(name=f'{member} has been banned', icon_url=member.display_avatar)
await ctx.send(embed=general_ban_embed)
# Ban!
await member.ban(delete_message_seconds=604800, reason=ban_reason)
# Also send the general ban embed to the banned user
try:
await member.send(embed=general_ban_embed)
except:
pass
else:
await self.timeout(ctx, member, warn_type, user_infractions)
else:
await ctx.send(f"**The user `{member}` is not on the server**", delete_after = 5)
async def get_warn_type(self, warn_type: str) -> Tuple[str, str, str, int]:
""" Gets the warn info based on the warn type.
:param warn_type: The warn type. [light/normal/heavy] """
if warn_type == "lwarn":
return "lightly ", "lwarn"
elif warn_type == "warn":
return "", "warn"
elif warn_type == "hwarn":
return "heavily ", "hwarn"
async def get_timeout_warns(self, warn_type: str, infractions: List[List[Union[str, int]]]) -> int:
"""Returns the number of total warns that user has taking all types of warns.
:param warn_type: The warn type.
:param infractions: The list of all infractions from a user. """
weight_map = {
"lwarn": 0.5,
"warn": 1,
"hwarn": 2
}
warns = await self.get_warns(infractions)
lwarns = sum(1 for w in warns if w[1] == "lwarn")
total = sum(weight_map[w[1]] for w in warns) + weight_map[warn_type]
if lwarns % 2 > 0 and warn_type != "lwarn":
total -= weight_map["lwarn"]
return total
async def get_warns(self, infractions: List[List[Union[str, int]]]) -> List[List[Union[str, int]]]:
"""Returns the number of total warns that user has taking all types of warns.
:param infractions: List of all infractions from a user. """
valid_types = {"lwarn", "warn", "hwarn"}
six_months_ago = await utils.get_timestamp() - 6*30*24*3600 # Approach of 30 days per month
warnings = [w for w in infractions if w[1] in valid_types and w[3] >= six_months_ago]
return warnings
async def get_timeout_time(self, ctx: commands.Context, member: discord.Member, warns: int) -> List[int]:
"""Gets the time of a time out based on their number of warnings.
:param warns: The number of warns the user have. """
weight_map = {
0: [0, 0, 0, False],
1: [6, 0, 0, False], # 6 hours
2: [0, 2, 0, False], # 2 days
3: [0, 0, 1, False], # 1 week
4: [0, 0, 0, True] # Ban!
}
if await utils.is_allowed(allowed_roles).predicate(channel=ctx.channel, member=member):
index = 0
elif warns in weight_map:
index = warns
elif warns > 4:
index = 4
else:
index = 0
return weight_map[index]
async def timeout(self, ctx: commands.Context, member: discord.Member, warn_type: str, infractions: List[List[Union[str, int]]]) -> None:
"""Times out a user based on their number of warnings.
:param ctx: The command context.
:param member: The member to timeout.
:param warn_type: The warn type. """
if await utils.is_allowed(allowed_roles).predicate(channel=ctx.channel, member=member):
return
muted_role = discord.utils.get(ctx.guild.roles, id=muted_role_id)
if muted_role in member.roles:
await self._unmute_callback(ctx, member)
warns = await self.get_timeout_warns(warn_type, infractions)
hours, days, weeks, ban = await self.get_timeout_time(ctx, member, warns)
if hours == 0 and days == 0 and weeks == 0:
return
timedout_role = discord.utils.get(ctx.guild.roles, id=timedout_role_id)
if timedout_role not in member.roles:
await member.add_roles(timedout_role)
timeout_reason = f"{int(warns)} warnings"
timeout_duration = sum([
weeks * 604800, # 1 week = 604800 seconds
days * 86400, # 1 day = 86400 seconds
hours * 3600 # 1 hour = 3600 seconds
])
try:
current_ts = await utils.get_timestamp() + timeout_duration
timedout_until = datetime.fromtimestamp(current_ts)
await member.timeout(until=timedout_until, reason=f"Timed out for: {timeout_reason}")
except:
pass
@tasks.loop(minutes=3)
async def check_timeouts_expirations(self) -> None:
""" Task that checks Timeouts expirations. """
guild = self.client.get_guild(server_id)
role = discord.utils.get(guild.roles, id=timedout_role_id)
members = role.members
for member in members:
try:
timeout_time = member.communication_disabled_until
if timeout_time == None:
await member.remove_roles(role)
except Exception as e:
print(e)
continue
async def get_remove_roles(self, member: discord.Member, keep_roles: Optional[List[Union[int, discord.Role]]] = []
) -> List[List[discord.Role]]:
""" Gets a list of roles the user will have after removing their roles
and a list that will be removed from them.
:param keep_roles: The list of roles to keep. [Optional] """
bot = discord.utils.get(member.guild.members, id=self.client.user.id)
keep_roles: List[int] = [
keep_role if isinstance(keep_role, discord.Role) else
discord.utils.get(member.guild.roles, id=keep_role)
for keep_role in keep_roles
]
keep_list = []
remove_list = []
for i, member_role in enumerate(member.roles):
if i == 0:
continue
for role in keep_roles:
if member_role.id == role.id:
keep_list.append(role)
continue
if member_role < bot.top_role:
if not member_role.is_premium_subscriber():
remove_list.append(member_role)
if member_role.is_premium_subscriber():
keep_list.append(member_role)
if member_role >= bot.top_role:
keep_list.append(member_role)
return list(set(keep_list)), list(set(remove_list))
@commands.command()
@utils.is_allowed(allowed_roles, throw_exc=True)
async def rar(self, ctx: commands.Context, member: discord.Member = None) -> None:
""" Removes all roles from a user.
:param member: The member to rar from. """
author = ctx.author
if not member:
return await ctx.send(f"**Please, inform a member to rar, {author.mention}!**")
keep_roles, _ = await self.get_remove_roles(member, keep_roles=allowed_roles)
confirm = await Confirm(f"**Are you sure you wanna rar {member.mention}, {author.mention}?**").prompt(ctx)
if not confirm:
return await ctx.send(f"**Not doing it, then, {author.mention}!**")
try:
await member.edit(roles=keep_roles)
except:
await ctx.send(f"**For some reason I couldn't do it, {author.mention}!**")
else:
await ctx.send(f"**Successfully rar'd `{member}`, {author.mention}!**")
@commands.command(aliases=['show_muted_roles', 'check_muted', 'muted_roles', 'removed_roles', 'srr', 'see_removed_roles'])
@utils.is_allowed(allowed_roles, throw_exc=True)
async def show_removed_roles(self, ctx, member: Union[discord.Member, discord.User] = None) -> None:
""" Shows the roles that were remove from the user when they got muted.
:param member: The member to check it. """
author = ctx.author
if not member:
return await ctx.send(f"**Please, inform the member to check the roles, {author.mention}!**")
if not member.get_role(muted_role_id):
return await ctx.send(f"**The given user is not even muted, {author.mention}!**")
roles = await self.get_muted_roles(member.id)
if not roles:
return await ctx.send(f"**User had no roles, {author.mention}!**")
roles = ', '.join([f"<@&{rid[1]}>" for rid in roles if rid[1] != preference_role_id])
embed: discord.Embed = discord.Embed(
title="__Removed Roles__",
description=f"{member.mention} got the following roles removed after being muted:\n\n{roles}",
color=member.color,
timestamp=ctx.message.created_at
)
await ctx.send(embed=embed)
async def add_galaxy_room_perms(self, member: discord.Member, muted_galaxies: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
""" Removes teh user's permissions in all Galaxy Rooms.
:param member: The member from whom to remove the permissions. """
# Gets all Galaxy rooms that are created
SmartRoom = self.client.get_cog('CreateSmartRoom')
all_galaxies = await SmartRoom.get_galaxy_rooms()
# Gets all Galaxy categories to give perms back
galaxy_categories: Dict[discord.CategoryChannel, List[int]] = {
gcat: galaxy for galaxy in all_galaxies
for mgalaxy in muted_galaxies
if galaxy[1] == mgalaxy[1]
and (gcat := discord.utils.get(member.guild.categories, id=galaxy[1]))
}
# Gives perms to all Galaxy categories
for gcat, ginfo in galaxy_categories.items():
await SmartRoom.handle_permissions([member], ginfo, member.guild, allow=True)
async def remove_galaxy_room_perms(self, member: discord.Member) -> List[Tuple[int, int]]:
""" Removes teh user's permissions in all Galaxy Rooms.
:param member: The member from whom to remove the permissions. """
removed_grooms = []
# Gets all Galaxy rooms that are created
SmartRoom = self.client.get_cog('CreateSmartRoom')
all_galaxies = await SmartRoom.get_galaxy_rooms()
# Gets all selected Galaxy categories to remove perms
galaxy_categories: Dict[discord.CategoryChannel, List[int]] = {
gcat: galaxy for galaxy in all_galaxies
if (gcat := discord.utils.get(member.guild.categories, id=galaxy[1]))
}
# Removes perms from the selected Galaxy categories
for gcat, ginfo in galaxy_categories.items():
overwrites = gcat.overwrites
if not overwrites.get(member):
continue
await SmartRoom.handle_permissions([member], ginfo, member.guild, allow=False)
removed_grooms.append((member.id, gcat.id))
return removed_grooms
@commands.command(name="mute", aliases=["shutup", "shut_up", "stfu", "zitto", "zitta", "shh", "tg", "ta_gueule", "tagueule", "mutado", "xiu", "calaboca", "callate", "calma_calabreso"])
@utils.is_allowed(allowed_roles, throw_exc=True)
async def _mute_command(self, ctx, *, message : str = None) -> None:
"""(MOD) Mutes one or more members.
:param member: The @ or the ID of one or more users to mute.
:param reason: The reason for muting one or all users. (Optional)"""
members, reason = await utils.greedy_member_reason(ctx, message)
await ctx.message.delete()
if not members:
return await ctx.send("**Please, inform a member!**", delete_after=3)
for member in members:
if ctx.guild.get_member(member.id):
await self._mute_callback(ctx, member, reason)
else:
await ctx.send(f"** The user `{member}` is not on the server**")
@user_command(name="Mute", guild_ids=guild_ids)
@utils.is_allowed(allowed_roles, throw_exc=True)
async def _mute_slash(self, ctx, user: discord.Member) -> None:
""" (MOD) Mutes a member.
:param member: The @ or the ID of the user to mute.
:param reason: The reason for the mute. """
await self._mute_callback(ctx, user)
async def _mute_callback(self, ctx: commands.Context, member: discord.Member = None, reason: Optional[str] = None):
""" (MOD) Mutes a member.
:param member: The @ or the ID of the user to mute.
:param reason: The reason for the mute. """
is_admin = ctx.author.guild_permissions.administrator
answer: discord.PartialMessageable = None
if isinstance(ctx, commands.Context):
answer = ctx.send