Convert Figma logo to code with AI

tdlib logotd

Cross-platform library for building Telegram clients

6,953
1,424
6,953
92

Top Related Projects

Pure Python 3 MTProto API Telegram client library, for bots too!

Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots

25,848

Telegram Desktop messaging app

Telegram-iOS

24,740

Telegram for Android source

Quick Overview

The tdlib/td repository is a cross-platform library for building Telegram clients. It provides a high-level API for interacting with the Telegram API, allowing developers to create their own Telegram applications with ease.

Pros

  • Cross-platform: tdlib is designed to be cross-platform, supporting a wide range of operating systems, including Windows, macOS, Linux, iOS, and Android.
  • Efficient and Scalable: The library is optimized for performance and can handle large amounts of data efficiently, making it suitable for building scalable Telegram applications.
  • Comprehensive API: tdlib provides a comprehensive API that covers a wide range of Telegram features, including messaging, file management, user management, and more.
  • Active Development: The project is actively maintained and developed, with regular updates and bug fixes.

Cons

  • Steep Learning Curve: The library has a relatively steep learning curve, especially for developers who are new to the Telegram API or the C++ programming language.
  • Limited Documentation: While the project has some documentation, it can be sparse or outdated in certain areas, making it challenging for new users to get started.
  • Dependency on C++: The library is written in C++, which may not be the preferred language for all developers, especially those working in other programming languages.
  • Limited Community Support: Compared to some other Telegram client libraries, the tdlib community may be smaller, which can make it harder to find support and resources.

Code Examples

Here are a few examples of how to use the tdlib library:

  1. Initializing the Library:
#include <td/telegram/td_json_client.h>

int main() {
    void* client = td_json_client_create();
    // Use the client to interact with the Telegram API
    td_json_client_destroy(client);
    return 0;
}
  1. Sending a Message:
#include <td/telegram/td_json_client.h>

void sendMessage(void* client, int64_t chatId, const char* text) {
    char* request = td_json_client_create_request("sendMessage", nullptr, "{\"chat_id\":%lld,\"text\":\"%s\"}", chatId, text);
    char* response = td_json_client_execute(client, request);
    // Process the response
    td_json_client_destroy_request(request);
}
  1. Updating User Profile:
#include <td/telegram/td_json_client.h>

void updateUserProfile(void* client, const char* firstName, const char* lastName) {
    char* request = td_json_client_create_request("setName", nullptr, "{\"first_name\":\"%s\",\"last_name\":\"%s\"}", firstName, lastName);
    char* response = td_json_client_execute(client, request);
    // Process the response
    td_json_client_destroy_request(request);
}
  1. Uploading a File:
#include <td/telegram/td_json_client.h>

void uploadFile(void* client, const char* filePath, const char* fileType) {
    char* request = td_json_client_create_request("uploadFile", nullptr, "{\"file\":\"%s\",\"file_type\":\"%s\"}", filePath, fileType);
    char* response = td_json_client_execute(client, request);
    // Process the response
    td_json_client_destroy_request(request);
}

Getting Started

To get started with the tdlib library, follow these steps:

  1. Install Dependencies: Ensure that you have the necessary dependencies installed, such as a C++ compiler, CMake, and any platform-specific libraries.

  2. Clone the Repository: Clone the tdlib repository from GitHub:

    git clone https://github.com/tdlib/td.git
    
  3. Build the Library: Navigate to the cloned repository and create a build directory. Then, use CMake to generate the build files and build the library:

    cd td
    mkdir build
    cd build
    cmake ..
    make
    

Competitor Comparisons

Pure Python 3 MTProto API Telegram client library, for bots too!

Pros of Telethon

  • Written in Python, making it more accessible for Python developers
  • Simpler API and easier to get started with for beginners
  • More lightweight and suitable for smaller projects or scripts

Cons of Telethon

  • Less performant than TD, especially for large-scale applications
  • Limited support for some advanced Telegram features
  • May require more frequent updates to keep up with Telegram API changes

Code Comparison

Telethon example:

from telethon import TelegramClient

client = TelegramClient('session', api_id, api_hash)

async def main():
    await client.send_message('username', 'Hello!')

with client:
    client.loop.run_until_complete(main())

TD example (using Python bindings):

from ctypes import *
from td import Client

client = Client()
client.send({'@type': 'setTdlibParameters', 'parameters': {...}})

result = client.receive()
if result['@type'] == 'ok':
    client.send({'@type': 'sendMessage', 'chat_id': chat_id, 'input_message_content': {...}})

Both libraries offer ways to interact with the Telegram API, but Telethon provides a more Pythonic interface, while TD offers a lower-level, potentially more efficient approach. TD is generally better suited for large-scale applications or when performance is critical, while Telethon is often preferred for its ease of use and Python-native design.

Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots

