A modern, type-safe Discord bot built with discord.py, featuring comprehensive command logging, error tracking, and performance metrics powered by MongoDB.
- Slash Commands - Modern Discord interactions with autocomplete and modals
- Database-First Observability - Track every command, error, and metric
- Type-Safe Configuration - Pydantic-powered YAML config with environment variables
- Production Ready - Graceful shutdown, structured logging, and error handling
- Beautiful Console Output - Colored logs and startup banners
- Moderation Tools - Kick, ban, timeout, purge, and more
- Developer Tools - Hot reloading, error viewer, metrics dashboard
- Extensible - Easy-to-add cogs with example implementations
- Python 3.10 or higher
- MongoDB 4.4 or higher (local or Atlas)
- A Discord bot token (Get one here)
Click to expand installation steps
git clone https://github.com/Lagden-Development/rickbot.git
cd rickbotpython -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activatepip install -r requirements.txtCreate a .env file in the project root:
DISCORD_TOKEN=your_bot_token_here
MONGO_URI=mongodb://localhost:27017
β οΈ SECURITY WARNING: Never commit your.envfile to version control! It contains sensitive credentials.
Copy the example configuration:
cp config.yaml.example config.yamlEdit config.yaml and set:
application_id: Your bot's application ID (from Discord Developer Portal)dev_guild_id: (Optional) Your test server ID for instant command syncingowner_ids: List of user IDs who can use owner-only commands
python app.pyThe bot uses environment variables for sensitive data. Set these in your .env file:
| Variable | Description | Required |
|---|---|---|
DISCORD_TOKEN |
Your Discord bot token | β Yes |
MONGO_URI |
MongoDB connection string | β Yes |
The config.yaml file controls all bot behavior. Key sections:
Bot Settings
bot:
token: ${DISCORD_TOKEN} # Bot token (from .env)
application_id: 123456789012345678 # Your app ID
dev_guild_id: null # Test server (optional)
owner_ids: [] # Owner user IDs
status_text: "Ready for commands" # Bot status
status_type: "playing" # playing, watching, listening, competing
sync_commands_on_ready: true # Auto-sync commandsDiscord Intents
intents:
guilds: true # β
Required
guild_messages: true # β
Required for message commands
message_content: false # β οΈ Privileged (not needed for slash-only bots)
members: false # β οΈ Privileged
presences: false # β οΈ PrivilegedNote: Privileged intents must be enabled in the Discord Developer Portal.
MongoDB Settings
mongodb:
uri: ${MONGO_URI} # Connection string
database: "rickbot" # Database name
pool_size: 10 # Connection pool size
timeout_ms: 5000 # Connection timeout
retry_writes: true # Enable retry writesObservability
observability:
track_command_execution: true # Log all commands
track_command_timing: true # Record execution time
track_command_args: true # β οΈ Log arguments (may contain PII)
track_errors: true # Log errors to database
store_error_traceback: true # Store full stack traces
aggregate_metrics_interval: 300 # Metric snapshots every 5 minutesLocal Installation
macOS (Homebrew):
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-communityUbuntu/Debian:
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl start mongodWindows: Download from mongodb.com
MongoDB Atlas (Cloud)
- Create a free cluster at mongodb.com/atlas
- Get your connection string
- Set in
.env:MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/
| Command | Description |
|---|---|
/ping |
Check bot latency |
/info |
View bot information and statistics |
/stats |
Detailed command usage statistics |
/uptime |
Bot uptime and performance metrics |
| Command | Description | Permission |
|---|---|---|
/kick |
Kick a member | Kick Members |
/ban |
Ban a member or user | Ban Members |
/unban |
Unban a user | Ban Members |
/timeout |
Timeout a member | Moderate Members |
/untimeout |
Remove timeout | Moderate Members |
/purge |
Delete multiple messages | Manage Messages |
/slowmode |
Set channel slowmode | Manage Channels |
| Command | Description |
|---|---|
/reload |
Hot reload a cog |
/sync |
Sync slash commands |
/errors |
View error logs from database |
/metrics |
View performance metrics |
/dbstats |
View database statistics |
Project Structure
rickbot/
βββ app.py # Application entry point
βββ config.yaml # Configuration file
βββ .env # Environment variables (create this!)
βββ core/ # Core bot functionality
β βββ bot.py # Main bot class
β βββ config.py # Configuration system
β βββ database.py # MongoDB integration
β βββ models.py # Pydantic models
β βββ observability.py # Command/error tracking
βββ cogs/ # Command modules
β βββ admin.py # Moderation commands
β βββ botinfo.py # Bot information commands
β βββ devtools.py # Developer utilities
β βββ examples/ # Example implementations
βββ helpers/ # Utility functions
β βββ logger.py # Colored logging
β βββ checks.py # Permission checks
β βββ colors.py # Embed colors
β βββ ui.py # UI components
βββ requirements.txt # Python dependencies
Creating a New Cog
- Create a new file in
cogs/(e.g.,mycog.py) - Use this template:
"""
Your cog description here.
"""
import discord
from discord import app_commands
from discord.ext import commands
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from core.bot import RickBot
class MyCog(commands.Cog):
"""Cog description"""
def __init__(self, bot: "RickBot"):
self.bot = bot
@app_commands.command(name="mycommand", description="Command description")
async def my_command(self, interaction: discord.Interaction):
"""Your command implementation"""
await interaction.response.send_message("Hello!")
async def setup(bot: "RickBot"):
"""Load the cog"""
await bot.add_cog(MyCog(bot))- The bot will automatically load it on startup
During development, use /reload <cog_name> to reload cogs without restarting:
/reload cogs.mycog
The project uses Black for code formatting:
black .Click to view database collections
The bot uses these MongoDB collections:
| Collection | Purpose |
|---|---|
command_logs |
Every command execution with timing and args |
error_logs |
Detailed error information with tracebacks |
metrics |
Periodic snapshots of bot performance |
guild_settings |
Per-guild configuration (extensible) |
Use MongoDB Compass or the mongo shell:
mongosh
use rickbot
db.command_logs.find().limit(5).pretty()
db.error_logs.find({resolved: false}).pretty()- Regenerate Discord token (don't use dev token in production)
- Use strong MongoDB credentials
- Never commit
.envorconfig.yamlto version control - Set
track_command_args: falseif handling sensitive data - Enable only required Discord intents
- Set appropriate owner IDs
- Use
dev_guild_id: nullfor global command deployment
- Increase
mongodb.pool_sizefor high-traffic bots (10-50) - Set
aggregate_metrics_intervalto 600+ seconds (10 min) - Monitor memory usage with
/metricscommand - Use MongoDB Atlas for automatic backups and scaling
The bot provides comprehensive observability:
- Command Tracking: Every command is logged with execution time
- Error Tracking: All errors get unique reference codes
- Metrics: Periodic snapshots of performance data
Use the /errors and /metrics commands to view real-time data.
Bot won't start
- Check MongoDB: Ensure MongoDB is running
- Verify credentials: Check your
.envfile - Check config.yaml: Ensure application_id is correct
- Check logs: Look for error messages in the console
Commands not showing
- Check intents: Ensure required intents are enabled
- Sync commands: Use
/syncor restart the bot - Check dev_guild_id: Set to your test server for instant updates
- Wait: Global commands can take up to 1 hour to sync
Permission errors
- Bot role position: Ensure bot's role is above target roles
- Bot permissions: Grant required permissions in server settings
- Command permissions: Check Discord's command permissions settings
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes
- Format code:
black . - Commit:
git commit -m 'Add amazing feature' - Push:
git push origin feature/amazing-feature - Open a Pull Request
- Documentation: Discord.py Docs
- Issues: Open an issue on GitHub
- Discord: Join our support server
Built with:
- discord.py - Discord API wrapper
- motor - Async MongoDB driver
- pydantic - Data validation
- termcolor - Colored terminal output
Made with β€οΈ by Lagden Development