Skip to content

05. Configuration Guide

ad1107 edited this page May 24, 2025 · 1 revision

Configuration Guide

Comprehensive guide for configuring UtilsBot+ for different environments and use cases.

Table of Contents


Environment Variables

UtilsBot+ uses environment variables for configuration. Create a .env file in the root directory:

Required Variables

# Discord Bot Configuration
BOT_TOKEN=your_discord_bot_token_here

# Developer Access
DEV_IDS=123456789012345678,987654321098765432
DEV_GUILD_ID=1234567890123456789

# AI Integration
GEMINI_API_KEY=your_gemini_api_key_here

# Security
SECRET_KEY=auto_generated_32_char_hex_key

Optional Variables

# Logging Configuration
DEBUG=false
LOG_LEVEL=INFO
LOG_FILE=logs/bot.log

# Database Configuration
DATABASE_URL=sqlite+aiosqlite:///data/bot.db

# Feature Toggles
ENABLE_GAMES=true
ENABLE_NETWORK_TOOLS=true
ENABLE_AI_COMMANDS=true
ENABLE_SYSTEM_COMMANDS=true

# Access Control
CLOSED_BETA=false
AUTO_SYNC_COMMANDS=false

# External APIs
SCREENSHOT_API_KEY=your_screenshot_api_key
RAPIDAPI_KEY=your_rapidapi_key

# Monitoring
SENTRY_DSN=your_sentry_url
ENABLE_METRICS=false

# Performance
REDIS_URL=redis://localhost:6379
CACHE_TTL=300

Database Configuration

SQLite (Default)

DATABASE_URL=sqlite+aiosqlite:///data/bot.db

Features:

  • File-based database
  • No setup required
  • Good for development and small deployments
  • Automatic creation if file doesn't exist

File Location:

  • Default: data/bot.db
  • Ensure data/ directory exists
  • Check file permissions for write access

PostgreSQL (Recommended for Production)

DATABASE_URL=postgresql+asyncpg://username:password@localhost:5432/utils_bot

Setup Steps:

  1. Install PostgreSQL:
# Ubuntu/Debian
sudo apt install postgresql postgresql-contrib

# macOS
brew install postgresql
  1. Create Database:
sudo -u postgres psql
CREATE DATABASE utils_bot;
CREATE USER bot_user WITH PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE utils_bot TO bot_user;
  1. Install Driver:
pip install asyncpg

Configuration:

DATABASE_URL=postgresql+asyncpg://bot_user:secure_password@localhost:5432/utils_bot
DATABASE_POOL_SIZE=20
DATABASE_MAX_OVERFLOW=30

MySQL/MariaDB

DATABASE_URL=mysql+aiomysql://username:password@localhost:3306/utils_bot

Setup:

pip install aiomysql cryptography

Connection Pool Settings

# Connection pool configuration
DATABASE_POOL_SIZE=20
DATABASE_MAX_OVERFLOW=30
DATABASE_POOL_TIMEOUT=30
DATABASE_POOL_RECYCLE=3600

Feature Toggles

Control which features are enabled:

Core Features

# AI Commands (/ask, /chat)
ENABLE_AI_COMMANDS=true

# Games (/wordle)
ENABLE_GAMES=true

# Network Tools (/screenshot, /ip, /unshorten)
ENABLE_NETWORK_TOOLS=true

# System Commands (/sync, /eval, /reload)
ENABLE_SYSTEM_COMMANDS=true

Advanced Features

# Monitoring and metrics
ENABLE_METRICS=false
ENABLE_HEALTH_CHECKS=true

# Caching
ENABLE_REDIS_CACHE=false
ENABLE_MEMORY_CACHE=true

# Auto-sync commands on startup
AUTO_SYNC_COMMANDS=false

Access Control

# Beta access control
CLOSED_BETA=false

# Whitelist enforcement
ENFORCE_WHITELIST=false

# Command cooldowns
GLOBAL_COOLDOWN_RATE=5
GLOBAL_COOLDOWN_PER=60

API Configuration

Google Gemini AI

GEMINI_API_KEY=your_api_key_here
GEMINI_MODEL=models/gemini-1.5-flash
GEMINI_MAX_TOKENS=8192
GEMINI_TEMPERATURE=0.7

Rate Limits:

  • Free tier: 15 requests per minute
  • Input limit: ~1M tokens
  • Output limit: 8,192 tokens

Error Handling:

GEMINI_RETRY_ATTEMPTS=3
GEMINI_RETRY_DELAY=1
GEMINI_TIMEOUT=30