Pros of Pyrogram

  • Easier to use and more Pythonic, with a simpler API
  • Faster development and prototyping for Python developers
  • Better documentation and community support for Python users

Cons of Pyrogram

  • Limited to Python, while TD supports multiple languages
  • May have fewer features compared to TD's comprehensive implementation
  • Potentially slower performance due to Python's interpreted nature

Code Comparison

TD (C++):

auto client = td::Client::create();
client->send(td_api::make_object<td_api::getMe>());

Pyrogram (Python):

from pyrogram import Client

app = Client("my_account")
me = app.get_me()

Summary

Pyrogram is a Python-specific Telegram client library, while TD is a cross-platform library written in C++. Pyrogram offers a more user-friendly API for Python developers, but TD provides broader language support and potentially better performance. The choice between the two depends on the developer's preferred language, project requirements, and performance needs.

25,848

Telegram Desktop messaging app

Pros of tdesktop

  • Full-featured desktop client with a complete GUI
  • Includes additional features like custom themes and local message search
  • Actively maintained with frequent updates and new feature implementations

Cons of tdesktop

  • Larger codebase and more complex due to GUI implementation
  • May have higher resource usage compared to a lightweight library
  • Potentially slower to integrate into custom applications

Code Comparison

td (C++ API example):

auto client = td::Client::create();
client->send({{"@type", "getAuthorizationState"}});

tdesktop (Qt-based GUI code snippet):

auto window = new MainWindow();
window->show();

Key Differences

  • td is a library for building Telegram clients, while tdesktop is a complete desktop application
  • td offers more flexibility for custom implementations, tdesktop provides a ready-to-use solution
  • td is better suited for integrating Telegram functionality into other applications, while tdesktop is ideal for users who want a standalone Telegram client

Use Cases

  • Choose td for building custom Telegram clients or integrating Telegram features into existing applications
  • Opt for tdesktop if you need a fully-featured desktop client with a polished user interface

Both projects are open-source and actively maintained, catering to different needs within the Telegram ecosystem.

Telegram-iOS

Pros of Telegram-iOS

  • Native iOS implementation, providing a smooth and platform-specific user experience
  • Includes a complete user interface, ready for end-users
  • Regularly updated with new iOS features and design guidelines

Cons of Telegram-iOS

  • Limited to iOS platform, not suitable for cross-platform development
  • Larger codebase, potentially more complex to understand and modify
  • Tightly coupled with Telegram's specific implementation

Code Comparison

Telegram-iOS (Swift):

class ChatListController: ViewController {
    func updateChatList() {
        // iOS-specific UI update logic
    }
}

td (C++):

void Client::send_query(td_api::object_ptr<td_api::Function> f, std::function<void(Object)> handler) {
    // Cross-platform API call
}

Key Differences

  • Telegram-iOS is a complete application, while td is a cross-platform library
  • td offers more flexibility for custom implementations across various platforms
  • Telegram-iOS provides a polished, ready-to-use iOS client
  • td requires additional work to create a user interface and platform-specific features

Use Cases

  • Choose Telegram-iOS for rapid iOS app development or official Telegram client modifications
  • Opt for td when building custom Telegram clients across multiple platforms or integrating Telegram functionality into existing applications
24,740

Telegram for Android source

Pros of Telegram

  • User-friendly Android client with a polished UI
  • Includes features specific to the Telegram mobile experience
  • Easier to set up for end-users who want a ready-to-use Telegram app

Cons of Telegram

  • Limited to Android platform
  • Less flexibility for developers who want to build custom Telegram-based applications
  • May not have access to all low-level Telegram API features

Code Comparison

Telegram (Java):

