Back

Telegram Bot API Essential Guide

Aug 3, 20246 minute read

What type of API does Telegram Bot provide?

The Telegram Bot API is a REST API. Here are the key points about Telegram's Bot API:

Type of API

  • Telegram Bot API is a REST API.

Key Characteristics

  • It is an HTTP-based interface created for developers to build bots for Telegram.
  • All queries to the Telegram Bot API must be served over HTTPS.
  • Requests are made to endpoints in the format: https://api.telegram.org/bot<token>/METHOD_NAME.
  • It supports both GET and POST HTTP methods.

Data Format and Methods

  • The API supports passing parameters in 4 ways:
    • URL query string
    • application/x-www-form-urlencoded
    • application/json (except for uploading files)
    • multipart/form-data (used to upload files)
  • Responses contain a JSON object with a Boolean 'ok' field and an optional 'description' field.
  • If successful, the result is in the 'result' field of the JSON response.

Implementation Example

Here's a simple example of using the Telegram Bot API to send a message:

import requests # Telegram Bot API endpoint url = 'https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage' # Send a message using the bot def send_message(chat_id, text): params = {'chat_id': chat_id, 'text': text} response = requests.post(url, json=params) if response.status_code == 200: print('Message sent successfully!') else: print('Failed to send message.') # Example usage send_message('123456789', 'Hello from your bot!')

Summary

The Telegram Bot API follows REST principles, using HTTP methods and JSON for data exchange. It provides a straightforward way for developers to interact with Telegram's platform and create bots. The API's design allows for easy integration with various programming languages and frameworks that support HTTP requests.

Does the Telegram Bot API have webhooks?

Yes, the official Telegram Bot API does support webhooks. Here are the key points about webhooks in the Telegram Bot API:

  1. Webhooks can be set up using the setWebhook method.

  2. When using webhooks, Telegram will send HTTPS POST requests to your specified URL whenever there is an update for your bot.

  3. The updates are sent as JSON-serialized Update objects.

  4. You can specify which types of updates you want to receive via webhook using the allowed_updates parameter. This allows you to subscribe to specific event types.

  5. Some of the event types you can subscribe to include:

    • message - New incoming message
    • edited_message - Edited message
    • channel_post - New channel post
    • edited_channel_post - Edited channel post
    • inline_query - Inline query
    • chosen_inline_result - Chosen inline result
    • callback_query - Callback query
    • shipping_query - Shipping query
    • pre_checkout_query - Pre-checkout query
    • poll - Poll update
    • poll_answer - Poll answer
    • And more
  6. Webhooks require SSL/TLS encryption and can only be set on certain ports (443, 80, 88, 8443).

  7. You can optionally set a secret token to verify webhook requests are coming from Telegram.

  8. When using webhooks, you cannot use the getUpdates method to receive updates.

So in summary, webhooks are fully supported and allow you to receive real-time updates for a wide variety of event types from the Telegram Bot API. The setWebhook method gives you fine-grained control over what types of events you want to subscribe to.

Rate Limits and other limitations

Here are the key API rate limits for the Telegram Bot API:

General Limits

  • When sending messages inside a particular chat, avoid sending more than one message per second. Exceeding this may eventually result in 429 errors.

  • For bulk notifications to multiple users, the API will not allow more than 30 messages per second overall.

  • Bots cannot send more than 20 messages per minute to the same group.

Limits for Different Chat Types

  • Individual chats: 1 message per second

  • Groups/channels: 20 messages per minute

  • Overall limit: 30 messages per second across all chats

Key Points to Consider

  • The limits are per bot account, not per host/server. Multiple bots on the same server each have their own limits.

  • There are no built-in methods for sending bulk messages. Spreading notifications over longer intervals (8-12 hours) is recommended to avoid hitting limits.

  • If limits are exceeded, you'll start receiving 429 (Too Many Requests) errors.

  • Telegram has "soft" limits where you may be able to exceed them briefly, but will eventually be restricted if continued.

