0
# AutoMod System
1
2
Discord's AutoMod system provides automated content moderation with configurable rules, triggers, and actions. Disnake provides comprehensive support for creating, managing, and monitoring AutoMod rules and their execution.
3
4
## Capabilities
5
6
### AutoMod Actions
7
8
Actions that can be taken when an AutoMod rule is triggered.
9
10
```python { .api }
11
class AutoModAction:
12
def __init__(self, *, type: AutoModActionType, metadata: Optional[AutoModActionMetadata] = None):
13
"""
14
Base AutoMod action.
15
16
Parameters:
17
- type: Type of action to take
18
- metadata: Additional action configuration
19
"""
20
21
@property
22
def type(self) -> AutoModActionType:
23
"""The type of action."""
24
25
class AutoModBlockMessageAction(AutoModAction):
26
def __init__(self, *, custom_message: Optional[str] = None):
27
"""
28
Block the message and optionally show a custom message.
29
30
Parameters:
31
- custom_message: Custom message to show when blocking (optional)
32
"""
33
34
@property
35
def custom_message(self) -> Optional[str]:
36
"""Custom message shown when action triggers."""
37
38
class AutoModSendAlertAction(AutoModAction):
39
def __init__(self, *, channel: Snowflake):
40
"""
41
Send an alert to a specified channel.
42
43
Parameters:
44
- channel: Channel to send alert to
45
"""
46
47
@property
48
def channel_id(self) -> int:
49
"""ID of channel to send alerts to."""
50
51
class AutoModTimeoutAction(AutoModAction):
52
def __init__(self, *, duration: int):
53
"""
54
Timeout the user for a specified duration.
55
56
Parameters:
57
- duration: Timeout duration in seconds (max 2419200 = 28 days)
58
"""
59
60
@property
61
def duration(self) -> int:
62
"""Timeout duration in seconds."""
63
```
64
65
### AutoMod Trigger Metadata
66
67
Configuration for different types of AutoMod triggers.
68
69
```python { .api }
70
class AutoModTriggerMetadata:
71
def __init__(
72
self,
73
*,
74
keyword_filter: Optional[Sequence[str]] = None,
75
regex_patterns: Optional[Sequence[str]] = None,
76
presets: Optional[Sequence[AutoModKeywordPresets]] = None,
77
allow_list: Optional[Sequence[str]] = None,
78
mention_total_limit: Optional[int] = None,
79
mention_raid_protection_enabled: Optional[bool] = None
80
):
81
"""
82
Configure AutoMod trigger behavior.
83
84
Parameters:
85
- keyword_filter: List of keywords to filter
86
- regex_patterns: Regular expression patterns to match
87
- presets: Predefined keyword preset categories
88
- allow_list: Keywords/phrases to exempt from filtering
89
- mention_total_limit: Maximum mentions allowed in a message
90
- mention_raid_protection_enabled: Whether to enable mention raid protection
91
"""
92
93
@property
94
def keyword_filter(self) -> List[str]:
95
"""Keywords to filter."""
96
97
@property
98
def regex_patterns(self) -> List[str]:
99
"""Regex patterns to match."""
100
101
@property
102
def presets(self) -> List[AutoModKeywordPresets]:
103
"""Keyword preset categories."""
104
105
@property
106
def allow_list(self) -> List[str]:
107
"""Allowed keywords/phrases."""
108
109
@property
110
def mention_total_limit(self) -> Optional[int]:
111
"""Maximum mentions allowed."""
112
113
@property
114
def mention_raid_protection_enabled(self) -> Optional[bool]:
115
"""Whether mention raid protection is enabled."""
116
```
117
118
### AutoMod Rules
119
120
Complete AutoMod rule configuration and management.
121
122
```python { .api }
123
class AutoModRule:
124
def __init__(self, *, data: AutoModRulePayload, guild: Guild):
125
"""
126
AutoMod rule instance.
127
128
Parameters:
129
- data: Raw rule data from Discord API
130
- guild: Guild this rule belongs to
131
"""
132
133
@property
134
def id(self) -> int:
135
"""Rule ID."""
136
137
@property
138
def guild(self) -> Guild:
139
"""Guild this rule belongs to."""
140
141
@property
142
def name(self) -> str:
143
"""Rule name."""
144
145
@property
146
def creator(self) -> Optional[Member]:
147
"""User who created this rule."""
148
149
@property
150
def creator_id(self) -> int:
151
"""ID of user who created this rule."""
152
153
@property
154
def event_type(self) -> AutoModEventType:
155
"""Event type that triggers this rule."""
156
157
@property
158
def trigger_type(self) -> AutoModTriggerType:
159
"""Type of trigger for this rule."""
160
161
@property
162
def trigger_metadata(self) -> AutoModTriggerMetadata:
163
"""Trigger configuration."""
164
165
@property
166
def actions(self) -> List[AutoModAction]:
167
"""Actions to take when rule triggers."""
168
169
@property
170
def enabled(self) -> bool:
171
"""Whether this rule is enabled."""
172
173
@property
174
def exempt_roles(self) -> List[Role]:
175
"""Roles exempt from this rule."""
176
177
@property
178
def exempt_channels(self) -> List[GuildChannel]:
179
"""Channels exempt from this rule."""
180
181
async def edit(
182
self,
183
*,
184
name: Optional[str] = None,
185
event_type: Optional[AutoModEventType] = None,
186
trigger_metadata: Optional[AutoModTriggerMetadata] = None,
187
actions: Optional[Sequence[AutoModAction]] = None,
188
enabled: Optional[bool] = None,
189
exempt_roles: Optional[Sequence[Snowflake]] = None,
190
exempt_channels: Optional[Sequence[Snowflake]] = None,
191
reason: Optional[str] = None
192
) -> AutoModRule:
193
"""
194
Edit this AutoMod rule.
195
196
Parameters:
197
- name: New rule name
198
- event_type: New event type
199
- trigger_metadata: New trigger configuration
200
- actions: New actions list
201
- enabled: Whether to enable/disable rule
202
- exempt_roles: Roles to exempt from rule
203
- exempt_channels: Channels to exempt from rule
204
- reason: Reason for audit log
205
206
Returns:
207
Updated AutoModRule instance
208
"""
209
210
async def delete(self, *, reason: Optional[str] = None) -> None:
211
"""
212
Delete this AutoMod rule.
213
214
Parameters:
215
- reason: Reason for audit log
216
"""
217
```
218
219
### AutoMod Action Execution
220
221
Information about AutoMod rule executions and violations.
222
223
```python { .api }
224
class AutoModActionExecution:
225
def __init__(self, *, data: AutoModerationActionExecutionEvent, guild: Guild):
226
"""
227
AutoMod action execution event.
228
229
Parameters:
230
- data: Execution event data
231
- guild: Guild where execution occurred
232
"""
233
234
@property
235
def guild(self) -> Guild:
236
"""Guild where action was executed."""
237
238
@property
239
def rule_id(self) -> int:
240
"""ID of rule that was triggered."""
241
242
@property
243
def rule_trigger_type(self) -> AutoModTriggerType:
244
"""Type of trigger that caused execution."""
245
246
@property
247
def user_id(self) -> int:
248
"""ID of user who triggered the rule."""
249
250
@property
251
def user(self) -> Optional[Member]:
252
"""Member who triggered the rule."""
253
254
@property
255
def channel_id(self) -> Optional[int]:
256
"""ID of channel where rule was triggered."""
257
258
@property
259
def channel(self) -> Optional[Union[GuildChannel, Thread]]:
260
"""Channel where rule was triggered."""
261
262
@property
263
def message_id(self) -> Optional[int]:
264
"""ID of message that triggered the rule."""
265
266
@property
267
def alert_system_message_id(self) -> Optional[int]:
268
"""ID of system alert message."""
269
270
@property
271
def content(self) -> str:
272
"""Content that triggered the rule."""
273
274
@property
275
def matched_keyword(self) -> Optional[str]:
276
"""Keyword that was matched."""
277
278
@property
279
def matched_content(self) -> Optional[str]:
280
"""Content that matched the rule."""
281
```
282
283
## Usage Examples
284
285
### Creating AutoMod Rules
286
287
```python
288
import disnake
289
from disnake import AutoModTriggerMetadata, AutoModBlockMessageAction, AutoModSendAlertAction
290
from disnake.enums import AutoModTriggerType, AutoModEventType
291
292
@bot.event
293
async def on_ready():
294
guild = bot.get_guild(GUILD_ID)
295
296
# Create a keyword filter rule
297
keyword_rule = await guild.create_automod_rule(
298
name="Profanity Filter",
299
event_type=AutoModEventType.message_send,
300
trigger_type=AutoModTriggerType.keyword,
301
trigger_metadata=AutoModTriggerMetadata(
302
keyword_filter=["badword1", "badword2"],
303
allow_list=["goodcontext"]
304
),
305
actions=[
306
AutoModBlockMessageAction(custom_message="Please keep it clean!"),
307
AutoModSendAlertAction(channel=moderation_channel)
308
],
309
enabled=True
310
)
311
312
# Create mention spam protection
313
mention_rule = await guild.create_automod_rule(
314
name="Mention Spam Protection",
315
event_type=AutoModEventType.message_send,
316
trigger_type=AutoModTriggerType.mention_spam,
317
trigger_metadata=AutoModTriggerMetadata(
318
mention_total_limit=5,
319
mention_raid_protection_enabled=True
320
),
321
actions=[
322
AutoModBlockMessageAction(),
323
AutoModTimeoutAction(duration=300) # 5 minute timeout
324
],
325
enabled=True,
326
exempt_roles=[moderator_role]
327
)
328
```
329
330
### Monitoring AutoMod Events
331
332
```python
333
@bot.event
334
async def on_automod_rule_create(rule):
335
print(f"New AutoMod rule created: {rule.name}")
336
337
@bot.event
338
async def on_automod_rule_update(rule):
339
print(f"AutoMod rule updated: {rule.name}")
340
341
@bot.event
342
async def on_automod_rule_delete(rule):
343
print(f"AutoMod rule deleted: {rule.name}")
344
345
@bot.event
346
async def on_automod_action_execution(execution):
347
print(f"AutoMod action executed:")
348
print(f" Rule: {execution.rule_id}")
349
print(f" User: {execution.user}")
350
print(f" Content: {execution.content}")
351
print(f" Matched: {execution.matched_content}")
352
353
# Log to moderation channel
354
if execution.channel:
355
embed = disnake.Embed(
356
title="AutoMod Action",
357
description=f"Rule triggered by {execution.user.mention}",
358
color=disnake.Color.orange()
359
)
360
embed.add_field(name="Content", value=execution.content[:1000])
361
embed.add_field(name="Matched", value=execution.matched_content)
362
363
await log_channel.send(embed=embed)
364
```
365
366
### Managing Existing Rules
367
368
```python
369
@bot.slash_command(description="Manage AutoMod rules")
370
async def automod(inter):
371
pass
372
373
@automod.sub_command(description="List all AutoMod rules")
374
async def list_rules(inter: disnake.ApplicationCommandInteraction):
375
rules = await inter.guild.fetch_automod_rules()
376
377
if not rules:
378
await inter.response.send_message("No AutoMod rules found.")
379
return
380
381
embed = disnake.Embed(title="AutoMod Rules", color=disnake.Color.blue())
382
383
for rule in rules:
384
status = "✅ Enabled" if rule.enabled else "❌ Disabled"
385
embed.add_field(
386
name=f"{rule.name} ({rule.id})",
387
value=f"{status}\nTrigger: {rule.trigger_type.name}",
388
inline=True
389
)
390
391
await inter.response.send_message(embed=embed)
392
393
@automod.sub_command(description="Toggle an AutoMod rule")
394
async def toggle_rule(
395
inter: disnake.ApplicationCommandInteraction,
396
rule_id: int = disnake.Param(description="Rule ID to toggle")
397
):
398
try:
399
rule = await inter.guild.fetch_automod_rule(rule_id)
400
await rule.edit(enabled=not rule.enabled)
401
402
status = "enabled" if not rule.enabled else "disabled"
403
await inter.response.send_message(f"Rule '{rule.name}' has been {status}.")
404
except disnake.NotFound:
405
await inter.response.send_message("Rule not found.", ephemeral=True)
406
```