CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-disnake

A modern, easy-to-use, feature-rich async-ready API wrapper for Discord written in Python

Pending
Overview
Eval results
Files

automod.mddocs/

AutoMod System

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.

Capabilities

AutoMod Actions

Actions that can be taken when an AutoMod rule is triggered.

class AutoModAction:
    def __init__(self, *, type: AutoModActionType, metadata: Optional[AutoModActionMetadata] = None):
        """
        Base AutoMod action.
        
        Parameters:
        - type: Type of action to take
        - metadata: Additional action configuration
        """

    @property
    def type(self) -> AutoModActionType:
        """The type of action."""

class AutoModBlockMessageAction(AutoModAction):
    def __init__(self, *, custom_message: Optional[str] = None):
        """
        Block the message and optionally show a custom message.
        
        Parameters:
        - custom_message: Custom message to show when blocking (optional)
        """

    @property
    def custom_message(self) -> Optional[str]:
        """Custom message shown when action triggers."""

class AutoModSendAlertAction(AutoModAction):
    def __init__(self, *, channel: Snowflake):
        """
        Send an alert to a specified channel.
        
        Parameters:
        - channel: Channel to send alert to
        """

    @property  
    def channel_id(self) -> int:
        """ID of channel to send alerts to."""

class AutoModTimeoutAction(AutoModAction):
    def __init__(self, *, duration: int):
        """
        Timeout the user for a specified duration.
        
        Parameters:
        - duration: Timeout duration in seconds (max 2419200 = 28 days)
        """

    @property
    def duration(self) -> int:
        """Timeout duration in seconds."""

AutoMod Trigger Metadata

Configuration for different types of AutoMod triggers.

class AutoModTriggerMetadata:
    def __init__(
        self,
        *,
        keyword_filter: Optional[Sequence[str]] = None,
        regex_patterns: Optional[Sequence[str]] = None,
        presets: Optional[Sequence[AutoModKeywordPresets]] = None,
        allow_list: Optional[Sequence[str]] = None,
        mention_total_limit: Optional[int] = None,
        mention_raid_protection_enabled: Optional[bool] = None
    ):
        """
        Configure AutoMod trigger behavior.
        
        Parameters:
        - keyword_filter: List of keywords to filter
        - regex_patterns: Regular expression patterns to match
        - presets: Predefined keyword preset categories
        - allow_list: Keywords/phrases to exempt from filtering
        - mention_total_limit: Maximum mentions allowed in a message
        - mention_raid_protection_enabled: Whether to enable mention raid protection
        """

    @property
    def keyword_filter(self) -> List[str]:
        """Keywords to filter."""

    @property
    def regex_patterns(self) -> List[str]:
        """Regex patterns to match."""

    @property
    def presets(self) -> List[AutoModKeywordPresets]:
        """Keyword preset categories."""

    @property
    def allow_list(self) -> List[str]:
        """Allowed keywords/phrases."""

    @property
    def mention_total_limit(self) -> Optional[int]:
        """Maximum mentions allowed."""

    @property
    def mention_raid_protection_enabled(self) -> Optional[bool]:
        """Whether mention raid protection is enabled."""

AutoMod Rules

Complete AutoMod rule configuration and management.

class AutoModRule:
    def __init__(self, *, data: AutoModRulePayload, guild: Guild):
        """
        AutoMod rule instance.
        
        Parameters:
        - data: Raw rule data from Discord API
        - guild: Guild this rule belongs to
        """

    @property
    def id(self) -> int:
        """Rule ID."""

    @property
    def guild(self) -> Guild:
        """Guild this rule belongs to."""

    @property
    def name(self) -> str:
        """Rule name."""

    @property
    def creator(self) -> Optional[Member]:
        """User who created this rule."""

    @property
    def creator_id(self) -> int:
        """ID of user who created this rule."""

    @property
    def event_type(self) -> AutoModEventType:
        """Event type that triggers this rule."""

    @property
    def trigger_type(self) -> AutoModTriggerType:
        """Type of trigger for this rule."""

    @property
    def trigger_metadata(self) -> AutoModTriggerMetadata:
        """Trigger configuration."""

    @property
    def actions(self) -> List[AutoModAction]:
        """Actions to take when rule triggers."""

    @property
    def enabled(self) -> bool:
        """Whether this rule is enabled."""

    @property
    def exempt_roles(self) -> List[Role]:
        """Roles exempt from this rule."""

    @property
    def exempt_channels(self) -> List[GuildChannel]:
        """Channels exempt from this rule."""

    async def edit(
        self,
        *,
        name: Optional[str] = None,
        event_type: Optional[AutoModEventType] = None,
        trigger_metadata: Optional[AutoModTriggerMetadata] = None,
        actions: Optional[Sequence[AutoModAction]] = None,
        enabled: Optional[bool] = None,
        exempt_roles: Optional[Sequence[Snowflake]] = None,
        exempt_channels: Optional[Sequence[Snowflake]] = None,
        reason: Optional[str] = None
    ) -> AutoModRule:
        """
        Edit this AutoMod rule.
        
        Parameters:
        - name: New rule name
        - event_type: New event type
        - trigger_metadata: New trigger configuration
        - actions: New actions list
        - enabled: Whether to enable/disable rule
        - exempt_roles: Roles to exempt from rule
        - exempt_channels: Channels to exempt from rule
        - reason: Reason for audit log
        
        Returns:
        Updated AutoModRule instance
        """

    async def delete(self, *, reason: Optional[str] = None) -> None:
        """
        Delete this AutoMod rule.
        
        Parameters:
        - reason: Reason for audit log
        """

AutoMod Action Execution

