or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication-sessions.mdchat-management.mdclient-management.mderror-handling.mdevent-system.mdfile-handling.mdindex.mdmessage-operations.mdutilities-helpers.md
tile.json

tessl/pypi-telethon

Full-featured Telegram client library for Python 3

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/telethon@1.41.x

To install, run

npx @tessl/cli install tessl/pypi-telethon@1.41.0

index.mddocs/

Telethon

A comprehensive Python 3 asyncio-based MTProto library for interacting with Telegram's API as both user and bot accounts. Telethon provides full access to Telegram's features including message handling, file transfers, user authentication, real-time updates, and complete raw API access, making it ideal for building sophisticated Telegram applications, bots, and automation tools.

Package Information

  • Package Name: Telethon
  • Language: Python
  • Installation: pip install Telethon
  • Requirements: Python 3.5+, asyncio support
  • Optional Dependencies: cryptg for performance improvements

Core Imports

from telethon import TelegramClient, events, Button

For specific components:

from telethon import TelegramClient, events, Button, utils, errors
from telethon.tl import types, functions
from telethon.sessions import StringSession, SQLiteSession

Basic Usage

Client Setup and Authentication

import asyncio
from telethon import TelegramClient

# Replace with your actual values from https://my.telegram.org
api_id = 'your_api_id'
api_hash = 'your_api_hash'

async def main():
    # Create client
    client = TelegramClient('session_name', api_id, api_hash)
    
    # Connect and authenticate
    await client.start()
    
    # Get current user info
    me = await client.get_me()
    print(f"Logged in as {me.first_name}")
    
    # Send a message
    await client.send_message('username', 'Hello from Telethon!')
    
    # Disconnect
    await client.disconnect()

# Run the client
asyncio.run(main())

Bot Usage

from telethon import TelegramClient, events

bot = TelegramClient('bot_session', api_id, api_hash)

@bot.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.respond('Hello! I am a bot created with Telethon.')
    
@bot.on(events.NewMessage)
async def echo_handler(event):
    if not event.text.startswith('/'):
        await event.respond(f'You said: {event.text}')

async def main():
    await bot.start(bot_token='your_bot_token')
    print("Bot is running...")
    await bot.run_until_disconnected()

asyncio.run(main())

Architecture

Telethon uses a layered architecture built around the MTProto protocol:

  • TelegramClient: Main interface combining all functionality through mixin classes
  • Session Management: Persistent storage of authentication and cache data
  • Event System: Real-time update handling with decorators and handlers
  • TL Objects: Type Language objects representing Telegram's data structures
  • Network Layer: Connection management, encryption, and protocol handling
  • Utility Layer: Helper functions for common operations and conversions

The client uses Python's asyncio for asynchronous operations and supports both high-level convenience methods and low-level raw API access for maximum flexibility.

Capabilities

Client Management

Core client functionality including connection management, authentication, session handling, and basic client operations.

class TelegramClient:
    def __init__(self, session, api_id: int, api_hash: str, **kwargs): ...
    async def start(self, phone=None, password=None, *, bot_token=None, **kwargs): ...
    async def connect(self) -> None: ...
    async def disconnect(self) -> None: ...
    def is_connected(self) -> bool: ...

Client Management

Authentication & Sessions

User and bot authentication, session management, two-factor authentication, and QR code login functionality.

async def sign_in(self, phone: str = None, code: Union[str, int] = None, **kwargs): ...
async def sign_up(self, code: Union[str, int], first_name: str, last_name: str = '', **kwargs): ...
async def send_code_request(self, phone: str, *, force_sms: bool = False): ...
async def log_out(self) -> bool: ...
async def qr_login(self, ignored_ids: List[int] = None): ...

Authentication & Sessions

Message Operations

Comprehensive message handling including sending, receiving, editing, deleting, forwarding, and reading messages with support for formatting, media, and buttons.

async def send_message(self, entity, message='', *, reply_to=None, parse_mode=(), **kwargs): ...
async def get_messages(self, entity, *args, **kwargs): ...
def iter_messages(self, entity, limit: int = 1, **kwargs): ...
async def edit_message(self, entity, message=None, text: str = None, **kwargs): ...
async def delete_messages(self, entity, message_ids, *, revoke: bool = True): ...
async def forward_messages(self, entity, messages, from_peer=None, **kwargs): ...

Message Operations

File Handling

File upload and download operations with progress tracking, including sending media, documents, photos, and handling various file formats.

async def send_file(self, entity, file, *, caption: str = '', **kwargs): ...
async def upload_file(self, file, *, part_size_kb: int = None, **kwargs): ...
async def download_media(self, message, file=None, **kwargs) -> str: ...
async def download_file(self, input_location, file=None, **kwargs) -> bytes: ...
def iter_download(self, file, **kwargs): ...

File Handling

Chat Management

Chat and channel administration including member management, permissions, admin operations, and participant handling.

def iter_participants(self, entity, limit: int = None, **kwargs): ...
async def get_participants(self, *args, **kwargs): ...
async def edit_admin(self, entity, user, **kwargs): ...
async def edit_permissions(self, entity, user=None, until_date=None, **kwargs): ...
async def kick_participant(self, entity, user): ...
async def get_permissions(self, entity, user): ...

Chat Management

Event System

Real-time update handling with event decorators, filters, and handlers for messages, edits, deletions, and other Telegram updates.

def on(self, event): ...
def add_event_handler(self, callback, event=None): ...
def remove_event_handler(self, callback, event=None) -> int: ...
def run_until_disconnected(self): ...

class NewMessage: ...
class MessageEdited: ...
class ChatAction: ...
class CallbackQuery: ...

Event System

Utilities & Helpers

Utility functions for entity resolution, input conversion, media type detection, and common Telegram operations.

def get_display_name(entity) -> str: ...
def get_input_peer(entity, allow_self=True, check_hash=True): ...
def get_peer_id(peer) -> int: ...
def parse_phone(phone) -> str: ...
def parse_username(username) -> str: ...
def is_image(file) -> bool: ...
def is_video(file) -> bool: ...

Utilities & Helpers

Error Handling

Comprehensive error handling system with specific exception types for different error conditions and RPC errors from Telegram.

class RPCError(Exception): ...
class FloodWaitError(RPCError): ...
class SessionPasswordNeededError(RPCError): ...
class PhoneCodeInvalidError(RPCError): ...
class UsernameNotOccupiedError(RPCError): ...

def rpc_message_to_error(rpc_error, request): ...

Error Handling

Types

Core Types

class TelegramClient:
    """Main client class for all Telegram operations"""
    
class Session:
    """Abstract base class for session storage"""
    
class Connection:
    """Abstract base class for network connections"""

Event Types

from typing import Union, List, Optional, Any, Callable
from datetime import datetime

EntityLike = Union[int, str, 'types.User', 'types.Chat', 'types.Channel']
MessageLike = Union[int, 'types.Message', 'custom.Message']
FileLike = Union[str, bytes, 'types.Document', 'types.Photo', 'io.IOBase']