Telegram API - Telethon - Summary - 2026

Материал из Wiki - Iphoster - the best ever hosting and support. 2005 - 2026
Перейти к:навигация, поиск

Published: 2026-08-06


Telegram API — Telethon — Summary, 2026 edition.

Telethon is a mature, community-driven Python library that talks to Telegram's servers directly through the MTProto protocol. Where most bot frameworks sit on top of Telegram's official HTTP Bot API, Telethon skips that middleman: it implements the wire protocol itself, so a single piece of code can drive a regular user account, a bot account, or both. This one decision changes what you can build — anything from a personal auto-responder to a full channel-parsing pipeline is within reach.

As of this writing the current release is Telethon 1.44.0, published on June 15, 2026. The project is MIT-licensed, developed mainly by Lonami Exo, and the canonical documentation lives at docs.telethon.dev. A companion site, tl.telethon.dev, hosts an auto-generated reference for every method and type in the Telegram MTProto schema.

Why Telethon Exists

Telegram is one of the world's most widely used messengers, and underneath every official client sits a protocol called MTProto. Building on that protocol directly is hard: it involves transport encryption, session management, update handling and dozens of obscure edge cases. Telethon is the wrapper that already did that heavy lifting, so developers can stay focused on application logic instead of protocol internals.

The headline capability is programmatic control over a normal user account. The official Bot API can only act as a bot; Telethon can sign in with a phone number or a QR code and then do essentially anything the desktop or mobile client can do:

  • send and receive messages, with full formatting and markup;
  • read chat and channel history, including paginated deep reads;
  • manage groups, supergroups and channels;
  • upload and download files up to Telegram's 2 GB limit;
  • look up users, messages and chats by name, ID or invite link;
  • react to incoming activity in real time through an event system;
  • handle contacts, dialogs, reactions, polls, pinned items and admin permissions;
  • expose online status, presence and premium-related features that Bot API cannot reach.

MTProto vs. the HTTP Bot API

Choosing a library for Telegram automation usually comes down to this fork in the road.

What the Bot API Is

The HTTP Bot API is Telegram's official interface for controlling bots. You send JSON requests over HTTP, and Telegram translates them into MTProto calls internally through TDLib. Bot configuration — commands, descriptions, avatars — goes through @BotFather.

In practice that means:

  • bot accounts only, never user accounts;
  • a fixed, documented set of methods;
  • real-time updates only via long polling or webhooks;
  • upload and download size limits baked into the API;
  • no access to presence, online status or certain premium features.

What MTProto Means Here

MTProto is Telegram's own protocol for client-server communication. Telethon is an alternative MTProto backend written entirely in Python — far easier to set up than TDLib (which ships as a native C++ library with JSON bindings).

What you gain:

  • sign in as a user (phone or QR) or as a bot (token);
  • one persistent connection delivering all updates as events;
  • files up to 2 GB with resume support;
  • direct access to client-only features: reactions, polls, premium stickers, profile customization;
  • full control over every MTProto method, for when the official API just isn't enough.
Telethon (MTProto) versus the HTTP Bot API
Aspect Telethon HTTP Bot API
Account type User and bot Bot only
Protocol MTProto, direct HTTP, proxied via TDLib
Real-time updates Events over persistent connection Long polling / webhooks
File handling Up to 2 GB, resumable API limits
Presence, reactions, premium Available Partial or missing
Setup complexity Low (pure Python) Low

Installation

Telethon targets modern Python 3 (3.8 and newer). Installing and upgrading is two commands:

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade telethon

Verify the install:

python3 -c "import telethon; print(telethon.__version__)"

You should see something like `1.44.0`.

Pre-release Builds

Need the very latest unreleased changes? Install straight from the repository:

python3 -m pip install --upgrade https://codeberg.org/Lonami/Telethon/archive/v1.zip

The docs are explicit: dev builds can be buggy and are not meant for production. That said, when you file a bug report, you are expected to first check whether it still reproduces on this build.

Speed and Feature Extras

Two optional packages matter most:

  • cryptg — a C implementation of Telegram's cryptography. Transfer speeds jump from hundreds of kilobytes per second to multiple megabytes per second whenever a lot of updates, uploads or downloads are involved. Without it, Telethon falls back to the slower pure-Python pyaes.
  • Pillow — useful whenever you manipulate images before sending (resizing, thumbnails, stickers).

Getting Your API Credentials

Before anything works you need an api_id and api_hash. These belong to your application, not to your phone number, and the same pair can be reused with any phone number or bot token.