Screenshot Service

ScreenshotOne (Recommended):

SCREENSHOT_API_KEY=your_screenshotone_api_key
SCREENSHOT_SERVICE=screenshotone
SCREENSHOT_TIMEOUT=30
SCREENSHOT_MAX_WIDTH=1920
SCREENSHOT_MAX_HEIGHT=1080

Alternative Services:

# Alternative screenshot service
SCREENSHOT_SERVICE=custom
SCREENSHOT_ENDPOINT=https://your-service.com/api/screenshot

IP Geolocation

# ip-api.com (free, no key required)
IP_API_SERVICE=ip-api
IP_API_TIMEOUT=10

# Alternative: ipinfo.io
IP_API_SERVICE=ipinfo
IP_API_KEY=your_ipinfo_token

Security Settings

Access Control

# Developer IDs (comma-separated)
DEV_IDS=123456789012345678,987654321098765432

# Test server for development
DEV_GUILD_ID=1234567890123456789

# Secret key for encryption
SECRET_KEY=your_32_character_secret_key_here

Rate Limiting

# Global rate limits
GLOBAL_RATE_LIMIT=5  # Commands per minute
COMMAND_COOLDOWN=2   # Seconds between commands

# Per-command rate limits
AI_COMMAND_RATE=3    # AI commands per minute
AI_COMMAND_PER=60    # Time window in seconds

SCREENSHOT_RATE=10   # Screenshots per hour
SCREENSHOT_PER=3600  # Time window in seconds

Input Validation

# Maximum input lengths
MAX_TEXT_LENGTH=2000
MAX_URL_LENGTH=2048
MAX_FILENAME_LENGTH=255

# URL security
BLOCK_PRIVATE_IPS=true
BLOCK_LOCALHOST=true
ALLOWED_PROTOCOLS=http,https

Sensitive Data Handling

# Ephemeral response defaults
DEFAULT_EPHEMERAL_TOTP=true
DEFAULT_EPHEMERAL_PASSWORD=true
DEFAULT_EPHEMERAL_EVAL=true

# Logging security
LOG_SENSITIVE_DATA=false
MASK_TOKENS_IN_LOGS=true

Development Configuration

Development Environment

# Development mode
DEBUG=true
LOG_LEVEL=DEBUG
ENVIRONMENT=development

# Auto-reload features
ENABLE_HOT_RELOAD=true
AUTO_SYNC_COMMANDS=true

# Development database
DATABASE_URL=sqlite+aiosqlite:///data/dev_bot.db

# Relaxed rate limits
GLOBAL_RATE_LIMIT=100
AI_COMMAND_RATE=30

Debugging Options

# Detailed logging
LOG_SQL_QUERIES=true
LOG_HTTP_REQUESTS=true
LOG_COMMAND_EXECUTION=true

# Performance monitoring
ENABLE_PROFILING=true
LOG_EXECUTION_TIME=true

# Error handling
SHOW_STACK_TRACES=true
DETAILED_ERROR_MESSAGES=true

Development APIs

# Use development/test API keys
GEMINI_API_KEY=your_dev_api_key
SCREENSHOT_API_KEY=your_test_api_key

# Local services
REDIS_URL=redis://localhost:6379
DATABASE_URL=postgresql://localhost/utils_bot_dev

Production Configuration

Production Environment

# Production mode
DEBUG=false
LOG_LEVEL=INFO
ENVIRONMENT=production

# Security
SECRET_KEY=very_secure_32_character_key_here
CLOSED_BETA=false

# Database
DATABASE_URL=postgresql+asyncpg://user:pass@db-server:5432/utils_bot
DATABASE_POOL_SIZE=20

# Monitoring
SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id
ENABLE_METRICS=true

Performance Settings

# Connection pools
DATABASE_POOL_SIZE=20
DATABASE_MAX_OVERFLOW=30
REDIS_POOL_SIZE=10

# Caching
ENABLE_REDIS_CACHE=true
REDIS_URL=redis://redis-server:6379
CACHE_TTL=300

# Rate limiting (production values)
GLOBAL_RATE_LIMIT=5
AI_COMMAND_RATE=3
SCREENSHOT_RATE=10

Monitoring and Logging

# Structured logging
LOG_FORMAT=json
LOG_LEVEL=INFO
LOG_FILE=/var/log/utils-bot/bot.log

# Error tracking
SENTRY_DSN=your_sentry_dsn
SENTRY_ENVIRONMENT=production
SENTRY_RELEASE=v2.0.0

