Implement GuardDen Discord moderation bot

Features:
- Core moderation: warn, kick, ban, timeout, strike system
- Automod: banned words filter, scam detection, anti-spam, link filtering
- AI moderation: Claude/OpenAI integration, NSFW detection, phishing analysis
- Verification system: button, captcha, math, emoji challenges
- Rate limiting system with configurable scopes
- Event logging: joins, leaves, message edits/deletes, voice activity
- Per-guild configuration with caching
- Docker deployment support

Bug fixes applied:
- Fixed await on session.delete() in guild_config.py
- Fixed memory leak in AI moderation message tracking (use deque)
- Added error handling to bot shutdown
- Added error handling to timeout command
- Removed unused Literal import
- Added prefix validation
- Added image analysis limit (3 per message)
- Fixed test mock for SQLAlchemy model
This commit is contained in:
2026-01-16 19:27:48 +01:00
parent ffe42b6d51
commit 4e16777f25
45 changed files with 5802 additions and 1 deletions

319
README.md
View File

@@ -1,3 +1,320 @@
# GuardDen
GuardDen is a comprehensive Discord moderation bot designed to protect your community while maintaining a warm, welcoming environment. Built with privacy and self-hosting in mind, GuardDen combines AI-powered content filtering with traditional moderation tools to create a safe space for your members.
GuardDen is a comprehensive Discord moderation bot designed to protect your community while maintaining a warm, welcoming environment. Built with privacy and self-hosting in mind, GuardDen combines AI-powered content filtering with traditional moderation tools to create a safe space for your members.
## Features
### Core Moderation
- **Warn, Kick, Ban, Timeout** - Standard moderation commands with logging
- **Strike System** - Configurable point-based system with automatic escalation
- **Moderation History** - Track all actions taken against users
- **Bulk Message Deletion** - Purge up to 100 messages at once
### Automod
- **Banned Words Filter** - Block words/phrases with regex support
- **Scam Detection** - Automatic detection of phishing/scam links
- **Anti-Spam** - Rate limiting, duplicate detection, mass mention protection
- **Link Filtering** - Block Discord invites and suspicious URLs
### AI Moderation
- **Text Analysis** - AI-powered content moderation using Claude or GPT
- **NSFW Image Detection** - Automatic flagging of inappropriate images
- **Phishing Analysis** - AI-enhanced detection of scam URLs
- **Configurable Sensitivity** - Adjust strictness per server (0-100)
### Verification System
- **Multiple Challenge Types** - Button, captcha, math problems, emoji selection
- **Automatic New Member Verification** - Challenge users on join
- **Configurable Verified Role** - Auto-assign role on successful verification
- **Rate Limited** - Prevents verification spam
### Logging
- Member joins/leaves
- Message edits and deletions
- Voice channel activity
- Ban/unban events
- All moderation actions
## Quick Start
### Prerequisites
- Python 3.11+
- PostgreSQL 15+
- Discord Bot Token ([Discord Developer Portal](https://discord.com/developers/applications))
- (Optional) Anthropic or OpenAI API key for AI features
### Docker Deployment (Recommended)
1. Clone the repository:
```bash
git clone https://github.com/yourusername/guardden.git
cd guardden
```
2. Create your environment file:
```bash
cp .env.example .env
# Edit .env and add your Discord token
```
3. Start with Docker Compose:
```bash
docker compose up -d
```
### Local Development
1. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
2. Install dependencies:
```bash
pip install -e ".[dev,ai]"
```
3. Set up environment variables:
```bash
cp .env.example .env
# Edit .env with your configuration
```
4. Start PostgreSQL (or use Docker):
```bash
docker compose up db -d
```
5. Run the bot:
```bash
python -m guardden
```
## Configuration
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `GUARDDEN_DISCORD_TOKEN` | Your Discord bot token | Required |
| `GUARDDEN_DISCORD_PREFIX` | Default command prefix | `!` |
| `GUARDDEN_DATABASE_URL` | PostgreSQL connection URL | `postgresql://guardden:guardden@localhost:5432/guardden` |
| `GUARDDEN_LOG_LEVEL` | Logging level | `INFO` |
| `GUARDDEN_AI_PROVIDER` | AI provider (anthropic/openai/none) | `none` |
| `GUARDDEN_ANTHROPIC_API_KEY` | Anthropic API key (if using Claude) | - |
| `GUARDDEN_OPENAI_API_KEY` | OpenAI API key (if using GPT) | - |
### Per-Guild Settings
Each server can configure:
- Command prefix
- Log channels (general and moderation)
- Welcome channel
- Mute role and verified role
- Automod toggles (spam, links, banned words)
- Strike action thresholds
- AI moderation settings (enabled, sensitivity, NSFW detection)
- Verification settings (type, enabled)
## Commands
### Moderation
| Command | Permission | Description |
|---------|------------|-------------|
| `!warn <user> [reason]` | Kick Members | Warn a user |
| `!strike <user> [points] [reason]` | Kick Members | Add strikes to a user |
| `!strikes <user>` | Kick Members | View user's strikes |
| `!timeout <user> <duration> [reason]` | Moderate Members | Timeout a user (e.g., 1h, 30m, 7d) |
| `!untimeout <user>` | Moderate Members | Remove timeout |
| `!kick <user> [reason]` | Kick Members | Kick a user |
| `!ban <user> [reason]` | Ban Members | Ban a user |
| `!unban <user_id> [reason]` | Ban Members | Unban a user by ID |
| `!purge <amount>` | Manage Messages | Delete multiple messages (max 100) |
| `!modlogs <user>` | Kick Members | View moderation history |
### Configuration (Admin only)
| Command | Description |
|---------|-------------|
| `!config` | View current configuration |
| `!config prefix <prefix>` | Set command prefix |
| `!config logchannel [#channel]` | Set general log channel |
| `!config modlogchannel [#channel]` | Set moderation log channel |
| `!config welcomechannel [#channel]` | Set welcome channel |
| `!config muterole [@role]` | Set mute role |
| `!config automod <true/false>` | Toggle automod |
| `!config antispam <true/false>` | Toggle anti-spam |
| `!config linkfilter <true/false>` | Toggle link filtering |
### Banned Words
| Command | Description |
|---------|-------------|
| `!bannedwords` | List all banned words |
| `!bannedwords add <word> [action] [is_regex]` | Add a banned word |
| `!bannedwords remove <id>` | Remove a banned word by ID |
### Automod
| Command | Description |
|---------|-------------|
| `!automod` | View automod status |
| `!automod test <text>` | Test text against filters |
### AI Moderation (Admin only)
| Command | Description |
|---------|-------------|
| `!ai` | View AI moderation settings |
| `!ai enable` | Enable AI moderation |
| `!ai disable` | Disable AI moderation |
| `!ai sensitivity <0-100>` | Set AI sensitivity level |
| `!ai nsfw <true/false>` | Toggle NSFW image detection |
| `!ai analyze <text>` | Test AI analysis on text |
### Verification (Admin only)
| Command | Description |
|---------|-------------|
| `!verify` | Request verification (for users) |
| `!verify setup` | View verification setup status |
| `!verify enable` | Enable verification for new members |
| `!verify disable` | Disable verification |
| `!verify role @role` | Set the verified role |
| `!verify type <type>` | Set verification type (button/captcha/math/emoji) |
| `!verify test [type]` | Test a verification challenge |
| `!verify reset @user` | Reset verification for a user |
## Project Structure
```
guardden/
├── src/guardden/
│ ├── bot.py # Main bot class
│ ├── config.py # Settings management
│ ├── cogs/ # Discord command groups
│ │ ├── admin.py # Configuration commands
│ │ ├── ai_moderation.py # AI-powered moderation
│ │ ├── automod.py # Automatic moderation
│ │ ├── events.py # Event logging
│ │ ├── moderation.py # Moderation commands
│ │ └── verification.py # Member verification
│ ├── models/ # Database models
│ │ ├── guild.py # Guild settings, banned words
│ │ └── moderation.py # Logs, strikes, notes
│ └── services/ # Business logic
│ ├── ai/ # AI provider implementations
│ ├── automod.py # Content filtering
│ ├── database.py # DB connections
│ ├── guild_config.py # Config caching
│ ├── ratelimit.py # Rate limiting
│ └── verification.py # Verification challenges
├── tests/ # Test suite
├── migrations/ # Database migrations
├── docker-compose.yml # Docker deployment
└── pyproject.toml # Dependencies
```
## Verification System
GuardDen includes a verification system to protect your server from bots and raids.
### Challenge Types
| Type | Description |
|------|-------------|
| `button` | Simple button click (default, easiest) |
| `captcha` | Text-based captcha code entry |
| `math` | Solve a simple math problem |
| `emoji` | Select the correct emoji from options |
### Setup
1. Create a verified role in your server
2. Configure the role permissions (verified members get full access)
3. Set up verification:
```
!verify role @Verified
!verify type captcha
!verify enable
```
### How It Works
1. New member joins the server
2. Bot sends verification challenge via DM (or channel if DMs disabled)
3. Member completes the challenge
4. Bot assigns the verified role
5. Member gains access to the server
## AI Moderation
GuardDen supports AI-powered content moderation using either Anthropic's Claude or OpenAI's GPT models.
### Setup
1. Set the AI provider in your environment:
```bash
GUARDDEN_AI_PROVIDER=anthropic # or "openai"
GUARDDEN_ANTHROPIC_API_KEY=sk-ant-... # if using Claude
GUARDDEN_OPENAI_API_KEY=sk-... # if using OpenAI
```
2. Enable AI moderation per server:
```
!ai enable
!ai sensitivity 50 # 0=lenient, 100=strict
!ai nsfw true # Enable NSFW image detection
```
### Content Categories
The AI analyzes content for:
- **Harassment** - Personal attacks, bullying
- **Hate Speech** - Discrimination, slurs
- **Sexual Content** - Explicit material
- **Violence** - Threats, graphic content
- **Self-Harm** - Suicide/self-injury content
- **Scams** - Phishing, fraud attempts
- **Spam** - Promotional, low-quality content
### How It Works
1. Messages are analyzed by the AI provider
2. Results include confidence scores and severity ratings
3. Actions are taken based on guild sensitivity settings
4. All AI actions are logged to the mod log channel
## Development
### Running Tests
```bash
pytest
pytest -v # Verbose output
pytest tests/test_automod.py # Specific file
pytest -k "test_scam" # Filter by name
```
### Code Quality
```bash
ruff check src tests # Linting
ruff format src tests # Formatting
mypy src # Type checking
```
## License
MIT License - see LICENSE file for details.
## Roadmap
- [x] AI-powered content moderation (Claude/OpenAI integration)
- [x] NSFW image detection
- [x] Verification/captcha system
- [x] Rate limiting
- [ ] Voice channel moderation
- [ ] Web dashboard