Steps at my.telegram.org:

  1. Log in with the phone number of the developer account.
  2. Open API development tools.
  3. In Create new application, fill in the details. No URL is required, and only App title and Short name can be edited later.
  4. Hit Create application.

Treat the api_hash as a secret: Telegram does not let you revoke it, so never paste it into public repos, chats or screenshots.

Your First Script

The canonical hello-world sends a message to yourself and downloads your own profile photo:

from telethon.sync import TelegramClient, events

with TelegramClient('name', api_id, api_hash) as client:
   client.send_message('me', 'Hello, myself!')
   print(client.download_profile_photo('me'))

   @client.on(events.NewMessage(pattern='(?i).*Hello'))
   async def handler(event):
      await event.reply('Hey!')

   client.run_until_disconnected()

On first run Telethon asks for the phone number and the verification code (or offers QR login). A successful login writes a session file — `name.session` in this example — holding your authorization keys, so later starts go straight in.

The fully async style looks like this:

import asyncio
from telethon import TelegramClient

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

async def main():
    await client.start()
    await client.send_message('me', 'Hello from async!')
    await client.disconnect()

asyncio.run(main())

One footgun worth repeating from the docs: do not name your script `telethon.py`. Python will try to import the client from your own file and fail with something like “ImportError: cannot import name 'TelegramClient'”.

Authentication Options

Telethon handles several login paths:

  • phone number plus SMS or call code;
  • QR code, handy for accounts with two-factor authentication;
  • bot token from @BotFather.

Key auth methods from the Client Reference:

  • `start()` — connect and log in if needed, in one call;
  • `send_code_request()` — request the login code for a phone number;
  • `sign_in()` — log into an existing user or bot account;
  • `qr_login()` — begin QR-based login;
  • `sign_up()` — register a brand-new account.

Two-factor passwords are supported: if the account has one, Telethon asks for it during sign-in, and you can also pass it programmatically.

Sessions

A session is a bundle of authorization state. By default it lives in a `.session` file, but other backends exist (SQLite, in-memory, custom databases). Session files are interchangeable between projects and can be paired with different API IDs.

Everyday Operations

Sending Messages

`send_message(entity, message)` is the workhorse. The target can be a username, phone number, invite link, numeric ID or an entity object:

await client.send_message('username', 'Hello!')
await client.send_message(123456789, 'By ID')
await client.send_message('https://t.me/joinchat/...', 'Into a group')

Companion methods: `send_file()`, `edit_message()`, `delete_messages()`, `forward_messages()`, `send_poll()`.

Reading History

`get_messages()` fetches history with filters and pagination; `iter_messages()` returns an async iterator that walks the entire backlog without loading it into memory. This is the foundation of every channel-parsing job:

async for message in client.iter_messages('channel', limit=200):
    print(message.sender_id, message.text)

Dialogs

`get_dialogs()` lists every chat the account belongs to — direct messages, groups, channels — with unread counts, drafts and pinned items. It is the natural starting point for inbox-style tools.

Events: Real-Time Processing

Events are Telethon's answer to “what happens right now”. Decorators register handlers, and the library dispatches to them as updates arrive over the persistent connection:

@client.on(events.NewMessage(chats='some_channel'))
async def watcher(event):
    if 'keyword' in event.text.lower():
        await event.reply('Keyword detected!')

Notable event types:

  • `events.NewMessage` — new messages anywhere (PM, groups, channels);
  • `events.MessageEdited` / `events.MessageDeleted` — edits and deletions;
  • `events.ChatAction` — membership changes, title edits, admin actions;
  • `events.UserUpdate` — user profile and presence changes;
  • `events.CallbackQuery` — inline button presses;
  • `events.InlineQuery` — inline mode queries;
  • `events.Album` — media groups arriving as one bundle.

Handlers can be filtered by chat, sender or text via regex patterns — the `(?i).*Hello` pattern above, for instance, matches “hello” case-insensitively.

Chats, Groups, Channels and People

The method catalog covers the whole lifecycle of dialogs and members:

  • `get_entity()` — resolve a user, chat or channel from a name, ID or link;
  • `get_participants()` — member lists with role filters (admins, banned, ...);
  • `create_group()` / `create_supergroup()` / `create_channel()` — new dialogs;
  • `edit_admin()` / `edit_permissions()` / `kick_participant()` — member management;
  • `invite_participants()` / `join_channel()` / `leave_channel()` — membership flow;
  • `pin_message()` / `unpin_message()` — pinned messages;
  • `get_profile_photos()` / `download_profile_photo()` — avatars;
  • `get_me()` / `get_common_chats()` — own profile and shared chats.