# Metrics
PROMETHEUS_ENABLED=true
PROMETHEUS_PORT=8000
HEALTH_CHECK_PORT=8080

Docker Configuration

Environment File for Docker

# Docker-specific configuration
DATABASE_URL=postgresql+asyncpg://postgres:password@db:5432/utils_bot
REDIS_URL=redis://redis:6379

# Container settings
LOG_LEVEL=INFO
DEBUG=false

# External connections
GEMINI_API_KEY=${GEMINI_API_KEY}
BOT_TOKEN=${BOT_TOKEN}

Docker Compose Environment

# docker-compose.yml
version: '3.8'
services:
  bot:
    build: .
    environment:
      - DATABASE_URL=postgresql+asyncpg://postgres:${POSTGRES_PASSWORD}@db:5432/utils_bot
      - REDIS_URL=redis://redis:6379
      - BOT_TOKEN=${BOT_TOKEN}
      - GEMINI_API_KEY=${GEMINI_API_KEY}
    env_file:
      - .env
    depends_on:
      - db
      - redis

Container Health Checks

# Health check configuration
HEALTH_CHECK_ENABLED=true
HEALTH_CHECK_INTERVAL=30
HEALTH_CHECK_TIMEOUT=10
HEALTH_CHECK_RETRIES=3

Configuration Validation

Settings Validation

UtilsBot+ uses Pydantic for configuration validation:

# config/settings.py
from pydantic import BaseModel, validator
from typing import List, Optional

class Settings(BaseModel):
    bot_token: str
    dev_ids: List[int] = []
    gemini_api_key: str
    debug: bool = False
    
    @validator("log_level")
    def validate_log_level(cls, v):
        valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        if v.upper() not in valid_levels:
            raise ValueError(f"Log level must be one of: {valid_levels}")
        return v.upper()
    
    @validator("dev_ids", pre=True)
    def parse_dev_ids(cls, v):
        if isinstance(v, str):
            return [int(id.strip()) for id in v.split(",") if id.strip()]
        return v

Configuration Testing

# Test configuration
python -c "
from config.settings import settings
print('Configuration valid!')
print(f'Debug mode: {settings.debug}')
print(f'Log level: {settings.log_level}')
"

Common Configuration Patterns

Multi-Environment Setup

# .env.development
DEBUG=true
LOG_LEVEL=DEBUG
DATABASE_URL=sqlite+aiosqlite:///data/dev_bot.db

# .env.staging
DEBUG=false
LOG_LEVEL=INFO
DATABASE_URL=postgresql+asyncpg://user:pass@staging-db:5432/utils_bot

# .env.production
DEBUG=false
LOG_LEVEL=WARNING
DATABASE_URL=postgresql+asyncpg://user:pass@prod-db:5432/utils_bot

Load Environment-Specific Config

import os
from dotenv import load_dotenv

# Load environment-specific config
env = os.getenv('ENVIRONMENT', 'development')
load_dotenv(f'.env.{env}')
load_dotenv('.env')  # Base config

Configuration Hierarchy

  1. Environment variables (highest priority)
  2. Environment-specific .env file (.env.production)
  3. Base .env file (.env)
  4. Default values in code (lowest priority)

Troubleshooting Configuration

Common Issues

Configuration Not Loading:

# Check file existence
ls -la .env*

# Verify file contents
cat .env | grep -v '^#' | grep -v '^$'

# Test loading
python -c "from config.settings import settings; print(settings.dict())"

Database Connection Issues:

# Test database URL
python -c "
from sqlalchemy import create_engine
engine = create_engine('your_database_url_here')
print('Database connection successful!')
"

Missing API Keys:

# Check environment variables
env | grep -E "(BOT_TOKEN|GEMINI_API_KEY)"

# Verify .env loading
python -c "
import os
from dotenv import load_dotenv
load_dotenv()
print(f'Bot token length: {len(os.getenv(\"BOT_TOKEN\", \"\"))}')
"

Configuration Validation Errors

# Debug configuration issues
try:
    from config.settings import settings
    print("Configuration loaded successfully!")
except Exception as e:
    print(f"Configuration error: {e}")
    # Check specific settings
    import os
    print(f"BOT_TOKEN set: {'BOT_TOKEN' in os.environ}")
    print(f"DEBUG value: {os.getenv('DEBUG')}")

Navigation: ← Commands Reference | API Integrations →

Related Pages: Getting Started | Security Guide | Deployment Guide

Clone this wiki locally