# curl https://devtools.krishanchawla.com/raw/telegram-bot-api.txt TELEGRAM BOT APIS Quick-access to Telegram Bot APIs plus common troubleshooting steps. Category: Telegram · Type: snippet Official docs: https://core.telegram.org/bots/api ──────────────────────────────────────────────────────────── ## What is Telegram Bot API? **Telegram Bot API** is a platform for creating automated bots that can send messages, photos, documents, and interact with users on Telegram. Perfect for notifications, alerts, and automated communication. **⚡ Key Features** - Send text, photos, and files - Rich text formatting (Markdown/HTML) - Inline keyboards and buttons - Webhook support - Multi-language SDKs **🎯 Use Cases** - Server monitoring alerts - CI/CD notifications - Automated reports - Customer support bots - Integration with services --- ## 💬 Send Message - Basic Send a simple text message to a user or group. ```bash curl -X POST "https://api.telegram.org/bot/sendMessage" \ -d "chat_id=" \ -d "text=Hello from DevTools!" ``` ## 📝 Send Message - Markdown Send message with Markdown formatting. ```bash curl -X POST "https://api.telegram.org/bot/sendMessage" \ -d chat_id= \ -d parse_mode="Markdown" \ -d text="*Bold* _Italic_ \`Code\`" ``` ## 🌐 Send Message - HTML Send message with HTML formatting. ```bash curl -X POST "https://api.telegram.org/bot/sendMessage" \ -d chat_id= \ -d parse_mode="HTML" \ -d text="Bold Italic" ``` ## 📸 Send Photo - From URL Send an image from a public URL. ```bash curl -X POST "https://api.telegram.org/bot/sendPhoto" \ -d chat_id= \ -d photo="https://example.com/image.png" ``` ## 🖼️ Send Photo - Local File Upload and send a local image file. ```bash curl -X POST "https://api.telegram.org/bot/sendPhoto" \ -F chat_id= \ -F photo=@"/path/to/image.png" ``` ## 🏷️ Send Photo - With Caption Send image with text caption. ```bash curl -X POST "https://api.telegram.org/bot/sendPhoto" \ -F chat_id= \ -F photo=@"screenshot.png" \ -F caption="Server status report" ``` ## 📄 Send Document - Any File Send PDF, ZIP, logs, or any file type. ```bash curl -X POST "https://api.telegram.org/bot/sendDocument" \ -F chat_id= \ -F document=@"/path/to/file.pdf" ``` ## 📎 Send Document - With Caption Send file with description and timestamp. ```bash curl -X POST "https://api.telegram.org/bot/sendDocument" \ -F chat_id= \ -F document=@"logs.txt" \ -F caption="Application logs - $(date)" ``` ## 🌍 Browser Request - Simple GET Quick GET request you can use directly in browser. ``` https://api.telegram.org/bot/sendMessage?chat_id=&text=Hello ``` ## 🔗 Browser Request - URL Encoded Send message with URL encoding for special characters. ``` https://api.telegram.org/bot/sendMessage?chat_id=&text=Server%20is%20up ``` ## ☕ Java - Send Text Message Basic Java implementation using HttpURLConnection. ```java String token = ""; String chatId = ""; String text = "Hello from Java!"; String url = "https://api.telegram.org/bot" + token + "/sendMessage?chat_id=" + chatId + "&text=" + URLEncoder.encode(text, "UTF-8"); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); int responseCode = conn.getResponseCode(); System.out.println("Response: " + responseCode); ``` ## 🔷 Java - HttpClient (Java 11+) Modern Java HttpClient implementation. ```java HttpClient client = HttpClient.newHttpClient(); String body = String.format( "chat_id=%s&text=%s", chatId, URLEncoder.encode(message, StandardCharsets.UTF_8) ); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.telegram.org/bot" + token + "/sendMessage")) .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ## 📷 Java - Send Photo Send photo using Apache HttpClient with multipart. ```java String token = ""; String chatId = ""; File file = new File("image.png"); String url = "https://api.telegram.org/bot" + token + "/sendPhoto"; HttpPost post = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("chat_id", chatId); builder.addBinaryBody("photo", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName()); post.setEntity(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(post); System.out.println(response.getStatusLine().getStatusCode()); ``` ## 🐘 PHP - Send Text Message Send message using PHP native functions. ```php $chatId, 'text' => $text ]; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); echo $result; ?> ``` ## 📤 PHP - Send Document Send file using cURL in PHP. ```php $chatId, 'document' => new CURLFile($filePath) ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ?> ``` ## ℹ️ Bot Info - Get Details Verify bot token and get bot information. ```bash curl https://api.telegram.org/bot/getMe ``` ### Response Example ```json { "ok": true, "result": { "id": 123456789, "is_bot": true, "first_name": "MyBot", "username": "my_bot" } } ``` ## 📥 Updates - Get Messages Retrieve messages sent to your bot. ```bash curl https://api.telegram.org/bot/getUpdates ``` ## 🆔 Chat ID - Find User ID Get chat ID from updates after sending a message. ```bash curl https://api.telegram.org/bot/getUpdates | grep -o '"chat":{"id":[0-9]*' ``` ## 🚫 Troubleshoot - 401 Unauthorized Fix "401 Unauthorized" error (wrong token). ### Solution 1. Get correct token from [@BotFather](https://t.me/botfather) 2. Verify with `/getMe` endpoint 3. Check for extra spaces in token ## ❌ Troubleshoot - 400 Chat Not Found Fix "400 Chat not found" error. ### Causes - User hasn't started the bot - Wrong chat ID - Bot not added to group ### Solutions - User must click **Start** button first - Bot must be added to group (for group messages) - Group chat IDs are **negative** (e.g., `-987654321`) ### Get Correct Chat ID ```bash # Send message to bot, then run: curl https://api.telegram.org/bot/getUpdates ``` ## ⏱️ Troubleshoot - 429 Rate Limit Fix "429 Too Many Requests" error. ### Rate Limits - **30 messages/second** per bot - **1 message/second** per chat - **20 requests/minute** for same group ### Solution - Add delays between messages - Use message queuing - Batch notifications ## 🔐 Proxy - Java Configuration Configure HTTP proxy in Java. ```java System.setProperty("http.proxyHost", "proxy.company.com"); System.setProperty("http.proxyPort", "8080"); System.setProperty("https.proxyHost", "proxy.company.com"); System.setProperty("https.proxyPort", "8080"); ``` ## 🌐 Proxy - cURL Configuration Use proxy with cURL requests. ```bash curl -x http://proxy.company.com:8080 \ "https://api.telegram.org/bot/getMe" ``` ## 📚 API Methods Reference Quick reference of common Telegram Bot API methods. | Method | Purpose | |--------|---------| | `sendMessage` | Send text | | `sendPhoto` | Send image | | `sendDocument` | Send file | | `sendVideo` | Send video | | `sendAudio` | Send audio | | `sendLocation` | Send GPS coordinates | | `getUpdates` | Get messages | | `getMe` | Get bot info | ## 🔑 Important Variables Key variables for Telegram Bot API. ``` → Bot token from @BotFather → User ID / Group ID Group IDs → Always negative (-123456789) User IDs → Always positive (123456789) ``` ## 🚀 Getting Started Steps to create and use your first Telegram bot. 1. Message [@BotFather](https://t.me/botfather) on Telegram 2. Send `/newbot` command 3. Follow prompts to name your bot 4. Save the token provided 5. Start bot by sending `/start` from your account 6. Get chat ID using `/getUpdates` 7. Send your first message using API ──────────────────────────────────────────────────────────── Full page: https://devtools.krishanchawla.com/devtools/telegram-bot-api More tools: https://devtools.krishanchawla.com