Skip to main content

Troubleshooting

This guide helps you troubleshoot common problems with BarStrad-Bot during development and production.

Bot Connection Issues

Bot Won't Connect to Discord

Symptoms:

  • Bot doesn't appear online in Discord
  • No console output after starting
  • Connection timeout errors

Solutions:

  1. Check Discord Token

    # Verify token is set correctly
    echo $DiscordBotToken
    • Ensure token is valid and not expired
    • Verify no extra spaces or characters
    • Check token hasn't been regenerated in Discord Developer Portal
  2. Verify Bot Permissions

    • Check bot has necessary permissions in Discord server
    • Ensure bot is properly invited to server
    • Verify bot role hierarchy is correct
  3. Network Connectivity

    # Test Discord API connectivity
    curl -H "Authorization: Bot YOUR_TOKEN" https://discord.com/api/users/@me

Bot Connects But Commands Don't Work

Symptoms:

  • Bot shows as online
  • No response to commands
  • Missing command acknowledgments

Solutions:

  1. Check Message Intent Permissions

    // Verify intents in Bot.ts
    const client = new Client({
    intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
    ]
    });
  2. Verify Command Prefix

    • Ensure using correct command prefix (!)
    • Check for typos in command names
    • Verify case sensitivity
  3. Check Console Logs

    # Look for error messages
    npm run dev
    # Watch for connection confirmations and error messages

Symptoms:

  • Commands return empty responses
  • Error messages about menu loading
  • JSON parsing errors

Solutions:

  1. Validate Menu JSON Files

    # Check JSON syntax
    node -e "console.log(JSON.parse(require('fs').readFileSync('src/data/menu-items.bg.json', 'utf8')))"
    node -e "console.log(JSON.parse(require('fs').readFileSync('src/data/menu-items.en.json', 'utf8')))"
  2. Check File Paths

    // Verify file paths in Menu.ts
    const bgMenuPath = path.join(__dirname, 'data', 'menu-items.bg.json');
    const enMenuPath = path.join(__dirname, 'data', 'menu-items.en.json');
  3. Verify File Permissions

    # Check file is readable
    ls -la src/data/menu-items.*.json

Incorrect Menu Formatting

Symptoms:

  • Menu displays with wrong formatting
  • Missing categories or items
  • Incorrect numbering

Solutions:

  1. Check Menu Structure

    // Correct structure:
    [
    {
    "name": "Category Name",
    "items": [
    {
    "name": "Item Name",
    "price": 10.50
    }
    ]
    }
    ]
  2. Verify Display Logic

    // Check formatting in Menu.ts
    formatMenuDisplay(): string {
    // Ensure proper category and item formatting
    }

Order Processing Issues

Orders Not Processing

Symptoms:

  • Order commands don't respond
  • No webhook notifications sent
  • Error messages about order processing

Solutions:

  1. Check Order Command Format

    # Correct format:
    !order [item_number] [customer_name]

    # Examples:
    !order 1 John Doe
    !order 15 Maria Garcia
  2. Verify Item Number Range

    // Check if item number exists
    if (itemNumber < 1 || itemNumber > totalItems) {
    return "Invalid item number";
    }
  3. Test Webhook URL

    # Test webhook manually
    curl -X POST -H "Content-Type: application/json" \
    -d '{"content":"Test message"}' \
    $DiscordWebhookUrl

Webhook Notifications Not Working

Symptoms:

  • Orders process but no notifications sent
  • Webhook errors in console
  • Discord channel doesn't receive messages

Solutions:

  1. Verify Webhook URL

    # Check webhook URL format
    echo $DiscordWebhookUrl
    # Should be: https://discord.com/api/webhooks/ID/TOKEN
  2. Check Webhook Permissions

    • Verify webhook hasn't been deleted
    • Ensure webhook has permission to send messages
    • Check channel permissions
  3. Test Webhook Service

    // Add error handling to webhook service
    try {
    await webhook.send(message);
    console.log('✅ Webhook sent successfully');
    } catch (error) {
    console.error('❌ Webhook error:', error);
    }

Development Environment Issues

TypeScript Compilation Errors

Symptoms:

  • Build fails with type errors
  • IDE shows TypeScript errors
  • Runtime errors due to type mismatches

Solutions:

  1. Check TypeScript Configuration

    // Verify tsconfig.json
    {
    "compilerOptions": {
    "target": "es2020",
    "module": "CommonJS",
    "strict": true,
    "outDir": "./artifacts",
    "rootDir": "./src"
    }
    }
  2. Update Type Definitions

    # Install/update type definitions
    npm install --save-dev @types/node
    npm install --save-dev @types/discord.js
  3. Fix Common Type Issues

    // Use proper type annotations
    const client: Client = new Client({ intents: [...] });
    const message: Message = ...; // Instead of any

Dependency Issues

Symptoms:

  • Module not found errors
  • Version compatibility issues
  • npm install failures

Solutions:

  1. Clear Node Modules

    # Clean installation
    rm -rf node_modules package-lock.json
    npm install
  2. Check Node.js Version

    # Verify Node.js version
    node --version
    # Should be v18 or higher
  3. Update Dependencies

    # Update to latest compatible versions
    npm update
    npm audit fix

