Skip to content

About Telegram's Bot API

Nill edited this page Dec 29, 2021 · 1 revision

Telegram's Bot API is a RESTful API that transports JSON (and occasionally html-form-encoded) payloads to provide a rapid development experience that is consistent with other messaging platforms' APIs.

The Bot API is drastically different from the MTProto protocol that is used by the Telegram clients and some bots (colloquially called "userbots"). The Bot API uses standard HTTPS, and compared to many other APIs of its nature, is fairly forgiving.

Methods

Telegram calls their API endpoints "methods", which is consistent with their invocation from a C# perspective. For this reason Telefrag refers to the process of making an outbound API call to Telegram's servers a method invocation despite the overlap with C#'s own internal method invocation.

  • Telegram methods will accept GET or POST regardless of what the method does
  • The name of a Telegram method is part of the URL used to access it (e.g. sendMessage)
  • The parameters of a Telegram method call can either be URL-encoded and sent as the query string (Telefrag doesn't do this), or JSON-encoded and sent in the request body of a POST request (Telefrag does this). They also can be supplied in the form of www-encoded form data (Telefrag uses this only in method calls that upload binary files).
  • Every method has a return value, which is usually an object, but in the simplest cases is a bool that always returns true (because if the operation fails, an error is thrown instead of the method returning a value. In Telefrag this manifests as a TelegramException and you find out more here).

Telegram method calls are synchronous; the server will not return a response until it has finished the operation. In Telefrag, anything that could initiate an outbound method call to Telegram is awaitable and returns a Task<T> (where T is the return type of the object that will come back from Telegram) which completes (or fails) upon Telegram's response.

Bots use a single HttpClient for outbound method calls (separate from the one used for polling) and thus method calls will execute synchronously with respect to each other; a single Bot cannot be making two or more outbound requests to Telegram at a time.

Updates

Telegram sends data to your Bot in the form of Updates, which are objects that describe an event (such a chat message or a user joining a chat).

As of this writing, Updates are never sent as a response to a method call; updates will always represent something that someone else is doing/has done; in other words, you will never receive data back from a method call you invoke in the form of an update.

Updates can be received either via polling or webhooks. Telefrag can automatically attempt to use a webhook and fall back to polling if the attempt fails.

Polling

Polling is the simplest mechanism for receiving updates; despite the name, polling typically does not introduce any delay or latency to receiving updates at low to medium volumes.

When polling, Telefrag uses a seperate HttpClient to invoke a special getUpdates method which uses long polling techniques to recieve data almost as soon as it is available without Telegram needing to connect inbound to your computer.

Telegram queues updates up for your Bot all the time (whether you're using polling or webhooks), and getUpdates merely retrieves the pending updates your bot hasn't yet acknowledged. The magic here is that if there are no pending updates (the case 98% of the time), the method call will block until there are, up to a certain timeout. Telefrag coordinates with Telegram to essentially always be ready to receive updates as they occur.

Telefrag tracks the ID of the last update received and sends this back to Telegram when it begins polling to better coordinate where the two systems left off successfully processing updates; if Telefrag doesn't have the ID of the last received update, it will ask Telegram to send all unacknowledged updates (per Telegram's tracking) when it begins polling.

Webhooks

Webhooks are the route to go when your bot receives a high volume of updates or if you want to load-balance your bot across multiple instances.

With webhooks, Telegram makes a connection out to you (and you're typically running Telefrag as part of a web server) and pushes the updates in the form of small HTTP POST messages containing an array of update objects.

Webhooks are the optimal choice for receiving updates but it has many requirements and technical hurdles that usually make it more hassle than it's worth for small bots:

  • Telegram must be able to reach your application on port 80, 443, 8080, or 8443
    • This means your firewall must be open
    • If you are behind a NAT the ports must be forwarded appropriately
    • If you are on a home connection your ISP may block these port numbers without a business contract
  • Telegram requires TLS
    • This means you must set up TLS on your web server and configure an X.509 certificate
    • Telegram needs to either trust your certificate natively (meaning you obtained it from a Publicly-trusted CA) or you need to explicitly inform Telegram of your certificates thumbprint (Telefrag does this for you)
    • Even if you're not using a publicly signed cert, it has an expiration date and will stop working beyond that date unless replaced.
  • Telegram sends updates from multiple servers/IP addresses.
    • If you are behind a firewall that you don't have the authority or protection required to open your app to the entire internet, you will need to keep your firewall rules up to date with Telegram's latest list of datacenter IP's.
  • Telegram usually requires the latest and greatest TLS version and cipher suites.
    • This means that one day your bot may stop working because the ambient security level of the internet has leveled up and Telegram no longer trusts web servers with specific cryptographic algorithms such as hashes, ciphers, and key exchange mechanisms (e.g. RC4, MD5, SHA1)

For more information on how you can set up Telefrag with webhooks, click here

Acknowledgement and Retry

Regardless of whether you use webhooks or polling; Telegram will queue updates up for your bot as they occur. There are limits to how long Telegram will keep updates queued, as well as how many queued updates Telegram will retain for a given bot, so it's important that your bot is relatively available; but the takeaway is that if your bot is offline briefly; it won't really miss anything it won't be re-sent.

Telegram considers an update acknowledged when either:

  • It's been sent to you (via getUpdates) as part of polling
  • It's been sent to you via webhook and your server responded with a 200 status.

If you stop polling, your server goes down, or your webhook is failing (and Telegram is receiving a 4xx/5xx error), Telegram will merely continue queuing updates. When using webhooks, Telegram will periodically reattempt to send the last unacknowledged update. If and when it is successful (you respond with 200), it will consider your webhook healthy again and begin sending you the rest of the missed updates.

You can use getWebhookInfo to check the status of your webhook, including how many queued updates are waiting.

var info = await Methods.GetWebhookInfo(Connection.Webhook.URL);
Console.WriteLine($"I have {info.pending_update_count} pending updates Telegram is trying to send me.");

Bot API vs MTProto

The Bot API is hosted by software that translates between the Rest API and MTProto. All of the methods you call turn into MTProto messages sent in turn to Telegram by the Bot API Server (typically also hosted by Telegram).

Bot Accounts vs Human Accounts

The Bot API itself must be authenticated using a bot token retrieved from BotFather. Client API connections can use either a normal user account (with phone number and MFA) or a Bot account and bot token.

Quirks and Features

  • getMe gets the User object that represents your Bot. Telefrag automatically pulls this upon bot initialization and stores it in Bot.Identity

Clone this wiki locally