Cogs and Commands - openguard-bot/openguard GitHub Wiki
Cogs and Commands
AIMod uses a modular cog system to organize functionality. This document provides comprehensive documentation for all cogs, their commands, and features.
🧩 Cog Architecture
Cog Loading System
# 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}")
core_ai_cog.py
)
🤖 Core AI Cog (The heart of AIMod's AI moderation system.
Key Features
- Automatic message analysis using AI
- Context-aware moderation decisions
- Multi-modal content processing (text, images)
- Configurable AI models per guild
- Appeal system integration
Commands
/aitest
- Test AI Moderation
@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
/aidecisions
- View Recent AI Decisions
async def aidecisions(interaction: discord.Interaction):
Usage: /aidecisions
Permissions: Administrator
Description: View the last 5 AI moderation decisions
/globalban
- Global Ban Management
@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
/unglobalban
- Remove Global Ban
@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
Event Listeners
Message Analysis
@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 notifications
Helper Methods
AI Analysis
async def analyze_message_with_ai(
self,
message: discord.Message,
rules_text: str,
ai_model: str
) -> dict:
"""Analyze message content using AI."""
Action Execution
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):
config_cog.py
)
⚙️ Configuration Cog (Manages guild-specific configuration settings.
Commands
/config
- Configuration Management
@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
/prefix
- Set Command Prefix
@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
Configuration Options
Core Settings:
ENABLED
- Enable/disable AI moderationPREFIX
- Command prefixAI_MODEL
- AI model to useRULES_TEXT
- Server rules for AI context
Moderation Settings:
AUTO_TIMEOUT_ENABLED
- Enable automatic timeoutsTIMEOUT_DURATION
- Default timeout durationAUTO_BAN_ENABLED
- Enable automatic bansBAN_THRESHOLD
- Number of infractions before ban
Channel Settings:
AI_EXCLUDED_CHANNELS
- Channels excluded from moderationAI_CHANNEL_RULES
- Channel-specific rules
human_moderation_cog.py
)
🛡️ Human Moderation Cog (Provides manual moderation tools for administrators.
Commands
/ban
- Ban User
@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
):
/unban
- Unban User
@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"
):
/timeout
- Timeout User
@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"
):
/kick
- Kick User
@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"
):
/warn
- Warn User
@app_commands.describe(
user="User to warn",
reason="Reason for warning"
)
async def warn(
interaction: discord.Interaction,
user: discord.Member,
reason: str
):
/infractions
- View User Infractions
@app_commands.describe(user="User to check infractions for")
async def infractions(
interaction: discord.Interaction,
user: discord.Member
):
botdetect.py
)
🔍 Bot Detection Cog (Detects and handles bot-like behavior.
Commands
/botdetect
- Configure Bot Detection
@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
):
Detection Methods
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]
}
raiddefence.py
)
🛡️ Raid Defense Cog (Protects against coordinated attacks and mass joining.
Commands
/raiddefense
- Configure Raid Defense
@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
):
Protection Features
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
statistics.py
)
📊 Statistics Cog (Provides comprehensive analytics and usage statistics.
Commands
/stats
- Server Statistics
async def stats(interaction: discord.Interaction):
Usage: /stats
Description: Display comprehensive server statistics
/userstats
- User Statistics
@app_commands.describe(user="User to get statistics for")
async def userstats(interaction: discord.Interaction, user: discord.Member = None):
/commandstats
- Command Usage Statistics
async def commandstats(interaction: discord.Interaction):
Analytics Features
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
logging_cog.py
)
📝 Logging Cog (Comprehensive event logging and audit trails.
Commands
/logging
- Configure Logging
@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
):
Logged Events
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
Log Formats
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)
appeal_cog.py
, ban_appeal_cog.py
)
🎯 Appeal System (Handles user appeals for moderation actions.
Commands
/appeal
- Submit Appeal
@app_commands.describe(reason="Reason for your appeal")
async def appeal(interaction: discord.Interaction, reason: str):
/banappeal
- Appeal Ban (DM Command)
async def banappeal(ctx: commands.Context):
Appeal Process
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)
🔧 Utility Cogs
help.py
)
Help Cog (Dynamic help system with categorized commands.
ping.py
)
Ping Cog (Bot latency and status monitoring.
update.py
)
Update Cog (Bot update and maintenance tools.
credits.py
)
Credits Cog (Information about bot developers and contributors.
hwinfo.py
)
Hardware Info Cog (System resource monitoring and diagnostics.
shell.py
)
Shell Cog (Administrative shell access (owner only).
/shell
- Execute Shell Commands
@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)
messagerate.py
)
Message Rate Cog (Message rate limiting and spam protection.
/messagerate
- Configure Rate Limiting
@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
ai_channel_config_cog.py
)
AI Channel Config Cog (Channel-specific AI moderation configuration.
/aichannel exclude
- Exclude Channel
@app_commands.describe(channel="Channel to exclude from AI moderation")
async def exclude_channel(
interaction: discord.Interaction,
channel: discord.TextChannel
):
/aichannel include
- Include Channel
@app_commands.describe(channel="Channel to include in AI moderation")
async def include_channel(
interaction: discord.Interaction,
channel: discord.TextChannel
):
/aichannel setrules
- Set Channel Rules
@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
):
model_management_cog.py
)
Model Management Cog (AI model configuration and management.
/aimodel
- Configure AI Model
@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-4anthropic/claude-3
- Anthropic Claudegoogle/gemini-pro
- Google Gemini
mod_log_cog.py
)
Mod Log Cog (Advanced moderation logging with webhook integration.
/modlog
- Configure Moderation Logging
@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
):
abtuser.py
)
About User Cog (Detailed user information and analysis.
/abtuser
- User Information
@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
🔄 Cog Interaction Patterns
Event Coordination
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)
Cross-Cog Communication
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)
Shared Resources
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_async
Next: Configuration System - Detailed configuration management and options