Convert Figma logo to code with AI

LonamiWebs logoTelethon

Pure Python 3 MTProto API Telegram client library, for bots too!

9,657
1,378
9,657
58

Top Related Projects

Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots

We have made you a wrapper you can't refuse

4,591

aiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio

Python Telegram bot api.

6,953

Cross-platform library for building Telegram clients

2,172

The Telegram Bot Framework.

Quick Overview

Telethon is a pure Python 3 MTProto library to interact with Telegram's API. It allows developers to create Telegram clients, bots, and automate various Telegram-related tasks efficiently. Telethon is known for its ease of use and comprehensive feature set.

Pros

  • Easy to use and well-documented
  • Supports both user accounts and bots
  • Actively maintained with frequent updates
  • Offers high-level abstractions for common tasks

Cons

  • Can be slower compared to compiled libraries
  • May require additional setup for certain features (e.g., media handling)
  • Learning curve for advanced usage and custom types
  • Potential for API changes due to Telegram's evolving platform

Code Examples

  1. Sending a message:
from telethon import TelegramClient

async with TelegramClient('session', api_id, api_hash) as client:
    await client.send_message('username', 'Hello from Telethon!')
  1. Listening for new messages:
from telethon import events

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.reply('Welcome! How can I help you?')
  1. Downloading media:
from telethon import types

async def download_media(message):
    if message.media:
        path = await message.download_media()
        print(f'File saved to {path}')
  1. Iterating through chat history:
async def print_chat_history(chat):
    async for message in client.iter_messages(chat):
        print(message.sender_id, ':', message.text)

Getting Started

  1. Install Telethon:

    pip install telethon
    
  2. Create a new application on https://my.telegram.org/apps and obtain api_id and api_hash.

  3. Basic usage:

from telethon import TelegramClient, events

api_id = 12345
api_hash = 'abcdefghijklmnopqrstuvwxyz123456'

async def main():
    async with TelegramClient('session', api_id, api_hash) as client:
        @client.on(events.NewMessage(pattern='/start'))
        async def start_handler(event):
            await event.reply('Hello! I am a Telethon bot.')

        print('Bot is running...')
        await client.run_until_disconnected()

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

This script creates a simple bot that responds to the /start command. Remember to replace api_id and api_hash with your own credentials.

Competitor Comparisons

Elegant, modern and asynchronous Telegram MTProto API framework in Python for users and bots

Pros of Pyrogram

  • Faster performance due to its asynchronous nature and optimized code
  • More user-friendly API design with intuitive method names and parameters
  • Better documentation with clear examples and explanations

Cons of Pyrogram

  • Smaller community and ecosystem compared to Telethon
  • Less frequent updates and potentially slower bug fixes
  • Limited support for some advanced Telegram features

Code Comparison

Telethon:

from telethon import TelegramClient, events

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

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.reply('Hello!')

client.start()
client.run_until_disconnected()

Pyrogram:

from pyrogram import Client, filters

app = Client('session', api_id=api_id, api_hash=api_hash)

@app.on_message(filters.command('start'))
async def start_command(client, message):
    await message.reply_text('Hello!')

app.run()

Both libraries offer similar functionality for basic Telegram bot operations, but Pyrogram's syntax is often considered more intuitive and Pythonic. Telethon provides more low-level access to Telegram's API, while Pyrogram focuses on simplicity and ease of use for common tasks.

We have made you a wrapper you can't refuse

Pros of python-telegram-bot

  • More beginner-friendly with simpler API and better documentation
  • Built-in support for webhooks and polling
  • Extensive examples and community support

Cons of python-telegram-bot

  • Slower performance compared to Telethon
  • Limited support for advanced Telegram features
  • Synchronous by default, requiring additional setup for asynchronous operations

Code Comparison

python-telegram-bot:

from telegram.ext import Updater, CommandHandler

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello!")

updater = Updater(token='YOUR_TOKEN', use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()

Telethon:

from telethon import TelegramClient, events

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

@client.on(events.NewMessage(pattern='/start'))
async def start(event):
    await event.reply('Hello!')

client.start()
client.run_until_disconnected()

Both libraries offer Python interfaces for Telegram bots, but they differ in approach and capabilities. python-telegram-bot is more suitable for beginners and simple bot development, while Telethon provides better performance and access to advanced Telegram features. The choice between them depends on the specific requirements of your project and your level of expertise with Telegram's API.

4,591

aiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio

Pros of aiogram

  • Built specifically for asynchronous programming, leveraging Python's asyncio
  • More Pythonic API design with decorators and context managers
  • Better suited for complex bot development with built-in FSM support

Cons of aiogram

  • Limited to bot development, while Telethon supports user accounts as well
  • Smaller community and fewer third-party extensions compared to Telethon
  • Steeper learning curve for developers new to asynchronous programming

Code Comparison

Telethon example:

from telethon import TelegramClient, events

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

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.reply('Hello!')

client.start()
client.run_until_disconnected()

aiogram example:

from aiogram import Bot, Dispatcher, types

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot)

@dp.message_handler(commands=['start'])
async def start_handler(message: types.Message):
    await message.reply('Hello!')

if __name__ == '__main__':
    from aiogram import executor
    executor.start_polling(dp, skip_updates=True)