Best Practices

  • Implement queuing and rate limiting in your bot code to stay within the limits proactively.

  • Use different queues/limits for individual chats vs groups/channels.

  • Implement retry logic with exponential backoff when receiving 429 errors.

  • For mass notifications, spread them out over longer time periods.

By following these limits and best practices, you can ensure your Telegram bot operates smoothly within the API constraints. Proper queuing and rate limiting implementation is key to avoiding issues.

Latest API Version

The most recent version of the Telegram Bot API is 7.7 [3].

Key points:

  • The Telegram Bot API is an HTTP-based interface created for developers to build bots for Telegram [1].

  • It provides JSON-encoded responses to queries [4].

  • The API is regularly updated with new features and improvements [2].

  • Developers can use libraries and frameworks in various programming languages to interact with the API more efficiently [4].

Additional information:

  • The Bot API documentation provides detailed information on all available methods and objects [1].

  • There are optional dependencies for certain features, but the core functionality requires only httpx ~= 0.27 [3].

  • python-telegram-bot is a popular library that supports all types and methods of the Telegram Bot API 7.7 [3].

  • Telegram offers both the Bot API and the Telegram API (for custom clients) to developers free of charge [5].

  • Developers can also make use of the Payments API to accept payments from Telegram users [5].

Best practices:

  • Stay updated with the latest API changes by checking the changelog regularly [2].

  • Use libraries and frameworks for more robust and scalable bot development [4].

  • Consider using optional dependencies for advanced features when needed [3].

  • Familiarize yourself with the official Telegram Bot API documentation for comprehensive information [3].

How to get a Telegram Bot developer account and API Keys?

1. Sign up for Telegram

First, you need to sign up for a Telegram account using any Telegram application if you don't already have one.

2. Create a Bot

To create a bot, you need to talk to the BotFather on Telegram:

  1. Open Telegram and search for @BotFather
  2. Start a chat with BotFather and send the command /newbot
  3. Follow the prompts to choose a name and username for your bot
  4. BotFather will generate an authorization token for your bot

3. Obtain API Credentials

To get API credentials for your bot:

  1. Log in to the Telegram website: https://my.telegram.org
  2. Go to "API development tools"
  3. Fill out the form to create a new application
  4. You will receive an api_id and api_hash for your application

4. Set Up the Bot API

With your bot token and API credentials, you can now use the Telegram Bot API:

  1. The API endpoint is: https://api.telegram.org/bot<token>/<method>
  2. Replace <token> with your bot's authorization token
  3. Replace <method> with the API method you want to call

What can you do with the Telegram Bot API?

Here are the key data models you can interact with using the Telegram Bot API:

User

  • Get user information like ID, name, username, language code
  • Check if user is a bot, premium user, etc.
  • Get user profile photos

Chat

  • Get chat information like ID, type, title, description
  • Manage chat members (kick, ban, unban, etc.)
  • Edit chat settings and permissions
  • Pin/unpin messages

Message

  • Send text, photo, video, audio, document messages
  • Edit and delete messages
  • Get message information like ID, date, sender, etc.
  • Forward messages

Inline Query

  • Receive inline queries from users
  • Answer inline queries with results

Callback Query

  • Receive callback queries from inline keyboard buttons
  • Answer callback queries

Poll

  • Create polls and quizzes
  • Stop polls
  • Get poll results

Sticker

  • Send stickers
  • Get sticker set information
  • Upload new sticker sets

File

  • Download files shared in chats
  • Upload files to send in messages

WebhookInfo

  • Set and delete webhooks
  • Get current webhook status

BotCommand

  • Set bot commands that appear in menu
  • Delete bot commands

ChatMember

  • Get information about chat members
  • Restrict and promote chat members

Update

  • Receive updates about new messages, edited messages, etc.

The API allows you to interact with these models by sending HTTP requests to perform actions like sending messages, editing chats, answering inline queries, etc. The full capabilities for each model are detailed in the official Bot API documentation.