Information about AutoMod rule executions and violations.

class AutoModActionExecution:
    def __init__(self, *, data: AutoModerationActionExecutionEvent, guild: Guild):
        """
        AutoMod action execution event.
        
        Parameters:
        - data: Execution event data
        - guild: Guild where execution occurred
        """

    @property
    def guild(self) -> Guild:
        """Guild where action was executed."""

    @property
    def rule_id(self) -> int:
        """ID of rule that was triggered."""

    @property
    def rule_trigger_type(self) -> AutoModTriggerType:
        """Type of trigger that caused execution."""

    @property
    def user_id(self) -> int:
        """ID of user who triggered the rule."""

    @property
    def user(self) -> Optional[Member]:
        """Member who triggered the rule."""

    @property
    def channel_id(self) -> Optional[int]:
        """ID of channel where rule was triggered."""

    @property
    def channel(self) -> Optional[Union[GuildChannel, Thread]]:
        """Channel where rule was triggered."""

    @property
    def message_id(self) -> Optional[int]:
        """ID of message that triggered the rule."""

    @property
    def alert_system_message_id(self) -> Optional[int]:
        """ID of system alert message."""

    @property
    def content(self) -> str:
        """Content that triggered the rule."""

    @property
    def matched_keyword(self) -> Optional[str]:
        """Keyword that was matched."""

    @property
    def matched_content(self) -> Optional[str]:
        """Content that matched the rule."""

Usage Examples

Creating AutoMod Rules

import disnake
from disnake import AutoModTriggerMetadata, AutoModBlockMessageAction, AutoModSendAlertAction
from disnake.enums import AutoModTriggerType, AutoModEventType

@bot.event
async def on_ready():
    guild = bot.get_guild(GUILD_ID)
    
    # Create a keyword filter rule
    keyword_rule = await guild.create_automod_rule(
        name="Profanity Filter",
        event_type=AutoModEventType.message_send,
        trigger_type=AutoModTriggerType.keyword,
        trigger_metadata=AutoModTriggerMetadata(
            keyword_filter=["badword1", "badword2"],
            allow_list=["goodcontext"]
        ),
        actions=[
            AutoModBlockMessageAction(custom_message="Please keep it clean!"),
            AutoModSendAlertAction(channel=moderation_channel)
        ],
        enabled=True
    )
    
    # Create mention spam protection
    mention_rule = await guild.create_automod_rule(
        name="Mention Spam Protection",
        event_type=AutoModEventType.message_send,
        trigger_type=AutoModTriggerType.mention_spam,
        trigger_metadata=AutoModTriggerMetadata(
            mention_total_limit=5,
            mention_raid_protection_enabled=True
        ),
        actions=[
            AutoModBlockMessageAction(),
            AutoModTimeoutAction(duration=300)  # 5 minute timeout
        ],
        enabled=True,
        exempt_roles=[moderator_role]
    )

Monitoring AutoMod Events

@bot.event
async def on_automod_rule_create(rule):
    print(f"New AutoMod rule created: {rule.name}")

@bot.event  
async def on_automod_rule_update(rule):
    print(f"AutoMod rule updated: {rule.name}")

@bot.event
async def on_automod_rule_delete(rule):
    print(f"AutoMod rule deleted: {rule.name}")

@bot.event
async def on_automod_action_execution(execution):
    print(f"AutoMod action executed:")
    print(f"  Rule: {execution.rule_id}")
    print(f"  User: {execution.user}")
    print(f"  Content: {execution.content}")
    print(f"  Matched: {execution.matched_content}")
    
    # Log to moderation channel
    if execution.channel:
        embed = disnake.Embed(
            title="AutoMod Action",
            description=f"Rule triggered by {execution.user.mention}",
            color=disnake.Color.orange()
        )
        embed.add_field(name="Content", value=execution.content[:1000])
        embed.add_field(name="Matched", value=execution.matched_content)
        
        await log_channel.send(embed=embed)

Managing Existing Rules

@bot.slash_command(description="Manage AutoMod rules")
async def automod(inter):
    pass

@automod.sub_command(description="List all AutoMod rules")
async def list_rules(inter: disnake.ApplicationCommandInteraction):
    rules = await inter.guild.fetch_automod_rules()
    
    if not rules:
        await inter.response.send_message("No AutoMod rules found.")
        return
    
    embed = disnake.Embed(title="AutoMod Rules", color=disnake.Color.blue())
    
    for rule in rules:
        status = "✅ Enabled" if rule.enabled else "❌ Disabled"
        embed.add_field(
            name=f"{rule.name} ({rule.id})",
            value=f"{status}\nTrigger: {rule.trigger_type.name}",
            inline=True
        )
    
    await inter.response.send_message(embed=embed)

@automod.sub_command(description="Toggle an AutoMod rule")
async def toggle_rule(
    inter: disnake.ApplicationCommandInteraction,
    rule_id: int = disnake.Param(description="Rule ID to toggle")
):
    try:
        rule = await inter.guild.fetch_automod_rule(rule_id)
        await rule.edit(enabled=not rule.enabled)
        
        status = "enabled" if not rule.enabled else "disabled"
        await inter.response.send_message(f"Rule '{rule.name}' has been {status}.")
    except disnake.NotFound:
        await inter.response.send_message("Rule not found.", ephemeral=True)

Install with Tessl CLI

npx tessl i tessl/pypi-disnake

docs

application-commands.md

automod.md

channels-messaging.md

client-bot.md

command-framework.md

error-handling.md

events-gateway.md

guild-management.md

index.md

interactions-ui.md

localization-i18n.md

permissions-security.md

polls.md

users-members.md

voice-audio.md

tile.json