-
Notifications
You must be signed in to change notification settings - Fork 0
Cogs and Commands
AIMod uses a modular cog system to organize functionality. This document provides comprehensive documentation for all cogs, their commands, and features.
# bot.py - Cog loading
COGS = [
"cogs.core_ai_cog",
"cogs.config_cog",
"cogs.human_moderation_cog",
"cogs.logging_cog",
"cogs.statistics",
"cogs.botdetect",
"cogs.raiddefence",
"cogs.appeal_cog",
"cogs.ban_appeal_cog",
"cogs.help",
"cogs.ping",
"cogs.update",
"cogs.credits",
"cogs.hwinfo",
"cogs.shell",
"cogs.messagerate",
"cogs.ai_channel_config_cog",
"cogs.model_management_cog",
"cogs.mod_log_cog",
"cogs.abtuser"
]
async def load_cogs():
for cog in COGS:
try:
await bot.load_extension(cog)
print(f"Loaded {cog}")
except Exception as e:
print(f"Failed to load {cog}: {e}")The heart of AIMod's AI moderation system.
- Automatic message analysis using AI
- Context-aware moderation decisions
- Multi-modal content processing (text, images)
- Configurable AI models per guild
- Appeal system integration
@app_commands.describe(
message="The message to test",
user="User to test as (optional)",
channel="Channel context (optional)"
)
async def aitest(
interaction: discord.Interaction,
message: str,
user: discord.Member = None,
channel: discord.TextChannel = None
):Usage: /aitest message:"Test message here"
Permissions: Administrator
Description: Test how the AI would respond to a specific message
async def aidecisions(interaction: discord.Interaction):Usage: /aidecisions
Permissions: Administrator
Description: View the last 5 AI moderation decisions
@app_commands.describe(
user="User to globally ban",
reason="Reason for the global ban"
)
async def globalban(
interaction: discord.Interaction,
user: discord.User,
reason: str
):Usage: /globalban user:@user reason:"Severe violation"
Permissions: Bot Owner
Description: Ban a user across all servers using the bot
@app_commands.describe(user="User to remove from global ban list")
async def unglobalban(interaction: discord.Interaction, user: discord.User):Usage: /unglobalban user:@user
Permissions: Bot Owner
Description: Remove a user from the global ban list
@commands.Cog.listener(name="on_message")
async def message_listener(self, message: discord.Message):
# Comprehensive message analysis pipeline
# 1. Initial filtering (bots, empty messages, DMs)
# 2. Guild configuration checks
# 3. Channel exclusion checks
# 4. Global ban enforcement
# 5. Content preprocessing
# 6. AI analysis
# 7. Action execution
# 8. Logging and notificationsasync def analyze_message_with_ai(
self,
message: discord.Message,
rules_text: str,
ai_model: str
) -> dict:
"""Analyze message content using AI."""async def _execute_ban(self, message: discord.Message, reason: str, rule_violated: str):
async def _execute_timeout(self, message: discord.Message, reason: str, rule_violated: str, duration: int):
async def _execute_warn(self, message: discord.Message, reason: str, rule_violated: str):Manages guild-specific configuration settings.
@app_commands.describe(
setting="Configuration setting to modify",
value="New value for the setting"
)
async def config(
interaction: discord.Interaction,
setting: str,
value: str = None
):Usage: /config setting:enabled value:true
Permissions: Administrator
Description: View or modify guild configuration
@app_commands.describe(new_prefix="New command prefix")
async def prefix(interaction: discord.Interaction, new_prefix: str):Usage: /prefix new_prefix:!
Permissions: Administrator
Description: Change the bot's command prefix
Core Settings:
-
ENABLED- Enable/disable AI moderation -
PREFIX- Command prefix -
AI_MODEL- AI model to use -
RULES_TEXT- Server rules for AI context
Moderation Settings:
-
AUTO_TIMEOUT_ENABLED- Enable automatic timeouts -
TIMEOUT_DURATION- Default timeout duration -
AUTO_BAN_ENABLED- Enable automatic bans -
BAN_THRESHOLD- Number of infractions before ban
Channel Settings:
-
AI_EXCLUDED_CHANNELS- Channels excluded from moderation -
AI_CHANNEL_RULES- Channel-specific rules
Provides manual moderation tools for administrators.
@app_commands.describe(
user="User to ban",
reason="Reason for the ban",
delete_days="Days of messages to delete (0-7)"
)
async def ban(
interaction: discord.Interaction,
user: discord.Member,
reason: str = "No reason provided",
delete_days: int = 1
):@app_commands.describe(
user="User to unban",
reason="Reason for unbanning"
)
async def unban(
interaction: discord.Interaction,
user: discord.User,
reason: str = "No reason provided"
):@app_commands.describe(
user="User to timeout",
duration="Duration in minutes",
reason="Reason for timeout"
)
async def timeout(
interaction: discord.Interaction,
user: discord.Member,
duration: int,
reason: str = "No reason provided"
):@app_commands.describe(
user="User to kick",
reason="Reason for kicking"
)
async def kick(
interaction: discord.Interaction,
user: discord.Member,
reason: str = "No reason provided"
):@app_commands.describe(
user="User to warn",
reason="Reason for warning"
)
async def warn(
interaction: discord.Interaction,
user: discord.Member,
reason: str
):@app_commands.describe(user="User to check infractions for")
async def infractions(
interaction: discord.Interaction,
user: discord.Member
):Detects and handles bot-like behavior.
@app_commands.describe(
enabled="Enable/disable bot detection",
action="Action to take (timeout/ban/kick)",
duration="Timeout duration in seconds"
)
async def botdetect(
interaction: discord.Interaction,
enabled: bool = None,
action: str = None,
duration: int = None
):Keyword Detection:
- Configurable keyword list
- Pattern matching for common bot phrases
- Whitelist for trusted users/roles
Behavioral Analysis:
- Message frequency analysis
- Repetitive content detection
- Suspicious timing patterns
Configuration Options:
{
"enabled": True,
"keywords": ["discord.gg/", "free nitro", "click here"],
"action": "timeout",
"timeout_duration": 3600,
"log_channel": 123456789,
"whitelist_roles": [987654321],
"whitelist_users": [111222333]
}Protects against coordinated attacks and mass joining.
@app_commands.describe(
enabled="Enable/disable raid defense",
threshold="Number of joins to trigger defense",
timeframe="Timeframe in seconds",
action="Action to take (lockdown/ban/kick)"
)
async def raiddefense(
interaction: discord.Interaction,
enabled: bool = None,
threshold: int = None,
timeframe: int = None,
action: str = None
):Join Rate Monitoring:
- Track member joins per time period
- Configurable thresholds and timeframes
- Automatic lockdown capabilities
Mass Action Detection:
- Detect coordinated message spam
- Identify suspicious account patterns
- Automatic response mechanisms
Lockdown Mode:
- Temporarily restrict new member permissions
- Pause invite creation
- Enhanced monitoring during incidents
Provides comprehensive analytics and usage statistics.
async def stats(interaction: discord.Interaction):Usage: /stats
Description: Display comprehensive server statistics
@app_commands.describe(user="User to get statistics for")
async def userstats(interaction: discord.Interaction, user: discord.Member = None):async def commandstats(interaction: discord.Interaction):Server Analytics:
- Member count trends
- Message activity patterns
- Moderation action statistics
- Command usage metrics
User Analytics:
- Individual user activity
- Infraction history
- Participation metrics
- Role progression
Performance Metrics:
- Bot response times
- Database query performance
- AI analysis metrics
- Error rates and types
Comprehensive event logging and audit trails.
@app_commands.describe(
channel="Channel for logs",
events="Events to log (comma-separated)"
)
async def logging(
interaction: discord.Interaction,
channel: discord.TextChannel = None,
events: str = None
):Moderation Events:
- Bans, kicks, timeouts
- Message deletions
- Role changes
- Channel modifications
User Events:
- Joins and leaves
- Nickname changes
- Avatar updates
- Voice channel activity
Server Events:
- Channel creation/deletion
- Role creation/modification
- Server setting changes
- Invite creation/deletion
Embed Format:
embed = discord.Embed(
title="π¨ User Banned",
color=discord.Color.red(),
timestamp=datetime.utcnow()
)
embed.add_field(name="User", value=f"{user} ({user.id})", inline=True)
embed.add_field(name="Moderator", value=f"{moderator}", inline=True)
embed.add_field(name="Reason", value=reason, inline=False)Handles user appeals for moderation actions.
@app_commands.describe(reason="Reason for your appeal")
async def appeal(interaction: discord.Interaction, reason: str):async def banappeal(ctx: commands.Context):Submission:
- User submits appeal with reason
- System checks for existing appeals
- Creates appeal record in database
- Notifies administrators
Review Process:
- Administrators review appeal
- Can approve, deny, or request more info
- User receives notification of decision
- Actions are automatically applied if approved
Appeal Types:
- Timeout appeals
- Ban appeals
- Warning appeals
- Global ban appeals (special process)
Dynamic help system with categorized commands.
Bot latency and status monitoring.
Bot update and maintenance tools.
Information about bot developers and contributors.
System resource monitoring and diagnostics.
Administrative shell access (owner only).
@commands.command(name="shell", aliases=["sh", "$"])
async def shell_command(self, ctx, *, command):Usage: !shell ls -la
Permissions: Bot Owner Only
Description: Execute system commands (dangerous - owner only)
Message rate limiting and spam protection.
@app_commands.describe(
enabled="Enable/disable rate limiting",
max_messages="Maximum messages per timeframe",
timeframe="Timeframe in seconds"
)
async def messagerate(
interaction: discord.Interaction,
enabled: bool = None,
max_messages: int = None,
timeframe: int = None
):Rate Limiting Features:
- Per-user message rate tracking
- Configurable limits and timeframes
- Automatic timeout for violations
- Whitelist for trusted roles
- Escalating penalties for repeat offenders
Channel-specific AI moderation configuration.
@app_commands.describe(channel="Channel to exclude from AI moderation")
async def exclude_channel(
interaction: discord.Interaction,
channel: discord.TextChannel
):@app_commands.describe(channel="Channel to include in AI moderation")
async def include_channel(
interaction: discord.Interaction,
channel: discord.TextChannel
):@app_commands.describe(
channel="Channel to set rules for",
rules="Custom rules for this channel"
)
async def set_channel_rules(
interaction: discord.Interaction,
channel: discord.TextChannel,
rules: str
):AI model configuration and management.
@app_commands.describe(
model="AI model to use",
api_key="API key for the model provider"
)
async def set_ai_model(
interaction: discord.Interaction,
model: str,
api_key: str = None
):Supported Models:
-
github_copilot/gpt-4.1- GitHub Copilot (default) -
openai/gpt-4- OpenAI GPT-4 -
anthropic/claude-3- Anthropic Claude -
google/gemini-pro- Google Gemini
Advanced moderation logging with webhook integration.
@app_commands.describe(
webhook_url="Webhook URL for external logging",
enabled="Enable/disable mod logging"
)
async def modlog(
interaction: discord.Interaction,
webhook_url: str = None,
enabled: bool = None
):Detailed user information and analysis.
@app_commands.describe(user="User to get information about")
async def about_user(
interaction: discord.Interaction,
user: discord.Member
):Information Provided:
- Account creation date
- Server join date
- Role information
- Permission analysis
- Activity statistics
- Infraction history
- Trust score calculation
Multiple cogs can respond to the same events:
# Core AI Cog - Analyzes message
@commands.Cog.listener()
async def on_message(self, message):
await self.analyze_message(message)
# Logging Cog - Logs message
@commands.Cog.listener()
async def on_message(self, message):
await self.log_message(message)
# Statistics Cog - Tracks metrics
@commands.Cog.listener()
async def on_message(self, message):
await self.update_stats(message)Cogs can interact through the bot instance:
# Get configuration from config cog
config_cog = self.bot.get_cog("Configuration")
setting = await config_cog.get_setting(guild_id, "AI_ENABLED")
# Trigger logging from another cog
logging_cog = self.bot.get_cog("Logging")
await logging_cog.log_moderation_action(action_data)Common resources are managed centrally:
# Shared database connection
from database.connection import get_connection
# Shared cache
from database.cache import get_cache, set_cache
# Shared configuration
from cogs.aimod_helpers.config_manager import get_guild_config_asyncNext: Configuration System - Detailed configuration management and options