-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmod.py
1244 lines (974 loc) · 40.3 KB
/
mod.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 argparse
import asyncio
import io
import logging
import shlex
from collections import defaultdict
from datetime import datetime, timedelta
from enum import Enum, IntEnum
from json import dumps, loads
from typing import Union
import disnake
from asyncpg.exceptions import UniqueViolationError
from disnake.ext import commands
from cogs.mixins import AceMixin
from ids import AHK_GUILD_ID, LEVEL_ROLE_IDS, RULES_MSG_ID
from utils.configtable import ConfigTable, ConfigTableRecord
from utils.context import AceContext, can_prompt, is_mod
from utils.converters import MaxLengthConverter, MaybeMemberConverter, RangeConverter
from utils.databasetimer import DatabaseTimer
from utils.fakeuser import FakeUser
from utils.string import po
from utils.time import TimeDeltaConverter, TimeMultConverter, pretty_timedelta
log = logging.getLogger(__name__)
MAX_DELTA = timedelta(days=365 * 10)
OK_EMOJI = "\U00002705"
SPAM_LOCK = asyncio.Lock()
MENTION_LOCK = asyncio.Lock()
CONTENT_LOCK = asyncio.Lock()
MOD_PERMS = (
"administrator",
"ban_members",
"kick_members",
"moderate_members",
"manage_guild",
"manage_channels",
"manage_threads",
"manage_messages",
"manage_emojis",
"manage_nicknames",
"manage_permissions",
"manage_roles",
"manage_webhooks",
"manage_events",
"mention_everyone",
"create_private_threads",
"view_audit_log",
"view_guild_insights",
"send_tts_messages",
"move_members",
"deafen_members",
"mute_members",
"priority_speaker",
#'attach_files', # "useful" to know but causes a lot of noise
)
DEFAULT_REASON = "No reason provided."
PURGE_LIMIT = 512
class NoExitArgumentParser(argparse.ArgumentParser):
def exit(self, code, error):
raise ValueError(error)
class SecurityAction(IntEnum):
TIMEOUT = 1
KICK = 2
BAN = 3
class SecurityVerb(Enum):
TIMEOUT = "timed out (for 28 days)"
KICK = "kicked"
BAN = "banned"
class Severity(Enum):
LOW = 1
MEDIUM = 2
HIGH = 3
RESOLVED = 4
class SeverityColors(Enum):
LOW = disnake.Embed().color
MEDIUM = 0xFF8C00
HIGH = 0xFF2000
RESOLVED = 0x32CD32
OTHER_CHANNEL_PENALTY = 2
class CooldownByContent(commands.CooldownMapping):
def __init__(self, original, type):
super().__init__(original, type)
self.bucket_to_channel = dict()
def _bucket_key(self, message):
return (message.guild.id, message.author.id, message.content)
def update_rate_limit(self, message, current=None):
bucket = self.get_bucket(message, current)
current_channel_id = message.channel.id
prev_channel_id = self.bucket_to_channel.get(bucket, None)
self.bucket_to_channel[bucket] = current_channel_id
ret = bucket.update_rate_limit(current)
if prev_channel_id is not None and current_channel_id != prev_channel_id:
for _ in range(OTHER_CHANNEL_PENALTY):
ret = bucket.update_rate_limit(current)
if ret is not None:
break
return ret
class SecurityConfigRecord(ConfigTableRecord):
spam_cooldown = None
mention_cooldown = None
content_cooldown = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.create_spam_cooldown()
self.create_mention_cooldown()
self.create_content_cooldown()
@property
def guild(self):
return self._config.bot.get_guild(self.guild_id)
@property
def log_channel(self):
if self.log_channel_id is None:
return None
guild = self._config.bot.get_guild(self.guild_id)
if guild is None:
return None
return guild.get_channel(self.log_channel_id)
def create_spam_cooldown(self):
self.spam_cooldown = commands.CooldownMapping.from_cooldown(
self.spam_count, self.spam_per, commands.BucketType.member
)
def create_mention_cooldown(self):
self.mention_cooldown = commands.CooldownMapping.from_cooldown(
self.mention_count, self.mention_per, commands.BucketType.member
)
def create_content_cooldown(self):
self.content_cooldown = CooldownByContent.from_cooldown(5, 32.0, commands.BucketType.member)
class EventTimer(DatabaseTimer):
async def get_record(self):
return await self.bot.db.fetchrow(
"SELECT * FROM mod_timer WHERE duration IS NOT NULL AND created_at + duration < $1 AND completed = FALSE "
"ORDER BY created_at + duration LIMIT 1",
datetime.utcnow() + self.MAX_SLEEP,
)
async def cleanup_record(self, record):
await self.bot.db.execute(
"UPDATE mod_timer SET completed=TRUE WHERE id=$1", record.get("id")
)
def when(self, record):
return record.get("created_at") + record.get("duration")
# ripped from RoboDanny
class BannedMember(commands.Converter):
async def convert(self, ctx, argument):
ban_list = [ban async for ban in ctx.guild.bans()]
try:
member_id = int(argument, base=10)
entity = disnake.utils.find(lambda u: u.user.id == member_id, ban_list)
except ValueError:
entity = disnake.utils.find(lambda u: str(u.user) == argument, ban_list)
if entity is None:
raise commands.BadArgument("Not a valid previously banned member.")
return entity
class ActionConverter(commands.Converter):
valid_actions = ", ".join("`{0}`".format(act.name) for act in SecurityAction)
async def convert(self, ctx, action):
try:
value = SecurityAction[action.upper()]
except KeyError:
raise commands.BadArgument(
"'{0}' is not a valid action. Valid actions are {1}".format(
action, self.valid_actions
)
)
return value
reason_converter = MaxLengthConverter(1024)
count_converter = RangeConverter(8, 24)
interval_converter = RangeConverter(8, 24)
class Moderation(AceMixin, commands.Cog):
"""Moderation commands to make your life simpler."""
def __init__(self, bot):
super().__init__(bot)
self.config = ConfigTable(bot, "mod_config", "guild_id", record_class=SecurityConfigRecord)
self.event_timer = EventTimer(bot, "event_complete")
asyncio.create_task(self.check_tempbans())
@commands.Cog.listener()
async def on_log(
self, guild, subject, action=None, severity=Severity.LOW, message=None, **fields
):
conf = await self.config.get_entry(guild.id)
log_channel = conf.log_channel
if log_channel is None:
return
desc = "NAME: " + str(subject)
if getattr(subject, "nick", None) is not None:
desc += "\nNICK: " + subject.nick
desc += "\nMENTION: " + subject.mention
desc += "\nID: " + str(subject.id)
color = SeverityColors[severity.name].value
e = disnake.Embed(
title=action or "INFO",
description=desc,
color=color,
timestamp=datetime.utcnow(),
)
for name, value in fields.items():
e.add_field(name=name.title(), value=value, inline=False)
e.set_thumbnail(url=subject.display_avatar.url)
e.set_footer(text=severity.name)
if message is not None:
e.add_field(
name="Context",
value="[Click here]({})".format(message.jump_url),
inline=False,
)
await log_channel.send(embed=e)
def _craft_user_data(self, member: disnake.Member):
data = dict(
name=member.name,
nick=member.nick,
discriminator=member.discriminator,
avatar_url=member.display_avatar.url,
)
return dumps(data)
@commands.command()
@commands.has_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def ban(self, ctx, member: disnake.Member, *, reason: reason_converter = None):
"""Ban a member. Requires Ban Members perms."""
try:
await member.ban(reason=reason, clean_history_duration=0)
except disnake.HTTPException:
raise commands.CommandError("Failed banning member.")
await ctx.send("{0} banned.".format(str(member)))
@commands.command()
@can_prompt()
@commands.has_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def unban(self, ctx, member: BannedMember, *, reason: reason_converter = None):
"""Unban a member. Requires Ban Members perms."""
if member.reason is None:
prompt = "No reason provided with the previous ban."
else:
prompt = "Ban reason:\n{0}".format(member.reason)
res = await ctx.prompt(title="Unban {0}?".format(member.user), prompt=prompt)
if not res:
return
try:
await ctx.guild.unban(member.user, reason=reason)
except disnake.HTTPException:
raise commands.CommandError("Failed unbanning member.")
await ctx.send("{0} unbanned.".format(str(member.user)))
@commands.command()
@commands.has_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True, embed_links=True)
async def tempban(
self,
ctx,
member: Union[disnake.Member, BannedMember],
amount: TimeMultConverter,
unit: TimeDeltaConverter,
*,
reason: reason_converter = None,
):
"""Temporarily ban a member. Requires Ban Members perms."""
now = datetime.utcnow()
duration = amount * unit
until = now + duration
on_guild = isinstance(member, disnake.Member)
if on_guild:
if await ctx.is_mod(member):
raise commands.CommandError("Can't tempban this member.")
else:
user: disnake.User = member.user
member = FakeUser(
user.id,
ctx.guild,
name=user.name,
avatar_url=str(user.display_avatar),
discriminator=user.discriminator,
)
is_tempbanned = await self.bot.db.fetchval(
"SELECT id FROM mod_timer WHERE guild_id=$1 AND user_id=$2 AND event=$3 AND completed=FALSE",
ctx.guild.id,
member.id,
"BAN",
)
if is_tempbanned:
raise commands.CommandError(
"This member is already tempbanned. Use `alterban` to change duration?"
)
if duration > MAX_DELTA:
raise commands.CommandError(
"Can't tempban for longer than {0}. Please `ban` instead.".format(
pretty_timedelta(MAX_DELTA)
)
)
pretty_duration = pretty_timedelta(duration)
# only send DMs for initial bans
if on_guild:
ban_msg = (
"You have received a ban lasting {0} from {1}.\n\nReason:\n```\n{2}\n```".format(
pretty_duration, ctx.guild.name, reason
)
)
try:
await member.send(ban_msg)
except disnake.HTTPException:
pass
# reason we start a transaction is so it auto-rollbacks if the CommandError on ban fails is raised
async with self.db.acquire() as con:
async with con.transaction():
try:
await self.db.execute(
"INSERT INTO mod_timer (guild_id, user_id, mod_id, event, created_at, duration, reason, userdata)"
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
ctx.guild.id,
member.id,
ctx.author.id,
"BAN",
now,
duration,
reason,
self._craft_user_data(member),
)
except UniqueViolationError:
# this *should* never happen but I'd rather leave it in
raise commands.CommandError("Member is already tempbanned.")
try:
await ctx.guild.ban(member, clean_history_duration=0, reason=reason)
except disnake.HTTPException:
raise commands.CommandError("Failed tempbanning member.")
self.event_timer.maybe_restart(until)
try:
await ctx.send("{0} tempbanned for {1}.".format(str(member), pretty_duration))
except disnake.HTTPException:
pass
self.bot.dispatch(
"log",
ctx.guild,
member,
action="TEMPBAN",
severity=Severity.HIGH,
message=ctx.message,
responsible=po(ctx.author),
duration=pretty_duration,
reason=reason,
)
@commands.command()
@commands.has_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True, embed_links=True)
async def alterban(
self,
ctx: AceContext,
member: BannedMember,
amount: TimeMultConverter,
*,
unit: TimeDeltaConverter,
):
"""Set a new duration for a tempban."""
duration = amount * unit
if duration > MAX_DELTA:
raise commands.CommandError(
"Can't tempban for longer than {0}. Please `ban` instead.".format(
pretty_timedelta(MAX_DELTA)
)
)
record = await self.bot.db.fetchrow(
"SELECT * FROM mod_timer WHERE guild_id=$1 AND user_id=$2 AND event=$3 AND completed=FALSE",
ctx.guild.id,
member.user.id,
"BAN",
)
if record is None:
raise commands.CommandError("Could not find a tempban referencing this member.")
now = datetime.utcnow()
old_now = record.get("created_at")
old_duration = record.get("duration")
new_until = old_now + duration
old_until = old_now + old_duration
if duration == old_duration:
raise commands.CommandError("New ban duration is the same as the current duration.")
old_duration_pretty = pretty_timedelta(old_duration)
old_end_pretty = pretty_timedelta(old_until - now)
duration_pretty = pretty_timedelta(duration)
prompt = f"The previous ban duration was {old_duration_pretty} and will end in {old_end_pretty}.\n\n"
if new_until < now:
prompt += "The new duration ends in the past and will cause an immediate unban."
else:
prompt += f"The new ban duration is {duration_pretty} and will end in {pretty_timedelta(new_until - now)}."
should_continue = await ctx.prompt(
title="Are you sure you want to alter this tempban?", prompt=prompt
)
if not should_continue:
return
await self.db.execute(
"UPDATE mod_timer SET duration=$1 WHERE guild_id=$2 AND user_id=$3 AND event=$4",
duration,
ctx.guild.id,
member.user.id,
"BAN",
)
self.event_timer.restart_task()
self.bot.dispatch(
"log",
ctx.guild,
member.user,
action="TEMPBAN UPDATE",
severity=Severity.HIGH,
message=ctx.message,
responsible=po(ctx.author),
duration=duration_pretty,
reason=f"Previous duration was {old_duration_pretty}",
)
async def do_action(self, message, action, reason, clean_history_duration=0):
"""Called when an event happens."""
member: disnake.Member = message.author
guild: disnake.Guild = message.guild
ctx = await self.bot.get_context(message, cls=AceContext)
# ignore if member is mod
if await ctx.is_mod():
self.bot.dispatch(
"log",
guild,
member,
action="IGNORED {0} (MEMBER IS MOD)".format(action.name),
severity=Severity.LOW,
message=message,
reason=reason,
)
return
role_ids = list(LEVEL_ROLE_IDS.values())[3:]
if any(role.id in role_ids for role in message.author.roles):
self.bot.dispatch(
"log",
guild,
member,
action="IGNORED {0} (MEMBER IS LEVEL 16+)".format(action.name),
severity=Severity.LOW,
message=message,
reason=reason,
)
return
# otherwise, check against security actions and perform punishment
try:
if action is SecurityAction.TIMEOUT:
await member.timeout(until=datetime.utcnow() + timedelta(days=28), reason=reason)
elif action is SecurityAction.KICK:
await member.kick(reason=reason)
elif action is SecurityAction.BAN:
await member.ban(clean_history_duration=clean_history_duration, reason=reason)
except Exception as exc:
# log error if something happened
self.bot.dispatch(
"log",
guild,
member,
action="{0} FAILED".format(action.name),
severity=Severity.HIGH,
message=message,
reason=reason,
error=str(exc),
)
return
# log successful security event
self.bot.dispatch(
"log",
guild,
member,
action=action.name,
severity=Severity(action.value),
message=message,
reason=reason,
)
try:
await message.channel.send(
"{0} {1}: {2}".format(po(member), SecurityVerb[action.name].value, reason)
)
except disnake.HTTPException:
pass
@commands.Cog.listener()
async def on_message(self, message):
if message.guild is None:
return
if message.author.bot:
return
mc = await self.config.get_entry(message.guild.id, construct=False)
if mc is None:
return
if mc.spam_action is not None:
# with a lock, figure out if user is spamming
async with SPAM_LOCK:
res = mc.spam_cooldown.update_rate_limit(message)
if res is not None:
mc.spam_cooldown._cache[mc.spam_cooldown._bucket_key(message)].reset()
# if so, perform the spam action
if res is not None:
await self.do_action(
message,
SecurityAction[mc.spam_action],
reason="Member is spamming messages",
)
if mc.mention_action is not None and message.mentions:
# same here. however run once for each mention
async with MENTION_LOCK:
for mention in message.mentions:
res = mc.mention_cooldown.update_rate_limit(message)
if res is not None:
mc.mention_cooldown._cache[mc.mention_cooldown._bucket_key(message)].reset()
break
if res is not None:
await self.do_action(
message,
SecurityAction[mc.mention_action],
reason="Member is spamming mentions",
)
if message.guild.id == AHK_GUILD_ID:
async with CONTENT_LOCK:
res = mc.content_cooldown.update_rate_limit(message)
# since we're using the bucket key (guild_id, author_id, message_content)
# we can just as well reset the bucket after a ban
if res is not None:
mc.content_cooldown._cache[mc.content_cooldown._bucket_key(message)].reset()
if res is not None:
await self.do_action(
message,
SecurityAction.BAN,
reason="Member is spamming (with cleanup)",
clean_history_duration=timedelta(days=1),
)
@commands.Cog.listener()
async def on_event_complete(self, record):
# relatively crucial that the bot is ready before we launch any events like tempban completions
await self.bot.wait_until_ready()
event = record.get("event")
if event == "BAN":
await self.ban_complete(record)
def fakeuser_from_record(self, record, guild):
return FakeUser(record.get("user_id"), guild, **loads(record.get("userdata")))
async def ban_complete(self, record):
guild_id = record.get("guild_id")
mod_id = record.get("mod_id")
duration = record.get("duration")
reason = record.get("reason")
guild = self.bot.get_guild(guild_id)
if guild is None:
return
mod = guild.get_member(mod_id)
pretty_mod = "(ID: {0})".format(str(mod_id)) if mod is None else po(mod)
member = self.fakeuser_from_record(record, guild)
try:
await guild.unban(member, reason="Completed tempban issued by {0}".format(pretty_mod))
except disnake.HTTPException:
return # rip :)
self.bot.dispatch(
"log",
guild,
member,
action="TEMPBAN COMPLETED",
severity=Severity.RESOLVED,
responsible=pretty_mod,
duration=pretty_timedelta(duration),
reason=reason,
)
async def check_tempbans(self):
"""Check for newly unbanned members on guild startup, and end tempbans if so"""
await self.bot.wait_until_ready()
tempbans = await self.db.fetch(
"SELECT * FROM mod_timer WHERE event='BAN' AND completed=FALSE"
)
guild_bans = dict()
for guild_id in set(tempban.get("guild_id") for tempban in tempbans):
guild = self.bot.get_guild(guild_id)
if guild is None:
continue
try:
bans = [ban async for ban in guild.bans()]
except disnake.HTTPException:
continue
guild_bans[guild_id] = (guild, [ban.user.id for ban in bans])
for tempban in tempbans:
guild_id = tempban.get("guild_id")
info = guild_bans.get(guild_id, None)
if info is None:
continue # not in guild (or could not fetch banlist), in which case just ignore and let the unban event fail whenever
guild, banned_ids = info
user_id = tempban.get("user_id")
# if this user is not banned anymore, run the on_member_unban event to clear the tempban
if user_id not in banned_ids:
await self.on_member_unban(guild, self.fakeuser_from_record(tempban, guild))
@commands.Cog.listener()
async def on_member_unban(self, guild, user):
# complete tempbans if user is manually unbanned
_id = await self.db.fetchval(
"UPDATE mod_timer SET completed=TRUE WHERE guild_id=$1 AND user_id=$2 AND event=$3 AND completed=FALSE RETURNING id",
guild.id,
user.id,
"BAN",
)
# also restart timer if the next in line *was* that tempban
if _id is not None:
self.event_timer.restart_if(lambda r: r.get("id") == _id)
self.bot.dispatch(
"log",
guild,
user,
action="TEMPBAN CANCELLED",
severity=Severity.RESOLVED,
reason="Tempbanned member manually unbanned.",
)
@commands.command()
@commands.has_permissions(manage_messages=True)
@commands.bot_has_permissions(manage_messages=True)
async def clear(self, ctx, message_count: int, user: MaybeMemberConverter = None):
"""Simple purge command. Clear messages, either from user or indiscriminately."""
if message_count < 1:
raise commands.CommandError("Please choose a positive message amount to clear.")
if message_count > 100:
raise commands.CommandError("Please choose a message count below 100.")
def all_check(msg):
if msg.id == RULES_MSG_ID:
return False
return True
def user_check(msg):
return msg.author.id == user.id and all_check(msg)
try:
await ctx.message.delete()
except disnake.HTTPException:
pass
try:
deleted = await ctx.channel.purge(
limit=message_count, check=all_check if user is None else user_check
)
except disnake.HTTPException:
raise commands.CommandError(
"Failed deleting messages. Does the bot have the necessary permissions?"
)
count = len(deleted)
log.info("%s cleared %s messages in %s", po(ctx.author), count, po(ctx.guild))
await ctx.send(f'Deleted {count} message{"s" if count > 1 else ""}.', delete_after=5)
@commands.command()
@commands.has_permissions(manage_messages=True)
@commands.bot_has_permissions(manage_messages=True)
async def purge(self, ctx, *, args: str = None):
"""Advanced purge command. Do `help purge` for usage examples and argument list.
Arguments are parsed as command line arguments.
Examples:
Delete all messages within the last 200 containing the word "spam": `purge --check 200 --contains "spam"`
Delete all messages within the last 100 from two members: `purge --user @runie @dave`
Delete maximum 6 messages within the last 400 starting with "ham": `purge --check 400 --max 6 --starts "ham"`
List of arguments:
```
--check <int>
Amount of messages the bot will check for deletion.
--max <int>
Maximum amount of messages the bot will delete.
--bot
Only delete messages from bots.
--user member [...]
Only delete messages from these members.
--after message_id
Start deleting after this message id.
--before message_id
Delete, at most, up until this message id.
--contains <string> [...]
Delete messages containing this string(s).
--starts <string> [...]
Delete messages starting with this string(s).
--ends <string> [...]
Delete messages ending with this string(s).```"""
parser = NoExitArgumentParser(prog="purge", add_help=False, allow_abbrev=False)
parser.add_argument(
"-c",
"--check",
type=int,
metavar="message_count",
help="Total amount of messages checked for deletion.",
)
parser.add_argument(
"-m",
"--max",
type=int,
metavar="message_count",
help="Total amount of messages the bot will delete.",
)
parser.add_argument("--bot", action="store_true", help="Only delete messages from bots.")
parser.add_argument(
"-u",
"--user",
nargs="+",
metavar="user",
help="Only delete messages from this member(s).",
)
parser.add_argument(
"-a",
"--after",
type=int,
metavar="id",
help="Start deleting after this message id.",
)
parser.add_argument(
"-b",
"--before",
type=int,
metavar="id",
help="Delete, at most, up until this message id.",
)
parser.add_argument(
"--contains",
nargs="+",
metavar="text",
help="Delete messages containing this string(s).",
)
parser.add_argument(
"--starts",
nargs="+",
metavar="text",
help="Delete messages starting with this string(s).",
)
parser.add_argument(
"--ends",
nargs="+",
metavar="text",
help="Delete messages ending with this string(s).",
)
if args is None:
await ctx.send("```\n{0}\n```".format(parser.format_help()))
return
try:
args = parser.parse_args(shlex.split(args))
except Exception as e:
raise commands.CommandError(str(e).partition("error: ")[2])
preds = [lambda m: m.id != ctx.message.id, lambda m: m.id != RULES_MSG_ID]
if args.user:
converter = MaybeMemberConverter()
members = []
for id in args.user:
try:
member = await converter.convert(ctx, id)
members.append(member)
except commands.CommandError:
raise commands.CommandError('Unknown user: "{0}"'.format(id))
# yes, if both objects were disnake.Member I could do m.author in members,
# but since member can be FakeUser I need to do an explicit id comparison
preds.append(lambda m: any(m.author.id == member.id for member in members))
if args.contains:
preds.append(lambda m: any((s.lower() in m.content.lower()) for s in args.contains))
if args.bot:
preds.append(lambda m: m.author.bot)
if args.starts:
preds.append(
lambda m: any(m.content.lower().startswith(s.lower()) for s in args.starts)
)
if args.ends:
preds.append(lambda m: any(m.content.lower().endswith(s.lower()) for s in args.ends))
count = args.max
deleted = 0
def predicate(message):
nonlocal deleted
if count is not None and deleted >= count:
return False
if all(pred(message) for pred in preds):
deleted += 1
return True
# limit is 100 be default
limit = 100
after = None
before = None
# set to 512 if after flag is set
if args.after:
after = disnake.Object(id=args.after)
limit = PURGE_LIMIT
if args.before:
before = disnake.Object(id=args.before)
# if we actually want to manually specify it doe
if args.check is not None:
limit = max(0, min(PURGE_LIMIT, args.check))
try:
deleted_messages = await ctx.channel.purge(
limit=limit, check=predicate, before=before, after=after
)
except disnake.HTTPException:
raise commands.CommandError("Error occurred when deleting messages.")
deleted_count = len(deleted_messages)
log.info("%s purged %s messages in %s", po(ctx.author), deleted_count, po(ctx.guild))
await ctx.send("{0} messages deleted.".format(deleted_count), delete_after=10)
@commands.command()
@is_mod()
async def logchannel(self, ctx, *, channel: disnake.TextChannel = None):
"""Set a channel for the bot to log moderation-related messages."""
conf = await self.config.get_entry(ctx.guild.id)
if channel is None:
await conf.update(log_channel_id=None)
await ctx.send("Log channel cleared.")
else:
await conf.update(log_channel_id=channel.id)
await ctx.send("Log channel has been set to {0}".format(po(channel)))
@commands.command(hidden=True)
@is_mod()
async def perms(self, ctx, user: disnake.Member = None, channel: disnake.TextChannel = None):
"""Lists a users permissions in a channel."""
if user is None:
user = ctx.author