-
Notifications
You must be signed in to change notification settings - Fork 186
/
Copy pathauto_mod.py
389 lines (308 loc) · 13.7 KB
/
auto_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
from typing import TYPE_CHECKING, Any, Optional, Union
import attrs
from interactions.client.const import MISSING, Absent, get_logger
from interactions.client.mixins.serialization import DictSerializationMixin
from interactions.client.utils import list_converter, optional
from interactions.client.utils.attr_utils import docs
from interactions.models.discord.base import ClientObject, DiscordObject
from interactions.models.discord.enums import (
AutoModAction,
AutoModEvent,
AutoModTriggerType,
KeywordPresetType,
)
from interactions.models.discord.snowflake import to_snowflake, to_snowflake_list
if TYPE_CHECKING:
from interactions import (
Client,
Guild,
GuildText,
Member,
Message,
Snowflake_Type,
User,
)
__all__ = ("AutoModerationAction", "AutoModRule")
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class BaseAction(DictSerializationMixin):
"""
A base implementation of a moderation action
Attributes:
type: The type of action that was taken
"""
type: AutoModAction = attrs.field(repr=False, converter=AutoModAction)
@classmethod
def from_dict_factory(cls, data: dict) -> "BaseAction":
action_class = ACTION_MAPPING.get(data.get("type"))
if not action_class:
get_logger().error(f"Unknown action type for {data}")
action_class = cls
return action_class.from_dict({"type": data.get("type")} | data["metadata"])
def as_dict(self) -> dict:
data = attrs.asdict(self)
data["metadata"] = {k: data.pop(k) for k, v in data.copy().items() if k != "type"}
return data
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class BaseTrigger(DictSerializationMixin):
"""
A base implementation of an auto-mod trigger
Attributes:
type: The type of event this trigger is for
"""
type: AutoModTriggerType = attrs.field(
converter=AutoModTriggerType, repr=True, metadata=docs("The type of trigger")
)
@classmethod
def _process_dict(cls, data: dict[str, Any]) -> dict[str, Any]:
data = super()._process_dict(data)
if meta := data.get("trigger_metadata"):
for key, val in meta.items():
data[key] = val
return data
@classmethod
def from_dict_factory(cls, data: dict) -> "BaseTrigger":
trigger_class = TRIGGER_MAPPING.get(data.get("trigger_type"))
meta = data.get("trigger_metadata", {})
if not trigger_class:
get_logger().error(f"Unknown trigger type for {data}")
trigger_class = cls
payload = {"type": data.get("trigger_type"), "trigger_metadata": meta}
return trigger_class.from_dict(payload)
def as_dict(self) -> dict:
data = attrs.asdict(self)
data["trigger_metadata"] = {k: data.pop(k) for k, v in data.copy().items() if k != "type"}
data["trigger_type"] = data.pop("type")
return data
def _keyword_converter(filter: str | list[str]) -> list[str]:
return filter if isinstance(filter, list) else [filter]
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class KeywordTrigger(BaseTrigger):
"""A trigger that checks if content contains words from a user defined list of keywords"""
keyword_filter: list[str] = attrs.field(
factory=list,
repr=True,
metadata=docs("Substrings which will be searched for in content"),
converter=_keyword_converter,
)
regex_patterns: list[str] = attrs.field(
factory=list,
repr=True,
metadata=docs("Regular expression patterns which will be matched against content"),
converter=_keyword_converter,
)
allow_list: list[str] = attrs.field(
factory=list,
repr=True,
metadata=docs("Substrings which should not trigger the rule"),
converter=_keyword_converter,
)
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class KeywordPresetTrigger(BaseTrigger):
"""A trigger that checks if content contains words from internal pre-defined wordsets"""
presets: list[KeywordPresetType] = attrs.field(
factory=list,
converter=list_converter(KeywordPresetType),
repr=True,
metadata=docs("The internally pre-defined wordsets which will be searched for in content"),
)
allow_list: str | list[str] = attrs.field(
factory=list,
repr=True,
metadata=docs("Substrings which should not trigger the rule"),
converter=_keyword_converter,
)
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class MentionSpamTrigger(BaseTrigger):
"""A trigger that checks if content contains more unique mentions than allowed"""
mention_total_limit: int = attrs.field(
default=3, repr=True, metadata=docs("The maximum number of mentions allowed")
)
mention_raid_protection_enabled: bool = attrs.field(
repr=True, metadata=docs("Whether to automatically detect mention raids")
)
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class MemberProfileTrigger(BaseTrigger):
"""A trigger that checks if member profile contains words from a user defined list of keywords"""
regex_patterns: list[str] = attrs.field(
factory=list, repr=True, metadata=docs("The regex patterns to check against"), converter=_keyword_converter
)
keyword_filter: str | list[str] = attrs.field(
factory=list, repr=True, metadata=docs("The keywords to check against"), converter=_keyword_converter
)
allow_list: list["Snowflake_Type"] = attrs.field(
factory=list, repr=True, metadata=docs("The roles exempt from this rule"), converter=_keyword_converter
)
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class SpamTrigger(BaseTrigger):
"""A trigger that checks if content represents generic spam"""
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class BlockMessage(BaseAction):
"""blocks the content of a message according to the rule"""
custom_message: Optional[str] = attrs.field(repr=True, default=None)
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class AlertMessage(BaseAction):
"""logs user content to a specified channel"""
channel_id: "Snowflake_Type" = attrs.field(repr=True)
@attrs.define(eq=False, order=False, hash=False, kw_only=False)
class TimeoutUser(BaseAction):
"""timeout user for a specified duration"""
duration_seconds: int = attrs.field(repr=True, default=60)
@attrs.define(eq=False, order=False, hash=False, kw_only=False)
class BlockMemberInteraction(BaseAction):
"""Block a member from using text, voice, or other interactions"""
# this action has no metadata
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class AutoModRule(DiscordObject):
"""A representation of an auto mod rule"""
name: str = attrs.field(
repr=False,
)
"""The name of the rule"""
enabled: bool = attrs.field(repr=False, default=False)
"""whether the rule is enabled"""
actions: list["TYPE_ALL_ACTION"] = attrs.field(repr=False, factory=list)
"""the actions which will execute when the rule is triggered"""
event_type: AutoModEvent = attrs.field(
repr=False,
)
"""the rule event type"""
trigger: "TYPE_ALL_TRIGGER" = attrs.field(
repr=False,
)
"""The trigger for this rule"""
exempt_roles: list["Snowflake_Type"] = attrs.field(repr=False, factory=list, converter=to_snowflake_list)
"""the role ids that should not be affected by the rule (Maximum of 20)"""
exempt_channels: list["Snowflake_Type"] = attrs.field(repr=False, factory=list, converter=to_snowflake_list)
"""the channel ids that should not be affected by the rule (Maximum of 50)"""
_guild_id: "Snowflake_Type" = attrs.field(repr=False, default=MISSING)
"""the guild which this rule belongs to"""
_creator_id: "Snowflake_Type" = attrs.field(repr=False, default=MISSING)
"""the user which first created this rule"""
id: "Snowflake_Type" = attrs.field(repr=False, default=MISSING, converter=optional(to_snowflake))
@classmethod
def _process_dict(cls, data: dict, client: "Client") -> dict:
data = super()._process_dict(data, client)
data["actions"] = [BaseAction.from_dict_factory(d) for d in data["actions"]]
data["trigger"] = BaseTrigger.from_dict_factory(data)
return data
def to_dict(self) -> dict:
data = super().to_dict()
trigger = data.pop("trigger")
data["trigger_type"] = trigger["trigger_type"]
data["trigger_metadata"] = trigger["trigger_metadata"]
return data
@property
def creator(self) -> "Member":
"""The original creator of this rule"""
return self._client.cache.get_member(self._guild_id, self._creator_id)
@property
def guild(self) -> "Guild":
"""The guild this rule belongs to"""
return self._client.cache.get_guild(self._guild_id)
async def delete(self, reason: Absent[str] = MISSING) -> None:
"""
Delete this rule
Args:
reason: The reason for deleting this rule
"""
await self._client.http.delete_auto_moderation_rule(self._guild_id, self.id, reason=reason)
async def modify(
self,
*,
name: Absent[str] = MISSING,
trigger: Absent["TYPE_ALL_TRIGGER"] = MISSING,
trigger_type: Absent[AutoModTriggerType] = MISSING,
trigger_metadata: Absent[dict] = MISSING,
actions: Absent[list["TYPE_ALL_ACTION"]] = MISSING,
exempt_channels: Absent[list["Snowflake_Type"]] = MISSING,
exempt_roles: Absent[list["Snowflake_Type"]] = MISSING,
event_type: Absent[AutoModEvent] = MISSING,
enabled: Absent[bool] = MISSING,
reason: Absent[str] = MISSING,
) -> "AutoModRule":
"""
Modify an existing automod rule.
Args:
name: The name of the rule
trigger: A trigger for this rule
trigger_type: The type trigger for this rule (ignored if trigger specified)
trigger_metadata: Metadata for the trigger (ignored if trigger specified)
actions: A list of actions to take upon triggering
exempt_roles: Roles that ignore this rule
exempt_channels: Channels that ignore this role
enabled: Is this rule enabled?
event_type: The type of event that triggers this rule
reason: The reason for this change
Returns:
The updated rule
"""
if trigger:
_data = trigger.to_dict()
trigger_type = _data["trigger_type"]
trigger_metadata = _data.get("trigger_metadata", {})
out = await self._client.http.modify_auto_moderation_rule(
self._guild_id,
self.id,
name=name,
trigger_type=trigger_type,
trigger_metadata=trigger_metadata,
actions=actions,
exempt_roles=to_snowflake_list(exempt_roles) if exempt_roles is not MISSING else MISSING,
exempt_channels=to_snowflake_list(exempt_channels) if exempt_channels is not MISSING else MISSING,
event_type=event_type,
enabled=enabled,
reason=reason,
)
return AutoModRule.from_dict(out, self._client)
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class AutoModerationAction(ClientObject):
rule_trigger_type: AutoModTriggerType = attrs.field(repr=False, converter=AutoModTriggerType)
rule_id: "Snowflake_Type" = attrs.field(
repr=False,
)
action: "TYPE_ALL_ACTION" = attrs.field(default=MISSING, repr=True)
matched_keyword: str = attrs.field(repr=True)
matched_content: Optional[str] = attrs.field(repr=False, default=None)
content: Optional[str] = attrs.field(repr=False, default=None)
_message_id: Optional["Snowflake_Type"] = attrs.field(repr=False, default=None)
_alert_system_message_id: Optional["Snowflake_Type"] = attrs.field(repr=False, default=None)
_channel_id: Optional["Snowflake_Type"] = attrs.field(repr=False, default=None)
_guild_id: "Snowflake_Type" = attrs.field(
repr=False,
)
_user_id: "Snowflake_Type" = attrs.field(repr=False)
@classmethod
def _process_dict(cls, data: dict, client: "Client") -> dict:
data = super()._process_dict(data, client)
data["action"] = BaseAction.from_dict_factory(data["action"])
return data
@property
def guild(self) -> "Guild":
return self._client.get_guild(self._guild_id)
@property
def channel(self) -> "Optional[GuildText]":
return self._client.get_channel(self._channel_id)
@property
def message(self) -> "Optional[Message]":
return self._client.cache.get_message(self._channel_id, self._message_id)
@property
def user(self) -> "User":
return self._client.cache.get_user(self._user_id)
@property
def member(self) -> "Optional[Member]":
return self._client.cache.get_member(self._guild_id, self._user_id)
ACTION_MAPPING = {
AutoModAction.BLOCK_MESSAGE: BlockMessage,
AutoModAction.ALERT_MESSAGE: AlertMessage,
AutoModAction.TIMEOUT_USER: TimeoutUser,
AutoModAction.BLOCK_MEMBER_INTERACTION: BlockMemberInteraction,
}
TRIGGER_MAPPING = {
AutoModTriggerType.KEYWORD: KeywordTrigger,
AutoModTriggerType.SPAM: SpamTrigger,
AutoModTriggerType.KEYWORD_PRESET: KeywordPresetTrigger,
AutoModTriggerType.MENTION_SPAM: MentionSpamTrigger,
AutoModTriggerType.MEMBER_PROFILE: MemberProfileTrigger,
}
TYPE_ALL_TRIGGER = Union[KeywordTrigger, SpamTrigger, KeywordPresetTrigger, MentionSpamTrigger, MemberProfileTrigger]
TYPE_ALL_ACTION = Union[BlockMessage, AlertMessage, TimeoutUser, BlockMemberInteraction]