/Telethon

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

Primary LanguagePythonMIT LicenseMIT

Telethon

⭐️ 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

pip3 install telethon

Creating a client

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

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.

File Attributes

from telethon.tl.types import InputPeerSelf, InputMediaUploadedDocument

msg_media = await event.client.upload_file(file_path)
thumbnail_file = await event.client.upload_file(thumb_path)

# Define audio attributes (you can leave it empty if not needed)
audio_attributes = []

# Create an input media object with the audio file and thumbnail
input_media = InputMediaUploadedDocument(
    file=msg_media,              # Audio file
    mime_type='audio/mpeg',      # Mime type of the audio file
    attributes=audio_attributes, # Audio attributes (empty list if not needed)
    thumb=thumbnail_file         # Thumbnail file
)

# Upload the media
file = await event.client(UploadMediaRequest(
    InputPeerSelf(),  # Upload to self
    media=input_media # Input media object
))