# API Troubleshooting Guide This guide helps you diagnose and resolve common issues with the Telegram Marketing Agent API. ## Table of Contents - [Authentication Issues](#authentication-issues) - [Rate Limiting](#rate-limiting) - [Campaign Execution Problems](#campaign-execution-problems) - [Data Import/Export Issues](#data-importexport-issues) - [Webhook Problems](#webhook-problems) - [Performance Issues](#performance-issues) - [Error Codes Reference](#error-codes-reference) ## Authentication Issues ### Problem: 401 Unauthorized Error **Symptoms:** ```json { "success": false, "error": "Unauthorized", "code": "UNAUTHORIZED" } ``` **Solutions:** 1. **Check Token Format** ```bash # Correct format curl -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com/v1/users # Common mistakes curl -H "Authorization: YOUR_TOKEN" # Missing "Bearer" prefix curl -H "Authorization: bearer YOUR_TOKEN" # Lowercase "bearer" ``` 2. **Verify Token Expiration** - Access tokens expire after 24 hours - Use the refresh token endpoint to get a new access token ```bash curl -X POST https://api.example.com/v1/auth/refresh \ -H "Content-Type: application/json" \ -d '{"refreshToken": "YOUR_REFRESH_TOKEN"}' ``` 3. **Check API Key (if using)** ```bash curl -H "X-API-Key: YOUR_API_KEY" https://api.example.com/v1/users ``` ### Problem: 403 Forbidden Error **Symptoms:** - User authenticated but lacks permissions - Specific endpoints return forbidden **Solutions:** 1. Check user role and permissions 2. Verify endpoint access requirements 3. Contact admin for permission updates ## Rate Limiting ### Problem: 429 Too Many Requests **Symptoms:** ```json { "success": false, "error": "Too many requests", "code": "RATE_LIMIT_EXCEEDED", "details": { "retryAfter": 60 } } ``` **Solutions:** 1. **Check Rate Limit Headers** ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1642012800 ``` 2. **Implement Exponential Backoff** ```javascript async function retryWithBackoff(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.status === 429 && i < maxRetries - 1) { const delay = Math.pow(2, i) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } } ``` 3. **Batch Operations** - Use bulk endpoints when available - Group multiple operations into single requests ## Campaign Execution Problems ### Problem: Campaign Fails to Execute **Symptoms:** - Campaign status remains "draft" - Execution endpoint returns errors **Solutions:** 1. **Validate Campaign Configuration** ```bash # Check campaign details curl -X GET https://api.example.com/v1/orchestrator/campaigns/CAMPAIGN_ID \ -H "Authorization: Bearer YOUR_TOKEN" ``` 2. **Common Issues:** - Empty target audience - Missing message content - Invalid scheduling parameters - Telegram account not connected 3. **Test Mode First** ```bash curl -X POST https://api.example.com/v1/orchestrator/campaigns/CAMPAIGN_ID/execute \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "test": true, "testUsers": ["user_123", "user_456"] }' ``` ### Problem: Low Delivery Rate **Solutions:** 1. **Check Rate Limits** - Telegram has strict rate limits - Reduce messages per second in campaign settings 2. **Verify User Status** - Check if users have blocked the bot - Ensure phone numbers are valid 3. **Monitor Telegram Account Health** - Check for account restrictions - Verify account connection status ## Data Import/Export Issues ### Problem: Import Fails with Validation Errors **Solutions:** 1. **Validate CSV Format** ```csv telegramId,username,firstName,lastName,phoneNumber,tags 123456789,johndoe,John,Doe,+1234567890,"customer,active" ``` 2. **Common Issues:** - Missing required fields - Invalid phone number format - Special characters in CSV - File encoding (use UTF-8) 3. **Use Template** ```bash # Download template curl -X GET https://api.example.com/v1/users/import/template \ -H "Authorization: Bearer YOUR_TOKEN" \ -o user_template.csv ``` ### Problem: Export Timeout for Large Datasets **Solutions:** 1. **Use Filters** ```json { "format": "csv", "filters": { "status": "active", "createdAt": { "from": "2024-01-01", "to": "2024-01-31" } }, "limit": 10000 } ``` 2. **Paginated Export** - Export in batches - Use background job for large exports ## Webhook Problems ### Problem: Webhooks Not Triggering **Solutions:** 1. **Verify Webhook Configuration** ```bash curl -X GET https://api.example.com/v1/webhooks/WEBHOOK_ID \ -H "Authorization: Bearer YOUR_TOKEN" ``` 2. **Test Webhook** ```bash curl -X POST https://api.example.com/v1/webhooks/WEBHOOK_ID/test \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "event": "campaign.completed", "payload": {"test": true} }' ``` 3. **Common Issues:** - URL not publicly accessible - SSL certificate problems - Timeout (webhook must respond within 10s) - Response status not 2xx ### Problem: Duplicate Webhook Events **Solutions:** 1. Implement idempotency using event IDs 2. Check webhook logs for retry attempts 3. Ensure webhook responds quickly ## Performance Issues ### Problem: Slow API Response Times **Solutions:** 1. **Use Caching Headers** ```bash # Check if response is cached curl -I https://api.example.com/v1/analytics/dashboard \ -H "Authorization: Bearer YOUR_TOKEN" ``` 2. **Optimize Queries** - Use specific field selection - Implement pagination - Add appropriate filters 3. **Batch Operations** ```json { "operations": [ {"method": "GET", "path": "/users/user_123"}, {"method": "GET", "path": "/users/user_456"} ] } ``` ### Problem: Timeout Errors **Solutions:** 1. **Increase Client Timeout** ```javascript const response = await fetch(url, { timeout: 30000 // 30 seconds }); ``` 2. **Use Async Operations** - For long-running tasks, use job queues - Poll for results ## Error Codes Reference ### HTTP Status Codes | Code | Meaning | Common Causes | |------|---------|---------------| | 400 | Bad Request | Invalid parameters, malformed JSON | | 401 | Unauthorized | Missing/invalid token, expired token | | 403 | Forbidden | Insufficient permissions | | 404 | Not Found | Resource doesn't exist | | 409 | Conflict | Duplicate resource, conflicting state | | 422 | Unprocessable Entity | Validation errors | | 429 | Too Many Requests | Rate limit exceeded | | 500 | Internal Server Error | Server-side issue | | 502 | Bad Gateway | Service unavailable | | 503 | Service Unavailable | Maintenance, overload | ### Application Error Codes | Code | Description | Solution | |------|-------------|----------| | `AUTH_FAILED` | Authentication failed | Check credentials | | `TOKEN_EXPIRED` | Access token expired | Refresh token | | `INVALID_INPUT` | Input validation failed | Check request body | | `RESOURCE_NOT_FOUND` | Requested resource not found | Verify ID/path | | `DUPLICATE_RESOURCE` | Resource already exists | Use update instead | | `CAMPAIGN_NOT_READY` | Campaign missing required data | Complete campaign setup | | `TELEGRAM_ERROR` | Telegram API error | Check account status | | `QUOTA_EXCEEDED` | Account quota exceeded | Upgrade plan | ## Debug Mode Enable debug mode for detailed error information: ```bash curl -X GET https://api.example.com/v1/users \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "X-Debug-Mode: true" ``` ## Getting Help If you're still experiencing issues: 1. **Check Logs** - Request ID in response headers - Include in support tickets 2. **API Status** - Check https://status.example.com - Follow @api_status for updates 3. **Support Channels** - Email: api-support@example.com - Discord: https://discord.gg/example - GitHub Issues: https://github.com/example/api/issues ## Best Practices 1. **Always Handle Errors** ```javascript try { const response = await api.createCampaign(data); } catch (error) { if (error.code === 'RATE_LIMIT_EXCEEDED') { // Handle rate limit } else if (error.code === 'VALIDATION_ERROR') { // Handle validation errors } else { // Handle other errors } } ``` 2. **Log Everything** - Request/response bodies - Headers - Timestamps - Error messages 3. **Monitor Your Integration** - Set up alerts for failures - Track success rates - Monitor response times 4. **Use SDK When Available** - Automatic retry logic - Built-in error handling - Type safety