public void sendMessage(String text) {
    SendMessage message = new SendMessage();
    message.setChatId(chatId);
    message.setText(text);
    try {
        execute(message);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

TD (C++):

void send_message(int64 chat_id, string text) {
    auto message = td_api::make_object<td_api::sendMessage>();
    message->chat_id_ = chat_id;
    message->input_message_content_ = td_api::make_object<td_api::inputMessageText>(
        td_api::make_object<td_api::formattedText>(text, vector<td_api::object_ptr<td_api::TextEntity>>())
    );
    send_query(std::move(message), {});
}

Summary

Telegram is a ready-to-use Android client, while TD is a cross-platform library for building Telegram clients. Telegram offers a more polished user experience but is limited to Android, whereas TD provides greater flexibility for developers to create custom Telegram-based applications across multiple platforms.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

TDLib

TDLib (Telegram Database library) is a cross-platform library for building Telegram clients. It can be easily used from almost any programming language.

Table of Contents

Features

TDLib has many advantages. Notably TDLib is:

  • Cross-platform: TDLib can be used on Android, iOS, Windows, macOS, Linux, FreeBSD, OpenBSD, NetBSD, illumos, Windows Phone, WebAssembly, watchOS, tvOS, visionOS, Tizen, Cygwin. It should also work on other *nix systems with or without minimal effort.
  • Multilanguage: TDLib can be easily used with any programming language that is able to execute C functions. Additionally, it already has native Java (using JNI) bindings and .NET (using C++/CLI and C++/CX) bindings.
  • Easy to use: TDLib takes care of all network implementation details, encryption and local data storage.
  • High-performance: in the Telegram Bot API, each TDLib instance handles more than 25000 active bots simultaneously.
  • Well-documented: all TDLib API methods and public interfaces are fully documented.
  • Consistent: TDLib guarantees that all updates are delivered in the right order.
  • Reliable: TDLib remains stable on slow and unreliable Internet connections.
  • Secure: all local data is encrypted using a user-provided encryption key.
  • Fully-asynchronous: requests to TDLib don't block each other or anything else, responses are sent when they are available.

Examples and documentation

See our Getting Started tutorial for a description of basic TDLib concepts.

Take a look at our examples.

See a TDLib build instructions generator for detailed instructions on how to build TDLib.

See description of our JSON, C++, Java and .NET interfaces.

See the td_api.tl scheme or the automatically generated HTML documentation for a list of all available TDLib methods and classes.

Dependencies

TDLib depends on:

  • C++14 compatible compiler (Clang 3.4+, GCC 4.9+, MSVC 19.0+ (Visual Studio 2015+), Intel C++ Compiler 17+)
  • OpenSSL
  • zlib
  • gperf (build only)
  • CMake (3.0.2+, build only)
  • PHP (optional, for documentation generation)

Building

The simplest way to build TDLib is to use our TDLib build instructions generator. You need only to choose your programming language and target operating system to receive complete build instructions.

In general, you need to install all TDLib dependencies, enter directory containing TDLib sources and compile them using CMake:

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build .

To build TDLib on low memory devices you can run SplitSource.php script before compiling main TDLib source code and compile only needed targets:

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build . --target prepare_cross_compiling
cd ..
php SplitSource.php
cd build
cmake --build . --target tdjson
cmake --build . --target tdjson_static
cd ..
php SplitSource.php --undo

In our tests clang 6.0 with libc++ required less than 500 MB of RAM per file and GCC 4.9/6.3 used less than 1 GB of RAM per file.

Using in CMake C++ projects

For C++ projects that use CMake, the best approach is to build TDLib as part of your project or to install it system-wide.

There are several libraries that you could use in your CMake project:

  • Td::TdJson, Td::TdJsonStatic — dynamic and static version of a JSON interface. This has a simple C interface, so it can be easily used with any programming language that is able to execute C functions. See td_json_client documentation for more information.
  • Td::TdStatic — static library with C++ interface for general usage. See ClientManager and Client documentation for more information.

For example, part of your CMakeLists.txt may look like this:

add_subdirectory(td)
target_link_libraries(YourTarget PRIVATE Td::TdStatic)

Or you could install TDLib and then reference it in your CMakeLists.txt like this:

find_package(Td 1.8.36 REQUIRED)
target_link_libraries(YourTarget PRIVATE Td::TdStatic)

See example/cpp/CMakeLists.txt.

Using in Java projects

TDLib provides native Java interface through JNI. To enable it, specify option -DTD_ENABLE_JNI=ON to CMake.

See example/java for example of using TDLib from Java and detailed build and usage instructions.

Using in .NET projects

TDLib provides native .NET interface through C++/CLI and C++/CX. To enable it, specify option -DTD_ENABLE_DOTNET=ON to CMake. .NET Core supports C++/CLI only since version 3.1 and only on Windows, so if older .NET Core is used or portability is needed, then TDLib JSON interface should be used through P/Invoke instead.

See example/csharp for example of using TDLib from C# and detailed build and usage instructions. See example/uwp for example of using TDLib from C# UWP application and detailed build and usage instructions for Visual Studio Extension "TDLib for Universal Windows Platform".

When TDLib is built with TD_ENABLE_DOTNET option enabled, C++ documentation is removed from some files. You need to checkout these files to return C++ documentation back:

git checkout td/telegram/Client.h td/telegram/Log.h td/tl/TlObject.h

Using from other programming languages

TDLib provides efficient native C++, Java, and .NET interfaces. But for most use cases we suggest to use the JSON interface, which can be easily used with any programming language that is able to execute C functions. See td_json_client documentation for detailed JSON interface description, the td_api.tl scheme or the automatically generated HTML documentation for a list of all available TDLib methods and classes.

TDLib JSON interface adheres to semantic versioning and versions with the same major version number are binary and backward compatible, but the underlying TDLib API can be different for different minor and even patch versions. If you need to support different TDLib versions, then you can use a value of the version option to find exact TDLib version to use appropriate API methods.

See example/python/tdjson_example.py for an example of such usage.

License

TDLib is licensed under the terms of the Boost Software License. See LICENSE_1_0.txt for more information.