SDKs overview
Telegraph's ecosystem supports developers in building applications that integrate with the Telegram messaging service through its extensive API. The Telegram API itself is a comprehensive interface for interacting with the core messaging functionality, enabling actions such as sending and receiving messages, managing chats, and handling user data. Developers can choose between official SDKs, which are typically maintained by the Telegram team or closely affiliated groups, and a wide array of community-contributed libraries. These SDKs and libraries abstract the underlying network communication and protocol details, allowing developers to focus on application logic rather than low-level API interactions. They often provide objects and methods that map directly to Telegram API concepts, streamlining development for various programming languages and platforms. The primary focus for many developers is bot creation, leveraging the Telegram Bot API, which is a specialized subset of the main API designed for automated accounts.
The Telegram API design emphasizes efficiency and reliability, using a custom protocol called MTProto for secure communication. While direct interaction with MTProto is possible, SDKs significantly simplify this process. They handle aspects like data serialization, encryption, and network requests, presenting a higher-level interface. This approach facilitates faster development cycles and reduces the likelihood of implementation errors when integrating with Telegram's services. The availability of diverse SDKs across multiple languages ensures that developers can work within their preferred programming environments, from backend services to desktop and mobile applications.
Official SDKs by language
While Telegram primarily provides a comprehensive API specification and documentation rather than a full suite of officially maintained SDKs for every language, certain tools and libraries are considered de facto official or are closely supported by the Telegram team due to their direct integration or historical significance. The Telegram API documentation serves as the primary reference for all implementations. For bot development, the Bot API is extensively covered and has robust support across various languages through community-driven wrappers.
The core API, which allows for building custom Telegram clients, is more complex and often relies on community efforts or specific foundational libraries provided by Telegram. The following table highlights some key libraries and approaches:
| Language | Package/Approach | Maturity | Description |
|---|---|---|---|
| Python | python-telegram-bot | Stable | A popular, full-featured wrapper for the Telegram Bot API. Widely used for creating bots. |
| JavaScript/Node.js | node-telegram-bot-api | Stable | A well-maintained library for interacting with the Telegram Bot API in Node.js environments. |
| PHP | telegram-bot-sdk | Stable | A robust PHP SDK for the Telegram Bot API, offering a fluent interface. |
| Go | go-telegram-bot-api | Stable | A simple and clean Go library for the Telegram Bot API. |
| Java | java-telegram-bot-api | Stable | A Java wrapper for the Telegram Bot API, supporting various features. |
| TDLib (C++/C/Java/Python/etc.) | Telegram Database Library | Official/Stable | Telegram's own cross-platform library for building custom Telegram clients. Provides a low-level interface to the Telegram API. |
TDLib (Telegram Database Library) is a particularly significant offering from Telegram. It is designed to simplify the development of custom Telegram client applications on any platform. TDLib handles all network implementation details, encryption, and local data storage, offering a high-level interface. Its cross-platform nature and official backing make it a foundational component for developers looking to build fully-fledged Telegram clients rather than just bots. Developers can find detailed instructions and examples for using TDLib across various languages in its official GitHub repository examples.
Installation
Installation methods for Telegram SDKs and libraries largely depend on the programming language and package manager in use. Below are common installation instructions for some of the widely used libraries, focusing on the Bot API given its prevalence.
Python: python-telegram-bot
This library is installed via pip, Python's package installer. Ensure you have Python and pip installed on your system.
pip install python-telegram-bot --pre
The --pre flag is currently recommended to install the latest stable version, as development often occurs rapidly.
Node.js: node-telegram-bot-api
For Node.js projects, npm (Node Package Manager) is the standard tool. Initialize your project and then add the library:
npm init -y
npm install node-telegram-bot-api
This command adds the package to your node_modules directory and updates your package.json file.
PHP: telegram-bot-sdk
Composer is the dependency manager for PHP. If you don't have Composer, you'll need to install Composer first.
composer require irazasyed/telegram-bot-sdk
This command will download and install the SDK and its dependencies into your project's vendor/ directory.
Go: go-telegram-bot-api
Go modules are used for dependency management. Navigate to your project directory and use go get:
go get github.com/go-telegram-bot-api/telegram-bot-api/v5
This fetches the library and adds it to your go.mod file. Note the /v5 for the current major version.
TDLib
TDLib installation is more involved as it often requires compilation from source or using pre-built binaries, depending on the target platform and language binding. Developers should refer to the official TDLib documentation for detailed build instructions specific to their environment. For example, building TDLib on Ubuntu might involve:
sudo apt update
sudo apt install build-essential git zlib1g-dev libssl-dev libreadline-dev libtool autoconf automake
git clone https://github.com/tdlib/td.git
cd td
./build.sh
These steps are a simplified example; actual build processes can vary significantly.
Quickstart example
This quickstart demonstrates creating a simple Telegram bot using the python-telegram-bot library. The bot will respond to the /start command and echo any text messages it receives. Before running this, you'll need a bot token, which you can obtain by talking to BotFather on Telegram.
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take two arguments: update and context.
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
f"Hi {user.mention_html()}!\nI'm an echo bot. Send me anything!",
)
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help!")
def main() -> None:
"""Start the bot."""
# Replace 'YOUR_BOT_TOKEN' with your actual bot token from BotFather
application = Application.builder().token("YOUR_BOT_TOKEN").build()
# On different commands - add handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
# On non-command messages - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), echo))
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
To run this example:
- Save the code as a
.pyfile (e.g.,echo_bot.py). - Replace
"YOUR_BOT_TOKEN"with the actual token you received from BotFather. - Run the script from your terminal:
python echo_bot.py. - Open Telegram, find your bot by its username, and send it
/startor any text message.
This script initializes the bot, sets up handlers for the /start command and all text messages that are not commands, and then starts polling for updates from Telegram. The Application object manages the lifecycle of the bot, including connecting to the Telegram API and dispatching updates to the registered handlers. The filters module helps to categorize incoming messages, ensuring that the correct handler processes each type of update.
Community libraries
The Telegram developer community is highly active, resulting in a vast ecosystem of libraries and tools that extend beyond the officially supported TDLib and the common Bot API wrappers. These community-driven projects cater to various programming languages, frameworks, and specific use cases, often providing features or abstractions not found in the more basic SDKs. Developers often turn to these libraries for specialized functionalities, improved developer experience, or support for less common programming languages.
Examples of prominent community libraries:
- Telethon (Python): A powerful, asynchronous Python client library for the Telegram API. It supports both bot and user accounts, offering fine-grained control over the API and enabling advanced features like custom client development. Telethon communicates directly with the Telegram API's MTProto protocol, providing more capabilities than the Bot API alone. You can find its documentation and repository on Telethon's official documentation site.
- Telegraf (Node.js): A modern Telegram Bot API framework for Node.js. It's known for its middleware-based approach, making bot development modular and scalable. Telegraf simplifies handling updates, managing sessions, and integrating with external services. Its active community and extensive plugins make it a popular choice for complex bot projects. Refer to the Telegraf.js official website for details.
- tg-bot-api (Rust): For developers working with Rust,
tg-bot-apiprovides a type-safe and performant interface to the Telegram Bot API. Rust's focus on safety and speed makes it suitable for high-performance bot applications. - GramJS (JavaScript): Similar to Telethon, GramJS is a pure JavaScript implementation of the Telegram API, supporting both browser and Node.js environments. It allows for building custom Telegram clients directly in JavaScript, offering an alternative to TDLib for web-based applications.
- Laravel Telegram Bot API (PHP): An integration for the Laravel PHP framework, this package simplifies building Telegram bots within a Laravel application, leveraging Laravel's ecosystem features like queues, events, and eloquent models.
When selecting a community library, it is important to consider factors such as ongoing maintenance, community activity, documentation quality, and compatibility with the latest Telegram API updates. Many of these libraries are hosted on GitHub, allowing developers to review their source code, check for recent commits, and assess the responsiveness of maintainers to issues and pull requests. The choice of library often depends on the specific project requirements, the developer's preferred language, and the desired level of abstraction over the Telegram API.