### Clone and Run Telethon Examples Source: https://github.com/lonamiwebs/telethon/blob/v1/telethon_examples/README.md Instructions to clone the Telethon repository and run an example script. ```sh git clone https://github.com/LonamiWebs/Telethon.git cd Telethon cd telethon_examples python3 gui.py ``` -------------------------------- ### Start Client with Bot Token Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst When starting the client, the 'bot_token' parameter can now be correctly used. If a password is not provided, the client will prompt for it. ```python await client.start(bot_token='YOUR_BOT_TOKEN') ``` -------------------------------- ### Start client, schedule task, and run Source: https://github.com/lonamiwebs/telethon/wiki/Scheduling-Functions Before scheduling tasks with callbacks like `foo_cb`, ensure the client is started using `client.start()`. Then, schedule the task and run the client until disconnected. ```python client.start() foo_cb() client.run_until_disconnected() ``` -------------------------------- ### Make Invoices with Bot Payments Source: https://github.com/lonamiwebs/telethon/blob/v1/telethon_examples/README.md Example demonstrating how to create invoices for payment requests using a bot account. Does not include shipping information. Requires a provider token and knowledge of Telegram's payment guide. ```python from telethon import TelegramClient from telethon.tl.types import InputMediaInvoice from telethon.tl.functions.messages import SendMessageRequest # Replace with your bot token and API details API_ID = 1234567 API_HASH = 'your_api_hash' BOT_TOKEN = 'your_bot_token' async def create_invoice(): bot_client = TelegramClient('bot_session', API_ID, API_HASH) await bot_client.start(bot_token=BOT_TOKEN) # Invoice details title = "Awesome Product" description = "This is a very awesome product." payload = "some-unique-payload-for-your-internal-use" provider_token = "your_provider_token" # Obtain from BotFather start_param = "click_here_for_the_product" currency = "USD" prices = [ {'label': 'Tax', 'amount': 100}, # Amount in the smallest currency unit (e.g., cents for USD) {'label': 'Product Price', 'amount': 99900} ] invoice = InputMediaInvoice( title=title, description=description, provider=provider_token, photo_url='', # Optional: URL of the product photo photo_size=0, # Optional: Size of the photo in bytes currency=currency, prices=prices, payload=payload, provider_data=None, # Optional: JSON string with additional provider data shipping_address_step=None, # Optional: 'name', 'phone_number', 'email', 'address' ); # Send the invoice to a chat (replace 'chat_id' with the target chat ID) await bot_client(SendMessageRequest(peer='chat_id', message=invoice, invert_media=True)) print("Invoice sent!") await bot_client.disconnect() if __name__ == '__main__': import asyncio asyncio.run(create_invoice()) ``` -------------------------------- ### Start client and sign up Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The .start() method can now also handle the sign-up process if required. Introduced in v0.17. ```python .start() ``` -------------------------------- ### PingRequest Example Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/full-api.rst Demonstrates how to import, construct, and invoke a simple PingRequest and inspect its response. ```APIDOC ## POST /api/ping ### Description Sends a ping request to the server and expects a pong response. ### Method POST ### Endpoint /api/ping ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ping_id** (long) - Required - The ID for the ping request. ### Request Example ```json { "ping_id": 48641868471 } ``` ### Response #### Success Response (200) - **msg_id** (long) - The message ID of the pong response. - **ping_id** (long) - The original ping ID. #### Response Example ```json { "msg_id": 781875678118, "ping_id": 48641868471 } ``` ``` -------------------------------- ### Install Telethon Source: https://github.com/lonamiwebs/telethon/blob/v1/README.rst Install the Telethon library using pip. Ensure you are using pip3 for Python 3. ```sh pip3 install telethon ``` -------------------------------- ### Create and Start Telethon Client Source: https://github.com/lonamiwebs/telethon/blob/v1/README.rst Initialize a Telethon client with your API ID and hash, then start the session. Obtain your API credentials from https://my.telegram.org. ```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() ``` -------------------------------- ### Verify Telethon Installation Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/installation.rst Run this command to confirm that Telethon has been installed correctly by printing its version number. ```python python3 -c "import telethon; print(telethon.__version__)" ``` -------------------------------- ### Start Takeout Session Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Easily start takeout sessions (data export sessions) through client.takeout(). Some requests will have lower flood limits when done through the takeout session. ```python client.takeout() ``` -------------------------------- ### Install Common Dependencies on apt-based Systems Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/installation.rst Installs essential development dependencies for Telethon on Debian/Ubuntu systems using apt, followed by pip installations for Telethon and optional packages. ```sh apt update apt install clang lib{jpeg-turbo,webp}-dev python{,-dev} zlib-dev pip install -U --user setuptools pip install -U --user telethon cryptg pillow ``` -------------------------------- ### Get Channel Entity Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/entities.rst Example of getting a channel entity. Note that you often don't need to explicitly get the entity before using it, as the library handles this. ```python my_channel = await client.get_entity(PeerChannel(some_id)) ``` -------------------------------- ### Handle Bot Token Start Parameter Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The 'bot_token' parameter would not work on .start(). This has been fixed, and changes to 'password' now correctly prompt if not provided. ```python await client.start(bot_token='YOUR_BOT_TOKEN', password='YOUR_PASSWORD') ``` -------------------------------- ### Install Telethon with Version Constraint Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Use this syntax to install a specific compatible version of Telethon. This ensures stability by allowing only patch releases that should not break your code. ```text telethon~=1.16.0 ``` -------------------------------- ### Install or Upgrade Telethon Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/installation.rst Use this command to install or upgrade Telethon to the latest stable version. Ensure pip is up-to-date first. ```sh python3 -m pip install --upgrade pip python3 -m pip install --upgrade telethon ``` -------------------------------- ### Install Development Version of Telethon Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/installation.rst Install the latest unreleased changes from the GitHub repository. This version may contain bugs and is not recommended for production. ```sh python3 -m pip install --upgrade https://github.com/LonamiWebs/Telethon/archive/v1.zip ``` -------------------------------- ### Get Me with Input Peer Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Use client.get_me(input_peer=True) if your only requirement is to obtain your own user ID. ```python me_info = await client.get_me(input_peer=True) ``` -------------------------------- ### Start Client with Existing Login Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst When calling `client.start()` while already logged in, the library now issues a warning. To avoid this, ensure you are logging into the correct account or log out of the previous session first. ```python client.start(phone) ``` -------------------------------- ### SendMessageRequest Example Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/full-api.rst Illustrates how to send a message using SendMessageRequest, including obtaining the peer entity. ```APIDOC ## POST /api/messages/send ### Description Sends a message to a specified peer. ### Method POST ### Endpoint /api/messages/send ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **peer** (InputPeer) - Required - The target peer to send the message to. - **message** (str) - Required - The content of the message. ### Request Example ```json { "peer": { "_type": "InputPeerUser", "user_id": 12345, "access_hash": "some_hash" }, "message": "Hello, Telegram!" } ``` ### Response #### Success Response (200) - **message** (Message) - The sent message object. #### Response Example ```json { "message": { "id": 1, "peer_id": { "_type": "PeerUser", "user_id": 12345 }, "message": "Hello, Telegram!" } } ``` ``` -------------------------------- ### Use TelegramClient with 'with' Statement Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Illustrates using `TelegramClient` within a `with` statement for automatic start and disconnect. ```python from telethon import TelegramClient, sync with TelegramClient(name, api_id, api_hash) as client: client.send_message('me', 'Hello!') ``` -------------------------------- ### Basic Echo Bot using python-telegram-bot Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This is a standard example of an echo bot using the python-telegram-bot library. It sets up handlers for the /start command and text messages. ```python from telegram.ext import Updater, CommandHandler, MessageHandler, Filters def start(update, context): """Send a message when the command /start is issued.""" update.message.reply_text('Hi!') def echo(update, context): """Echo the user message.""" update.message.reply_text(update.message.text) def main(): """Start the bot.""" updater = Updater("TOKEN") dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo)) updater.start_polling() updater.idle() if __name__ == '__main__': main() ``` -------------------------------- ### Iterate Dialogs Example Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Demonstrates using `client.iter_dialogs()` to iterate through dialogs, allowing for early termination once a desired dialog is found. This is more efficient than fetching all dialogs at once. ```python async for dialog in client.iter_dialogs(): if dialog.name == "Example Name": break ``` -------------------------------- ### Initialize Telegram Client Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/updates.rst Normal client creation requires a session name, API ID, and API hash. This is the standard way to start a Telethon client. ```python from telethon import TelegramClient, events client = TelegramClient('anon', api_id, api_hash) ``` -------------------------------- ### Iterate Participants Example Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Shows how to use `client.iter_participants()` with a filter to retrieve specific participants. The returned users expose a `.participant` attribute. ```python async for participant in client.iter_participants(group_chat, filter=InputPeerChannel): # participant.participant is the actual Peer object ``` -------------------------------- ### Start the Telethon client and run until disconnected Source: https://github.com/lonamiwebs/telethon/wiki/Scheduling-Functions Use `client.run_until_disconnected()` to keep the client running and connected until explicitly stopped. ```python client.run_until_disconnected() ``` -------------------------------- ### Initialize TelegramClient with HTTP Connection Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Example of initializing a Telethon TelegramClient using the HTTP connection mode. This is useful for proxies that only allow HTTP connections. ```python from telethon import TelegramClient, sync from telethon.network import ConnectionHttp client = TelegramClient(..., connection=ConnectionHttp) with client: client.send_message('me', 'Hi!') ``` -------------------------------- ### Access Nested Entity Attribute Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/strings.rst Access nested attributes within a Telethon entity. For example, to get the year from the entity's date attribute. ```python channel_year = entity.date.year ``` -------------------------------- ### Setup.py Gen Command Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Introduces a more powerful `setup.py gen` command for generating package information. ```bash python setup.py gen ``` -------------------------------- ### Run the main async function with APScheduler Source: https://github.com/lonamiwebs/telethon/wiki/Scheduling-Functions To use APScheduler with Telethon, an async main function is required to start the client, the scheduler, and run until disconnected. This setup also includes basic exception handling for graceful shutdown. ```python async def main(): await client.start() scheduler.start() print("Scheduler started...\n(Press Ctrl+C to stop this)") await client.run_until_disconnected() if __name__ == "__main__": try: asyncio.run(main()) except (KeyboardInterrupt, SystemExit): pass ``` -------------------------------- ### Download Media with Web Previews Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `download_media` method now accepts web previews. This enhancement allows for more flexible media handling. ```python client.download_media(web_preview=True) ``` -------------------------------- ### Get Entity by Username or Link Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/entities.rst Demonstrates retrieving entities using various string formats including usernames, t.me links, and Telegram join chat links. ```python # All of these work and do the same. username = await client.get_entity('username') username = await client.get_entity('t.me/username') username = await client.get_entity('https://telegram.dog/username') ``` -------------------------------- ### Schedule a job to run at specific intervals using APScheduler Source: https://github.com/lonamiwebs/telethon/wiki/Scheduling-Functions This example demonstrates scheduling a job to run at a fixed interval, such as every 60 minutes, using APScheduler. ```python from apscheduler.schedulers.asyncio import AsyncIOScheduler async def this_will_run_at_every_one_hour(): await client.send_message('me', 'One hour has passed.') scheduler = AsyncIOScheduler() scheduler.add_job(this_will_run_at_every_one_hour, 'interval', minutes=60) scheduler.start() ``` -------------------------------- ### Chat Action Indicator Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Use the client.action context manager to indicate chat actions like 'typing'. This example shows how to simulate typing for 2 seconds before sending a message. ```python async with client.action(chat, 'typing'): await asyncio.sleep(2) # type for 2 seconds await client.send_message(chat, 'Hello world! I type slow ^^') ``` -------------------------------- ### Sign up and sign in return user object Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Both `.sign_up()` and `.sign_in()` methods now return the user object of the logged-in user. ```python .sign_up() ``` ```python .sign_in() ``` -------------------------------- ### Example Pong Response Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/full-api.rst This is an example of the stringified output for a Pong response, showing its members msg_id and ping_id. ```python Pong( msg_id=781875678118, ping_id=48641868471 ) ``` -------------------------------- ### Basic asyncio Hello World Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/asyncio.rst Demonstrates a simple asynchronous function that prints 'Hello, world!' character by character with a delay. Requires Python 3.7+. ```python import asyncio async def main(): for char in 'Hello, world!\n': print(char, end='', flush=True) await asyncio.sleep(0.2) asyncio.run(main()) ``` -------------------------------- ### Get Input Entity Directly Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/full-api.rst Use `client.get_input_entity()` for a more direct way to get an entity, especially if it's already known or cached. ```python entity = await client.get_input_entity('someone') ``` -------------------------------- ### Initialize and Use TelegramClient Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/quick-start.rst Demonstrates how to initialize a TelegramClient with API credentials and run asynchronous operations within a client context. Ensure you use your own API ID and hash from my.telegram.org. ```python from telethon import TelegramClient # Remember to use your own values from my.telegram.org! api_id = 12345 api_hash = '0123456789abcdef0123456789abcdef' client = TelegramClient('anon', api_id, api_hash) async def main(): # Getting information about yourself me = await client.get_me() # "me" is a user object. You can pretty-print # any Telegram object with the "stringify" method: print(me.stringify()) # When you print something, you see a representation of it. # You can access all attributes of Telegram objects with # the dot operator. For example, to get the username: username = me.username print(username) print(me.phone) # You can print all the dialogs/conversations that you are part of: async for dialog in client.iter_dialogs(): print(dialog.name, 'has ID', dialog.id) # You can send messages to yourself... await client.send_message('me', 'Hello, myself!') # ...to some chat ID await client.send_message(-100123456, 'Hello, group!') # ...to your contacts await client.send_message('+34600123123', 'Hello, friend!') # ...or even to any username await client.send_message('username', 'Testing Telethon!') # You can, of course, use markdown in your messages: message = await client.send_message( 'me', 'This message has **bold**, `code`, __italics__ and ' 'a [nice website](https://example.com)!', link_preview=False ) # Sending a message returns the sent message object, which you can use print(message.raw_text) # You can reply to messages directly if you have a message object await message.reply('Cool!') # Or send files, songs, documents, albums... await client.send_file('me', '/home/me/Pictures/holidays.jpg') # You can print the message history of any chat: async for message in client.iter_messages('me'): print(message.id, message.text) # You can download media from messages, too! # The method will return the path where the file was saved. if message.photo: path = await message.download_media() print('File saved to', path) # printed after download is done with client: client.loop.run_until_complete(main()) ``` -------------------------------- ### Git Command for Version Comparison Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst This is a command-line example using `git shortlog` to view changes between two specific versions of the library. It's provided as a way to inspect undocumented patch versions. ```bash git shortlog v1.7.1...v1.7.4 ``` -------------------------------- ### Initialize TelegramClient Source: https://context7.com/lonamiwebs/telethon/llms.txt Create a client instance using your API credentials. The client handles authentication and connection to Telegram servers. It can be run using `run_until_complete` or as an async context manager. ```python from telethon import TelegramClient # Create the client with session name and API credentials client = TelegramClient('session_name', api_id=123456, api_hash='your_api_hash') # Start the client (prompts for phone/code on first run) async def main(): await client.start() me = await client.get_me() print(f'Logged in as {me.first_name}') # Run the client client.loop.run_until_complete(main()) # Or use the context manager approach async with TelegramClient('session_name', api_id, api_hash) as client: await client.send_message('me', 'Hello from Telethon!') ``` -------------------------------- ### Getting Forwarded Sender Entity in Events Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Illustrates how to get the sender of a forwarded message within an event handler using .get_fwd_sender(). The 'fwd_from_entity' property has been replaced. ```python await message.get_fwd_sender() ``` -------------------------------- ### Run Asyncio Main Function Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/asyncio.rst This example shows how to create and run asynchronous tasks using asyncio. It defines two tasks, 'hello' and 'world', with different delays and runs them concurrently within a main function. The main function then waits for all tasks to complete before exiting. ```python import asyncio async def hello(delay): await asyncio.sleep(delay) # await tells the loop this task is "busy" print('hello') # eventually the loop resumes the code here async def world(delay): # the loop decides this method should run first await asyncio.sleep(delay) # await tells the loop this task is "busy" print('world') # eventually the loop finishes all tasks async def main(): asyncio.create_task(world(2)) # create the world task, passing 2 as delay asyncio.create_task(hello(delay=1)) # another task, but with delay 1 await asyncio.sleep(3) # wait for three seconds before exiting try: # create a new temporary asyncio loop and use it to run main asyncio.run(main()) except KeyboardInterrupt: pass ``` ```python import asyncio async def hello(delay): await asyncio.sleep(delay) print('hello') async def world(delay): await asyncio.sleep(delay) print('world') async def main(): asyncio.create_task(world(2)) asyncio.create_task(hello(delay=1)) await asyncio.sleep(3) try: asyncio.run(main()) except KeyboardInterrupt: pass ``` -------------------------------- ### Sign in with process_updates=True Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Users can now sign in even with `process_updates=True` and no prior session. ```python process_updates=True ``` -------------------------------- ### Sign Up Manually Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Use `client.sign_up` for manual sign-up operations. This method should now correctly handle sign-up attempts instead of returning an 'code invalid' error. ```python client.sign_up(phone, code, password) ``` -------------------------------- ### Get Input Sender and Send Message Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/entities.rst Shows how to get the input sender explicitly and then use it to send a message. This method may make a network request to find the input sender. ```python async def handler(event): # This method may make a network request to find the input sender. # Properties can't make network requests, so we need a method. sender = await event.get_input_sender() await client.send_message(sender, 'Hi') await client.send_message(sender, 'Hi') ``` -------------------------------- ### Example Message with Spoiler and Custom Emoji Source: https://github.com/lonamiwebs/telethon/wiki/Sending-more-than-just-messages This is an example of how to format a message string to include spoiler text and custom emoji using the custom markdown parser. The spoiler is indicated by the URL 'spoiler', and custom emoji by 'emoji/DOCUMENT_ID'. ```python message = 'this is a [link text](spoiler) and [❤️](emoji/5449505950283078474) too' ``` -------------------------------- ### Download Media with PhotoSize Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Addresses a bug where `client.download_media` did not support `PhotoSize` objects. ```python await client.download_media(photo_size_object, file='path/to/save') ``` -------------------------------- ### Get Dialogs with Limit None Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Retrieve all dialogs by setting limit=None in .get_dialogs(). ```python await client.get_dialogs(limit=None) ``` -------------------------------- ### Python Requires in Setup.py Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `setup.py` script now utilizes `python_requires` to specify the required Python version. ```python from setuptools import setup setup( name='my_package', version='0.1.0', python_requires='>=3.7', # ... other setup arguments ) ``` -------------------------------- ### Instantiate TelegramClient Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/modules/client.rst This is the basic way to create a TelegramClient instance. You need to provide a name for the session, your API ID, and your API hash. The client can then be used to send messages and perform other actions. ```python from telethon import TelegramClient client = TelegramClient(name, api_id, api_hash) ``` ```python async def main(): # Now you can use all client methods listed below, like for example... await client.send_message('me', 'Hello to myself!') with client: client.loop.run_until_complete(main()) ``` -------------------------------- ### TLMessage String Representation Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Get a string representation of a TLMessage object using .stringify(). ```python message.stringify() ``` -------------------------------- ### Get Drafts Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Retrieve drafts using the .get_drafts() method, which returns custom Draft objects. ```python await client.get_drafts() ``` -------------------------------- ### Get Input Entity Missing Case Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `InputPeerSelf` case was previously missing from `telethon.telegram_client.TelegramClient.get_input_entity` and has now been added. ```python input_entity = await client.get_input_entity(InputPeerSelf()) ``` -------------------------------- ### Automate Replies to 'hello' Messages Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/basic/updates.rst This example demonstrates how to create a Telegram client and set up an event handler to automatically reply 'hi!' to any message containing 'hello'. Event handlers must be async functions. ```python from telethon import TelegramClient, events client = TelegramClient('anon', api_id, api_hash) @client.on(events.NewMessage) async def my_event_handler(event): if 'hello' in event.raw_text: await event.reply('hi!') client.start() client.run_until_disconnected() ``` -------------------------------- ### Get Full User Information Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/examples/users.rst Retrieves comprehensive information about a user, including their bio and other details. ```APIDOC ## Get Full User Information ### Description Retrieves the bio, biography, or about information for a user. ### Method POST ### Endpoint /api/users/getFullUser ### Parameters #### Path Parameters - **user** (string or User) - Required - The username or user ID of the user to retrieve information for. ### Request Example ```json { "user": "username_or_id" } ``` ### Response #### Success Response (200) - **full_user** (UserFull) - An object containing the full user details. - **about** (string) - The user's biography or about information. #### Response Example ```json { "full_user": { "about": "This is the user's bio." } } ``` ``` -------------------------------- ### Get Entity by ID Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/entities.rst Retrieves a User, Chat, or Channel entity using its unique ID. ```python # Getting entities through their ID (User, Chat or Channel) entity = await client.get_entity(some_id) ``` -------------------------------- ### Download File with Pathlib Support Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `client.download_file()` method now accepts `pathlib.Path` objects as the destination path for downloaded files. ```python client.download_file(file_ref, destination_path) ``` -------------------------------- ### Set Update Workers Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Configure the number of worker threads for updates. Recommended to start with update_workers=4. ```python update_workers=4 ``` -------------------------------- ### Get full message object after sending Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `.send_message()` method now returns the complete message object that was just sent. ```python .send_message() now returns the full message ``` -------------------------------- ### Basic Telegram Client Usage in Python Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/index.rst Demonstrates sending a message, downloading a profile photo, and setting up a message event handler using TelegramClient. Requires api_id and api_hash. ```python 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() ``` -------------------------------- ### Streaming Downloads with Flexibility Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Introduces `client.iter_download()`, a new method for streaming downloads that offers significant flexibility, including support for arbitrary offsets for efficient seeking. ```python client.iter_download() ``` -------------------------------- ### Get message history with more parameters Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The .get_message_history() method has additional parameters available. This enhancement was part of v0.17. ```python .get_message_history() ``` -------------------------------- ### Download Media as Bytes Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Downloading to file=bytes will now return a bytes object with the downloaded media. This is useful for processing media directly in memory. ```python downloaded_media = client.download_media(message, file=bytes) ``` -------------------------------- ### Using Async Callbacks for Media Downloads Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `progress_callback` in `client.download_media()` now supports asynchronous functions (`async def`), allowing for non-blocking operations during media downloads. ```python async def ``` -------------------------------- ### Using StringSession with TelegramClient Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/sessions.rst Demonstrates how to initialize TelegramClient with StringSession and save the session data as a string. This method is useful for reusing session data without relying on disk files. ```python from telethon.sync import TelegramClient from telethon.sessions import StringSession with TelegramClient(StringSession(string), api_id, api_hash) as client: ... # use the client # Save the string session as a string; you should decide how # you want to save this information (over a socket, remote # database, print it and then paste the string in the code, # etc.); the advantage is that you don't need to save it # on the current disk as a separate file, and can be reused # anywhere else once you log in. string = client.session.save() ``` -------------------------------- ### UserUpdate Event Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/quick-references/events-reference.rst This event is triggered when a user's status changes, such as going online or starting to type. ```APIDOC ## UserUpdate Event ### Description Occurs whenever a user goes online, starts typing, etc. ### Method Event ### Endpoint N/A (Event-driven) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Attributes - **user** (User) - The user whose status updated. - **input_user** (InputUser) - The input version of the user. - **user_id** (int) - The ID of the user. ### Methods - **get_user()**: Gets the user whose status updated. - **get_input_user()**: Gets the input version of the user. - **typing()**: Checks if the user is typing. - **uploading()**: Checks if the user is uploading. - **recording()**: Checks if the user is recording. - **playing()**: Checks if the user is playing. - **cancel()**: Cancels an ongoing action. - **geo()**: Gets the user's location. - **audio()**: Checks if the user is sending audio. - **round()**: Checks if the user is sending a round video. - **video()**: Checks if the user is sending video. - **contact()**: Checks if the user is sending a contact. - **document()**: Checks if the user is sending a document. - **photo()**: Checks if the user is sending a photo. - **last_seen()**: Gets the user's last seen information. - **until()**: Gets the time until which a status is valid. - **online()**: Checks if the user is currently online. - **recently()**: Checks if the user was recently online. - **within_weeks(weeks)**: Checks if the user was online within a specified number of weeks. - **within_months(months)**: Checks if the user was online within a specified number of months. ``` -------------------------------- ### Get entity using TelegramClient with LRU cache Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `TelegramClient.get_entity()` method is now public and utilizes the `@lru_cache()` decorator for performance. ```python TelegramClient.get_entity() ``` -------------------------------- ### Answer Inline Queries with Media Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Answering inline queries with media now works properly, enabling the creation of inline bots that can send stickers and other media. ```python # Example for answering inline query with media ``` -------------------------------- ### Use Asyncio with Telethon Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Demonstrates how to use Telethon methods with `asyncio`. ```python import asyncio async def main(): await client.send_message('me', 'Hello!') asyncio.run(main()) ``` -------------------------------- ### Get drafts for a single entity Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst You can now use `client.get_drafts` to retrieve drafts from a specific chat or user, rather than fetching all drafts. ```python drafts = await client.get_drafts(entity='me') for draft in drafts: print(draft.text) ``` -------------------------------- ### Run Other Code While Loop is Running Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/asyncio.rst This example shows how to create and run additional tasks, like a clock, while the main event loop is kept alive by `client.run_until_disconnected()`. This prevents blocking and allows concurrent operations. ```python from datetime import datetime async def clock(): while True: print('The time:', datetime.now()) await asyncio.sleep(1) loop.create_task(clock()) ... client.run_until_disconnected() ``` -------------------------------- ### Get Channel Statistics Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Retrieve raw statistics for channels or megagroups using `client.get_stats()`. This method is available with scheme layer 116. ```python client.get_stats(channel) ``` -------------------------------- ### Get Input Peer from Entity Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/full-api.rst Convert a complete user entity to its 'input' peer version using `telethon.utils.get_input_peer()`. This can be useful for caching. ```python from telethon import utils peer = utils.get_input_peer(entity) ``` -------------------------------- ### Initialize Telethon Client Source: https://github.com/lonamiwebs/telethon/wiki/Docs-Overhaul Demonstrates the basic initialization of a Telethon TelegramClient. Ensure you replace '...' with your actual API ID, API hash, and session name. ```python from Telethon import TelegramClient client = TelegramClient(...) with client: ... ``` -------------------------------- ### Get Telegram Entity Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/concepts/full-api.rst Use `client.get_entity()` to retrieve full user information. The library automatically converts it to the 'input' version when needed. ```python entity = await client.get_entity('someone') ``` -------------------------------- ### TelegramClient Initialization Source: https://context7.com/lonamiwebs/telethon/llms.txt The main entry point for using Telethon. Creates a client instance that connects to Telegram servers using your API credentials. ```APIDOC ## TelegramClient Initialization ### Description The main entry point for using Telethon. Creates a client instance that connects to Telegram servers using your API credentials obtained from https://my.telegram.org. ### Method Instantiation and asynchronous operations ### Endpoint N/A (Client-side library) ### Request Example ```python from telethon import TelegramClient # Create the client with session name and API credentials client = TelegramClient('session_name', api_id=123456, api_hash='your_api_hash') # Start the client (prompts for phone/code on first run) async def main(): await client.start() me = await client.get_me() print(f'Logged in as {me.first_name}') # Run the client client.loop.run_until_complete(main()) # Or use the context manager approach async with TelegramClient('session_name', api_id, api_hash) as client: await client.send_message('me', 'Hello from Telethon!') ``` ### Response N/A (Client-side library, operations are asynchronous) ``` -------------------------------- ### Download Media with Thumbnails Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst The `download_media` function now supports a `thumb` parameter which accepts either a string or a `VideoSize` object. Thumbnails are sorted, with -1 representing the largest. ```python client.download_media(message, thumb=-1) ``` -------------------------------- ### Postpone Event Resolution Until Connected Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Event resolution is now postponed until the client is successfully connected. This allows attaching events before starting the client. ```python client.add_event_handler(my_handler) await client.start() # Events are resolved after client.start() ``` -------------------------------- ### New Message Event Pattern Match Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Access NewMessage.Event.pattern_match to get details about the pattern that matched a message. This is useful for advanced event filtering. ```python async def handler(event): if event.pattern_match: print(f'Matched pattern: {event.pattern_match.group(0)}') ``` -------------------------------- ### Running TelegramClient Synchronously Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Demonstrates how to run client.start() and client.run_until_disconnected() synchronously without manually starting the event loop. For use within an async def function, these methods require 'await'. ```python client.start() client.run_until_disconnected() ``` -------------------------------- ### Send File with Path-like Thumbnails Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Path-like files are now supported for thumbnails when sending files. This enhances flexibility in specifying thumbnail sources. ```python client.send_file(chat, file, thumb='path/to/thumbnail.jpg') ``` -------------------------------- ### Get Self ID with Input Peer Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Use .get_me(input_peer=True) when only the self ID is needed. This is an optimized way to retrieve your user ID. ```python await client.get_me(input_peer=True) ``` -------------------------------- ### Bot API Style IDs on Get Input Entity Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Fixes an issue where Bot API style IDs were not working correctly with `client.get_input_entity`. ```python entity = await client.get_input_entity(1234567890) ``` -------------------------------- ### Authentication Methods Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/quick-references/client-reference.rst Methods for handling user authentication, including starting sessions, sending verification codes, signing in, QR code login, logging out, and managing two-factor authentication. ```APIDOC ## Authentication Methods ### Description Methods for handling user authentication, including starting sessions, sending verification codes, signing in, QR code login, logging out, and managing two-factor authentication. ### Methods - `start()` - `send_code_request(phone_number)` - `sign_in(phone_number, code)` - `qr_login()` - `log_out()` - `edit_2fa(password, new_password)` ``` -------------------------------- ### Get Input Entity for Unseen Integer IDs Source: https://github.com/lonamiwebs/telethon/blob/v1/readthedocs/misc/changelog.rst Fixed client.get_input_entity() for integer IDs that the client has not seen before. This ensures proper entity resolution. ```python client.get_input_entity(user_id) ```