# Troubleshooting Guide Common issues and solutions for UtilsBot+ deployment and operation. ## Table of Contents - [Bot Won't Start](#bot-wont-start) - [Commands Not Working](#commands-not-working) - [Permission Issues](#permission-issues) - [Database Problems](#database-problems) - [API Integration Issues](#api-integration-issues) - [Performance Problems](#performance-problems) - [Discord-Specific Issues](#discord-specific-issues) - [Logging and Debugging](#logging-and-debugging) - [Common Error Messages](#common-error-messages) --- ## Bot Won't Start ### Check Python Version ```bash python3 --version # Should be 3.11 or higher ``` **Solution for wrong version:** ```bash # Install Python 3.11+ sudo apt update sudo apt install python3.11 # Use specific version python3.11 -m venv venv source venv/bin/activate ``` ### Verify Dependencies ```bash pip install -r requirements.txt ``` **If installation fails:** ```bash # Clear pip cache pip cache purge # Upgrade pip pip install --upgrade pip # Install with verbose output pip install -r requirements.txt -v ``` ### Check Environment Variables ```bash # Verify required variables exist cat .env | grep -E "(BOT_TOKEN|GEMINI_API_KEY|DEV_IDS)" ``` **Missing variables:** ```bash # Check if .env file exists ls -la .env # Create from template if missing cp .env.example .env # Edit .env with your credentials ``` ### Database Initialization ```bash # Initialize database python migrations/init_db.py ``` **If initialization fails:** ```bash # Check data directory permissions ls -la data/ mkdir -p data chmod 755 data/ # Remove corrupted database rm data/bot.db python migrations/init_db.py ``` ### File Permissions ```bash # Check script permissions chmod +x setup.sh chmod +x verify_setup.sh # Check log directory mkdir -p logs chmod 755 logs/ ``` --- ## Commands Not Working ### Slash Commands Not Appearing **Solution 1: Sync Commands** ``` /sync scope:"guild" # For current server (immediate) /sync scope:"global" # For all servers (takes 1 hour) ``` **Solution 2: Check Bot Permissions** - Bot needs `applications.commands` scope - Bot role should have `Use Slash Commands` permission - Check server-specific permission overrides **Solution 3: Re-invite Bot** 1. Go to Discord Developer Portal 2. OAuth2 → URL Generator 3. Select: `bot` + `applications.commands` 4. Re-invite with new URL ### Commands Return Errors **Check Bot Permissions:** ``` /info # Check if basic commands work ``` **Required Permissions:** - Send Messages - Use Slash Commands - Embed Links - Attach Files (for screenshots, QR codes) - Read Message History ### Whitelist Issues **If in beta mode:** ```bash # Check beta status grep CLOSED_BETA .env ``` **Add yourself to whitelist:** ``` /whitelist add user:@yourusername ``` **Check whitelist status:** ``` /whitelist check user:@yourusername ``` --- ## Permission Issues ### Developer Commands Not Working **Check Developer IDs:** ```bash # Verify your Discord ID is in DEV_IDS grep DEV_IDS .env ``` **Get your Discord ID:** 1. Enable Developer Mode in Discord 2. Right-click your profile → Copy User ID 3. Add to `.env`: `DEV_IDS=123456789012345678` ### Bot Missing Permissions **Check Server Permissions:** 1. Server Settings → Roles 2. Find bot role 3. Ensure required permissions are enabled **Channel-Specific Permissions:** 1. Channel Settings → Permissions 2. Check bot role overrides 3. Allow necessary permissions ### Permission Denied Errors **Common causes:** - Bot role below other roles - Channel permission overrides - Server-wide permission restrictions **Solutions:** 1. Move bot role higher in hierarchy 2. Grant permissions at channel level 3. Check for permission overwrites --- ## Database Problems ### Database Connection Errors **SQLite Issues:** ```bash # Check database file ls -la data/bot.db # Test database connection python -c " import sqlite3 conn = sqlite3.connect('data/bot.db') print('Database accessible') conn.close() " ``` **PostgreSQL Issues:** ```bash # Test connection python -c " import asyncpg import asyncio async def test(): conn = await asyncpg.connect('your_database_url') print('PostgreSQL connection successful') await conn.close() asyncio.run(test()) " ``` ### Database Corruption **SQLite Recovery:** ```bash # Backup current database cp data/bot.db data/bot.db.backup # Recreate database rm data/bot.db python migrations/init_db.py # Restore data if possible python migrations/restore_backup.py ``` ### Migration Errors **Reset Database:** ```bash # Nuclear option - recreates everything rm data/bot.db python migrations/init_db.py python migrations/populate_data.py ``` **Check Migration Status:** ```python # migrations/check_schema.py from models.database import Database import asyncio async def check(): db = Database() await db.initialize() # Check table existence print("Database schema OK") asyncio.run(check()) ``` --- ## API Integration Issues ### Google Gemini API Problems **Test API Key:** ```python import google.generativeai as genai genai.configure(api_key="your_api_key_here") model = genai.GenerativeModel('models/gemini-1.5-flash') try: response = model.generate_content("Hello") print("API working:", response.text) except Exception as e: print("API error:", e) ``` **Common Gemini Issues:** - **Invalid API Key**: Check key in Google AI Studio - **Rate Limit Exceeded**: Wait or upgrade plan - **Region Restrictions**: VPN to supported region - **Model Not Available**: Check model name ### Screenshot API Issues **Test Screenshot Service:** ```bash curl -X GET "https://api.screenshotone.com/take?url=https://example.com" \ -H "Authorization: Bearer your_api_key" ``` **Fallback Options:** - Disable screenshot features: `ENABLE_NETWORK_TOOLS=false` - Use local screenshot service - Implement basic placeholder generation ### IP Geolocation API **Test ip-api.com:** ```bash curl "http://ip-api.com/json/8.8.8.8" ``` **If service is down:** - API returns limited data - Commands may work with reduced functionality - Consider alternative services (ipinfo.io) --- ## Performance Problems ### High Memory Usage **Monitor Memory:** ```bash # Check bot memory usage ps aux | grep python # Monitor in real-time top -p $(pgrep -f "python.*main.py") ``` **Optimize Memory:** ```env # Reduce database pool size DATABASE_POOL_SIZE=5 DATABASE_MAX_OVERFLOW=10 # Enable garbage collection PYTHON_GC_ENABLED=true ``` ### Slow Response Times **Check Bot Latency:** ``` /ping # Check response time ``` **Common Causes:** - Database connection issues - External API timeouts - Memory leaks - High CPU usage **Solutions:** ```env # Reduce timeouts API_TIMEOUT=10 DATABASE_TIMEOUT=5 # Enable caching ENABLE_MEMORY_CACHE=true CACHE_TTL=300 ``` ### Database Performance **Add Indexes:** ```sql -- Add to migration CREATE INDEX idx_users_discord_id ON users(discord_id); CREATE INDEX idx_api_usage_user_api ON api_usage(user_discord_id, api_name); ``` **Monitor Queries:** ```env # Enable SQL logging LOG_SQL_QUERIES=true DEBUG=true ``` --- ## Discord-Specific Issues ### Bot Appears Offline **Check Bot Status:** 1. Discord Developer Portal 2. Bot section 3. Verify bot token is correct 4. Check if bot is in your server **Token Issues:** ```bash # Test token validity python -c " import discord import asyncio async def test(): client = discord.Client(intents=discord.Intents.default()) try: await client.login('your_bot_token') print('Token valid') except: print('Invalid token') finally: await client.close() asyncio.run(test()) " ``` ### Commands Take Long Time **Discord Rate Limits:** - Global rate limit: 50 requests per second - Per-endpoint limits vary - Bot automatically handles rate limiting **Check Logs:** ```bash grep "rate limit" logs/bot.log ``` ### Interaction Timeouts **Discord has strict timeouts:** - Initial response: 3 seconds - Follow-up response: 15 minutes - Edit/delete: 15 minutes **Solutions:** ```python # Defer response for long operations await interaction.response.defer() # Do long operation await interaction.followup.send("Result") ``` --- ## Logging and Debugging ### Enable Debug Mode ```env DEBUG=true LOG_LEVEL=DEBUG ``` ### Check Log Files ```bash # View recent logs tail -f logs/bot.log # Search for errors grep -i "error" logs/bot.log # Find specific command issues grep "/ask" logs/bot.log ``` ### Live Debugging **Use eval command:** ```python # Check bot state /eval code:"len(bot.guilds)" # Test database /eval code:"await bot.db.get_user(interaction.user.id)" # Check settings /eval code:"bot.settings.debug" ``` ### Structured Logging **Log Analysis:** ```bash # Parse JSON logs cat logs/bot.log | jq '.level' # Filter by user cat logs/bot.log | jq 'select(.user_id == "123456789")' # Count errors grep '"level":"ERROR"' logs/bot.log | wc -l ``` --- ## Common Error Messages ### "Missing Permissions" **Cause**: Bot lacks required Discord permissions **Solution**: 1. Check bot role permissions 2. Check channel overrides 3. Re-invite bot with correct scopes ### "Application did not respond" **Cause**: Command took longer than 3 seconds **Solution**: ```python # Use defer for long operations await interaction.response.defer() # Long operation here await interaction.followup.send("Done!") ``` ### "Invalid API Key" **Cause**: Incorrect or expired API key **Solution**: 1. Regenerate API key 2. Update `.env` file 3. Restart bot ### "Database is locked" **Cause**: SQLite database access conflict **Solution**: ```bash # Check for multiple bot instances ps aux | grep python # Kill duplicate processes pkill -f "python.*main.py" # Restart bot python main.py ``` ### "Command not found" **Cause**: Commands not synced or bot missing permissions **Solution**: ``` /sync scope:"guild" # Sync commands ``` ### "Rate limit exceeded" **Cause**: Too many API requests **Solution**: - Wait for rate limit to reset - Check rate limiting configuration - Implement backoff strategy --- ## Getting Additional Help ### Check Documentation 1. [Getting Started](Getting-Started) - Basic setup 2. [Configuration Guide](Configuration-Guide) - Advanced config 3. [Developer Guide](Developer-Guide) - Code-level issues ### Debug Information When reporting issues, provide: ```bash # System information python --version pip list | grep -E "(discord|sqlalchemy|pydantic)" # Configuration (without secrets) cat .env | grep -v -E "(TOKEN|KEY|SECRET)" | grep -v "^#" # Recent logs (last 50 lines) tail -50 logs/bot.log # Bot status /info # If bot responds ``` ### Community Support - **GitHub Issues**: [Report bugs](https://github.com/ad1107/utils-bot-plus/issues) - **GitHub Discussions**: [Ask questions](https://github.com/ad1107/utils-bot-plus/discussions) - **Discord Server**: [Community support] (coming soon) ### Emergency Recovery **Complete Reset:** ```bash # Backup current state cp .env .env.backup cp -r data/ data.backup/ # Clean installation git pull origin main pip install -r requirements.txt --force-reinstall rm data/bot.db python migrations/init_db.py python main.py ``` --- **Navigation**: [← Configuration Guide](Configuration-Guide) | [FAQ →](FAQ) **Related Pages**: [Getting Started](Getting-Started) | [Developer Guide](Developer-Guide) | [Security Guide](Security-Guide)