Telethon - Telegram Client Library

1.43.0 · active · verified Sat Apr 11

Telethon is a full-featured, asynchronous Python 3 client library for the Telegram API. It allows interaction with Telegram's MTProto API as a user or through a bot account. Currently at version 1.43.0, the library receives regular updates, including new API layers and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize and connect a Telethon client. It logs in the user (or registers if it's the first run) using the `api_id` and `api_hash` provided via environment variables. The session is saved to a `.session` file for persistence. The client runs asynchronously until manually disconnected.

import os
import asyncio
from telethon import TelegramClient

# Get API ID and API Hash from environment variables for security
# You can obtain these from https://my.telegram.org
api_id = int(os.environ.get('TG_API_ID', 0))
api_hash = os.environ.get('TG_API_HASH', '')

# 'session_name' will create 'session_name.session' file
# This file stores your login information and should be kept private.
client = TelegramClient('session_name', api_id, api_hash)

async def main():
    if not api_id or not api_hash:
        print("Please set TG_API_ID and TG_API_HASH environment variables.")
        return

    print("Connecting to Telegram...")
    await client.start()
    print("Client Connected!")

    # Get information about yourself
    me = await client.get_me()
    print(f"Logged in as: {me.first_name} (@{me.username})")

    # Example: Send a message to yourself
    # await client.send_message('me', 'Hello from Telethon!')
    # print("Message sent to self!")

    # Keep the client running until disconnected (e.g., by Ctrl+C)
    await client.run_until_disconnected()

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

view raw JSON →