4.8 KiB
4.8 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
GuardDen is a Discord moderation bot built with discord.py, PostgreSQL, and optional AI integration (Claude/OpenAI). Self-hosted with Docker support.
Commands
# Install dependencies
pip install -e ".[dev,ai]"
# Run the bot
python -m guardden
# Run tests
pytest
# Run single test
pytest tests/test_verification.py::TestVerificationService::test_verify_correct
# Lint and format
ruff check src tests
ruff format src tests
# Type checking
mypy src
# Docker deployment
docker compose up -d
Architecture
src/guardden/bot.py- Main bot class (GuardDen) extendingcommands.Bot, manages lifecycle and servicessrc/guardden/config.py- Pydantic settings loaded from environment variables (prefix:GUARDDEN_)src/guardden/models/- SQLAlchemy 2.0 async models for PostgreSQLsrc/guardden/services/- Business logic (database, guild config, automod, AI, verification, rate limiting)src/guardden/cogs/- Discord command groups (events, moderation, admin, automod, ai_moderation, verification)
Key Patterns
- All database operations use async SQLAlchemy with
asyncpg - Guild configurations are cached in
GuildConfigService._cache - Discord snowflake IDs stored as
BigIntegerin PostgreSQL - Moderation actions logged to
ModerationLogtable with automatic strike escalation - Environment variables:
GUARDDEN_DISCORD_TOKEN,GUARDDEN_DATABASE_URL
Automod System
AutomodServiceinservices/automod.pyhandles rule-based content filtering- Checks run in order: banned words → scam links → spam → invite links
- Spam tracking uses per-guild, per-user trackers with automatic cleanup
- Scam detection uses compiled regex patterns in
SCAM_PATTERNSlist - Results return
AutomodResultdataclass with actions to take - Whitelist: Users in
GuildSettings.whitelisted_user_idsbypass ALL automod checks - Users with "Manage Messages" permission also bypass automod
AI Moderation System
services/ai/contains provider abstraction and implementationsAIProviderbase class defines interface:moderate_text(),analyze_image(),analyze_phishing()AnthropicProviderandOpenAIProviderimplement the interfaceNullProviderused when AI is disabled (returns empty results)- Factory pattern via
create_ai_provider(provider, api_key) ModerationResultincludes severity scoring based on confidence + category weights- Sensitivity setting (0-100) adjusts thresholds per guild
- NSFW-Only Filtering (default:
True): When enabled, only sexual content is filtered; violence, harassment, etc. are allowed - Filtering controlled by
nsfw_only_filteringfield inGuildSettings - Whitelist: Users in
GuildSettings.whitelisted_user_idsbypass ALL AI moderation checks
Verification System
VerificationServiceinservices/verification.pymanages challenges- Challenge types: button, captcha, math, emoji (via
ChallengeGeneratorclasses) PendingVerificationtracks user challenges with expiry and attempt limits- Discord UI components in
cogs/verification.py:VerifyButton,EmojiButton,CaptchaModal - Background task cleans up expired verifications every 5 minutes
Rate Limiting System
RateLimiterinservices/ratelimit.pyprovides general-purpose rate limiting- Scopes: USER (global), MEMBER (per-guild), CHANNEL, GUILD
@ratelimit()decorator for easy command rate limitingget_rate_limiter()returns singleton instance- Default limits configured for commands, moderation, verification, messages
Notification System
utils/notifications.pycontainssend_moderation_notification()utility- Handles sending moderation warnings to users with DM → in-channel fallback
- In-Channel Warnings (default:
False): Optional PUBLIC channel messages when DMs fail - IMPORTANT: In-channel messages are PUBLIC, visible to all users (Discord API limitation)
- Temporary messages auto-delete after 10 seconds to minimize clutter
- Used by automod, AI moderation, and manual moderation commands
- Controlled by
send_in_channel_warningsfield inGuildSettings - Disabled by default for privacy reasons
Adding New Cogs
- Create file in
src/guardden/cogs/ - Implement
setup(bot)async function - Add cog path to
_load_cogs()inbot.py
Adding New AI Provider
- Create
src/guardden/services/ai/newprovider.py - Implement
AIProviderabstract class - Add to factory in
services/ai/factory.py - Add config option in
config.py
Adding New Challenge Type
- Create new
ChallengeGeneratorsubclass inservices/verification.py - Add to
ChallengeTypeenum - Register in
VerificationService._generators - Create corresponding UI components in
cogs/verification.pyif needed