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.
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_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.
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.
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.
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
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 »
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:
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.
The second received authorization state is always
authorizationStateWaitEncryptionKey. When it is received, the database encryption key must be provided through a call to
checkDatabaseEncryptionKey. For most mobile apps, you can provide an empty database encryption key here (more info). If user isn't authorized yet, then some of
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.
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.
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:
chat_id, it never needs to use a
getChatrequest 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.
user_id, it never needs to use the
getUserrequest 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.
basic_group_id, it never needs to use the
getBasicGrouprequest to receive the
basicGroupobject. 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.
supergroup_id, it never needs to use the
getSupergrouprequest 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.
secret_chat_id, it never needs to use the
getSecretChatrequest 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.
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.
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
You can find an example of retrieving the Main chat list in our Java example.
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.