RickBot handles sensitive data including Discord bot tokens, MongoDB credentials, and potentially user data. This document outlines security best practices and guidelines.
DO NOT open public issues for security vulnerabilities.
Instead, please report security issues privately:
- Email security concerns to the repository maintainers
- Include detailed information about the vulnerability
- Allow reasonable time for a fix before public disclosure
Critical: Your Discord bot token provides full access to your bot account.
- NEVER commit your token to version control
- NEVER share your token publicly (Discord, forums, screenshots, etc.)
- NEVER hardcode tokens in your source code
- ALWAYS use environment variables (
.envfile) - ALWAYS regenerate tokens if exposed
- ROTATE tokens periodically (every 90 days recommended)
✅ CORRECT:
# .env file (in .gitignore)
DISCORD_TOKEN=your_token_here# config.yaml
bot:
token: ${DISCORD_TOKEN} # References environment variable❌ INCORRECT:
# NEVER DO THIS!
token = "MTQyODg5NjE4NDk1MjQyMjU0Mg.G6tZ7g...."- Immediately go to Discord Developer Portal
- Navigate to your application → Bot
- Click "Regenerate" next to the token
- Update your
.envfile with the new token - Restart your bot
- Review audit logs for unauthorized actions
MongoDB credentials provide access to all your bot's data.
- Use strong, unique passwords (20+ characters)
- Enable authentication on MongoDB
- Use IP whitelisting when possible
- Enable SSL/TLS for connections
- Create dedicated database users per environment
- Grant minimum required permissions (principle of least privilege)
- Rotate credentials every 90 days
✅ CORRECT:
# .env file
MONGO_URI=mongodb://username:password@localhost:27017/dbname❌ INCORRECT:
# config.yaml - NEVER put credentials directly here!
mongodb:
uri: "mongodb://admin:password123@localhost:27017"If using MongoDB Atlas:
- Enable IP Access List (whitelist only your server IPs)
- Use VPC Peering for production deployments
- Enable Encryption at Rest
- Enable Audit Logs
- Use M10+ clusters for production (automatic backups)
- Enable Two-Factor Authentication on Atlas account
The .env file contains all sensitive credentials.
# Correct file permissions (Linux/macOS)
chmod 600 .env # Only owner can read/writeVerify .env is in .gitignore:
# Environment files
.env
.env.local
.env.production
# Configuration (may contain app IDs)
config.yamlProvide .env.example and config.yaml.example with no real credentials:
# .env.example
DISCORD_TOKEN=your_discord_bot_token_here
MONGO_URI=mongodb://username:password@localhost:27017/databaseThe bot logs command executions which may contain PII:
- User IDs
- Usernames
- Guild IDs
- Command arguments (could be anything!)
observability:
track_command_args: true # ⚠️ SET TO FALSE IF HANDLING SENSITIVE DATAIf your bot handles sensitive data (passwords, emails, etc.), set track_command_args: false.
Implement data retention policies:
// Example MongoDB TTL index (30 days)
db.command_logs.createIndex(
{ "executed_at": 1 },
{ expireAfterSeconds: 2592000 } // 30 days
)If your bot has European users:
- Provide a privacy policy
- Implement data deletion requests
- Allow users to export their data
- Obtain consent for data collection
- Encrypt sensitive data at rest
Error logs include:
- Stack traces (may reveal code internals)
- User IDs and interaction data
- Potentially sensitive arguments
- Set
store_error_traceback: falsein production if concerned about leaks - Regularly review and purge error logs
- Restrict access to
/errorscommand (owner-only)
Request only the intents you need.
These require explicit approval from Discord:
| Intent | Risk Level | Use Case |
|---|---|---|
message_content |
HIGH | Reading message content |
members |
MEDIUM | Accessing member data |
presences |
MEDIUM | Tracking online status |
Note: Slash-command-only bots DO NOT need message_content intent.
intents:
message_content: false # Only enable if absolutely necessary
members: false # Only enable for member-specific features
presences: false # Only enable for status trackingRestrict dangerous commands:
@app_commands.command()
@app_commands.default_permissions(administrator=True)
async def dangerous_command(self, interaction):
# Only admins can see/use this
passUse the @is_owner() check:
from helpers.checks import is_owner
@app_commands.command()
@is_owner()
async def reload(self, interaction):
# Only bot owners can use this
passAlways validate user input:
@app_commands.command()
async def ban(self, interaction, user_id: str):
# Validate input
try:
user_id_int = int(user_id)
if user_id_int < 0:
raise ValueError("Invalid user ID")
except ValueError:
await interaction.response.send_message("❌ Invalid user ID!")
return
# Proceed with ban...Discord.py handles API rate limiting, but implement application-level limits for resource-intensive operations:
from discord.ext import commands
@commands.cooldown(1, 60, commands.BucketType.user)
@app_commands.command()
async def expensive_command(self, interaction):
# Limited to once per minute per user
pass- Regenerate all credentials (fresh tokens/passwords for production)
- Verify
.envandconfig.yamlare in.gitignore - Set
track_command_args: falseif handling sensitive data - Enable only required Discord intents
- Set appropriate owner IDs in config
- Use production MongoDB with authentication
- Enable MongoDB SSL/TLS
- Implement IP whitelisting
- Set up automated backups
- Configure monitoring and alerts
- Review and test error handling
- Implement logging rotation
- Set up firewall rules
- Use reverse proxy (if applicable)
- Enable HTTPS for webhooks (if applicable)
Use separate environments for development, staging, and production:
# Development
.env.development
# Staging
.env.staging
# Production
.env.productionNEVER use production credentials in development!
Only expose necessary ports:
- MongoDB:
27017(localhost only or IP-whitelisted) - HTTPS:
443(if using webhooks)
# Example UFW rules (Ubuntu)
sudo ufw default deny incoming
sudo ufw allow ssh
sudo ufw enableUse a process manager to automatically restart the bot:
systemd (Linux):
[Unit]
Description=RickBot Discord Bot
After=network.target
[Service]
Type=simple
User=botuser
WorkingDirectory=/opt/rickbot
Environment="PATH=/opt/rickbot/.venv/bin"
ExecStart=/opt/rickbot/.venv/bin/python app.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.targetPM2 (Cross-platform):
pm2 start app.py --name rickbot --interpreter python3
pm2 save
pm2 startupImplement monitoring for:
- Bot uptime
- Memory usage
- Error rates
- Command execution times
- Database connection health
- Unauthorized access attempts
Use the built-in /metrics and /errors commands for real-time monitoring.
Keep dependencies up to date:
pip list --outdated
pip install --upgrade <package>Use tools to scan for vulnerabilities:
# Install safety
pip install safety
# Scan dependencies
safety check- Review all code changes for security issues
- Never execute arbitrary code from users
- Sanitize all user inputs
- Use parameterized queries (Pydantic models prevent injection)
Before committing:
# Install git-secrets
git secrets --install
git secrets --register-aws
# Scan for secrets
git secrets --scan- Immediately rotate all affected credentials
- Review audit logs for unauthorized actions
- Check database for suspicious modifications
- Notify affected users if PII was exposed
- Document the incident
- Implement preventive measures
- Immediately shut down the bot
- Revoke all tokens and credentials
- Review all code for malicious changes
- Check database for unauthorized access
- Restore from known-good backup
- Investigate how compromise occurred
- Implement fixes and security improvements
- Redeploy with new credentials
- Discord Security Best Practices
- OWASP Top 10
- MongoDB Security Checklist
- Python Security Best Practices
| Version | Date | Changes |
|---|---|---|
| 1.0 | 2025-01-XX | Initial security policy |
Remember: Security is not a one-time task, it's an ongoing process.