Skip to content

12. Troubleshooting

ad1107 edited this page May 24, 2025 · 2 revisions

Troubleshooting Guide

Common issues and solutions for UtilsBot+ deployment and operation.

Table of Contents


Bot Won't Start

Check Python Version

python3 --version
# Should be 3.11 or higher

Solution for wrong version:

# 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

pip install -r requirements.txt

If installation fails:

# 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

# Verify required variables exist
cat .env | grep -E "(BOT_TOKEN|GEMINI_API_KEY|DEV_IDS)"

Missing variables:

# Check if .env file exists
ls -la .env

# Create from template if missing
cp .env.example .env
# Edit .env with your credentials

Database Initialization

# Initialize database
python migrations/init_db.py

If initialization fails:

# 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

# 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:

# 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:

# 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:

# 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:

# 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:

# 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:

# Nuclear option - recreates everything
rm data/bot.db
python migrations/init_db.py
python migrations/populate_data.py

Check Migration Status:

# 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:

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:

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:

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:

# Check bot memory usage
ps aux | grep python

# Monitor in real-time
top -p $(pgrep -f "python.*main.py")

Optimize Memory:

# 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:

# Reduce timeouts
API_TIMEOUT=10
DATABASE_TIMEOUT=5

# Enable caching
ENABLE_MEMORY_CACHE=true
CACHE_TTL=300

Database Performance

Add Indexes:

-- 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:

# 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:

# 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:

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:

# Defer response for long operations
await interaction.response.defer()
# Do long operation
await interaction.followup.send("Result")

Logging and Debugging

Enable Debug Mode

DEBUG=true
LOG_LEVEL=DEBUG

Check Log Files

# 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:

# 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:

# 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:

# 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:

# 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 - Basic setup
  2. Configuration Guide - Advanced config
  3. Developer Guide - Code-level issues

Debug Information

When reporting issues, provide:

# 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

Emergency Recovery

Complete Reset:

# 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 | FAQ →

Related Pages: Getting Started | Developer Guide | Security Guide

Clone this wiki locally