Docker Issues

Container Won't Start

Symptoms:

  • Docker container exits immediately
  • Container shows "Exited" status
  • No application logs in container

Solutions:

  1. Check Docker Logs

    # View container logs
    docker logs barstrad-bot

    # View real-time logs
    docker logs -f barstrad-bot
  2. Verify Environment Variables

    # Check environment inside container
    docker exec barstrad-bot env | grep Discord
  3. Test Container Interactively

    # Run container with shell access
    docker run -it --env-file .env barstrad-bot sh

Build Failures

Symptoms:

  • Docker build command fails
  • Image creation errors
  • Build context issues

Solutions:

  1. Check Dockerfile Syntax

    # Verify Dockerfile structure
    FROM node:18-alpine
    WORKDIR /app
    COPY package*.json ./
    RUN npm ci --only=production
    COPY . .
    CMD ["npm", "start"]
  2. Verify Build Context

    # Build with verbose output
    docker build --no-cache -t barstrad-bot .
  3. Check File Permissions

    # Ensure files are readable
    ls -la Dockerfile package.json

Production Issues

Performance Problems

Symptoms:

  • Slow response times
  • High memory usage
  • CPU usage spikes

Solutions:

  1. Monitor Resource Usage

    # Check container resources
    docker stats barstrad-bot

    # Monitor memory usage
    docker exec barstrad-bot node -e "console.log(process.memoryUsage())"
  2. Optimize Code

    // Add performance monitoring
    const startTime = Date.now();
    // ... operation ...
    const duration = Date.now() - startTime;
    console.log(`Operation took ${duration}ms`);
  3. Check for Memory Leaks

    // Monitor memory over time
    setInterval(() => {
    const usage = process.memoryUsage();
    console.log('Memory:', Math.round(usage.heapUsed / 1024 / 1024) + 'MB');
    }, 60000);

Deployment Failures

Symptoms:

  • CI/CD pipeline failures
  • Deployment rollbacks
  • Service unavailable errors

Solutions:

  1. Check GitHub Actions Logs

    • Review workflow execution logs
    • Identify failed steps
    • Check environment variables and secrets
  2. Verify Build Agent

    # Test build agent connectivity
    docker pull your-build-agent-image
  3. Rollback if Necessary

    # Deploy previous version
    docker run -d --name barstrad-bot-rollback \
    --env-file .env \
    ghcr.io/the-running-dev/barstrad-bot:previous-version

Debugging Tools and Techniques

Console Debugging

Add comprehensive logging:

// Enhanced logging
console.log(`🤖 Bot starting at ${new Date().toISOString()}`);
console.log(`📝 Loading menu for language: ${language}`);
console.log(`💬 Processing command: ${command} from ${user}`);
console.error(`❌ Error occurred: ${error.message}`);

VS Code Debugging

Configure debugging in VS Code:

// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Bot",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.ts",
"runtimeArgs": ["-r", "ts-node/register"],
"env": {
"NODE_ENV": "development"
}
}
]
}

Network Debugging

Test connectivity:

# Test Discord API
curl -I https://discord.com/api/v10/gateway

# Test webhook
curl -X POST -H "Content-Type: application/json" \
-d '{"content":"Test"}' \
$DiscordWebhookUrl

# Check DNS resolution
nslookup discord.com

Error Codes and Messages

Common Error Codes

Error CodeDescriptionSolution
ECONNREFUSEDConnection refusedCheck network/firewall
ENOTFOUNDDNS resolution failedCheck internet connection
401 UnauthorizedInvalid Discord tokenUpdate bot token
403 ForbiddenMissing permissionsCheck bot permissions
429 Too Many RequestsRate limitedImplement rate limiting

Error Message Patterns

Bot Connection Errors:

❌ No Bot Token Found in .env File!
❌ Failed to login: Invalid token
❌ WebSocket connection failed

Menu Loading Errors:

❌ Error loading menu: ENOENT
❌ JSON parsing error in menu file
❌ Invalid menu structure detected

Command Processing Errors:

❌ Invalid command format
❌ Item number out of range
❌ Missing required parameters

Getting Help

Self-Diagnosis Checklist

Before seeking help, check:

  • Environment variables are set correctly
  • Bot token is valid and has necessary permissions
  • Menu JSON files are valid and accessible
  • Network connectivity is working
  • Dependencies are installed correctly
  • No conflicting processes running

Gathering Debug Information

When reporting issues, include:

  1. Environment Details

    node --version
    npm --version
    docker --version
  2. Error Logs

    # Application logs
    npm run dev 2>&1 | tee debug.log

    # Docker logs
    docker logs barstrad-bot > docker-debug.log
  3. Configuration

    # Environment variables (without sensitive values)
    env | grep -v Token | grep -v Webhook

Contact Information

  • GitHub Issues: Create an issue
  • Development Team: Contact via project repository
  • Documentation: Check latest documentation for updates

Still having issues? Create a detailed issue report with logs and steps to reproduce the problem!