### Sign in as a Bot Account Source: https://docs.telethon.dev/en/stable/_sources/basic/signing-in.rst.txt This example shows how to sign in using a bot token. You need to obtain a bot token from @BotFather. The client must be explicitly started with the bot token. ```python from telethon.sync import TelegramClient api_id = 12345 api_hash = '0123456789abcdef0123456789abcdef' bot_token = '12345:0123456789abcdef0123456789abcdef' # We have to manually call "start" if we want an explicit bot token bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token) # But then we can use the client instance as usual with bot: ... ``` -------------------------------- ### Initialize and Start TelegramClient Source: https://docs.telethon.dev/en/stable/modules/client.html Demonstrates how to initialize a TelegramClient and start a session. Supports starting as a bot account using a token, or as a user account requiring phone number and authentication codes. It also shows usage with a context manager. ```python client = TelegramClient('anon', api_id, api_hash) # Starting as a bot account await client.start(bot_token=bot_token) # Starting as a user account await client.start(phone) # Please enter the code you received: 12345 # Please enter your password: ******* # (You are now logged in) # Starting using a context manager (this calls start()): with client: pass ``` -------------------------------- ### gen_tl Call on Installation Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt The `setup.py` script now includes a call to `gen_tl` during installation if needed, ensuring the TL schema is up-to-date. ```python setup.py ``` -------------------------------- ### start Source: https://docs.telethon.dev/en/stable/modules/client.html Starts the client, connecting and logging in if necessary. This method handles interactive login, including 2FA, and can be used for both user and bot accounts. ```APIDOC ## start(phone: ~typing.Callable[[]_, _str] | str = >_, password: ~typing.Callable[[]_, _str] | str = >_, *, bot_token: str = None, force_sms: bool = False, code_callback: ~typing.Callable[[]_, _str | int] = None, first_name: str = 'New User'_, last_name: str = ''_, max_attempts: int = 3_) -> TelegramClient ### Description Starts the client (connects and logs in if necessary). By default, this method will be interactive (asking for user input if needed), and will handle 2FA if enabled too. If the event loop is already running, this method returns a coroutine that you should await on your own code; otherwise the loop is ran until said coroutine completes. ### Method `async` (returns a coroutine if event loop is running) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **phone** (`str` | `int` | `callable`): The phone (or callable without arguments to get it) to which the code will be sent. If a bot-token-like string is given, it will be used as such instead. The argument may be a coroutine. - **password** (`str`, `callable`, optional): The password for 2 Factor Authentication (2FA). This is only required if it is enabled in your account. The argument may be a coroutine. - **bot_token** (`str`): Bot Token obtained by @BotFather to log in as a bot. Cannot be specified with `phone` (only one of either allowed). - **force_sms** (`bool`, optional): Whether to force sending the code request as SMS. This only makes sense when signing in with a `phone`. - **code_callback** (`callable`, optional): A callable that will be used to retrieve the Telegram login code. Defaults to `input()`. The argument may be a coroutine. - **first_name** (`str`, optional): The first name to be used if signing up. This has no effect if the account already exists and you sign in. - **last_name** (`str`, optional): Similar to the first name, but for the last. Optional. - **max_attempts** (`int`, optional): How many times the code/password callback should be retried or switching between signing in and signing up. ### Returns - This `TelegramClient`, so initialization can be chained with `.start()`. ### Example ```python # Example for interactive login await client.start() # Example for bot login await client.start(bot_token='YOUR_BOT_TOKEN') ``` ``` -------------------------------- ### aiogram Example with Command, Regex, and Echo Handlers Source: https://docs.telethon.dev/en/stable/concepts/botapi-vs-mtproto.html This is an example using aiogram with handlers for a command, a regex pattern, and general echo. ```Python from aiogram import Bot, Dispatcher, executor, types API_TOKEN = 'BOT TOKEN HERE' # Initialize bot and dispatcher bot = Bot(token=API_TOKEN) dp = Dispatcher(bot) @dp.message_handler(commands=['start']) async def send_welcome(message: types.Message): """ This handler will be called when client send /start command. """ await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.") @dp.message_handler(regexp='(^cat[s]?$|puss)') def cats(message: types.Message): with open('data/cats.jpg', 'rb') as photo: await bot.send_photo(message.chat.id, photo, caption='Cats is here 😺', reply_to_message_id=message.message_id) @dp.message_handler() def echo(message: types.Message): await bot.send_message(message.chat.id, message.text) if __name__ == '__main__': executor.start_polling(dp, skip_updates=True) ``` -------------------------------- ### Peer Information in Interactive Client Example Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt A new addition to the interactive client example demonstrates how to show peer information. This is useful for understanding and debugging peer-related data. ```python # Example added to interactive client ``` -------------------------------- ### Start Client and Authenticate Source: https://docs.telethon.dev/en/stable/modules/client.html Starts the TelegramClient, connecting and logging in. This method is interactive by default and handles 2FA. It can be used for both user and bot accounts. Provide callbacks for phone, password, and code retrieval if needed. ```python # Example usage for starting the client (interactive) # client.start() # Example usage for starting with a bot token # client.start(bot_token='YOUR_BOT_TOKEN') ``` -------------------------------- ### Verify Telethon Installation Source: https://docs.telethon.dev/en/stable/basic/installation.html Run this command to confirm that Telethon has been installed correctly by printing its version number. ```python python3 -c "import telethon; print(telethon.__version__)" ``` -------------------------------- ### Simplified .start() Method Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt The `.start()` method now only asks for your phone number if it's strictly required, simplifying the initial setup process. ```python .start() ``` -------------------------------- ### Telethon Full Quick-Start Example Source: https://docs.telethon.dev/en/stable/basic/quick-start.html This snippet demonstrates a wide range of Telethon functionalities, including client initialization, user authentication, retrieving user information, iterating through dialogs, sending various types of messages (text, markdown, files), and downloading media. It's a comprehensive example for understanding basic library usage. ```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()) ``` -------------------------------- ### PingRequest Example Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Demonstrates how to send a PingRequest and process the Pong response. ```APIDOC ## POST /api/ping ### Description Sends a ping request to the Telegram server and expects a pong response. ### Method POST ### Endpoint /api/ping ### Parameters #### 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 ping ID that was echoed back. #### Response Example ```json { "msg_id": 781875678118, "ping_id": 48641868471 } ``` ``` -------------------------------- ### Basic asyncio Example Source: https://docs.telethon.dev/en/stable/concepts/asyncio.html Demonstrates a simple asynchronous function that prints characters 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()) ``` -------------------------------- ### pyTelegramBotAPI Echobot Example Source: https://docs.telethon.dev/en/stable/concepts/botapi-vs-mtproto.html This is the original echobot example using pyTelegramBotAPI. ```Python import telebot bot = telebot.TeleBot("TOKEN") @bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to(message, "Howdy, how are you doing?") @bot.message_handler(func=lambda m: True) def echo_all(message): bot.reply_to(message, message.text) bot.polling() ``` -------------------------------- ### Telethon Echobot Migration Example Source: https://docs.telethon.dev/en/stable/concepts/botapi-vs-mtproto.html This is the equivalent echobot example rewritten using Telethon. ```Python from telethon import TelegramClient, events bot = TelegramClient('bot', 11111, 'a1b2c3d4').start(bot_token='TOKEN') @bot.on(events.NewMessage(pattern='/start')) async def start(event): """Send a message when the command /start is issued.""" await event.respond('Hi!') raise events.StopPropagation @bot.on(events.NewMessage) async def echo(event): """Echo the user message.""" await event.respond(event.text) def main(): """Start the bot.""" bot.run_until_disconnected() if __name__ == '__main__': main() ``` -------------------------------- ### Install Common Dependencies on apt-based Systems Source: https://docs.telethon.dev/en/stable/basic/installation.html Install essential development libraries and Telethon with optional dependencies like cryptg and pillow on Debian/Ubuntu systems. This can significantly improve performance. ```bash 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 ``` -------------------------------- ### Install or Upgrade Telethon Source: https://docs.telethon.dev/en/stable/basic/installation.html Use this command to install or upgrade Telethon to the latest stable version. Ensure pip is up-to-date first. ```bash python3 -m pip install --upgrade pip python3 -m pip install --upgrade telethon ``` -------------------------------- ### Constructing InputPeerUser in Python Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Provides an example of manually constructing an InputPeerUser object, which is often required as a parameter for API requests like sending messages. ```python from telethon.tl.types import InputPeerUser peer = InputPeerUser(user_id, user_hash) ``` -------------------------------- ### Configure Proxy for TelegramClient Source: https://docs.telethon.dev/en/stable/_sources/basic/signing-in.rst.txt Use this to connect through a proxy. Ensure 'python-socks[asyncio]' is installed. The proxy argument is a dictionary containing connection details. ```python TelegramClient('anon', api_id, api_hash, proxy=...) ``` -------------------------------- ### Entity Retrieval: get_entity vs get_input_entity Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Explains the difference between `client.get_entity()` and `client.get_input_entity()`, and how to get an input peer using `utils.get_input_peer()`. ```APIDOC ## Entity Retrieval: get_entity vs get_input_entity ### Description This section clarifies the usage of `client.get_entity()` and `client.get_input_entity()`. `client.get_input_entity()` is more direct for obtaining an entity's input version, especially if the user has been seen before or their ID is known. `client.get_entity()` retrieves complete user information and automatically casts it to its input version when used. For caching the input version, `telethon.utils.get_input_peer()` can be used. ### Method N/A (Conceptual explanation of library functions) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from telethon import utils # Using get_entity entity = await client.get_entity('someone') # Getting the input peer version peer = utils.get_input_peer(entity) ``` ### Response N/A ``` -------------------------------- ### Dumbot Subclassing Example Source: https://docs.telethon.dev/en/stable/concepts/botapi-vs-mtproto.html This snippet demonstrates how to subclass a Bot API-based bot using the 'dumbot' library. It shows basic initialization and message handling. ```python from dumbot import Bot class Subbot(Bot): async def init(self): self.me = await self.getMe() async def on_update(self, update): await self.sendMessage( chat_id=update.message.chat.id, text='i am {}'.format(self.me.username) ) Subbot(token).run() ``` -------------------------------- ### Get Specific Entities Text Example Source: https://docs.telethon.dev/en/stable/modules/custom.html Filters and retrieves text for specific types of markup entities, such as MessageEntityCode. Requires importing the desired entity type. ```python from telethon.tl.types import MessageEntityCode m = ... # get the message for _, inner_text in m.get_entities_text(MessageEntityCode): print(inner_text) ``` -------------------------------- ### Get Entities Text Example Source: https://docs.telethon.dev/en/stable/modules/custom.html Retrieves a list of markup entities and their corresponding inner text from a message. Useful for parsing formatted text like bold, italics, or code. ```python print(repr(message.text)) # shows: 'Hello **world**!' for ent, txt in message.get_entities_text(): print(ent) # shows: MessageEntityBold(offset=6, length=5) print(txt) # shows: world ``` -------------------------------- ### Example Pong Response Source: https://docs.telethon.dev/en/stable/concepts/full-api.html This is an example of the stringified Pong response structure. ```python Pong( msg_id=781875678118, ping_id=48641868471 ) ``` -------------------------------- ### Connect to Test Server with Phone and Code Callback Source: https://docs.telethon.dev/en/stable/developing/test-servers.html This example demonstrates connecting to a test server using a phone number and a lambda function for the code callback. The phone number format and the code format are specific to the data center ID. ```python client = TelegramClient(None, api_id, api_hash) client.session.set_dc(2, '149.154.167.40', 80) client.start( phone='9996621234', code_callback=lambda: '22222' ) ``` -------------------------------- ### python-telegram-bot Echobot Example Source: https://docs.telethon.dev/en/stable/concepts/botapi-vs-mtproto.html This is the original echobot example using python-telegram-bot. ```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() ``` -------------------------------- ### Initialize and Use TelegramClient Source: https://docs.telethon.dev/en/stable/modules/client.html This snippet demonstrates the basic setup for creating a TelegramClient instance and performing a simple action like sending a message to yourself. Ensure you have your api_id and api_hash. ```python from telethon import TelegramClient client = TelegramClient(name, api_id, api_hash) 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()) ``` -------------------------------- ### Initiating QR Login Source: https://docs.telethon.dev/en/stable/modules/client.html Demonstrates the initiation of the QR login procedure. The returned `QRLogin` object should be used to handle the subsequent steps of the authentication process. ```python await client.qr_login() ``` -------------------------------- ### Initialize and Use TelegramClient Source: https://docs.telethon.dev/en/stable/_sources/basic/quick-start.rst.txt Demonstrates how to initialize a TelegramClient with API credentials, authenticate, and perform basic operations within an asynchronous context. It covers getting user information, iterating through dialogs, sending messages to different recipients, and handling message replies. ```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()) ``` -------------------------------- ### Get Input Peer using Telethon Utils Source: https://docs.telethon.dev/en/stable/concepts/full-api.html Get the input peer version of an entity using telethon.utils.get_input_peer for caching. ```python from telethon import utils peer = utils.get_input_peer(entity) ``` -------------------------------- ### TelegramClient Initialization Source: https://docs.telethon.dev/en/stable/_sources/modules/client.rst.txt Demonstrates how to initialize and use the TelegramClient to send messages. ```APIDOC ## TelegramClient Initialization ### Description This section shows the basic setup for creating a `TelegramClient` instance and performing a simple action, like sending a message. ### Method Initialization and asynchronous execution ### Endpoint N/A (Client-side library) ### Parameters - **name** (string) - Required - The name of the session file to use. - **api_id** (integer) - Required - Your Telegram API ID. - **api_hash** (string) - Required - Your Telegram API Hash. ### Request Example ```python from telethon import TelegramClient client = TelegramClient(name, api_id, api_hash) async def main(): await client.send_message('me', 'Hello to myself!') with client: client.loop.run_until_complete(main()) ``` ### Response #### Success Response (200) N/A (Client-side operation) #### Response Example N/A ``` -------------------------------- ### Install Development Version of Telethon Source: https://docs.telethon.dev/en/stable/basic/installation.html Install the latest unreleased changes from the development branch. This version may contain bugs and is not recommended for production. ```bash python3 -m pip install --upgrade https://codeberg.org/Lonami/Telethon/archive/v1.zip ``` -------------------------------- ### Python Asyncio Task Creation and Execution Source: https://docs.telethon.dev/en/stable/_sources/concepts/asyncio.rst.txt Demonstrates how to create and run asynchronous tasks using Python's asyncio library. It shows how to schedule tasks, manage their execution, and wait for them to complete. ```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 ``` -------------------------------- ### Using TelegramClient Action Context Manager Source: https://docs.telethon.dev/en/stable/modules/client.html Demonstrates how to use the client.action context manager to show user activity like typing or uploading. It also shows how to cancel a pending action. ```python async with client.action(chat, 'typing'): await asyncio.sleep(2) await client.send_message(chat, 'Hello world! I type slow ^^') # Cancel any previous action await client.action(chat, 'cancel') # Upload a document, showing its progress (most clients ignore this) async with client.action(chat, 'document') as action: await client.send_file(chat, zip_file, progress_callback=action.progress) ``` -------------------------------- ### Get Telethon Input Entity Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Obtains the input entity version, which is often more immediate if the user is known. This is a more direct way to get an entity for use in requests. The library can automatically call this when required. ```python entity = await client.get_input_entity('username') result = await client(SendMessageRequest(entity, 'Hello there!')) ``` -------------------------------- ### Concise Task Management in Asyncio Source: https://docs.telethon.dev/en/stable/concepts/asyncio.html A cleaner version of the concurrent task management example, removing comments for brevity. It demonstrates creating tasks and allowing the asyncio event loop to manage their execution. ```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 ``` -------------------------------- ### Initialize TelegramClient with HTTP Connection Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt Demonstrates how to initialize a `TelegramClient` using the `ConnectionHttp` mode, which 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!') ``` -------------------------------- ### Get Entity ID Source: https://docs.telethon.dev/en/stable/modules/client.html Obtain the integer ID for a given entity. Use add_mark=False to get a positive ID. This method is asynchronous to support various entity formats like usernames and phone numbers. ```python print(await client.get_peer_id('me')) ``` -------------------------------- ### telethon.utils.get_extension Source: https://docs.telethon.dev/en/stable/modules/utils.html Gets the corresponding extension for any Telegram media. ```APIDOC ## telethon.utils.get_extension ### Description Determines the file extension for a given Telegram media object. ### Parameters * **_media_** - The Telegram media object. ### Returns The file extension string. ``` -------------------------------- ### Sign Up with Integer Codes Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt The `.sign_up` method now accepts `int` codes. This provides more flexibility when handling sign-up verification codes. ```python client.sign_up(code=12345) ``` -------------------------------- ### retry_range Source: https://docs.telethon.dev/en/stable/modules/helpers.html Generates a sequence of retry attempts, starting from 1. ```APIDOC ## Function: retry_range ### Description Generates an integer sequence starting from 1. If `retries` is not a zero or a positive integer value, the sequence will be infinite, otherwise it will end at `retries + 1`. ### Parameters - `retries` (int) - The maximum number of retries. - `force_retry` (boolean) - Optional. If `True`, the sequence starts from 1 even if `retries` is 0. Defaults to `True`. ``` -------------------------------- ### Start takeout sessions with client.takeout() Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt Enables the creation of takeout sessions (data export sessions) using the client.takeout() method. This can result in lower flood limits for certain requests. ```python await client.takeout(email='your_email@example.com', file_path='export_data.zip') ``` -------------------------------- ### SendMessageRequest Example Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Illustrates sending a message to a peer using SendMessageRequest. ```APIDOC ## POST /api/messages/send ### Description Sends a message to a specified peer. ### Method POST ### Endpoint /api/messages/send ### Parameters #### Request Body - **peer** (InputPeer) - Required - The peer to send the message to (e.g., InputPeerUser, InputPeerChat). - **message** (string) - 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!", "date": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Automated Reply to New Messages Source: https://docs.telethon.dev/en/stable/basic/updates.html This example demonstrates how to set up an event handler for new messages. If a message contains 'hello', the client will reply with 'hi!'. 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() ``` -------------------------------- ### Instantiate and Use TelegramClient in Python Source: https://docs.telethon.dev/en/stable/_sources/modules/client.rst.txt Demonstrates how to create an instance of TelegramClient, define an asynchronous main function to interact with the client, and run the event loop. This is the fundamental setup for any Telethon application. ```python from telethon import TelegramClient client = TelegramClient(name, api_id, api_hash) 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()) ``` -------------------------------- ### Get All Dialogs Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt Retrieve all dialogs by setting the limit parameter to None in .get_dialogs(). ```python limit=None ``` -------------------------------- ### Initialize TelegramClient with Proxy Source: https://docs.telethon.dev/en/stable/basic/signing-in.html Initialize a TelegramClient to connect through a proxy. Ensure you have 'python-socks[asyncio]' installed. The proxy argument should be a dictionary containing proxy details. ```python TelegramClient('anon', api_id, api_hash, proxy=...) ``` ```python proxy = { 'proxy_type': 'socks5', # (mandatory) protocol to use (see above) 'addr': '1.1.1.1', # (mandatory) proxy IP address 'port': 5555, # (mandatory) proxy port number 'username': 'foo', # (optional) username if the proxy requires auth 'password': 'bar', # (optional) password if the proxy requires auth 'rdns': True # (optional) whether to use remote or local resolve, default remote } ``` -------------------------------- ### Get Running Asyncio Loop Source: https://docs.telethon.dev/en/stable/modules/helpers.html Retrieves the currently running asyncio event loop. ```python telethon.helpers.get_running_loop() ``` -------------------------------- ### GET /dialogs Source: https://docs.telethon.dev/en/stable/_sources/quick-references/objects-reference.rst.txt Iterates through user dialogs and provides methods for management such as archiving or deleting. ```APIDOC ## GET /dialogs ### Description Retrieves a list of dialogs and provides actions to interact with them. ### Method GET ### Endpoint client.iter_dialogs() ### Response #### Success Response (200) - **Dialog** (object) - An object containing methods like send_message, archive, and delete. #### Response Example { "dialog_id": 123456, "name": "Chat Name" } ``` -------------------------------- ### sign_up Source: https://docs.telethon.dev/en/stable/modules/client.html This method is deprecated and will raise a ValueError. It is no longer possible to sign up new users directly through this method. ```APIDOC ## async sign_up(code: str | int, first_name: str, last_name: str = '', *, phone: str = None, phone_code_hash: str = None) ### Description This method can no longer be used, and will immediately raise a `ValueError`. See issue #4050 for context. ### Method `async` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **code** (`str` | `int`): The confirmation code. - **first_name** (`str`): The user's first name. - **last_name** (`str`, optional): The user's last name. - **phone** (`str`, optional): The phone number associated with the account. - **phone_code_hash** (`str`, optional): The hash returned by `send_code_request`. ### Returns - `types.User` ### Example This method is deprecated and should not be used. ``` -------------------------------- ### Importing and Invoking PingRequest in Python Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Demonstrates how to import the PingRequest, construct an instance with a ping ID, and invoke it using a Telethon client. It also shows how to print the stringified response. ```python from telethon.tl.functions import PingRequest response = await client(PingRequest( ping_id=48641868471 )) ``` -------------------------------- ### telethon.utils.get_attributes Source: https://docs.telethon.dev/en/stable/modules/utils.html Get a list of attributes for the given file and the mime type as a tuple ([attribute], mime_type). ```APIDOC ## telethon.utils.get_attributes ### Description Determines the attributes and MIME type for a given file. ### Parameters * **_file_** - The file path or object. * **_attributes** - Optional list of attributes to apply. * **_mime_type_** - Optional MIME type. * **_force_document_** - Whether to force the media as a document. * **_voice_note_** - Whether the media is a voice note. * **_video_note_** - Whether the media is a video note. * **_supports_streaming_** - Whether the media supports streaming. * **_thumb_** - Optional thumbnail data. ### Returns A tuple containing a list of attributes and the determined MIME type. ``` -------------------------------- ### Send Voice Notes or Round Videos Source: https://docs.telethon.dev/en/stable/modules/client.html Shows how to send audio files as voice notes and video files as round videos using the respective boolean flags. ```python await client.send_file(chat, '/my/songs/song.mp3', voice_note=True) await client.send_file(chat, '/my/videos/video.mp4', video_note=True) ``` -------------------------------- ### Bot Token and Password Handling Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt The `bot_token` parameter would not work on `.start()`. Changes to `password` now ensure it will ask for the password if not provided, as hinted by the docstring. ```python client.start(bot_token='YOUR_BOT_TOKEN') ``` ```python client.start(password='YOUR_PASSWORD') ``` -------------------------------- ### GET /drafts Source: https://docs.telethon.dev/en/stable/_sources/quick-references/objects-reference.rst.txt Manages message drafts for specific entities, allowing retrieval, modification, and deletion. ```APIDOC ## GET /drafts ### Description Retrieves drafts associated with entities and provides methods to manipulate them. ### Method GET ### Endpoint client.iter_drafts() ### Response #### Success Response (200) - **Draft** (object) - Contains properties like text, raw_text and methods like set_message, send, delete. #### Response Example { "entity": "user_id", "text": "Draft content" } ``` -------------------------------- ### Get Full User Information Source: https://docs.telethon.dev/en/stable/_sources/examples/users.rst.txt Retrieves the complete user information, including bio and biography. ```APIDOC ## GET /api/users/full ### Description Retrieves the full user information, including their bio, biography, and other details. ### Method GET ### Endpoint /api/users/full ### Parameters #### Query Parameters - **user** (string | int) - Required - The username or user ID of the user to retrieve information for. ### Response #### Success Response (200) - **full_user** (object) - Contains the full user object with detailed information. - **about** (string) - The user's biography or about information. #### Response Example ```json { "full_user": { "about": "This is the user's biography." } } ``` ``` -------------------------------- ### Chaining .start() with 'with' block for TelegramClient Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt Chain the .start() method when using TelegramClient in a 'with' block. This allows for immediate client configuration, such as providing a bot token, before the block is entered. ```python with TelegramClient(name, api_id, api_hash).start(bot_token=token) as bot: bot.send_message(chat, 'Hello!') ``` -------------------------------- ### Answering Inline Query Results Source: https://docs.telethon.dev/en/stable/modules/events.html This example shows how to answer an inline query with a list of results, using the `builder` to create different types of inline results like articles. It demonstrates creating two distinct article results. ```python builder = inline.builder r1 = builder.article('Be nice', text='Have a nice day') r2 = builder.article('Be bad', text="I don't like you") await inline.answer([r1, r2]) ``` -------------------------------- ### Iterate Through Photos List Source: https://docs.telethon.dev/en/stable/_sources/quick-references/faq.rst.txt This example demonstrates how to loop through a list of photo objects returned by a Telethon request. ```python for photo in result.photos: # Process each photo object ``` -------------------------------- ### Running Asyncio Main Function Source: https://docs.telethon.dev/en/stable/_sources/misc/compatibility-and-convenience.rst.txt Shows the standard way to run an asynchronous main function using asyncio.run(). This is essential for starting and managing asyncio applications. ```python import asyncio async def main(): # Your asynchronous code here print('Running main async function') await asyncio.sleep(1) print('Main async function finished') if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### download_media Source: https://docs.telethon.dev/en/stable/modules/client.html Downloads the given media from a message object. Note that if the download is too slow, you should consider installing `cryptg`. ```APIDOC ## download_media ### Description Downloads the given media from a message object. Note that if the download is too slow, you should consider installing `cryptg`. ### Parameters #### Path Parameters - **message** (Message | Media): The media or message containing the media that will be downloaded. #### Query Parameters - **file** (str | file, optional): The output file path, directory, or stream-like object. If the path exists and is a file, it will be overwritten. If file is the type `bytes`, it will be downloaded in-memory and returned as a bytestring. - **thumb** (Union[int, types.TypePhotoSize], optional): Use this to download thumbnails instead of the full media. - **progress_callback** (hints.ProgressCallback, optional): A callback function accepting two parameters: `(received bytes, total)`. ### Returns str | bytes | None ``` -------------------------------- ### Configure Update Workers Source: https://docs.telethon.dev/en/stable/_sources/misc/changelog.rst.txt Set the number of worker threads for processing updates. Recommended to start with 4. ```python update_workers=4 ``` -------------------------------- ### Creating a Pong Object in Python Source: https://docs.telethon.dev/en/stable/_sources/concepts/full-api.rst.txt Shows how to manually create an instance of the Pong object, which is a typical response type, by providing its members as input parameters. ```python from telethon.tl.types import Pong my_pong = Pong( msg_id=781875678118, ping_id=48641868471 ) ``` -------------------------------- ### telethon.utils.get_display_name Source: https://docs.telethon.dev/en/stable/modules/utils.html Gets the display name for the given User, Chat or Channel. Returns an empty string otherwise. ```APIDOC ## telethon.utils.get_display_name ### Description Retrieves the display name for a Telegram entity (User, Chat, or Channel). ### Parameters * **_entity_** - The User, Chat, or Channel object. ### Returns The display name of the entity, or an empty string if not applicable. ```