CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-telethon

Full-featured Telegram client library for Python 3

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

client-management.mddocs/

Client Management

Core client functionality for managing connections, configuration, and basic client operations in Telethon.

Capabilities

Client Initialization

Create and configure a TelegramClient instance with various connection and behavior options.

class TelegramClient:
    def __init__(
        self,
        session: Union[str, pathlib.Path, Session],
        api_id: int,
        api_hash: str,
        *,
        connection: Type[Connection] = ConnectionTcpFull,
        use_ipv6: bool = False,
        proxy: Union[tuple, dict] = None,
        local_addr: Union[str, tuple] = None,
        timeout: int = 10,
        request_retries: int = 5,
        connection_retries: int = 5,
        retry_delay: int = 1,
        auto_reconnect: bool = True,
        sequential_updates: bool = False,
        flood_sleep_threshold: int = 60,
        raise_last_call_error: bool = False,
        device_model: str = None,
        system_version: str = None,
        app_version: str = None,
        lang_code: str = 'en',
        system_lang_code: str = 'en',
        loop: asyncio.AbstractEventLoop = None,
        base_logger: Union[str, logging.Logger] = None,
        receive_updates: bool = True,
        catch_up: bool = False,
        entity_cache_limit: int = 5000
    ):
        """
        Initialize a new TelegramClient.
        
        Parameters:
        - session: Session storage (filename, Session object, or StringSession)
        - api_id: API ID from https://my.telegram.org
        - api_hash: API hash from https://my.telegram.org
        - connection: Connection type to use (default: ConnectionTcpFull)
        - use_ipv6: Whether to use IPv6 connections
        - proxy: Proxy configuration (tuple or dict)
        - local_addr: Local address to bind to
        - timeout: Request timeout in seconds
        - request_retries: Number of request retries
        - connection_retries: Number of connection retries
        - retry_delay: Delay between retries in seconds
        - auto_reconnect: Automatically reconnect on disconnection
        - sequential_updates: Process updates sequentially
        - flood_sleep_threshold: Sleep threshold for flood wait (seconds)
        - raise_last_call_error: Raise error on last call failure
        - device_model: Device model string
        - system_version: System version string
        - app_version: Application version string
        - lang_code: Language code
        - system_lang_code: System language code
        - loop: Event loop to use
        - base_logger: Logger for client operations
        - receive_updates: Whether to receive updates
        - catch_up: Catch up on missed updates when connecting
        - entity_cache_limit: Entity cache size limit
        """

Connection Management

Manage the connection to Telegram servers including connecting, disconnecting, and checking connection status.

async def connect(self) -> None:
    """
    Connect to Telegram servers.
    
    Must be called before using any client methods.
    Handles authentication if session exists.
    """

async def disconnect(self) -> None:
    """
    Disconnect from Telegram servers and clean up resources.
    
    Should be called when done using the client.
    """

def is_connected(self) -> bool:
    """
    Check if the client is currently connected to Telegram.
    
    Returns:
    bool: True if connected, False otherwise
    """

Convenient Client Startup

Simplified client startup that handles connection and authentication in one step.

def start(
    self,
    phone: Union[Callable[[], str], str] = lambda: input('Please enter your phone (or bot token): '),
    password: Union[Callable[[], str], str] = lambda: getpass.getpass('Please enter your password: '),
    *,
    bot_token: str = None,
    force_sms: bool = False,
    code_callback: Callable[[], Union[str, int]] = None,
    first_name: str = 'New User',
    last_name: str = '',
    max_attempts: int = 3
) -> 'TelegramClient':
    """
    Start the client and handle authentication interactively.
    
    Parameters:
    - phone: Phone number or callback to get phone number
    - password: Password or callback to get password for 2FA
    - bot_token: Bot token for bot authentication
    - force_sms: Force SMS code instead of Telegram app
    - code_callback: Callback to get verification code
    - first_name: First name for new user registration
    - last_name: Last name for new user registration
    - max_attempts: Maximum login attempts
    
    Returns:
    TelegramClient: The client instance for method chaining
    """

Client Properties

Access client configuration and state information.

@property
def loop(self) -> asyncio.AbstractEventLoop:
    """Get the event loop used by the client."""

@property
def disconnected(self) -> asyncio.Future:
    """Get a future that completes when the client disconnects."""

@property
def flood_sleep_threshold(self) -> int:
    """Get the flood sleep threshold in seconds."""

@flood_sleep_threshold.setter
def flood_sleep_threshold(self, value: int):
    """Set the flood sleep threshold in seconds."""

Proxy Configuration

Configure and manage proxy settings for the client connection.

def set_proxy(self, proxy: Union[tuple, dict]) -> None:
    """
    Set proxy configuration for the client.
    
    Parameters:
    - proxy: Proxy configuration as tuple (type, addr, port, username, password)
             or dict with proxy parameters
    """

User Information

Get information about the current authenticated user.

async def get_me(self, input_peer: bool = False) -> Union[types.User, types.InputPeerUser]:
    """
    Get information about the current user.
    
    Parameters:
    - input_peer: Return InputPeerUser instead of User
    
    Returns:
    User object or InputPeerUser if input_peer=True
    """

async def is_bot(self) -> bool:
    """
    Check if the current user is a bot.
    
    Returns:
    bool: True if the current user is a bot, False otherwise
    """

async def is_user_authorized(self) -> bool:
    """
    Check if the user is currently authorized.
    
    Returns:
    bool: True if authorized, False otherwise
    """

Usage Examples

Basic Client Setup

import asyncio
from telethon import TelegramClient

async def main():
    # Create client with basic configuration
    client = TelegramClient('session_name', api_id, api_hash)
    
    # Connect and start
    await client.start()
    
    # Check if connected
    if client.is_connected():
        print("Connected successfully!")
        
        # Get current user info
        me = await client.get_me()
        print(f"Logged in as: {me.first_name}")
        
        # Check if bot
        if await client.is_bot():
            print("Running as a bot")
        else:
            print("Running as a user")
    
    # Clean disconnect
    await client.disconnect()

asyncio.run(main())

Client with Custom Configuration

from telethon import TelegramClient
from telethon.network import ConnectionTcpObfuscated

# Create client with custom settings
client = TelegramClient(
    'session_name',
    api_id,
    api_hash,
    connection=ConnectionTcpObfuscated,  # Use obfuscated connection
    proxy=('socks5', '127.0.0.1', 9050),  # Use SOCKS5 proxy
    timeout=30,                          # 30 second timeout
    request_retries=10,                  # More retries
    flood_sleep_threshold=120,           # Higher flood threshold
    device_model='Custom Device',        # Custom device model
    app_version='1.0.0'                  # Custom app version
)

Context Manager Usage

async def main():
    async with TelegramClient('session', api_id, api_hash) as client:
        # Client automatically connects on enter
        me = await client.get_me()
        print(f"Hello, {me.first_name}!")
        # Client automatically disconnects on exit

Types

from typing import Union, Callable, Optional, Type
import pathlib
import asyncio
import logging

Session = Union[str, pathlib.Path, 'telethon.sessions.Session']
Connection = Type['telethon.network.connection.Connection']
ProxyConfig = Union[tuple, dict]
EntityLike = Union[int, str, 'types.InputPeer']

Install with Tessl CLI

npx tessl i tessl/pypi-telethon

docs

authentication-sessions.md

chat-management.md

client-management.md

error-handling.md

event-system.md

file-handling.md

index.md

message-operations.md

utilities-helpers.md

tile.json