Message objects carry text, sender, timestamps, replies, reactions, media and buttons, and can be replied to, forwarded, edited, deleted or reacted to in place.

Files and Media

File work is one of Telethon's strongest areas:

  • `send_file()` — by local path, URL, bytes or stream;
  • `download_media()` — pull any attachment out of a message;
  • `download_profile_photo()` — grab avatars;
  • `upload_file()` — pre-upload into Telegram's media library.

Bulk download example:

async for message in client.iter_messages('channel', limit=50):
    if message.media:
        await message.download_media(file='downloads/')

With cryptg installed, throughput can be an order of magnitude higher.

Advanced Features

  • Reactions — set and read message reactions, including premium ones, via `react()` or `send_reaction()`.
  • Polls and quizzes — `send_poll()` covers single and multiple choice, anonymous and timed variants.
  • Contacts — `get_contacts()`, `add_contact()`, `delete_contacts()`, `import_contacts()`.
  • Profile — `edit_profile()`, `update_username()`, `get_me()`.
  • Administration — ban/unban, permission edits, channel deletion, mass invites.
  • Presence and premium — online status, last-seen, emoji statuses and other client-only details.

Typical Use Cases

  • automating a personal account — auto-posting, auto-replies, activity stats;
  • building userbots — bots that do what Bot API cannot;
  • parsing channels and chats — collecting posts, members and metrics;
  • keyword monitoring — alert on matching text in watched chats;
  • bulk messaging — strictly within Telegram's anti-spam limits;
  • archiving conversations — dumping history to files or databases;
  • integrations — bridging Telegram to CRMs, notifications, other messengers.

Limits, Risks and Best Practices

Automation is allowed, abuse is not. Telegram's API Terms matter:

  • unsolicited mass messaging is the fastest way to get an account limited;
  • rate limits apply to messages, joins and invites per unit of time;
  • heavy use of a personal account risks temporary restrictions;
  • monitor `FloodWaitError` — Telethon can wait automatically when Telegram demands a pause.

Security checklist:

  • never commit `api_hash` or `.session` files — they are full account access;
  • prefer environment variables for secrets;
  • use dedicated sessions per purpose;
  • add delays for large batches;
  • expect every active session to show up as a separate device in the account.

Performance Notes

  • install cryptg for C-speed cryptography;
  • stay async — one connection handles many concurrent operations;
  • prefer `iter_*` over `get_*` for large datasets to save memory;
  • filter and paginate requests instead of pulling everything;
  • for trivial bot-only tasks the Bot API is simpler — but the moment you need user-account features, Telethon is usually the only option.

Alternatives at a Glance

Telethon and its neighbors
Library Protocol Account type Style Notes
Telethon MTProto (Python) User + bot asyncio (+sync mode) Rich ecosystem, event system, full schema reference
Pyrogram MTProto User + bot asyncio Popular counterpart with similar capabilities
python-telegram-bot HTTP Bot API Bot only asyncio Official-style wrapper, thorough docs
aiogram HTTP Bot API Bot only asyncio Fast framework with routing and FSM
pyTelegramBotAPI HTTP Bot API Bot only Synchronous Simple, beginner-friendly
TDLib MTProto (native C++) User + bot JSON events Telegram's own low-level library

Picking Telethon

Go with Telethon when you need user-account access, live events without webhooks, big files, or direct MTProto control. Choose a Bot API wrapper when a plain command-and-keyboard bot is all you need and simplicity outweighs reach.

How to Read the Docs

The documentation at docs.telethon.dev is organized as:

  • Installation — environment and package setup;
  • Signing In — credentials and first login;
  • Client Reference — a relevance-ordered summary of every important method and property on `TelegramClient`;
  • Modules — deep dives into client, messages, chats, uploads, downloads, updates and more;
  • Quick References — cheatsheets for client, messages, chats, files;
  • Misc — changelog, compatibility notes, FAQ;
  • tl.telethon.dev — the auto-generated schema reference.

Sensible learning path: install, sign in, send a message, handle an event, manage chats, move files, then go advanced.

Summary

Telethon remains, in 2026, the most direct way to drive Telegram from Python: user accounts and bots, real-time events, 2 GB files, reactions and premium features — all over MTProto, with no TDLib in the way. Setup takes minutes, cryptg makes it fast, and the documentation plus schema reference cover the rest. For anything beyond a plain Bot API bot, Telethon is the pragmatic default.

Links

×
Реклама
ИКС