Both libraries offer similar functionality for bot development, but aiogram's syntax is more aligned with modern Python practices. Telethon provides a broader range of features for interacting with Telegram's API, including user account operations.

Python Telegram bot api.

Pros of pyTelegramBotAPI

  • Simpler and more straightforward API, making it easier for beginners to get started
  • Lightweight and focused specifically on bot development
  • Extensive documentation with clear examples and tutorials

Cons of pyTelegramBotAPI

  • Limited functionality compared to Telethon, especially for advanced use cases
  • Less efficient for handling large-scale operations or high-volume messaging
  • Lacks some of the more advanced features available in Telethon, such as custom client development

Code Comparison

pyTelegramBotAPI:

import telebot

bot = telebot.TeleBot("TOKEN")

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "Hello!")

bot.polling()

Telethon:

from telethon import TelegramClient, events

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

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.reply('Hello!')

client.start()
client.run_until_disconnected()

The code comparison shows that pyTelegramBotAPI has a more straightforward approach to bot creation, while Telethon offers more flexibility and control over the client. pyTelegramBotAPI is ideal for simple bot development, whereas Telethon is better suited for more complex applications and custom client development.

6,953

Cross-platform library for building Telegram clients

Pros of td

  • Written in C++, offering potentially better performance and lower resource usage
  • Provides a more comprehensive and low-level API for Telegram functionality
  • Supports multiple programming languages through bindings

Cons of td

  • Steeper learning curve due to its lower-level nature
  • Requires more setup and configuration compared to Telethon
  • Less Pythonic and may feel less intuitive for Python developers

Code Comparison

td (C++):

auto send_message = td_api::make_object<td_api::sendMessage>();
send_message->chat_id_ = chat_id;
send_message->input_message_content_ = td_api::make_object<td_api::inputMessageText>();
send_message->input_message_content_->as_input_message_text()->text_ = td_api::make_object<td_api::formattedText>();
send_message->input_message_content_->as_input_message_text()->text_->text_ = "Hello, World!";

Telethon (Python):

await client.send_message(chat_id, "Hello, World!")

The code comparison illustrates the difference in complexity and abstraction level between td and Telethon. While td offers more granular control, Telethon provides a more straightforward and Pythonic approach for common tasks like sending messages.

2,172

The Telegram Bot Framework.

Pros of grammY

  • Written in TypeScript, providing better type safety and developer experience
  • Designed specifically for modern JavaScript/TypeScript environments
  • Supports both Node.js and browser environments

Cons of grammY

  • Smaller community and ecosystem compared to Telethon
  • Less comprehensive documentation and examples
  • Limited support for advanced Telegram features

Code Comparison

Telethon (Python):

from telethon import TelegramClient, events

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

@client.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
    await event.reply('Hello!')

client.start()
client.run_until_disconnected()

grammY (TypeScript):

import { Bot } from "grammy";

const bot = new Bot("BOT_TOKEN");

bot.command("start", (ctx) => ctx.reply("Hello!"));

bot.start();

Both libraries provide similar functionality for creating Telegram bots, but grammY offers a more concise syntax and type-safe approach. Telethon, being a more mature library, provides broader support for Telegram's API and additional features beyond bot development. The choice between the two depends on the specific project requirements, preferred programming language, and desired level of API access.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Telethon

.. epigraph::

⭐️ Thanks everyone who has starred the project, it means a lot!

|logo| Telethon is an asyncio_ Python 3 MTProto_ library to interact with Telegram_'s API as a user or through a bot account (bot API alternative).

.. important::

If you have code using Telethon before its 1.0 version, you must
read `Compatibility and Convenience`_ to learn how to migrate.
As with any third-party library for Telegram, be careful not to
break `Telegram's ToS`_ or `Telegram can ban the account`_.

What is this?

Telegram is a popular messaging application. This library is meant to make it easy for you to write Python programs that can interact with Telegram. Think of it as a wrapper that has already done the heavy job for you, so you can focus on developing an application.

Installing

.. code-block:: sh

pip3 install telethon

Creating a client

.. code-block:: python

from telethon import TelegramClient, events, sync

# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

client = TelegramClient('session_name', api_id, api_hash)
client.start()

Doing stuff

.. code-block:: python

print(client.get_me().stringify())

client.send_message('username', 'Hello! Talking to you from Telethon')
client.send_file('username', '/home/myself/Pictures/holidays.jpg')

client.download_profile_photo('me')
messages = client.get_messages('username')
messages[0].download_media()

@client.on(events.NewMessage(pattern='(?i)hi|hello'))
async def handler(event):
    await event.respond('Hey!')

Next steps

Do you like how Telethon looks? Check out Read The Docs_ for a more in-depth explanation, with examples, troubleshooting issues, and more useful information.

.. _asyncio: https://docs.python.org/3/library/asyncio.html .. _MTProto: https://core.telegram.org/mtproto .. _Telegram: https://telegram.org .. _Compatibility and Convenience: https://docs.telethon.dev/en/stable/misc/compatibility-and-convenience.html .. _Telegram's ToS: https://core.telegram.org/api/terms .. _Telegram can ban the account: https://docs.telethon.dev/en/stable/quick-references/faq.html#my-account-was-deleted-limited-when-using-the-library .. _Read The Docs: https://docs.telethon.dev

.. |logo| image:: logo.svg :width: 24pt :height: 24pt