Telethon Python Client Library

repository·v1·Indexed 11 days ago

https://github.com/lonamiwebs/telethon

An asynchronous Python client library for the Telegram API (MTProto) used to build user and bot accounts. It provides tools for automating interactions, sending messages and files, handling events via @client.on, and managing sessions. Supports optional dependencies like cryptg for performance and aiohttp for WebDocument downloads.

Tokens
29.6K
Snippets
91
Records
146
Agent score
92%

What's inside Telethon

  1. What is Telegram's Type Language (TL)?

    v1

    Telegram's Type Language (TL), often found in .tl files, is a concise schema used to define objects (similar to classes or structs in other languages). It defines the name, a unique ID, and the arguments (including their types) for a TLObject. This language is used to describe how objects are structured and how they should be serialized into bytes for network transmission via MTProto.

    A standard definition follows this pattern:

    name#id argument_name:argument_type = CommonType

    name#id argument_name:argument_type = CommonType
  2. Choose a Telethon connection mode

    v1

    Telethon supports several connection modes depending on your network environment and requirements. When initializing a client, you can specify the connection type to handle different levels of protocol obfuscation or transport methods (TCP vs HTTP).

    # Example of how connection modes are typically applied during client initialization
    from telethon import TelegramClient
    from telethon.network.connection import TCPFullConnection
    
    client = TelegramClient('session_name', api_id, api_hash, connection=TCPFullConnection)
  3. Understand the concept of Entities in Telethon

    v1

    In Telethon, an Entity refers to any User, Chat, or Channel object returned by the Telegram API. Most methods (like sending a message or getting a username) require an entity to function.

    When a method requires an "entity-like" object, you can provide several types of identifiers:

    • Usernames
    • Exact titles
    • IDs
    • Peer objects
    • Entire User, Chat, or Channel objects
    • Phone numbers (only if the person is in your contact list)

    Important: The Entity Cache Telethon uses a .session file (SQLite) to cache the access_hash for entities you have already "encountered" (e.g., via dialogs or group participant lists). Most API calls require both an ID and an access_hash. If you try to use an ID that the library hasn't seen yet, it may fail with a ValueError. To fix this, you must first "encounter" the entity by calling methods like client.get_dialogs() or client.get_participants(group) to populate the cache.

  4. Understand ChatGetter and SenderGetter abstractions

    v1

    Telethon uses two base abstractions to provide easy access to chat and sender information across various objects:

    • ChatGetter: Provides methods and properties to identify a chat. Common properties include chat, input_chat, chat_id, is_private, is_group, and is_channel. It also provides get_chat() and get_input_chat() methods.
    • SenderGetter: Similar to ChatGetter, but focused on the sender of a message. It provides sender, input_sender, and sender_id, along with get_sender() and get_input_sender() methods.

    Many core objects like Message and Conversation inherit from these to make interaction easier.

  5. Resolving entities with get_input_entity() and get_entity()

    v1

    When using raw TL requests, you often need to provide an InputPeer (or similar input types like InputUser or InputChat).

    • client.get_input_entity(identifier): The most straightforward way to get an input version of a user, chat, or channel. It is efficient and often immediate if the entity has been seen before.
    • client.get_entity(identifier): Use this if you need the full information about the entity (e.g., user profile details). The library will automatically cast a full entity to its "input" version when used in a request.
    • telethon.utils.get_input_peer(entity): If you already have a full entity object and want to cache its input version to avoid repeated lookups, use this utility.

    Note: Since v0.16.2, many requests will automatically call get_input_entity for you if you pass a string username or a full entity object.

    # Option 1: Manual construction
    from telethon.tl.types import InputPeerUser
    peer = InputPeerUser(user_id, user_hash)
    
    # Option 2: Using get_input_entity
    peer = await client.get_input_entity('someone')
    
    # Option 3: Using get_entity (returns full object)
    entity = await client.get_entity('someone')
    
    # Option 4: Caching the input version
    from telethon import utils
    peer = utils.get_input_peer(entity)
  6. Distinguish between Chats and Channels

    v1

    Telegram distinguishes between different types of entities, which Telethon handles using specific ID prefixes to identify the entity type:

    Chats (Small Groups)

    • Often referred to as "Groups" in official applications.
    • ID Pattern: Telethon negates the real ID with a minus sign (e.g., real ID 123 becomes -123).

    Channels

    • Broadcast Channels: Used for broadcasting messages where only admins can post. Identified by channel.broadcast == True.
    • Megagroups (Supergroups): Migrated from small chats when they exceed user limits or gain public usernames. Identified by channel.megagroup == True.
    • Gigagroups: Very large megagroups that can be transformed into broadcast-style groups. Identified by channel.gigagroup == True.
    • ID Pattern: Telethon prepends -100 to the real ID (e.g., real ID 456 becomes -1000000000456).
  7. Difference between Entities and Input Entities

    v1

    Understanding the distinction between full Entities and Input Entities is crucial for performance:

    • Entities (User, Chat, Channel): Contain full information (name, username, etc.). Calling client.get_entity() always makes a network request to get the most recent data.
    • Input Entities (InputPeerUser, InputChat, etc.): Contain only the minimum information required by the Telegram API: the ID and the access_hash.
    • Peers (PeerUser, PeerChat, etc.): Contain only the ID. They are not enough to make a request on their own, but the library can use them to look up the hash in the cache.

    Best Practice: Always favor client.get_input_entity() over client.get_entity(). get_input_entity() uses the cache whenever possible and makes zero API calls most of the time, whereas get_entity() is intended for when you actually need to read the entity's properties (like its bio or username).

  8. Understand the difference between HTTP Bot API and MTProto

    v1

    When developing for Telegram, you can choose between two primary communication methods:

    1. HTTP Bot API: An official HTTP-based interface provided by Telegram. It acts as a middleman, translating HTTP requests into MTProto calls via tdlib. It is commonly used by libraries like python-telegram-bot, pyTelegramBotAPI, and aiogram.
    2. MTProto: Telegram's native protocol. Telethon is an MTProto-based client. Unlike the Bot API, MTProto clients connect directly to Telegram's servers.

    Advantages of using Telethon (MTProto) over Bot API:

    • Lower Overhead: Direct connection means no HTTP/JSON overhead; the protocol is more compact.
    • Reliability: You can connect directly to Telegram even if the Bot API endpoint is down.
    • Full Control: You are not limited to the public Bot API surface. You can perform actions that standard bots cannot.
    • Hybrid Capability: You can easily switch between acting as a bot and acting as a user within the same library/codebase.
  9. Requirements for sending media files

    v1

    You cannot send media using only an integer ID. To successfully send media, you generally need a combination of three components:

    1. ID: An integer that is consistent across all accounts.
    2. access_hash: An integer that is unique to a specific account. You cannot use an access_hash obtained from one account to send media from another.
    3. file_reference: A random bytes sequence that expires after a few hours and must be refetched before reuse.

    Note: Telethon provides message.file.id for HTTP Bot API-style file IDs, but this feature is unmaintained and may be removed in future versions.

  10. Understanding Functions, Types, and Constructors in the TL Reference

    v1

    The Telegram API is defined via .tl files which Telethon uses to generate code. The TL reference (available at https://tl.telethon.dev) is the primary way to explore these definitions.

    Functions (RPCs)

    Functions are Remote Procedure Calls used to perform actions (e.g., SendMessageRequest). When you look up a function in the TL reference, it provides:

    • Account Type: Whether it requires a bot or a user account.
    • Returns: The type returned by the request.
    • Parameters: The required and optional inputs.
    • Known RPC errors: A list of potential errors.

    Types

    Types represent the data structures used in the API. In Telethon, 'Types' act as abstract base classes. The TL reference shows:

    • Constructors: The actual generated classes used to create instances of a type.
    • Relationships: Which requests return this type, which requests accept it, and which other types contain it.

    Constructors

    Constructors are the concrete classes used to create instances of a Type or to represent the data returned by a Function. They contain the actual data fields (members) you interact with in Python.

  11. How to invoke low-level Telegram API requests

    v1

    While Telethon provides high-level 'friendly' methods for common tasks, you can invoke any request defined in Telegram's API using the TL reference. This is useful when a specific method doesn't exist in the high-level API or when you need more granular control.

    To invoke a request, you instantiate a function class from telethon.tl.functions and pass it directly to the TelegramClient instance as a callable.

    Note: Always prefer the high-level methods listed in the client reference unless you have a specific reason to use the low-level TL requests.

    client = TelegramClient(...)
    function_instance = SomeRequest(...)
    
    # Invoke the request
    returned_type = await client(function_instance)