|
|
@@ -1,242 +1,53 @@
|
|
1
|
|
-from discord import Guild, Intents, Member, Message, PartialEmoji, RawReactionActionEvent
|
|
|
1
|
+from datetime import datetime, timedelta
|
|
|
2
|
+from discord import Guild, Member
|
|
2
|
3
|
from discord.ext import commands
|
|
3
|
|
-from storage import Storage
|
|
4
|
|
-from cogs.basecog import BaseCog
|
|
5
|
|
-from config import CONFIG
|
|
6
|
|
-from datetime import datetime
|
|
7
|
|
-
|
|
8
|
|
-class JoinRecord:
|
|
9
|
|
- """
|
|
10
|
|
- Data object containing details about a single guild join event.
|
|
11
|
|
- """
|
|
12
|
|
- def __init__(self, member: Member):
|
|
13
|
|
- self.member = member
|
|
14
|
|
- self.join_time = member.joined_at or datetime.now()
|
|
15
|
|
- # These flags only track whether this bot has kicked/banned
|
|
16
|
|
- self.is_kicked = False
|
|
17
|
|
- self.is_banned = False
|
|
18
|
|
-
|
|
19
|
|
- def age_seconds(self, now: datetime) -> float:
|
|
20
|
|
- """
|
|
21
|
|
- Returns the age of this join in seconds from the given "now" time.
|
|
22
|
|
- """
|
|
23
|
|
- a = now - self.join_time
|
|
24
|
|
- return float(a.total_seconds())
|
|
25
|
|
-
|
|
26
|
|
-class RaidPhase:
|
|
27
|
|
- """
|
|
28
|
|
- Enum of phases in a JoinRaidRecord. Phases progress monotonically.
|
|
29
|
|
- """
|
|
30
|
|
- NONE = 0
|
|
31
|
|
- JUST_STARTED = 1
|
|
32
|
|
- CONTINUING = 2
|
|
33
|
|
- ENDED = 3
|
|
34
|
|
-
|
|
35
|
|
-class JoinRaidRecord:
|
|
36
|
|
- """
|
|
37
|
|
- Tracks recent joins to a guild to detect join raids, where a large number
|
|
38
|
|
- of automated users all join at the same time. Manages list of joins to not
|
|
39
|
|
- grow unbounded.
|
|
40
|
|
- """
|
|
41
|
|
- def __init__(self):
|
|
42
|
|
- self.joins = []
|
|
43
|
|
- self.phase = RaidPhase.NONE
|
|
44
|
|
- # datetime when the raid started, or None.
|
|
45
|
|
- self.raid_start_time = None
|
|
46
|
|
- # Message posted to Discord to warn of the raid. Convenience property
|
|
47
|
|
- # managed by caller. Ignored by this class.
|
|
48
|
|
- self.warning_message = None
|
|
49
|
|
-
|
|
50
|
|
- def handle_join(self,
|
|
51
|
|
- member: Member,
|
|
52
|
|
- now: datetime,
|
|
53
|
|
- max_join_count: int,
|
|
54
|
|
- max_age_seconds: float) -> None:
|
|
55
|
|
- """
|
|
56
|
|
- Processes a new member join to a guild and detects join raids. Updates
|
|
57
|
|
- self.phase and self.raid_start_time properties.
|
|
58
|
|
- """
|
|
59
|
|
- # Check for existing record for this user
|
|
60
|
|
- join: JoinRecord = None
|
|
61
|
|
- i: int = 0
|
|
62
|
|
- while i < len(self.joins):
|
|
63
|
|
- elem = self.joins[i]
|
|
64
|
|
- if elem.member.id == member.id:
|
|
65
|
|
- join = self.joins.pop(i)
|
|
66
|
|
- join.join_time = now
|
|
67
|
|
- break
|
|
68
|
|
- i += 1
|
|
69
|
|
- # Add new record to end
|
|
70
|
|
- self.joins.append(join or JoinRecord(member))
|
|
71
|
|
- # Check raid status and do upkeep
|
|
72
|
|
- self.__process_joins(now, max_age_seconds, max_join_count)
|
|
73
|
|
-
|
|
74
|
|
- def __process_joins(self,
|
|
75
|
|
- now: datetime,
|
|
76
|
|
- max_age_seconds: float,
|
|
77
|
|
- max_join_count: int) -> None:
|
|
78
|
|
- """
|
|
79
|
|
- Processes self.joins after each addition, detects raids, updates
|
|
80
|
|
- self.phase, and throws out unneeded records.
|
|
81
|
|
- """
|
|
82
|
|
- i: int = 0
|
|
83
|
|
- recent_count: int = 0
|
|
84
|
|
- should_cull: bool = self.phase == RaidPhase.NONE
|
|
85
|
|
- while i < len(self.joins):
|
|
86
|
|
- join: JoinRecord = self.joins[i]
|
|
87
|
|
- age: float = join.age_seconds(now)
|
|
88
|
|
- is_old: bool = age > max_age_seconds
|
|
89
|
|
- if not is_old:
|
|
90
|
|
- recent_count += 1
|
|
91
|
|
- if is_old and should_cull:
|
|
92
|
|
- self.joins.pop(i)
|
|
93
|
|
- else:
|
|
94
|
|
- i += 1
|
|
95
|
|
- is_raid = recent_count > max_join_count
|
|
96
|
|
- if is_raid:
|
|
97
|
|
- if self.phase == RaidPhase.NONE:
|
|
98
|
|
- self.phase = RaidPhase.JUST_STARTED
|
|
99
|
|
- self.raid_start_time = now
|
|
100
|
|
- elif self.phase == RaidPhase.JUST_STARTED:
|
|
101
|
|
- self.phase = RaidPhase.CONTINUING
|
|
102
|
|
- elif self.phase == self.phase in (RaidPhase.JUST_STARTED, RaidPhase.CONTINUING):
|
|
103
|
|
- self.phase = RaidPhase.ENDED
|
|
104
|
|
-
|
|
105
|
|
- # Undo join add if the raid is over
|
|
106
|
|
- if self.phase == RaidPhase.ENDED and len(self.joins) > 0:
|
|
107
|
|
- last = self.joins.pop(-1)
|
|
108
|
|
-
|
|
109
|
|
- async def kick_all(self,
|
|
110
|
|
- reason: str = "Part of join raid") -> list[Member]:
|
|
111
|
|
- """
|
|
112
|
|
- Kicks all users in this join raid. Skips users who have already been
|
|
113
|
|
- flagged as having been kicked or banned. Returns a List of Members
|
|
114
|
|
- who were newly kicked.
|
|
115
|
|
- """
|
|
116
|
|
- kicks = []
|
|
117
|
|
- guild = None
|
|
118
|
|
- for join in self.joins:
|
|
119
|
|
- guild = join.member.guild
|
|
120
|
|
- if join.is_kicked or join.is_banned:
|
|
121
|
|
- continue
|
|
122
|
|
- await join.member.kick(reason=reason)
|
|
123
|
|
- join.is_kicked = True
|
|
124
|
|
- kicks.append(join.member)
|
|
125
|
|
- self.phase = RaidPhase.ENDED
|
|
126
|
|
- if len(kicks) > 0:
|
|
127
|
|
- self.log(guild, f'Mod kicked {len(kicks)} people')
|
|
128
|
|
- return kicks
|
|
129
|
|
-
|
|
130
|
|
- async def ban_all(self,
|
|
131
|
|
- reason: str = "Part of join raid",
|
|
132
|
|
- delete_message_days: int = 0) -> list[Member]:
|
|
133
|
|
- """
|
|
134
|
|
- Bans all users in this join raid. Skips users who have already been
|
|
135
|
|
- flagged as having been banned. Users who were previously kicked can
|
|
136
|
|
- still be banned. Returns a List of Members who were newly banned.
|
|
137
|
|
- """
|
|
138
|
|
- bans = []
|
|
139
|
|
- guild = None
|
|
140
|
|
- for join in self.joins:
|
|
141
|
|
- guild = join.member.guild
|
|
142
|
|
- if join.is_banned:
|
|
143
|
|
- continue
|
|
144
|
|
- await join.member.ban(
|
|
145
|
|
- reason=reason,
|
|
146
|
|
- delete_message_days=delete_message_days)
|
|
147
|
|
- join.is_banned = True
|
|
148
|
|
- bans.append(join.member)
|
|
149
|
|
- self.phase = RaidPhase.ENDED
|
|
150
|
|
- if len(bans) > 0:
|
|
151
|
|
- self.log(guild, f'Mod banned {len(bans)} people')
|
|
152
|
|
- return bans
|
|
|
4
|
+import weakref
|
|
153
|
5
|
|
|
154
|
|
-class GuildContext:
|
|
155
|
|
- """
|
|
156
|
|
- Logic and state for a single guild serviced by the bot.
|
|
157
|
|
- """
|
|
158
|
|
- def __init__(self, guild_id: int):
|
|
159
|
|
- self.guild_id = guild_id
|
|
160
|
|
- # Non-persisted runtime state
|
|
161
|
|
- self.current_raid = JoinRaidRecord()
|
|
162
|
|
- self.all_raids = [ self.current_raid ] # periodically culled of old ones
|
|
163
|
|
-
|
|
164
|
|
- def reset_raid(self, now: datetime):
|
|
165
|
|
- """
|
|
166
|
|
- Retires self.current_raid and creates a new empty one.
|
|
167
|
|
- """
|
|
168
|
|
- self.current_raid = JoinRaidRecord()
|
|
169
|
|
- self.all_raids.append(self.current_raid)
|
|
170
|
|
- self.__cull_old_raids(now)
|
|
171
|
|
-
|
|
172
|
|
- def find_raid_for_message_id(self, message_id: int) -> JoinRaidRecord:
|
|
173
|
|
- """
|
|
174
|
|
- Retrieves a JoinRaidRecord instance for the given raid warning message.
|
|
175
|
|
- Returns None if not found.
|
|
176
|
|
- """
|
|
177
|
|
- for raid in self.all_raids:
|
|
178
|
|
- if raid.warning_message is not None and raid.warning_message.id == message_id:
|
|
179
|
|
- return raid
|
|
180
|
|
- return None
|
|
|
6
|
+from cogs.basecog import BaseCog, BotMessage, BotMessageReaction, CogSetting
|
|
|
7
|
+from config import CONFIG
|
|
|
8
|
+from rscollections import AgeBoundList
|
|
|
9
|
+from storage import Storage
|
|
181
|
10
|
|
|
182
|
|
- def __cull_old_raids(self, now: datetime):
|
|
183
|
|
- """
|
|
184
|
|
- Gets rid of old JoinRaidRecord records from self.all_raids that are too
|
|
185
|
|
- old to still be useful.
|
|
186
|
|
- """
|
|
187
|
|
- i: int = 0
|
|
188
|
|
- while i < len(self.all_raids):
|
|
189
|
|
- raid = self.all_raids[i]
|
|
190
|
|
- if raid == self.current_raid:
|
|
191
|
|
- i += 1
|
|
192
|
|
- continue
|
|
193
|
|
- age_seconds = float((raid.raid_start_time - now).total_seconds())
|
|
194
|
|
- if age_seconds > 86400.0:
|
|
195
|
|
- self.__trace('Culling old raid')
|
|
196
|
|
- self.all_raids.pop(i)
|
|
197
|
|
- else:
|
|
198
|
|
- i += 1
|
|
|
11
|
+class JoinRaidContext:
|
|
|
12
|
+ def __init__(self, join_members: list):
|
|
|
13
|
+ self.join_members = list(join_members)
|
|
|
14
|
+ self.kicked_members = set()
|
|
|
15
|
+ self.banned_members = set()
|
|
|
16
|
+ self.warning_message_ref = None
|
|
199
|
17
|
|
|
200
|
|
- def __trace(self, message):
|
|
201
|
|
- """
|
|
202
|
|
- Debugging trace.
|
|
203
|
|
- """
|
|
204
|
|
- print(f'{self.guild_id}: {message}')
|
|
|
18
|
+ def last_join_time(self) -> datetime:
|
|
|
19
|
+ return self.join_members[-1].joined_at
|
|
205
|
20
|
|
|
206
|
21
|
class JoinRaidCog(BaseCog):
|
|
207
|
22
|
"""
|
|
208
|
23
|
Cog for monitoring member joins and detecting potential bot raids.
|
|
209
|
24
|
"""
|
|
210
|
|
- MIN_JOIN_COUNT = 2
|
|
211
|
|
-
|
|
212
|
|
- STATE_KEY_RAID_COUNT = 'joinraid_count'
|
|
213
|
|
- STATE_KEY_RAID_SECONDS = 'joinraid_seconds'
|
|
214
|
|
- STATE_KEY_ENABLED = 'joinraid_enabled'
|
|
|
25
|
+ SETTING_ENABLED = CogSetting('enabled', bool,
|
|
|
26
|
+ brief='join raid detection',
|
|
|
27
|
+ description='Whether this cog is enabled for a guild.')
|
|
|
28
|
+ SETTING_JOIN_COUNT = CogSetting('joincount', int,
|
|
|
29
|
+ brief='number of joins to trigger a warning',
|
|
|
30
|
+ description='The number of joins occuring within the time ' + \
|
|
|
31
|
+ 'window to trigger a mod warning.',
|
|
|
32
|
+ usage='<count:int>',
|
|
|
33
|
+ min_value=2)
|
|
|
34
|
+ SETTING_JOIN_TIME = CogSetting('jointime', float,
|
|
|
35
|
+ brief='time window length to look for joins',
|
|
|
36
|
+ description='The number of seconds of join history to look ' + \
|
|
|
37
|
+ 'at when counting recent joins. If joincount or more ' + \
|
|
|
38
|
+ 'joins occur within jointime seconds a mod warning is issued.',
|
|
|
39
|
+ usage='<seconds:float>',
|
|
|
40
|
+ min_value=1.0,
|
|
|
41
|
+ max_value=900.0)
|
|
|
42
|
+
|
|
|
43
|
+ STATE_KEY_RECENT_JOINS = "JoinRaidCog.recent_joins"
|
|
|
44
|
+ STATE_KEY_LAST_RAID = "JoinRaidCog.last_raid"
|
|
215
|
45
|
|
|
216
|
46
|
def __init__(self, bot):
|
|
217
|
47
|
super().__init__(bot)
|
|
218
|
|
- self.guild_id_to_context = {} # Guild.id -> GuildContext
|
|
219
|
|
-
|
|
220
|
|
- # -- Config -------------------------------------------------------------
|
|
221
|
|
-
|
|
222
|
|
- def __get_raid_rate(self, guild: Guild) -> tuple:
|
|
223
|
|
- """
|
|
224
|
|
- Returns the join rate configured for this guild.
|
|
225
|
|
- """
|
|
226
|
|
- count: int = Storage.get_config_value(guild, self.STATE_KEY_RAID_COUNT) \
|
|
227
|
|
- or self.get_cog_default('warning_count')
|
|
228
|
|
- seconds: float = Storage.get_config_value(guild, self.STATE_KEY_RAID_SECONDS) \
|
|
229
|
|
- or self.get_cog_default('warning_seconds')
|
|
230
|
|
- return (count, seconds)
|
|
231
|
|
-
|
|
232
|
|
- def __is_enabled(self, guild: Guild) -> bool:
|
|
233
|
|
- """
|
|
234
|
|
- Returns whether join raid detection is enabled in this guild.
|
|
235
|
|
- """
|
|
236
|
|
- return Storage.get_config_value(guild, self.STATE_KEY_ENABLED) \
|
|
237
|
|
- or self.get_cog_default('enabled')
|
|
238
|
|
-
|
|
239
|
|
- # -- Commands -----------------------------------------------------------
|
|
|
48
|
+ self.add_setting(JoinRaidCog.SETTING_ENABLED)
|
|
|
49
|
+ self.add_setting(JoinRaidCog.SETTING_JOIN_COUNT)
|
|
|
50
|
+ self.add_setting(JoinRaidCog.SETTING_JOIN_TIME)
|
|
240
|
51
|
|
|
241
|
52
|
@commands.group(
|
|
242
|
53
|
brief='Manages join raid detection and handling',
|
|
|
@@ -248,257 +59,102 @@ class JoinRaidCog(BaseCog):
|
|
248
|
59
|
if context.invoked_subcommand is None:
|
|
249
|
60
|
await context.send_help()
|
|
250
|
61
|
|
|
251
|
|
- @joinraid.command(
|
|
252
|
|
- name='enable',
|
|
253
|
|
- brief='Enables join raid detection',
|
|
254
|
|
- description='Join raid detection is off by default.',
|
|
255
|
|
- )
|
|
256
|
|
- async def joinraid_enable(self, context: commands.Context):
|
|
257
|
|
- 'Command handler'
|
|
258
|
|
- guild = context.guild
|
|
259
|
|
- Storage.set_config_value(guild, self.STATE_KEY_ENABLED, True)
|
|
260
|
|
- # TODO: Startup tracking if necessary
|
|
261
|
|
- await context.message.reply(
|
|
262
|
|
- CONFIG['success_emoji'] + ' ' +
|
|
263
|
|
- self.__describe_raid_settings(guild, force_enabled_status=True),
|
|
264
|
|
- mention_author=False)
|
|
265
|
|
-
|
|
266
|
|
- @joinraid.command(
|
|
267
|
|
- name='disable',
|
|
268
|
|
- brief='Disables join raid detection',
|
|
269
|
|
- description='Join raid detection is off by default.',
|
|
270
|
|
- )
|
|
271
|
|
- async def joinraid_disable(self, context: commands.Context):
|
|
272
|
|
- 'Command handler'
|
|
273
|
|
- guild = context.guild
|
|
274
|
|
- Storage.set_config_value(guild, self.STATE_KEY_ENABLED, False)
|
|
275
|
|
- # TODO: Tear down tracking if necessary
|
|
276
|
|
- await context.message.reply(
|
|
277
|
|
- CONFIG['success_emoji'] + ' ' +
|
|
278
|
|
- self.__describe_raid_settings(guild, force_enabled_status=True),
|
|
279
|
|
- mention_author=False)
|
|
280
|
|
-
|
|
281
|
|
- @joinraid.command(
|
|
282
|
|
- name='setrate',
|
|
283
|
|
- brief='Sets the rate of joins which triggers a warning to mods',
|
|
284
|
|
- description='Each time a member joins, the join records from the ' +
|
|
285
|
|
- 'previous _x_ seconds are counted up, where _x_ is the number of ' +
|
|
286
|
|
- 'seconds configured by this command. If that count meets or ' +
|
|
287
|
|
- 'exceeds the maximum join count configured by this command then ' +
|
|
288
|
|
- 'a raid is detected and a warning is issued to the mods.',
|
|
289
|
|
- usage='<join_count:int> <seconds:float>',
|
|
290
|
|
- )
|
|
291
|
|
- async def joinraid_setrate(self, context: commands.Context,
|
|
292
|
|
- join_count: int,
|
|
293
|
|
- seconds: float):
|
|
294
|
|
- 'Command handler'
|
|
295
|
|
- guild = context.guild
|
|
296
|
|
- if join_count < self.MIN_JOIN_COUNT:
|
|
297
|
|
- await context.message.reply(
|
|
298
|
|
- CONFIG['warning_emoji'] + ' ' +
|
|
299
|
|
- f'`join_count` must be >= {self.MIN_JOIN_COUNT}',
|
|
300
|
|
- mention_author=False)
|
|
301
|
|
- return
|
|
302
|
|
- if seconds <= 0:
|
|
303
|
|
- await context.message.reply(
|
|
304
|
|
- CONFIG['warning_emoji'] + ' ' +
|
|
305
|
|
- f'`seconds` must be > 0',
|
|
306
|
|
- mention_author=False)
|
|
307
|
|
- return
|
|
308
|
|
- Storage.set_config_values(guild, {
|
|
309
|
|
- self.STATE_KEY_RAID_COUNT: join_count,
|
|
310
|
|
- self.STATE_KEY_RAID_SECONDS: seconds,
|
|
311
|
|
- })
|
|
312
|
|
-
|
|
313
|
|
- await context.message.reply(
|
|
314
|
|
- CONFIG['success_emoji'] + ' ' +
|
|
315
|
|
- self.__describe_raid_settings(guild, force_rate_status=True),
|
|
316
|
|
- mention_author=False)
|
|
317
|
|
-
|
|
318
|
|
- @joinraid.command(
|
|
319
|
|
- name='getrate',
|
|
320
|
|
- brief='Shows the rate of joins which triggers a warning to mods',
|
|
321
|
|
- )
|
|
322
|
|
- async def joinraid_getrate(self, context: commands.Context):
|
|
323
|
|
- 'Command handler'
|
|
324
|
|
- await context.message.reply(
|
|
325
|
|
- CONFIG['info_emoji'] + ' ' +
|
|
326
|
|
- self.__describe_raid_settings(context.guild, force_rate_status=True),
|
|
327
|
|
- mention_author=False)
|
|
328
|
|
-
|
|
329
|
|
- # -- Listeners ----------------------------------------------------------
|
|
330
|
|
-
|
|
331
|
|
- @commands.Cog.listener()
|
|
332
|
|
- async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
|
|
333
|
|
- 'Event handler'
|
|
334
|
|
- if payload.user_id == self.bot.user.id:
|
|
335
|
|
- # Ignore bot's own reactions
|
|
336
|
|
- return
|
|
337
|
|
- member: Member = payload.member
|
|
338
|
|
- if member is None:
|
|
339
|
|
- return
|
|
340
|
|
- guild: Guild = self.bot.get_guild(payload.guild_id)
|
|
341
|
|
- if guild is None:
|
|
342
|
|
- # Possibly a DM
|
|
343
|
|
- return
|
|
344
|
|
- channel: GuildChannel = guild.get_channel(payload.channel_id)
|
|
345
|
|
- if channel is None:
|
|
346
|
|
- # Possibly a DM
|
|
347
|
|
- return
|
|
348
|
|
- message: Message = await channel.fetch_message(payload.message_id)
|
|
349
|
|
- if message is None:
|
|
350
|
|
- # Message deleted?
|
|
351
|
|
- return
|
|
352
|
|
- if message.author.id != self.bot.user.id:
|
|
353
|
|
- # Bot didn't author this
|
|
354
|
|
- return
|
|
355
|
|
- if not member.permissions_in(channel).ban_members:
|
|
356
|
|
- # Not a mod
|
|
357
|
|
- # TODO: Remove reaction?
|
|
358
|
|
- return
|
|
359
|
|
- gc: GuildContext = self.__get_guild_context(guild)
|
|
360
|
|
- raid: JoinRaidRecord = gc.find_raid_for_message_id(payload.message_id)
|
|
361
|
|
- if raid is None:
|
|
362
|
|
- # Either not a warning message or one we stopped tracking
|
|
363
|
|
- return
|
|
364
|
|
- emoji: PartialEmoji = payload.emoji
|
|
365
|
|
- if emoji.name == CONFIG['kick_emoji']:
|
|
366
|
|
- await raid.kick_all()
|
|
367
|
|
- gc.reset_raid(message.created_at)
|
|
368
|
|
- await self.__update_raid_warning(guild, raid)
|
|
369
|
|
- elif emoji.name == CONFIG['ban_emoji']:
|
|
370
|
|
- await raid.ban_all()
|
|
371
|
|
- gc.reset_raid(message.created_at)
|
|
372
|
|
- await self.__update_raid_warning(guild, raid)
|
|
|
62
|
+ async def on_mod_react(self,
|
|
|
63
|
+ bot_message: BotMessage,
|
|
|
64
|
+ reaction: BotMessageReaction,
|
|
|
65
|
+ reacted_by: Member) -> None:
|
|
|
66
|
+ guild: Guild = bot_message.guild
|
|
|
67
|
+ raid: JoinRaidRecord = bot_message.context
|
|
|
68
|
+ if reaction.emoji == CONFIG['kick_emoji']:
|
|
|
69
|
+ to_kick = set(raid.join_members) - raid.kicked_members
|
|
|
70
|
+ for member in to_kick:
|
|
|
71
|
+ await member.kick(
|
|
|
72
|
+ reason=f'Rocketbot: Part of join raid. Kicked by {reacted_by.name}.')
|
|
|
73
|
+ raid.kicked_members |= to_kick
|
|
|
74
|
+ await self.__update_warning_message(raid)
|
|
|
75
|
+ self.log(guild, f'Join raid users kicked by {reacted_by.name}.')
|
|
|
76
|
+ elif reaction.emoji == CONFIG['ban_emoji']:
|
|
|
77
|
+ to_ban = set(raid.join_members) - raid.banned_members
|
|
|
78
|
+ for member in to_ban:
|
|
|
79
|
+ await member.ban(
|
|
|
80
|
+ reason=f'Rocketbot: Part of join raid. Banned by {reacted_by.name}.',
|
|
|
81
|
+ delete_message_days=0)
|
|
|
82
|
+ raid.banned_members |= to_ban
|
|
|
83
|
+ await self.__update_warning_message(raid)
|
|
|
84
|
+ self.log(guild, f'Join raid users banned by {reacted_by.name}')
|
|
373
|
85
|
|
|
374
|
86
|
@commands.Cog.listener()
|
|
375
|
87
|
async def on_member_join(self, member: Member) -> None:
|
|
376
|
88
|
'Event handler'
|
|
377
|
89
|
guild: Guild = member.guild
|
|
378
|
|
- if not self.__is_enabled(guild):
|
|
|
90
|
+ if not self.get_guild_setting(guild, self.SETTING_ENABLED):
|
|
379
|
91
|
return
|
|
380
|
|
- (count, seconds) = self.__get_raid_rate(guild)
|
|
381
|
|
- now = member.joined_at
|
|
382
|
|
- gc: GuildContext = self.__get_guild_context(guild)
|
|
383
|
|
- raid: JoinRaidRecord = gc.current_raid
|
|
384
|
|
- raid.handle_join(member, now, count, seconds)
|
|
385
|
|
- if raid.phase == RaidPhase.JUST_STARTED:
|
|
386
|
|
- await self.__post_raid_warning(guild, raid)
|
|
387
|
|
- elif raid.phase == RaidPhase.CONTINUING:
|
|
388
|
|
- await self.__update_raid_warning(guild, raid)
|
|
389
|
|
- elif raid.phase == RaidPhase.ENDED:
|
|
390
|
|
- # First join that occurred too late to be part of last raid. Join
|
|
391
|
|
- # not added. Start a new raid record and add it there.
|
|
392
|
|
- gc.reset_raid(now)
|
|
393
|
|
- gc.current_raid.handle_join(member, now, count, seconds)
|
|
394
|
|
-
|
|
395
|
|
- # -- Misc ---------------------------------------------------------------
|
|
396
|
|
-
|
|
397
|
|
- def __describe_raid_settings(self,
|
|
398
|
|
- guild: Guild,
|
|
399
|
|
- force_enabled_status=False,
|
|
400
|
|
- force_rate_status=False) -> str:
|
|
401
|
|
- """
|
|
402
|
|
- Creates a Discord message describing the current join raid settings.
|
|
403
|
|
- """
|
|
404
|
|
- enabled = self.__is_enabled(guild)
|
|
405
|
|
- (count, seconds) = self.__get_raid_rate(guild)
|
|
406
|
|
-
|
|
407
|
|
- sentences = []
|
|
408
|
|
-
|
|
409
|
|
- if enabled or force_rate_status:
|
|
410
|
|
- sentences.append(f'Join raids will be detected at {count} or more joins per {seconds} seconds.')
|
|
411
|
|
-
|
|
412
|
|
- if enabled and force_enabled_status:
|
|
413
|
|
- sentences.append('Raid detection enabled.')
|
|
414
|
|
- elif not enabled:
|
|
415
|
|
- sentences.append('Raid detection disabled.')
|
|
416
|
|
-
|
|
417
|
|
- tips = []
|
|
418
|
|
- if enabled or force_rate_status:
|
|
419
|
|
- tips.append('• Use `setrate` subcommand to change detection threshold')
|
|
420
|
|
- if enabled:
|
|
421
|
|
- tips.append('• Use `disable` subcommand to disable detection.')
|
|
|
92
|
+ min_count = self.get_guild_setting(guild, self.SETTING_JOIN_COUNT)
|
|
|
93
|
+ seconds = self.get_guild_setting(guild, self.SETTING_JOIN_TIME)
|
|
|
94
|
+ timespan: timedelta = timedelta(seconds=seconds)
|
|
|
95
|
+
|
|
|
96
|
+ last_raid: JoinRaidContext = Storage.get_state_value(guild, self.STATE_KEY_LAST_RAID)
|
|
|
97
|
+ recent_joins: AgeBoundList = Storage.get_state_value(guild, self.STATE_KEY_RECENT_JOINS)
|
|
|
98
|
+ if recent_joins is None:
|
|
|
99
|
+ recent_joins = AgeBoundList(timespan, lambda i, member : member.joined_at)
|
|
|
100
|
+ Storage.set_state_value(guild, self.STATE_KEY_RECENT_JOINS, recent_joins)
|
|
|
101
|
+ if last_raid:
|
|
|
102
|
+ if member.joined_at - last_raid.last_join_time() > timespan:
|
|
|
103
|
+ # Last raid is over
|
|
|
104
|
+ Storage.set_state_value(guild, self.STATE_KEY_LAST_RAID, None)
|
|
|
105
|
+ recent_joins.append(member)
|
|
|
106
|
+ return
|
|
|
107
|
+ # Add join to existing raid
|
|
|
108
|
+ last_raid.join_members.append(member)
|
|
|
109
|
+ await self.__update_warning_message(last_raid)
|
|
422
|
110
|
else:
|
|
423
|
|
- tips.append('• Use `enable` subcommand to enable detection.')
|
|
424
|
|
-
|
|
425
|
|
- message = ''
|
|
426
|
|
- message += ' '.join(sentences)
|
|
427
|
|
- if len(tips) > 0:
|
|
428
|
|
- message += '\n\n' + ('\n'.join(tips))
|
|
429
|
|
- return message
|
|
430
|
|
-
|
|
431
|
|
- def __get_guild_context(self, guild: Guild) -> GuildContext:
|
|
432
|
|
- """
|
|
433
|
|
- Looks up the GuildContext for the given Guild or creates a new one if
|
|
434
|
|
- one does not yet exist.
|
|
435
|
|
- """
|
|
436
|
|
- gc: GuildContext = self.guild_id_to_context.get(guild.id)
|
|
437
|
|
- if gc is not None:
|
|
438
|
|
- return gc
|
|
439
|
|
- gc = GuildContext(guild.id)
|
|
440
|
|
- gc.join_warning_count = self.get_cog_default('warning_count')
|
|
441
|
|
- gc.join_warning_seconds = self.get_cog_default('warning_seconds')
|
|
442
|
|
-
|
|
443
|
|
- self.guild_id_to_context[guild.id] = gc
|
|
444
|
|
- return gc
|
|
445
|
|
-
|
|
446
|
|
- async def __post_raid_warning(self, guild: Guild, raid: JoinRaidRecord) -> None:
|
|
447
|
|
- """
|
|
448
|
|
- Posts a warning message about the given raid.
|
|
449
|
|
- """
|
|
450
|
|
- (message, can_kick, can_ban) = self.__describe_raid(raid)
|
|
451
|
|
- raid.warning_message = await self.warn(guild, message)
|
|
452
|
|
- if can_kick:
|
|
453
|
|
- await raid.warning_message.add_reaction(CONFIG['kick_emoji'])
|
|
454
|
|
- if can_ban:
|
|
455
|
|
- await raid.warning_message.add_reaction(CONFIG['ban_emoji'])
|
|
456
|
|
- self.log(guild, f'New join raid detected!')
|
|
457
|
|
-
|
|
458
|
|
- async def __update_raid_warning(self, guild: Guild, raid: JoinRaidRecord) -> None:
|
|
459
|
|
- """
|
|
460
|
|
- Updates the existing warning message for a raid.
|
|
461
|
|
- """
|
|
462
|
|
- if raid.warning_message is None:
|
|
|
111
|
+ # Add join to the general, non-raid recent join list
|
|
|
112
|
+ recent_joins.append(member)
|
|
|
113
|
+ if len(recent_joins) >= min_count:
|
|
|
114
|
+ self.log(guild, '\u0007Join raid detected')
|
|
|
115
|
+ last_raid = JoinRaidContext(recent_joins)
|
|
|
116
|
+ Storage.set_state_value(guild, self.STATE_KEY_LAST_RAID, last_raid)
|
|
|
117
|
+ recent_joins.clear()
|
|
|
118
|
+ msg = BotMessage(guild,
|
|
|
119
|
+ text='',
|
|
|
120
|
+ type=BotMessage.TYPE_MOD_WARNING,
|
|
|
121
|
+ context=last_raid)
|
|
|
122
|
+ last_raid.warning_message_ref = weakref.ref(msg)
|
|
|
123
|
+ await self.__update_warning_message(last_raid)
|
|
|
124
|
+ await self.post_message(msg)
|
|
|
125
|
+
|
|
|
126
|
+ async def on_setting_updated(self, guild: Guild, setting: CogSetting) -> None:
|
|
|
127
|
+ if setting is self.SETTING_JOIN_TIME:
|
|
|
128
|
+ seconds = self.get_guild_setting(guild, self.SETTING_JOIN_TIME)
|
|
|
129
|
+ timespan: timedelta = timedelta(seconds=seconds)
|
|
|
130
|
+ recent_joins: AgeBoundList = Storage.get_state_value(guild,
|
|
|
131
|
+ self.STATE_KEY_RECENT_JOINS)
|
|
|
132
|
+ if recent_joins:
|
|
|
133
|
+ recent_joins.max_age = timespan
|
|
|
134
|
+ recent_joins.purge_old_elements()
|
|
|
135
|
+
|
|
|
136
|
+ async def __update_warning_message(self, context: JoinRaidContext) -> None:
|
|
|
137
|
+ if context.warning_message_ref is None:
|
|
463
|
138
|
return
|
|
464
|
|
- (message, can_kick, can_ban) = self.__describe_raid(raid)
|
|
465
|
|
- await self.update_warn(raid.warning_message, message)
|
|
466
|
|
- if not can_kick:
|
|
467
|
|
- await raid.warning_message.clear_reaction(CONFIG['kick_emoji'])
|
|
468
|
|
- if not can_ban:
|
|
469
|
|
- await raid.warning_message.clear_reaction(CONFIG['ban_emoji'])
|
|
470
|
|
-
|
|
471
|
|
- def __describe_raid(self, raid: JoinRaidRecord) -> tuple:
|
|
472
|
|
- """
|
|
473
|
|
- Creates a Discord warning message with details about the given raid.
|
|
474
|
|
- Returns a tuple containing the message text, a flag if any users can
|
|
475
|
|
- still be kicked, and a flag if anyone can still be banned.
|
|
476
|
|
- """
|
|
477
|
|
- message = '🚨 **JOIN RAID DETECTED** 🚨'
|
|
478
|
|
- message += '\nThe following members joined in close succession:\n'
|
|
479
|
|
- any_kickable = False
|
|
480
|
|
- any_bannable = False
|
|
481
|
|
- for join in raid.joins:
|
|
482
|
|
- message += '\n• '
|
|
483
|
|
- if join.is_banned:
|
|
484
|
|
- message += '~~' + join.member.mention + '~~ - banned'
|
|
485
|
|
- elif join.is_kicked:
|
|
486
|
|
- message += '~~' + join.member.mention + '~~ - kicked'
|
|
487
|
|
- any_bannable = True
|
|
|
139
|
+ bot_message = context.warning_message_ref()
|
|
|
140
|
+ if bot_message is None:
|
|
|
141
|
+ return
|
|
|
142
|
+ text = 'JOIN RAID DETECTED\n\n' + \
|
|
|
143
|
+ 'The following members joined in close succession:\n'
|
|
|
144
|
+ for member in context.join_members:
|
|
|
145
|
+ text += '\n• '
|
|
|
146
|
+ if member in context.banned_members:
|
|
|
147
|
+ text += f'~~{member.mention} ({member.id})~~ - banned'
|
|
|
148
|
+ elif member in context.kicked_members:
|
|
|
149
|
+ text += f'~~{member.mention} ({member.id})~~ - kicked'
|
|
488
|
150
|
else:
|
|
489
|
|
- message += join.member.mention
|
|
490
|
|
- any_bannable = True
|
|
491
|
|
- any_kickable = True
|
|
492
|
|
- message += '\n_(list updates automatically)_'
|
|
493
|
|
-
|
|
494
|
|
- message += '\n'
|
|
495
|
|
- if any_kickable:
|
|
496
|
|
- message += f'\nReact to this message with {CONFIG["kick_emoji"]} to kick all these users.'
|
|
497
|
|
- else:
|
|
498
|
|
- message += '\nNo users left to kick.'
|
|
499
|
|
- if any_bannable:
|
|
500
|
|
- message += f'\nReact to this message with {CONFIG["ban_emoji"]} to ban all these users.'
|
|
501
|
|
- else:
|
|
502
|
|
- message += '\nNo users left to ban.'
|
|
503
|
|
-
|
|
504
|
|
- return (message, any_kickable, any_bannable)
|
|
|
151
|
+ text += f'{member.mention} ({member.id})'
|
|
|
152
|
+ text += '\n_(list updates automatically)_'
|
|
|
153
|
+ await bot_message.set_text(text)
|
|
|
154
|
+ member_count = len(context.join_members)
|
|
|
155
|
+ kick_count = len(context.kicked_members)
|
|
|
156
|
+ ban_count = len(context.banned_members)
|
|
|
157
|
+ await bot_message.set_reactions(BotMessageReaction.standard_set(
|
|
|
158
|
+ did_kick=kick_count >= member_count,
|
|
|
159
|
+ did_ban=ban_count >= member_count,
|
|
|
160
|
+ user_count=member_count))
|