Getting started with TDLib

TDLib is a fully functional Telegram client which takes care of all networking, local storage and data consistency details. In this tutorial we describe the main concepts understanding of which is required for efficient TDLib usage.

TDLib interface

In this text, Client means an interface for interaction with a TDLib instance and Application means the program that uses TDLib to interact with Telegram.

The main TDLib API is fully-asyncronous. An Application can send a request to TDLib through ClientManager.send method and receive a response asynchronously through the ClientManager.receive method when it becomes available. The exact naming of these methods and the way in which requests are matched with responses is different for different TDLib interfaces, but the concept as a whole remains the same. For example, in TDLib JSON interface these methods are called td_send and td_receive, and their @extra field must be used to match requests with the corresponding responses.

In a high-level interface used by an Application the matching of responses with corresponding requests is often automated and transformed by some wrapper into a call to a continuation, a callback, a Promise or a Future to simplify the handling of responses.

Aside from responses to requests, an Application receives a lot of important data through incoming updates. Updates are used to pass new data from TDLib to the Application and often control the behavior of the Application, leaving no chance to implement something wrong. The correct handling of updates is crucial for creating an Application that is efficient and works correctly.

You can find a list of all available TDLib API methods in our web-documentation. You can also find the descriptions of all available TDLib methods and classes in the TDLIB API scheme.

TDLib can be used from any programming language. You can find a lot of examples of TDLib-based frameworks in various programming languages in our examples section.

TDLib glossary

This section describes the basic notions required for understanding the TDLib API. If you have used the TDLib-based Telegram Bot API most of them should be already familiar to you.

Telegram is a messenger, so the main object is a message. Each message belongs to some chat and has a unique identifier within that chat. Messages inside a chat must be sorted by that identifier. Telegram supports many different kinds of messages, so a message can have many different kinds of message content. Currently there are more than 45 different kinds of message content, for example messageText for text messages, messagePhoto for photos, or messageScreenshotTaken for notifications about screenshots taken by the other party.

A Telegram user is called user. Each user has a unique identifier and a first name, and can also have an optional last name, username and profile photo among other useful fields. Bot is a special type of user which can be controlled through the Telegram Bot API.

Each chat has members, i.e. users that immediately receive all messages sent to the chat. Currently there are 6 possible chat member statuses which describe different rights and restrictions a user can have in a chat, ranging from the owner of the chat who has more rights in the chat than any other user, to a user banned in the chat who is banned in the chat and can't return to it by self or even view chat messages, even if the chat is public.

As noted earlier, each message belongs to a chat. Currently there are 4 different types of chats on Telegram:

  • Private chats are ordinary one-to-one chats with another user (or with oneself in the case of the special “Saved messages” chat).
  • Basic groups are basic groups with 0-200 members. Every basic group member has their own copy of the message history, so new basic group members may not see older messages (unless another user forwards their own copy to them).
  • Supergroups are groups with up to 200000 members who share a common message history, so new supergroup members can see all the previously sent messages (unless this is explicitly forbidden by the chat creator). There are special kinds of supergroups, called broadcast groups and channels, which can have an unlimited number of members and where only the chat creator and some chat administrators can write. All other chat members can only read messages in channel and broadcast group chats.
  • Secret chats are end-to-end encrypted one-to-one chats with another user, available only on the device which was used to initiate and accept the chat.

Each chat has a unique identifier, a title and an optional chat photo. Chats comprise sorted lists shown to the user, position in which is determined, roughly speaking, by the time of latest activity. The correct order of chats in chat lists is maintained by TDLib, so the Application only needs to listen to updates that change the chat.positions field and sort all chats by the pair (position.order, chat.id) in a given position.list.

Messages, chat photos and many other objects can have a file inside of them. Each file has an identifier and may be available locally on a local storage or remotely on a cloud server. A file can be usually downloaded to the local storage or uploaded to Telegram cloud servers.

Messages with media content like photos or videos can have a short accompanying text called caption. The texts of text messages and media captions can contain fragments, which must be formatted in some unusual way. These fragments are called text entities and the combination of a text and its entities are referred together as a formatted text.

TDLib sends a lot of important data to the Application through updates. For example, if there is a user unknown to the Application, or some data about a user has changed, then TDLib immediately sends an updateUser to the Application.

You can find list of all currently available updates here »

User authorization

Authorization is an example of a behavior, which is controlled by TDLib through updates. Whenever an action is required to proceed with user authorization, the Application receives an updateAuthorizationState with the description of the current AuthorizationState. The Application only needs to handle this update appropriately to correctly implement user authorization.

The first authorization state received by the Application is always of the type authorizationStateWaitTdlibParameters. When it is received, the Application must provide parameters for TDLib initialization by calling the setTdlibParameters method. In this method the Application will need to specify, among other parameters:

  • api_id — Application identifier for accessing the Telegram API, which can be obtained at https://my.telegram.org.
  • api_hash — Hash of the Application identifier for accessing the Telegram API, which can be obtained at https://my.telegram.org.
  • database_directory — The path to the directory on the local disk where the TDLib database is to be stored; must point to a writable directory.
  • use_message_database — If set to true, the library will maintain a local cache of chats and messages.
  • use_secret_chats — If set to true, support for secret chats will be enabled.
  • system_language_code — IETF language tag of the user's operating system language, like “en-GB”.
  • device_model — Model of the device the Application is being run on, like “iPhone Z”.

