LonamiWebs/Telethon
Pure Python 3 MTProto API Telegram client library, for bots too!
Healthy across the board
weakest axisPermissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 2mo ago
- ✓33+ active contributors
- ✓Distributed ownership (top contributor 36% of recent commits)
Show all 6 evidence items →Show less
- ✓MIT licensed
- ✓Tests present
- ⚠No CI workflows detected
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/lonamiwebs/telethon)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/lonamiwebs/telethon on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: LonamiWebs/Telethon
Generated by RepoPilot · 2026-05-07 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/LonamiWebs/Telethon shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across the board
- Last commit 2mo ago
- 33+ active contributors
- Distributed ownership (top contributor 36% of recent commits)
- MIT licensed
- Tests present
- ⚠ No CI workflows detected
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live LonamiWebs/Telethon
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/LonamiWebs/Telethon.
What it runs against: a local clone of LonamiWebs/Telethon — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in LonamiWebs/Telethon | Confirms the artifact applies here, not a fork |
| 2 | License is still MIT | Catches relicense before you depend on it |
| 3 | Default branch v1 exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 104 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of LonamiWebs/Telethon. If you don't
# have one yet, run these first:
#
# git clone https://github.com/LonamiWebs/Telethon.git
# cd Telethon
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of LonamiWebs/Telethon and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "LonamiWebs/Telethon(\\.git)?\\b" \\
&& ok "origin remote is LonamiWebs/Telethon" \\
|| miss "origin remote is not LonamiWebs/Telethon (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
&& ok "license is MIT" \\
|| miss "license drift — was MIT at generation time"
# 3. Default branch
git rev-parse --verify v1 >/dev/null 2>&1 \\
&& ok "default branch v1 exists" \\
|| miss "default branch v1 no longer exists"
# 4. Critical files exist
test -f "telethon/__init__.py" \\
&& ok "telethon/__init__.py" \\
|| miss "missing critical file: telethon/__init__.py"
test -f "telethon/client/telegramclient.py" \\
&& ok "telethon/client/telegramclient.py" \\
|| miss "missing critical file: telethon/client/telegramclient.py"
test -f "telethon/client/telegrambaseclient.py" \\
&& ok "telethon/client/telegrambaseclient.py" \\
|| miss "missing critical file: telethon/client/telegrambaseclient.py"
test -f "telethon/crypto/authkey.py" \\
&& ok "telethon/crypto/authkey.py" \\
|| miss "missing critical file: telethon/crypto/authkey.py"
test -f "telethon/events/__init__.py" \\
&& ok "telethon/events/__init__.py" \\
|| miss "missing critical file: telethon/events/__init__.py"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 104 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~74d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/LonamiWebs/Telethon"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
Telethon is a pure Python 3 MTProto client library that lets you interact with Telegram's API as a user account or bot without using Telegram's official Bot API. It handles the low-level MTProto protocol encryption, serialization, and async communication so you can send messages, download files, handle updates, and manage chats via simple Python code. Monolithic structure: core MTProto protocol logic lives in telethon package (inferred from imports), docs live in ./readthedocs/ (basic/, concepts/, examples/, developing/), with bot/user client abstractions layered on top. Session management and entity handling are cross-cutting concerns. Type definitions generated from Telegram's Type Language spec.
👥Who it's for
Python developers building Telegram bots, automation scripts, or user clients who want direct MTProto API access instead of the limited official Bot API. Contributors include protocol enthusiasts maintaining the MTProto type definitions and async I/O patterns.
🌱Maturity & risk
Production-ready with active maintenance, evidenced by the complete test suite (.coveragerc present), pre-commit config, ReadTheDocs integration with comprehensive docs in ./readthedocs/, and migration guidance for v1.0+ in the README. The project has been maintained for years with clear API stability expectations.
Single maintainer (LonamiWebs) creates sustainability risk. The project has recently moved to Codeberg (repo note warns GitHub may be deleted), which could fragment the contributor base. Python version constraints and MTProto protocol changes from Telegram could introduce breaking changes, but the migration guide suggests active planning for this.
Active areas of work
Active development with recent .readthedocs.yaml and .pre-commit-config.yaml updates. Documentation is comprehensive with separate sections for botapi-vs-mtproto concepts, asyncio patterns, and entity handling. No CI visible in workflows (workflows.disabled/ suggests it may be disabled), which is concerning for an actively maintained library.
🚀Get running
git clone https://github.com/LonamiWebs/Telethon.git && cd Telethon && pip3 install -e . && pip3 install -r dev-requirements.txt (for development dependencies listed in the repo root)
Daily commands: Development: readthedocs/Makefile provides doc building (make html). No traditional 'dev server' — Telethon is a client library. To test: instantiate TelegramClient with API credentials from https://my.telegram.org, call client.start() to authenticate, then use async/sync patterns per readthedocs/concepts/asyncio.rst.
🗺️Map of the codebase
telethon/__init__.py— Main package entry point; exports TelegramClient and core public API that all users importtelethon/client/telegramclient.py— Core TelegramClient class definition; implements the primary async interface for all Telegram operationstelethon/client/telegrambaseclient.py— Base client class handling MTProto protocol logic, session management, and connection lifecycletelethon/crypto/authkey.py— Authentication key generation and management; critical for secure MTProto communicationtelethon/events/__init__.py— Event system entry point; defines decorators and event handlers that enable reactive client programmingtelethon/_updates/messagebox.py— Update message box and state machine; orchestrates handling of server updates and message acknowledgmenttelethon/errors/rpcbaseerrors.py— RPC error definitions and exception hierarchy; maps Telegram API errors to Python exceptions for all error handling
🛠️How to make changes
Add a new client method for a Telegram API call
- Determine which client module the method belongs to (e.g., telethon/client/messages.py for message operations) (
telethon/client/messages.py) - Add an async method to TelegramClient or relevant mixin; use self._invoke(TL_RequestClass(...)) to call MTProto (
telethon/client/telegramclient.py) - Handle errors by catching RPC exceptions from telethon/errors/rpcbaseerrors.py (
telethon/errors/rpcbaseerrors.py) - Wrap TL response objects with custom helper classes from telethon/custom.py for user convenience (
telethon/custom.py) - Document method in readthedocs/modules/client.rst and add example usage to readthedocs/examples/ (
readthedocs/modules/client.rst)
Add a new event type
- Create a new event class in telethon/events/ inheriting from EventBuilder in telethon/events/common.py (
telethon/events/common.py) - Implement build_event() classmethod to construct event from incoming TL update; implement filter logic (
telethon/events/callbackquery.py) - Register event class in telethon/events/init.py to make it importable (
telethon/events/__init__.py) - Update event dispatch logic in telethon/client/updates.py to route updates to your new event handler (
telethon/client/updates.py) - Add documentation to readthedocs/quick-references/events-reference.rst with usage examples (
readthedocs/quick-references/events-reference.rst)
Add a new crypto or session mechanism
- For crypto: add new cipher/mode implementation in telethon/crypto/; for session: extend telethon/_updates/session.py (
telethon/crypto/aesctr.py) - Register new mechanism in the base client initialization (telegrambaseclient.py or crypto init) (
telethon/client/telegrambaseclient.py) - Add configuration option to allow users to opt-in or use new mechanism (
telethon/__init__.py) - Document new mechanism in readthedocs/concepts/sessions.rst or cryptography section (
readthedocs/concepts/sessions.rst)
Handle a new Telegram RPC error
- Auto-generated RPC error classes are created from schema; if not present, add to telethon/errors/rpcbaseerrors.py manually (
telethon/errors/rpcbaseerrors.py) - Add handling logic in the client method that calls the RPC; use try/except to catch specific RPC exception (
telethon/client/auth.py) - Optionally add user-friendly wrapper exception in telethon/errors/common.py if error requires special handling (
telethon/errors/common.py) - Document error and recovery strategy in readthedocs/concepts/errors.rst (
readthedocs/concepts/errors.rst)
🔧Why these technologies
- asyncio (Python 3.5+) — Enables non-blocking concurrent request handling and long-polling update streams without threading overhead
- MTProto (Telegram's binary protocol) — Only way to access the full Telegram API surface (vs Bot API); supports user accounts, media CDNs, and real-time updates
- AES-CTR encryption — MTProto security standard; fast streaming cipher for encrypting all client-server communication
- TL (Type Language) schema — Telegram's serialization format; enables type-safe RPC calls and auto-code generation for API methods
⚖️Trade-offs already made
- Pure Python implementation vs ctypes/C extension
- Why: Portability and ease of installation; avoids compiled binary distribution complexity
- Consequence: Crypto operations (~2–10ms per AES block) are slower than native C; mitigated by bat
🪤Traps & gotchas
API credentials must be obtained from https://my.telegram.org (not obvious from docs, only in README example). Telegram can ban accounts using this library per ToS (readthedocs/quick-references/faq.rst warns this), making rate-limiting and authentication practices critical. Workflows are disabled (.github/workflows.disabled/) so CI isn't catching regressions. Type Language code generation process isn't visible in file structure — likely tooling external to repo. Async-only in newer versions; older code using sync patterns needs migration per compatibility guide. MTProto version pinning against Telegram server changes isn't explicitly documented.
🏗️Architecture
💡Concepts to learn
- MTProto (Mobile Telegram Protocol) — Telethon's entire value is implementing MTProto correctly; understanding its binary serialization, encryption (AES-256-IGE), and handshake is necessary to debug protocol-level issues and understand why this library exists instead of just using HTTP APIs
- Type Language (TL-Scheme) — Telegram defines all MTProto messages and types in a custom Type Language schema that Telethon must parse and code-generate; grasping this explains how the library stays in sync with Telegram API changes
- Asyncio event loop and async/await — Telethon is designed around Python asyncio for concurrent message handling and non-blocking I/O; the entire client API assumes async context (though sync wrappers exist), so understanding event loop semantics is critical for correct usage
- Session persistence and authentication tokens — Telethon manages long-lived authenticated sessions with Telegram servers using auth_key and other tokens; understanding how sessions are encrypted and stored locally (readthedocs/concepts/sessions.rst) prevents account lockouts and credential leaks
- Event handler decorator pattern — Telethon's update handling uses @client.on(events.EventType) decorators to register callbacks for incoming messages and updates; this pattern is central to bot and user script logic
- Binary protocol serialization (TLObject) — All MTProto messages are serialized to binary TL format and then encrypted; understanding how TLObjects serialize/deserialize is essential for protocol debugging and extending the library
- Connection pooling and socket management — Telethon maintains persistent TCP/TLS connections to Telegram's data centers with automatic reconnection; understanding connection state and multiplexing prevents race conditions and hanging requests
🔗Related repos
pyrogram/pyrogram— Direct competitor: also a pure Python MTProto client library with similar scope but different API design and async handlingpython-telegram-bot/python-telegram-bot— Ecosystem companion: official Bot API wrapper; Telethon's botapi-vs-mtproto docs explicitly contrast against thisTelegramBots/Telegram-bot-api— Upstream reference: official Bot API server that python-telegram-bot wraps; understanding it clarifies why Telethon's MTProto approach offers more controltdlib/td— Inspiration and competitor: Telegram's official TDLib in C++ that other clients wrap; Telethon's philosophy of native Python avoids TDLib's complexityLonamiWebs/Telethon-asana— Companion: curates community examples and extensions for Telethon
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive unit tests for telethon/_updates/entitycache.py
The entity cache is a critical component for managing Telegram entities (users, chats, channels) in the client. Currently, there's no visible test coverage for this module. Adding unit tests would ensure reliability of entity caching, deduplication, and retrieval logic - essential for the core functionality of any Telethon-based application.
- [ ] Create tests/test_entitycache.py with test cases for cache initialization, entity insertion, retrieval, and updates
- [ ] Test edge cases like duplicate entity handling, cache invalidation, and concurrent access patterns
- [ ] Add tests to verify entity lookups by ID, username, and phone number work correctly
- [ ] Reference entitycache.py implementation to ensure all public methods have corresponding tests
- [ ] Integrate tests into CI workflow (update .github/workflows.disabled/python.yml if needed)
Complete the interrupted README.rst installation section
The README installation section is incomplete - it ends with 'pip3 i' which is clearly truncated. This is the first thing new users encounter. Completing this section with proper installation instructions for different scenarios (pip, git, optional dependencies) would significantly improve the onboarding experience.
- [ ] Complete the pip3 install command with full package name: pip3 install telethon
- [ ] Add installation from optional-requirements.txt with explanation of what each optional dependency provides (e.g., cryptography, aiohttp)
- [ ] Add section for installing from source using setup.py and dev-requirements.txt for contributors
- [ ] Include troubleshooting notes for common installation issues on different Python versions
- [ ] Add links to readthedocs/basic/installation.rst for detailed setup guides
Add GitHub Actions workflow for automated code quality checks and testing
The .github/workflows.disabled/python.yml file exists but is disabled, suggesting testing infrastructure was previously in place but is now dormant. Re-enabling and modernizing this workflow would catch regressions early, ensure code quality standards are met (leveraging .pre-commit-config.yaml and .coveragerc), and provide confidence to contributors.
- [ ] Restore and update .github/workflows.disabled/python.yml to .github/workflows/test.yml for Python 3.8+ matrix testing
- [ ] Add coverage reporting using .coveragerc configuration, fail if coverage drops below threshold
- [ ] Integrate pre-commit hooks from .pre-commit-config.yaml into the workflow for linting and formatting checks
- [ ] Add documentation build validation using readthedocs/conf.py to catch broken doc references
- [ ] Configure workflow to run on PR, push to main branches, and provide clear failure messages
🌿Good first issues
- Add type hints coverage to telethon/client.py and related modules (mentioned in .coveragerc but likely incomplete) — improves IDE support and catches bugs early
- Expand readthedocs/examples/ with a complete webhook bot example (readthedocs/concepts/asyncio.rst covers async but webhooks deserve a concrete worked example for Bot API users)
- Document the Type Language code generation pipeline in readthedocs/developing/ so contributors can modify MTProto definitions without reverse-engineering the toolchain
⭐Top contributors
Click to expand
Top contributors
- @Lonami — 36 commits
- @Nick80835 — 16 commits
- @Darskiy — 7 commits
- @cjwatson — 3 commits
- @humbertogontijo — 3 commits
📝Recent commits
Click to expand
Recent commits
dab6bc4— Migrate off GitHub (Lonami)6e9bf16— Add error code for sending videos in chat (#4741) (ouyooung)295c736— Fix InvalidBuffedError on incomplete recv data (#4740) (elysium31)208ac30— Update to layer 222 (Lonami)d57be74— Catch-all unknown RPCError and treat them as transient during getDifference (Lonami)416570f— Fix doc typos on some raw API types (#4732) (abcdenis)980a2c0— Update to layer 221 (Lonami)f3bd039— Add errors for chat restrictions (#4729) (ouyooung)5efa1fe— Update proxy docs and warn if python-socks is not installed (Lonami)05b8488— Fix Telethon could not be imported without sqlite3 (Lonami)
🔒Security observations
The Telethon codebase shows moderate security maturity. The primary concerns are: (1) dependency management practices could be more strict, (2) incomplete documentation creates usability and security awareness risks, (3) repository migration process lacks security considerations, and (4) automated security testing appears to be disabled. No critical hardcoded secrets, injection vulnerabilities, or infrastructure misconfigurations are evident from the visible file structure. The project would benefit from enabling automated dependency scanning, establishing a formal security policy, and completing migration documentation.
- Medium · Outdated Documentation Theme Dependency —
pyproject.toml (sphinx-rtd-theme~=1.3.0). The sphinx-rtd-theme dependency version constraint (~=1.3.0) allows patches up to 1.4.0 but doesn't enforce the latest stable version. This could potentially include versions with unpatched vulnerabilities if not regularly updated. Fix: Regularly update dependencies and consider using pip-audit or similar tools to scan for known vulnerabilities. Consider pinning to the latest stable version or using a more restrictive constraint like >=1.3.0,<2.0.0 with regular updates. - Medium · Incomplete Package Dependencies Documentation —
README.rst - Installation section. The README.rst file contains an incomplete pip installation command ('pip3 i'), which suggests incomplete documentation. This could lead to users installing the package incorrectly or not installing optional dependencies needed for security-related features. Fix: Complete the documentation with proper installation instructions including all recommended and optional dependencies from requirements.txt and optional-requirements.txt. - Low · Repository Migration Without Deprecation Notice —
README.rst - First section. The README indicates the project has moved to Codeberg and the GitHub repository 'may be deleted in the future'. This could pose risks if users fork/depend on the GitHub version without being aware of the migration, potentially leading to security updates being missed. Fix: Add prominent deprecation warnings and migration guides. Consider setting up GitHub redirects and security advisories before archiving. Ensure users are directed to the new repository for security updates. - Low · Missing Security Policy Documentation —
Repository root. No SECURITY.md or security policy file is visible in the repository structure. This makes it unclear how to report security vulnerabilities responsibly. Fix: Create a SECURITY.md file documenting responsible disclosure procedures, security contact information, and vulnerability reporting guidelines. - Low · Disabled CI/CD Workflows —
.github/workflows.disabled/. GitHub workflows are disabled (.github/workflows.disabled/), which could indicate that automated security tests, dependency scanning, and code quality checks are not running on pull requests. Fix: Re-enable CI/CD workflows including security scanning tools like bandit, safety, and dependabot to automatically detect vulnerabilities in commits and dependencies.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.