/
mod.py
1838 lines (1470 loc) · 71.6 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
from discord.ext import commands, tasks
from .utils import checks, db, time, cache
from .utils.formats import plural
from collections import Counter, defaultdict
from inspect import cleandoc
import re
import json
import discord
import enum
import datetime
import asyncio
import argparse, shlex
import logging
import asyncpg
import io
log = logging.getLogger(__name__)
## Misc utilities
class Arguments(argparse.ArgumentParser):
def error(self, message):
raise RuntimeError(message)
class RaidMode(enum.Enum):
off = 0
on = 1
strict = 2
def __str__(self):
return self.name
## Tables
class GuildConfig(db.Table, table_name='guild_mod_config'):
id = db.Column(db.Integer(big=True), primary_key=True)
raid_mode = db.Column(db.Integer(small=True))
broadcast_channel = db.Column(db.Integer(big=True))
mention_count = db.Column(db.Integer(small=True))
safe_mention_channel_ids = db.Column(db.Array(db.Integer(big=True)))
mute_role_id = db.Column(db.Integer(big=True))
muted_members = db.Column(db.Array(db.Integer(big=True)))
## Configuration
class ModConfig:
__slots__ = ('raid_mode', 'id', 'bot', 'broadcast_channel_id', 'mention_count',
'safe_mention_channel_ids', 'mute_role_id', 'muted_members')
@classmethod
async def from_record(cls, record, bot):
self = cls()
# the basic configuration
self.bot = bot
self.raid_mode = record['raid_mode']
self.id = record['id']
self.broadcast_channel_id = record['broadcast_channel']
self.mention_count = record['mention_count']
self.safe_mention_channel_ids = set(record['safe_mention_channel_ids'] or [])
self.muted_members = set(record['muted_members'] or [])
self.mute_role_id = record['mute_role_id']
return self
@property
def broadcast_channel(self):
guild = self.bot.get_guild(self.id)
return guild and guild.get_channel(self.broadcast_channel_id)
@property
def mute_role(self):
guild = self.bot.get_guild(self.id)
return guild and self.mute_role_id and guild.get_role(self.mute_role_id)
def is_muted(self, member):
return member.id in self.muted_members
async def apply_mute(self, member, reason):
if self.mute_role_id:
await member.add_roles(discord.Object(id=self.mute_role_id), reason=reason)
## Converters
def can_execute_action(ctx, user, target):
return user.id == ctx.bot.owner_id or \
user == ctx.guild.owner or \
user.top_role > target.top_role
class MemberNotFound(Exception):
pass
async def resolve_member(guild, member_id):
member = guild.get_member(member_id)
if member is None:
if guild.chunked:
raise MemberNotFound()
try:
member = await guild.fetch_member(member_id)
except discord.NotFound:
raise MemberNotFound() from None
return member
class MemberID(commands.Converter):
async def convert(self, ctx, argument):
try:
m = await commands.MemberConverter().convert(ctx, argument)
except commands.BadArgument:
try:
member_id = int(argument, base=10)
m = await resolve_member(ctx.guild, member_id)
except ValueError:
raise commands.BadArgument(f"{argument} is not a valid member or member ID.") from None
except MemberNotFound:
# hackban case
return type('_Hackban', (), {'id': member_id, '__str__': lambda s: f'Member ID {s.id}'})()
if not can_execute_action(ctx, ctx.author, m):
raise commands.BadArgument('You cannot do this action on this user due to role hierarchy.')
return m
class BannedMember(commands.Converter):
async def convert(self, ctx, argument):
if argument.isdigit():
member_id = int(argument, base=10)
try:
return await ctx.guild.fetch_ban(discord.Object(id=member_id))
except discord.NotFound:
raise commands.BadArgument('This member has not been banned before.') from None
ban_list = await ctx.guild.bans()
entity = discord.utils.find(lambda u: str(u.user) == argument, ban_list)
if entity is None:
raise commands.BadArgument('This member has not been banned before.')
return entity
class ActionReason(commands.Converter):
async def convert(self, ctx, argument):
ret = f'{ctx.author} (ID: {ctx.author.id}): {argument}'
if len(ret) > 512:
reason_max = 512 - len(ret) + len(argument)
raise commands.BadArgument(f'Reason is too long ({len(argument)}/{reason_max})')
return ret
def safe_reason_append(base, to_append):
appended = base + f'({to_append})'
if len(appended) > 512:
return base
return appended
## Spam detector
# TODO: add this to d.py maybe
class CooldownByContent(commands.CooldownMapping):
def _bucket_key(self, message):
return (message.channel.id, message.content)
class SpamChecker:
"""This spam checker does a few things.
1) It checks if a user has spammed more than 10 times in 12 seconds
2) It checks if the content has been spammed 15 times in 17 seconds.
3) It checks if new users have spammed 30 times in 35 seconds.
4) It checks if "fast joiners" have spammed 10 times in 12 seconds.
The second case is meant to catch alternating spam bots while the first one
just catches regular singular spam bots.
From experience these values aren't reached unless someone is actively spamming.
"""
def __init__(self):
self.by_content = CooldownByContent.from_cooldown(15, 17.0, commands.BucketType.member)
self.by_user = commands.CooldownMapping.from_cooldown(10, 12.0, commands.BucketType.user)
self.last_join = None
self.new_user = commands.CooldownMapping.from_cooldown(30, 35.0, commands.BucketType.channel)
# user_id flag mapping (for about 30 minutes)
self.fast_joiners = cache.ExpiringCache(seconds=1800.0)
self.hit_and_run = commands.CooldownMapping.from_cooldown(10, 12, commands.BucketType.channel)
def is_new(self, member):
now = datetime.datetime.utcnow()
seven_days_ago = now - datetime.timedelta(days=7)
ninety_days_ago = now - datetime.timedelta(days=90)
return member.created_at > ninety_days_ago and member.joined_at > seven_days_ago
def is_spamming(self, message):
if message.guild is None:
return False
current = message.created_at.replace(tzinfo=datetime.timezone.utc).timestamp()
if message.author.id in self.fast_joiners:
bucket = self.hit_and_run.get_bucket(message)
if bucket.update_rate_limit(current):
return True
if self.is_new(message.author):
new_bucket = self.new_user.get_bucket(message)
if new_bucket.update_rate_limit(current):
return True
user_bucket = self.by_user.get_bucket(message)
if user_bucket.update_rate_limit(current):
return True
content_bucket = self.by_content.get_bucket(message)
if content_bucket.update_rate_limit(current):
return True
return False
def is_fast_join(self, member):
joined = member.joined_at or datetime.datetime.utcnow()
if self.last_join is None:
self.last_join = joined
return False
is_fast = (joined - self.last_join).total_seconds() <= 2.0
self.last_join = joined
if is_fast:
self.fast_joiners[member.id] = True
return is_fast
## Checks
class NoMuteRole(commands.CommandError):
def __init__(self):
super().__init__('This server does not have a mute role set up.')
def can_mute():
async def predicate(ctx):
is_owner = await ctx.bot.is_owner(ctx.author)
if ctx.guild is None:
return False
if not ctx.author.guild_permissions.manage_roles and not is_owner:
return False
# This will only be used within this cog.
ctx.guild_config = config = await ctx.cog.get_guild_config(ctx.guild.id)
role = config and config.mute_role
if role is None:
raise NoMuteRole()
return ctx.author.top_role > role
return commands.check(predicate)
## The actual cog
class Mod(commands.Cog):
"""Moderation related commands."""
def __init__(self, bot):
self.bot = bot
# guild_id: SpamChecker
self._spam_check = defaultdict(SpamChecker)
# guild_id: List[(member_id, insertion)]
# A batch of data for bulk inserting mute role changes
# True - insert, False - remove
self._data_batch = defaultdict(list)
self._batch_lock = asyncio.Lock(loop=bot.loop)
self._disable_lock = asyncio.Lock(loop=bot.loop)
self.batch_updates.add_exception_type(asyncpg.PostgresConnectionError)
self.batch_updates.start()
# (guild_id, channel_id): List[str]
# A batch list of message content for message
self.message_batches = defaultdict(list)
self._batch_message_lock = asyncio.Lock(loop=bot.loop)
self.bulk_send_messages.start()
def __repr__(self):
return '<cogs.Mod>'
def cog_unload(self):
self.batch_updates.stop()
self.bulk_send_messages.stop()
async def cog_command_error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
elif isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, discord.Forbidden):
await ctx.send('I do not have permission to execute this action.')
elif isinstance(original, discord.NotFound):
await ctx.send(f'This entity does not exist: {original.text}')
elif isinstance(original, discord.HTTPException):
await ctx.send('Somehow, an unexpected error occurred. Try again later?')
elif isinstance(error, NoMuteRole):
await ctx.send(error)
async def bulk_insert(self):
query = """UPDATE guild_mod_config
SET muted_members = x.result_array
FROM jsonb_to_recordset($1::jsonb) AS
x(guild_id BIGINT, result_array BIGINT[])
WHERE guild_mod_config.id = x.guild_id;
"""
if not self._data_batch:
return
final_data = []
for guild_id, data in self._data_batch.items():
# If it's touched this function then chances are that this has hit cache before
# so it's not actually doing a query, hopefully.
config = await self.get_guild_config(guild_id)
as_set = config.muted_members
for member_id, insertion in data:
func = as_set.add if insertion else as_set.discard
func(member_id)
final_data.append({
'guild_id': guild_id,
'result_array': list(as_set)
})
self.get_guild_config.invalidate(self, guild_id)
await self.bot.pool.execute(query, final_data)
self._data_batch.clear()
@tasks.loop(seconds=15.0)
async def batch_updates(self):
async with self._batch_lock:
await self.bulk_insert()
@tasks.loop(seconds=10.0)
async def bulk_send_messages(self):
async with self._batch_message_lock:
for ((guild_id, channel_id), messages) in self.message_batches.items():
guild = self.bot.get_guild(guild_id)
channel = guild and guild.get_channel(channel_id)
if channel is None:
continue
paginator = commands.Paginator(suffix='', prefix='')
for message in messages:
paginator.add_line(message)
for page in paginator.pages:
try:
await channel.send(page)
except discord.HTTPException:
pass
self.message_batches.clear()
@cache.cache()
async def get_guild_config(self, guild_id):
query = """SELECT * FROM guild_mod_config WHERE id=$1;"""
async with self.bot.pool.acquire() as con:
record = await con.fetchrow(query, guild_id)
if record is not None:
return await ModConfig.from_record(record, self.bot)
return None
async def check_raid(self, config, guild_id, member, message):
if config.raid_mode != RaidMode.strict.value:
return
checker = self._spam_check[guild_id]
if not checker.is_spamming(message):
return
try:
await member.ban(reason='Auto-ban from spam (strict raid mode ban)')
except discord.HTTPException:
log.info(f'[Raid Mode] Failed to ban {member} (ID: {member.id}) from server {member.guild} via strict mode.')
else:
log.info(f'[Raid Mode] Banned {member} (ID: {member.id}) from server {member.guild} via strict mode.')
@commands.Cog.listener()
async def on_message(self, message):
author = message.author
if author.id in (self.bot.user.id, self.bot.owner_id):
return
if message.guild is None:
return
if not isinstance(author, discord.Member):
return
if author.bot:
return
# we're going to ignore members with roles
if len(author.roles) > 1:
return
guild_id = message.guild.id
config = await self.get_guild_config(guild_id)
if config is None:
return
# check for raid mode stuff
await self.check_raid(config, guild_id, author, message)
# auto-ban tracking for mention spams begin here
if len(message.mentions) <= 3:
return
if not config.mention_count:
return
# check if it meets the thresholds required
mention_count = sum(not m.bot and m.id != author.id for m in message.mentions)
if mention_count < config.mention_count:
return
if message.channel.id in config.safe_mention_channel_ids:
return
try:
await author.ban(reason=f'Spamming mentions ({mention_count} mentions)')
except Exception as e:
log.info(f'Failed to autoban member {author} (ID: {author.id}) in guild ID {guild_id}')
else:
to_send = f'Banned {author} (ID: {author.id}) for spamming {mention_count} mentions.'
async with self._batch_message_lock:
self.message_batches[(guild_id, message.channel.id)].append(to_send)
log.info(f'Member {author} (ID: {author.id}) has been autobanned from guild ID {guild_id}')
@commands.Cog.listener()
async def on_member_join(self, member):
guild_id = member.guild.id
config = await self.get_guild_config(guild_id)
if config is None:
return
if config.is_muted(member):
return await config.apply_mute(member, 'Member was previously muted.')
if not config.raid_mode:
return
now = datetime.datetime.utcnow()
is_new = member.created_at > (now - datetime.timedelta(days=7))
checker = self._spam_check[guild_id]
# Do the broadcasted message to the channel
title = 'Member Joined'
if checker.is_fast_join(member):
colour = 0xdd5f53 # red
if is_new:
title = 'Member Joined (Very New Member)'
else:
colour = 0x53dda4 # green
if is_new:
colour = 0xdda453 # yellow
title = 'Member Joined (Very New Member)'
e = discord.Embed(title=title, colour=colour)
e.timestamp = now
e.set_author(name=str(member), icon_url=member.avatar_url)
e.add_field(name='ID', value=member.id)
e.add_field(name='Joined', value=member.joined_at)
e.add_field(name='Created', value=time.human_timedelta(member.created_at), inline=False)
if config.broadcast_channel:
try:
await config.broadcast_channel.send(embed=e)
except discord.Forbidden:
async with self._disable_lock:
await self.disable_raid_mode(guild_id)
@commands.Cog.listener()
async def on_member_update(self, before, after):
# Comparing roles in memory is faster than potentially fetching from
# database, even if there's a cache layer
if before.roles == after.roles:
return
guild_id = after.guild.id
config = await self.get_guild_config(guild_id)
if config is None:
return
if config.mute_role_id is None:
return
# Use private API because d.py does not expose this yet
before_has = before._roles.has(config.mute_role_id)
after_has = after._roles.has(config.mute_role_id)
# No change in the mute role
# both didn't have it or both did have it
if before_has == after_has:
return
async with self._batch_lock:
# If `after_has` is true, then it's an insertion operation
# if it's false, then the role for removed
self._data_batch[guild_id].append((after.id, after_has))
@commands.Cog.listener()
async def on_guild_role_delete(self, role):
guild_id = role.guild.id
config = await self.get_guild_config(guild_id)
if config is None or config.mute_role_id != role.id:
return
query = """UPDATE guild_mod_config SET (mute_role_id, muted_members) = (NULL, '{}'::bigint[]) WHERE id=$1;"""
await self.bot.pool.execute(query, guild_id)
self.get_guild_config.invalidate(self, guild_id)
@commands.command(aliases=['newmembers'])
@commands.guild_only()
async def newusers(self, ctx, *, count=5):
"""Tells you the newest members of the server.
This is useful to check if any suspicious members have
joined.
The count parameter can only be up to 25.
"""
count = max(min(count, 25), 5)
if not ctx.guild.chunked:
await self.bot.request_offline_members(ctx.guild)
members = sorted(ctx.guild.members, key=lambda m: m.joined_at, reverse=True)[:count]
e = discord.Embed(title='New Members', colour=discord.Colour.green())
for member in members:
body = f'Joined {time.human_timedelta(member.joined_at)}\nCreated {time.human_timedelta(member.created_at)}'
e.add_field(name=f'{member} (ID: {member.id})', value=body, inline=False)
await ctx.send(embed=e)
@commands.group(aliases=['raids'], invoke_without_command=True)
@checks.is_mod()
async def raid(self, ctx):
"""Controls raid mode on the server.
Calling this command with no arguments will show the current raid
mode information.
You must have Manage Server permissions to use this command or
its subcommands.
"""
query = "SELECT raid_mode, broadcast_channel FROM guild_mod_config WHERE id=$1;"
row = await ctx.db.fetchrow(query, ctx.guild.id)
if row is None:
fmt = 'Raid Mode: off\nBroadcast Channel: None'
else:
ch = f'<#{row[1]}>' if row[1] else None
mode = RaidMode(row[0]) if row[0] is not None else RaidMode.off
fmt = f'Raid Mode: {mode}\nBroadcast Channel: {ch}'
await ctx.send(fmt)
@raid.command(name='on', aliases=['enable', 'enabled'])
@checks.is_mod()
async def raid_on(self, ctx, *, channel: discord.TextChannel = None):
"""Enables basic raid mode on the server.
When enabled, server verification level is set to table flip
levels and allows the bot to broadcast new members joining
to a specified channel.
If no channel is given, then the bot will broadcast join
messages on the channel this command was used in.
"""
channel = channel or ctx.channel
try:
await ctx.guild.edit(verification_level=discord.VerificationLevel.high)
except discord.HTTPException:
await ctx.send('\N{WARNING SIGN} Could not set verification level.')
query = """INSERT INTO guild_mod_config (id, raid_mode, broadcast_channel)
VALUES ($1, $2, $3) ON CONFLICT (id)
DO UPDATE SET
raid_mode = EXCLUDED.raid_mode,
broadcast_channel = EXCLUDED.broadcast_channel;
"""
await ctx.db.execute(query, ctx.guild.id, RaidMode.on.value, channel.id)
self.get_guild_config.invalidate(self, ctx.guild.id)
await ctx.send(f'Raid mode enabled. Broadcasting join messages to {channel.mention}.')
async def disable_raid_mode(self, guild_id):
query = """INSERT INTO guild_mod_config (id, raid_mode, broadcast_channel)
VALUES ($1, $2, NULL) ON CONFLICT (id)
DO UPDATE SET
raid_mode = EXCLUDED.raid_mode,
broadcast_channel = NULL;
"""
await self.bot.pool.execute(query, guild_id, RaidMode.off.value)
self._spam_check.pop(guild_id, None)
self.get_guild_config.invalidate(self, guild_id)
@raid.command(name='off', aliases=['disable', 'disabled'])
@checks.is_mod()
async def raid_off(self, ctx):
"""Disables raid mode on the server.
When disabled, the server verification levels are set
back to Low levels and the bot will stop broadcasting
join messages.
"""
try:
await ctx.guild.edit(verification_level=discord.VerificationLevel.low)
except discord.HTTPException:
await ctx.send('\N{WARNING SIGN} Could not set verification level.')
await self.disable_raid_mode(ctx.guild.id)
await ctx.send('Raid mode disabled. No longer broadcasting join messages.')
@raid.command(name='strict')
@checks.is_mod()
async def raid_strict(self, ctx, *, channel: discord.TextChannel = None):
"""Enables strict raid mode on the server.
Strict mode is similar to regular enabled raid mode, with the added
benefit of auto-banning members that are spamming. The threshold for
spamming depends on a per-content basis and also on a per-user basis
of 15 messages per 17 seconds.
If this is considered too strict, it is recommended to fall back to regular
raid mode.
"""
channel = channel or ctx.channel
perms = ctx.me.guild_permissions
if not (perms.kick_members and perms.ban_members):
return await ctx.send('\N{NO ENTRY SIGN} I do not have permissions to kick and ban members.')
try:
await ctx.guild.edit(verification_level=discord.VerificationLevel.high)
except discord.HTTPException:
await ctx.send('\N{WARNING SIGN} Could not set verification level.')
query = """INSERT INTO guild_mod_config (id, raid_mode, broadcast_channel)
VALUES ($1, $2, $3) ON CONFLICT (id)
DO UPDATE SET
raid_mode = EXCLUDED.raid_mode,
broadcast_channel = EXCLUDED.broadcast_channel;
"""
await ctx.db.execute(query, ctx.guild.id, RaidMode.strict.value, channel.id)
self.get_guild_config.invalidate(self, ctx.guild.id)
await ctx.send(f'Raid mode enabled strictly. Broadcasting join messages to {channel.mention}.')
async def _basic_cleanup_strategy(self, ctx, search):
count = 0
async for msg in ctx.history(limit=search, before=ctx.message):
if msg.author == ctx.me:
await msg.delete()
count += 1
return { 'Bot': count }
async def _complex_cleanup_strategy(self, ctx, search):
prefixes = tuple(self.bot.get_guild_prefixes(ctx.guild)) # thanks startswith
def check(m):
return m.author == ctx.me or m.content.startswith(prefixes)
deleted = await ctx.channel.purge(limit=search, check=check, before=ctx.message)
return Counter(m.author.display_name for m in deleted)
@commands.command()
@checks.has_permissions(manage_messages=True)
async def cleanup(self, ctx, search=100):
"""Cleans up the bot's messages from the channel.
If a search number is specified, it searches that many messages to delete.
If the bot has Manage Messages permissions then it will try to delete
messages that look like they invoked the bot as well.
After the cleanup is completed, the bot will send you a message with
which people got their messages deleted and their count. This is useful
to see which users are spammers.
You must have Manage Messages permission to use this.
"""
strategy = self._basic_cleanup_strategy
if ctx.me.permissions_in(ctx.channel).manage_messages:
strategy = self._complex_cleanup_strategy
spammers = await strategy(ctx, search)
deleted = sum(spammers.values())
messages = [f'{deleted} message{" was" if deleted == 1 else "s were"} removed.']
if deleted:
messages.append('')
spammers = sorted(spammers.items(), key=lambda t: t[1], reverse=True)
messages.extend(f'- **{author}**: {count}' for author, count in spammers)
await ctx.send('\n'.join(messages), delete_after=10)
@commands.command()
@commands.guild_only()
@checks.has_permissions(kick_members=True)
async def kick(self, ctx, member: MemberID, *, reason: ActionReason = None):
"""Kicks a member from the server.
In order for this to work, the bot must have Kick Member permissions.
To use this command you must have Kick Members permission.
"""
if reason is None:
reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'
await ctx.guild.kick(member, reason=reason)
await ctx.send('\N{OK HAND SIGN}')
@commands.command()
@commands.guild_only()
@checks.has_permissions(ban_members=True)
async def ban(self, ctx, member: MemberID, *, reason: ActionReason = None):
"""Bans a member from the server.
You can also ban from ID to ban regardless whether they're
in the server or not.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Ban Members permission.
"""
if reason is None:
reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'
await ctx.guild.ban(member, reason=reason)
await ctx.send('\N{OK HAND SIGN}')
@commands.command()
@commands.guild_only()
@checks.has_permissions(ban_members=True)
async def multiban(self, ctx, members: commands.Greedy[MemberID], *, reason: ActionReason = None):
"""Bans multiple members from the server.
This only works through banning via ID.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Ban Members permission.
"""
if reason is None:
reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'
total_members = len(members)
if total_members == 0:
return await ctx.send('Missing members to ban.')
confirm = await ctx.prompt(f'This will ban **{plural(total_members):member}**. Are you sure?', reacquire=False)
if not confirm:
return await ctx.send('Aborting.')
failed = 0
for member in members:
try:
await ctx.guild.ban(member, reason=reason)
except discord.HTTPException:
failed += 1
await ctx.send(f'Banned {total_members - failed}/{total_members} members.')
@commands.command()
@commands.guild_only()
@checks.has_permissions(ban_members=True)
async def massban(self, ctx, *, args):
"""Mass bans multiple members from the server.
This command has a powerful "command line" syntax. To use this command
you and the bot must both have Ban Members permission. **Every option is optional.**
Users are only banned **if and only if** all conditions are met.
The following options are valid.
`--channel` or `-c`: Channel to search for message history.
`--reason` or `-r`: The reason for the ban.
`--regex`: Regex that usernames must match.
`--created`: Matches users whose accounts were created less than specified minutes ago.
`--joined`: Matches users that joined less than specified minutes ago.
`--joined-before`: Matches users who joined before the member ID given.
`--joined-after`: Matches users who joined after the member ID given.
`--no-avatar`: Matches users who have no avatar. (no arguments)
`--no-roles`: Matches users that have no role. (no arguments)
`--show`: Show members instead of banning them (no arguments).
Message history filters (Requires `--channel`):
`--contains`: A substring to search for in the message.
`--starts`: A substring to search if the message starts with.
`--ends`: A substring to search if the message ends with.
`--match`: A regex to match the message content to.
`--search`: How many messages to search. Default 100. Max 2000.
`--after`: Messages must come after this message ID.
`--before`: Messages must come before this message ID.
`--files`: Checks if the message has attachments (no arguments).
`--embeds`: Checks if the message has embeds (no arguments).
"""
# For some reason there are cases due to caching that ctx.author
# can be a User even in a guild only context
# Rather than trying to work out the kink with it
# Just upgrade the member itself.
if not isinstance(ctx.author, discord.Member):
try:
author = await ctx.guild.fetch_member(ctx.author.id)
except discord.HTTPException:
return await ctx.send('Somehow, Discord does not seem to think you are in this server.')
else:
author = ctx.author
parser = Arguments(add_help=False, allow_abbrev=False)
parser.add_argument('--channel', '-c')
parser.add_argument('--reason', '-r')
parser.add_argument('--search', type=int, default=100)
parser.add_argument('--regex')
parser.add_argument('--no-avatar', action='store_true')
parser.add_argument('--no-roles', action='store_true')
parser.add_argument('--created', type=int)
parser.add_argument('--joined', type=int)
parser.add_argument('--joined-before', type=int)
parser.add_argument('--joined-after', type=int)
parser.add_argument('--contains')
parser.add_argument('--starts')
parser.add_argument('--ends')
parser.add_argument('--match')
parser.add_argument('--show', action='store_true')
parser.add_argument('--embeds', action='store_const', const=lambda m: len(m.embeds))
parser.add_argument('--files', action='store_const', const=lambda m: len(m.attachments))
parser.add_argument('--after', type=int)
parser.add_argument('--before', type=int)
try:
args = parser.parse_args(shlex.split(args))
except Exception as e:
return await ctx.send(str(e))
members = []
if args.channel:
channel = await commands.TextChannelConverter().convert(ctx, args.channel)
before = args.before and discord.Object(id=args.before)
after = args.after and discord.Object(id=args.after)
predicates = []
if args.contains:
predicates.append(lambda m: args.contains in m.content)
if args.starts:
predicates.append(lambda m: m.content.startswith(args.starts))
if args.ends:
predicates.append(lambda m: m.content.endswith(args.ends))
if args.match:
try:
_match = re.compile(args.match)
except re.error as e:
return await ctx.send(f'Invalid regex passed to `--match`: {e}')
else:
predicates.append(lambda m, x=_match: x.match(m.content))
if args.embeds:
predicates.append(args.embeds)
if args.files:
predicates.append(args.files)
async for message in channel.history(limit=min(max(1, args.search), 2000), before=before, after=after):
if all(p(message) for p in predicates):
members.append(message.author)
else:
members = ctx.guild.members
# member filters
predicates = [
lambda m: isinstance(m, discord.Member) and can_execute_action(ctx, author, m), # Only if applicable
lambda m: not m.bot, # No bots
lambda m: m.discriminator != '0000', # No deleted users
]
async def _resolve_member(member_id):
r = ctx.guild.get_member(member_id)
if r is None:
try:
return await ctx.guild.fetch_member(member_id)
except discord.HTTPException as e:
raise commands.BadArgument(f'Could not fetch member by ID {member_id}: {e}') from None
return r
if args.regex:
try:
_regex = re.compile(args.regex)
except re.error as e:
return await ctx.send(f'Invalid regex passed to `--regex`: {e}')
else:
predicates.append(lambda m, x=_regex: x.match(m.name))
if args.no_avatar:
predicates.append(lambda m: m.avatar is None)
if args.no_roles:
predicates.append(lambda m: len(getattr(m, 'roles', [])) <= 1)
now = datetime.datetime.utcnow()
if args.created:
def created(member, *, offset=now - datetime.timedelta(minutes=args.created)):
return member.created_at > offset
predicates.append(created)
if args.joined:
def joined(member, *, offset=now - datetime.timedelta(minutes=args.joined)):
if isinstance(member, discord.User):
# If the member is a user then they left already
return True
return member.joined_at and member.joined_at > offset
predicates.append(joined)
if args.joined_after:
_joined_after_member = await _resolve_member(args.joined_after)
def joined_after(member, *, _other=_joined_after_member):
return member.joined_at and _other.joined_at and member.joined_at > _other.joined_at
predicates.append(joined_after)
if args.joined_before:
_joined_before_member = await _resolve_member(args.joined_before)
def joined_before(member, *, _other=_joined_before_member):
return member.joined_at and _other.joined_at and member.joined_at < _other.joined_at
predicates.append(joined_before)
members = {m for m in members if all(p(m) for p in predicates)}
if len(members) == 0:
return await ctx.send('No members found matching criteria.')
if args.show:
members = sorted(members, key=lambda m: m.joined_at or now)
fmt = "\n".join(f'{m.id}\tJoined: {m.joined_at}\tCreated: {m.created_at}\t{m}' for m in members)
content = f'Current Time: {datetime.datetime.utcnow()}\nTotal members: {len(members)}\n{fmt}'
file = discord.File(io.BytesIO(content.encode('utf-8')), filename='members.txt')
return await ctx.send(file=file)
if args.reason is None:
return await ctx.send('--reason flag is required.')
else:
reason = await ActionReason().convert(ctx, args.reason)
confirm = await ctx.prompt(f'This will ban **{plural(len(members)):member}**. Are you sure?')
if not confirm:
return await ctx.send('Aborting.')
count = 0
for member in members:
try:
await ctx.guild.ban(member, reason=reason)
except discord.HTTPException:
pass
else:
count += 1
await ctx.send(f'Banned {count}/{len(members)}')
@commands.command()
@commands.guild_only()
@checks.has_permissions(kick_members=True)
async def softban(self, ctx, member: MemberID, *, reason: ActionReason = None):
"""Soft bans a member from the server.
A softban is basically banning the member from the server but
then unbanning the member as well. This allows you to essentially
kick the member while removing their messages.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Kick Members permissions.
"""
if reason is None:
reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'
await ctx.guild.ban(member, reason=reason)
await ctx.guild.unban(member, reason=reason)
await ctx.send('\N{OK HAND SIGN}')
@commands.command()
@commands.guild_only()
@checks.has_permissions(ban_members=True)
async def unban(self, ctx, member: BannedMember, *, reason: ActionReason = None):
"""Unbans a member from the server.
You can pass either the ID of the banned member or the Name#Discrim
combination of the member. Typically the ID is easiest to use.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Ban Members permissions.
"""