After call to setTdlibParameters in case of success Application will receive updateAuthorizationState with new state and just needs to handle that update, nothing should be done explicitly. If setTdlibParameters fails, then authorization state is not changed and the Application must try to handle the current authorization state again.

If user isn't authorized yet, then some of authorizationStateWaitPhoneNumber, authorizationStateWaitEmailAddress, authorizationStateWaitEmailCode, authorizationStateWaitCode, authorizationStateWaitRegistration and authorizationStateWaitPassword authorization states may be received. After completing these authorization steps, the Application will receive authorizationStateReady, meaning that authorization was successful and ordinary requests can be sent now.

You can find complete examples of user authorization in our Java and C# examples.

Sending a message

To send any kind of message, the Application needs to call the method sendMessage providing a chat identifier and the content of the message to be sent. For example, the Application can send a text message using inputMessageText class as input message content, a photo using inputMessagePhoto, or a location using inputMessageLocation. The Application can use inputFileLocal as InputFile in these objects to send a local file from the local storage.

You can find examples of sending a text message in our Java and C# examples.

Handling updates

All updates and responses to requests must be handled in the order they are received. Here is a list of the most important updates and how they must be handled:

  • updateAuthorizationState — The handling of this update is essential for correct user authorization.
  • updateNewChat — This update is received whenever a new chat is discovered. This update is guaranteed to come before the chat identifier is returned to the Application. So, whenever an Application receives a chat_id, it never needs to use a getChat request to receive the chat object. Instead it must maintain a cache of chats received through this update and take all the necessary data about chats from this cache.
  • updateUser — This update is received whenever a new user has been discovered or some data about a known user has changed. This update is guaranteed to come before the user identifier is returned to the Application. So, whenever an Application receives a user_id, it never needs to use the getUser request to receive the user object. Instead it must maintain a cache of users received through this update and take all the necessary data about users from this cache.
  • updateBasicGroup — This update is received whenever a new basic group has been discovered or some data about a known basic group has changed. This update is guaranteed to come before the basic group identifier is returned to the Application. So, whenever an Application receives a basic_group_id, it never needs to use the getBasicGroup request to receive the basicGroup object. Instead it must maintain a cache of basic groups received through this update and take all the necessary data about basic groups from this cache.
  • updateSupergroup — This update is received whenever a new supergroup has been discovered or some data about a known supergroup has changed. This update is guaranteed to come before the supergroup identifier is returned to the Application. So, whenever an Application receives a supergroup_id, it never needs to use the getSupergroup request to receive the supergroup object. Instead it must maintain a cache of supergroups received through this update and take all the necessary data about supergroups from this cache.
  • updateSecretChat — This update is received whenever a new secret chat has been discovered or some data about a known secret chat has changed. This update is guaranteed to come before the secret chat identifier is returned to the Application. So, whenever an Application receives a secret_chat_id, it never needs to use the getSecretChat request to receive the secret chat object. Instead it must maintain a cache of secret chats received through this update and take all the necessary data about secret chats from this cache.
  • updateNewMessage — This update is received whenever a new message is added to a chat.
  • updateMessageSendSucceeded — This update is received whenever a message is successfully sent.
  • updateMessageContent — This update is received whenever the content of a message changes.
  • updateFile — This update is received whenever information about a file is updated. The handling of this update is essential to follow the progress of files being downloaded or uploaded.
  • updateChatTitle, updateChatPhoto, updateChatPermissions, updateChatLastMessage, updateChatPosition, updateChatReadInbox, updateChatReadOutbox, updateChatActionBar, updateChatDraftMessage, updateChatMessageSender, updateChatMessageTtl, updateChatNotificationSettings, updateChatPendingJoinRequests, updateChatReplyMarkup, updateChatTheme, updateChatUnreadMentionCount, updateChatVideoChat, updateChatDefaultDisableNotification, updateChatHasProtectedContent, updateChatHasScheduledMessages, updateChatIsBlocked, updateChatIsMarkedAsUnread — These updates are received whenever some information about a chat changes, the chats cache must be updated accordingly

For a full list of currently available updates see the documentation for the Update class.

You can find an example of correct handling of some updates in our Java example.

Getting the lists of chats

Currently there are 3 different types of chat lists:
- Main chat list.
- Archive chat list.
- A folder chat list.

The positions of chats in chat lists are managed by TDLib, so the Application only needs to listen to updates that change the chat.positions field, maintain the list of all chats, sorted by the pair (position.order, chat.id) in descending order, and call loadChats only if more chats are needed. For optimal performance, the number of loaded chats is chosen by TDLib and can be smaller than the specified limit. If the Application needs more chats, it must send another loadChats request.

You can find an example of retrieving the Main chat list in our Java example.

Getting chat messages

The Application can use the method getChatHistory to get messages in a chat. The messages will be returned in the reverse chronological order (i.e., in descending order of message_id). The Application can pass from_message_id == 0 to get messages from the last message. To get more messages than can be returned in one response, the Application needs to pass the identifier of the last message it has received as from_message_id to next request. For optimal performance, the number of the returned messages is chosen by TDLib and can be smaller than the specified limit. If the Application needs more messages, it needs to adjust the from_message_id parameter and repeat the request.