Skip to content

Troubleshooting

maule edited this page Aug 16, 2026 · 1 revision

Troubleshooting

Common issues and solutions.

Bot Not Responding

1. Check Webhook Registration

curl "https://api.telegram.org/bot<YOUR_TOKEN>/getWebhookInfo"

Expected:

{
  "ok": true,
  "result": {
    "url": "https://your-domain.com/webhook.php",
    "has_custom_certificate": false,
    "pending_update_count": 0
  }
}

Problems:

Issue Solution
"url": "" Register webhook again
pending_update_count > 0 Bot is not processing updates
"has_custom_certificate": true Use standard certificate

2. Test Webhook Manually

# Send test update
curl -X POST "https://your-domain.com/webhook.php" \
  -H "Content-Type: application/json" \
  -H "X-Telegram-Bot-Api-Secret-Token: your_secret" \
  -d '{
    "update_id": 123456,
    "message": {
      "message_id": 1,
      "date": '$(date +%s)',
      "chat": {"id": 123456, "type": "private"},
      "text": "test"
    }
  }'

3. Check Server Logs

# PHP errors
tail -f /var/log/php-errors.log

# Web server logs
tail -f /var/log/nginx/error.log      # Nginx
tail -f /var/log/apache2/error.log    # Apache

# Bot logs
tail -f /var/log/telegram-bot.log

HTTPS Issues

Certificate Not Valid

# Check certificate
openssl s_client -connect your-domain.com:443

# Renew Let's Encrypt
certbot renew --force-renewal

Mixed Content Error

Problem: HTTP endpoint registered instead of HTTPS

Solution:

# Re-register with HTTPS
curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \
  -d "url=https://your-domain.com/webhook.php"

Webhook URL Rejected

Telegram only accepts:

  • HTTPS (not HTTP)
  • Valid certificate
  • Public domain (not localhost or IP)
  • Port 443

Token Issues

Invalid Token Error

{"ok":false,"error_code":401,"description":"Unauthorized"}

Solutions:

  1. Verify token spelling
  2. Copy from @BotFather (not from URL)
  3. Check for extra spaces
  4. Token might be revoked

Revoke and get new token:

  • Message @BotFather
  • Select bot
  • /revoke or /newtoken

Token Exposed

Immediate Action:

  1. Revoke old token (in @BotFather)
  2. Get new token
  3. Update environment variables
  4. Redeploy bot

Connection Problems

Connection Timeout

Connection timeout to Telegram API

Solutions:

  1. Check network connectivity:
ping api.telegram.org
curl -v https://api.telegram.org/
  1. Check firewall:
sudo ufw status
# Should allow port 443
  1. Check cURL:
php -m | grep curl

SSL Certificate Error

SSL certificate problem: self signed certificate

Solution:

// Temporarily disable SSL verification (not recommended)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Better: install CA certificates
apt install ca-certificates

Message Not Sent

Empty Message Error

{"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}

Solutions:

  1. Check if text is empty
  2. Use null-safe operator:
$text = $bot->getTextMessage() ?? "default";
  1. Validate input:
if (!$bot->getTextMessage()) {
    return;
}

Invalid Chat ID

{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}

Solutions:

  1. Get correct chat ID:
echo $bot->getChatId(); // Verify it's correct
  1. Check message before sending:
if (!$bot->getChatId()) {
    error_log("No chat ID available");
    exit;
}

Keyboard Parse Error

{"ok":false,"error_code":400,"description":"Bad Request: reply_markup_invalid"}

Solutions:

  1. Verify keyboard structure:
$keyboard = $bot->buildKeyboardOfInline([
    "Button" => "data", // Both key and value must be strings
]);

// Verify JSON
echo json_encode($keyboard);
  1. Check for encoding issues:
// Use UTF-8
header('Content-Type: text/html; charset=utf-8');

File Upload Issues

Photo Not Found

// Check file exists
if (!file_exists($photoPath)) {
    error_log("Photo not found: $photoPath");
}

// Validate path
$safe = validatePhotoPath($photo);
if (!$safe) {
    error_log("Invalid photo path");
}

File Too Large

{"ok":false,"error_code":413,"description":"Payload Too Large"}

Telegram limits:

  • Photos: 5 MB
  • Documents: 50 MB

Solution:

$maxSize = 5 * 1024 * 1024; // 5 MB
if (filesize($photo) > $maxSize) {
    error_log("Photo too large");
}

Performance Issues

Slow Response Time

Causes:

  1. Slow database queries
  2. Inefficient code
  3. Network latency

Solutions:

// Measure execution time
$start = microtime(true);
// ... bot code ...
$elapsed = microtime(true) - $start;
error_log("Bot took {$elapsed}s");

// Cache frequently accessed data
$user = $cache->get("user_$id") ?? fetchUser($id);

// Optimize database queries
SELECT * FROM users WHERE id = 123; // Good
SELECT * FROM users; // Bad - loads all users

High CPU Usage

Solutions:

  1. Check for infinite loops
  2. Monitor with:
top -p $(pgrep -f php)
ps aux | grep php
  1. Reduce logging verbosity
  2. Cache API responses

Memory Leak

Fatal error: Allowed memory size exhausted

Solutions:

// Increase memory limit (temporary)
ini_set('memory_limit', '256M');

// Debug memory usage
echo memory_get_usage() / 1024 / 1024 . " MB";

// Unset large variables
unset($largeArray);
gc_collect_cycles();

Database Issues

Connection Failed

Connection refused to localhost:3306

Solutions:

# Check MySQL is running
systemctl status mysql

# Start MySQL
systemctl start mysql

# Test connection
mysql -h localhost -u bot -p

Query Errors

// Enable error reporting
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Catch errors
try {
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
} catch (Exception $e) {
    error_log("Database error: " . $e->getMessage());
}

Debugging

Enable Debug Mode

$bot = new botTG(
    token: $token,
    updates: $updates,
    debug: true,           // Enable debug
    debugFile: '/var/log/bot-debug.log'
);

Log Webhook Data

// Log all incoming updates
error_log("Webhook received: " . file_get_contents("php://input"));

Test Locally

// Simulate webhook update
$testUpdate = json_encode([
    'update_id' => 123456,
    'message' => [
        'message_id' => 1,
        'date' => time(),
        'chat' => ['id' => 123456, 'type' => 'private'],
        'text' => 'test',
    ],
]);

$bot = new botTG(token: $token, updates: $testUpdate, debug: true);

Check PHP Configuration

# Test PHP
php -v
php -m | grep curl

# Test specific extension
php -i | grep "curl"

Common Error Codes

Code Meaning Solution
400 Bad Request Check message/keyboard format
401 Unauthorized Verify bot token
403 Forbidden Check webhook URL/certificate
404 Not Found Endpoint or chat doesn't exist
409 Conflict Webhook already registered
429 Too Many Requests Rate limited - wait before retrying
500 Server Error Telegram API issue - retry later

Getting Help

Check Documentation

Debug with Telegram

# Get bot info
curl "https://api.telegram.org/bot<TOKEN>/getMe"

# Check webhook
curl "https://api.telegram.org/bot<TOKEN>/getWebhookInfo"

# Get updates manually
curl "https://api.telegram.org/bot<TOKEN>/getUpdates"

Ask for Help


Still stuck? Check Security Guide or open an issue.

Clone this wiki locally