### Downloading and Running Telethon Examples Source: https://github.com/hikariatama/hikka-tl/blob/v1/telethon_examples/README.md This snippet provides the shell commands necessary to clone the Telethon repository from GitHub, navigate into the examples directory, and execute the GUI example script using Python 3. It assumes Git and Python 3 are installed and accessible from the terminal. ```Shell git clone https://github.com/LonamiWebs/Telethon.git cd Telethon cd telethon_examples python3 gui.py ``` -------------------------------- ### Installing Apt System Dependencies and Optional Libraries (sh) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/installation.rst This sequence provides commands for installing necessary system libraries on Debian/Ubuntu-based systems, which are often prerequisites for compiling Python packages like cryptg and pillow. It updates package lists, installs essential development packages, upgrades setuptools, and then installs Telethon, cryptg, and pillow using pip with the --user flag. ```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 ``` -------------------------------- ### Verifying Telethon Installation (sh) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/installation.rst This command executes a simple Python script directly from the shell that attempts to import the Telethon library and print its installed version number. Successful execution confirms that the library is installed correctly and accessible in the Python environment. ```sh python3 -c "import telethon; print(telethon.__version__)" ``` -------------------------------- ### Installing Development Telethon Version (sh) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/installation.rst This command installs the development version of the Telethon library directly from its GitHub repository's latest commit. Use this if you need the newest features or bug fixes before a release, but be aware it may be less stable than official releases and is not recommended for production use. ```sh python3 -m pip install --upgrade https://github.com/LonamiWebs/Telethon/archive/v1.zip ``` -------------------------------- ### Installing Telethon Library (Shell) Source: https://github.com/hikariatama/hikka-tl/blob/v1/README.rst Provides the standard command-line instruction to install the Telethon library using pip, the Python package installer. This is the first step required before using the library in Python scripts. ```sh pip3 install telethon ``` -------------------------------- ### Installing Standard Telethon Library (sh) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/installation.rst This command sequence upgrades the pip package installer to its latest version and then installs or upgrades the Telethon Python library to the latest stable release. It's the recommended method for general users to obtain the library. ```sh python3 -m pip install --upgrade pip python3 -m pip install --upgrade telethon ``` -------------------------------- ### Initializing Client and Performing Basic Operations with Telethon Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/quick-start.rst This snippet demonstrates how to initialize a Telethon client using API ID and hash, retrieve user information, iterate through dialogues and messages, send various types of messages (to users, groups, contacts, usernames, with markdown), send files, and download media attached to messages. It utilizes asynchronous functions (`async def`) and runs the main async routine. ```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()) ``` -------------------------------- ### Creating and Starting Telethon Client (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/README.rst Demonstrates how to initialize and start a connection with Telegram using the Telethon client. It requires importing the necessary class, providing valid API credentials obtained from Telegram's developer portal, and starting the client to establish the connection. ```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() ``` -------------------------------- ### Configuring TelegramClient with Standard Proxy (Dict) - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst Provides an example of configuring `TelegramClient` to use a standard proxy by passing proxy details as a dictionary to the `proxy` parameter. This is the recommended format for modern Python versions. It outlines the mandatory and optional dictionary keys like `proxy_type`, `addr`, `port`, `username`, `password`, and `rdns`. Requires the appropriate proxy library installed. ```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 } ``` -------------------------------- ### Using TelegramClient with context manager and start chaining (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/changelog.rst Illustrates using the TelegramClient as a context manager and chaining the `.start()` method directly after instantiation. This allows passing authentication parameters like `bot_token` during the client's setup within the 'with' statement, which then returns the client instance for use inside the block. The context manager still handles disconnection. ```python with TelegramClient(name, api_id, api_hash).start(bot_token=token) as bot: bot.send_message(chat, 'Hello!') ``` -------------------------------- ### Handling New Messages and Replying - Telethon Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/updates.rst This basic example demonstrates how to initialize a Telethon client, register an event handler for new messages, check the message content for a specific string, and reply to the message if the condition is met. The script then starts the client and runs until disconnected. ```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() ``` -------------------------------- ### Initializing TelegramClient for User Account - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst Demonstrates how to initialize the `TelegramClient` for a user account using API ID and hash. It utilizes a `with` block for automatic connection management and shows a basic message sending example using `run_until_complete` due to the asynchronous nature of Telethon. Requires the Telethon library and valid API credentials. ```python from telethon import TelegramClient # Use your own values from my.telegram.org api_id = 12345 api_hash = '0123456789abcdef0123456789abcdef' # The first parameter is the .session file name (absolute paths allowed) with TelegramClient('anon', api_id, api_hash) as client: client.loop.run_until_complete(client.send_message('me', 'Hello, myself!')) ``` -------------------------------- ### Structuring Asynchronous Telethon Code in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/quick-start.rst This snippet illustrates the recommended structure for writing asynchronous code with Telethon. It shows how to define an asynchronous main function (`async def main`), potentially call other asynchronous functions (`async def do_something`) within it, and execute the main function using the client's event loop (`client.loop.run_until_complete`). This structure is fundamental for handling asynchronous operations required by Telethon. ```Python client = ... async def do_something(me): ... async def main(): # Most of your code should go here. # You can of course make and use your own async def (do_something). # They only need to be async if they need to await things. me = await client.get_me() await do_something(me) with client: client.loop.run_until_complete(main()) ``` -------------------------------- ### Initializing TelegramClient for Bot Account - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst Shows how to initialize `TelegramClient` specifically for a bot account. It requires an API ID, API hash, and a bot token. Unlike user accounts using a `with` block for implicit login, the `start()` method is called explicitly with the `bot_token` parameter to authenticate as a bot. Requires the Telethon library and bot credentials. ```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: ... ``` -------------------------------- ### Concise Concurrent Tasks Example with asyncio in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/asyncio.rst This snippet provides a streamlined version of the previous example, demonstrating how to run concurrent coroutines as tasks using `asyncio.create_task`. It showcases the core pattern of creating tasks and using `await asyncio.sleep` to yield control, allowing the event loop to manage concurrent 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 ``` -------------------------------- ### Performing Common Telethon Operations (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/README.rst Showcases various basic functionalities available with a connected Telethon client. Examples include fetching user information, sending text messages and files, downloading profile photos, retrieving messages, and setting up an event handler for incoming messages. ```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!') ``` -------------------------------- ### Configuring TelegramClient with Standard Proxy (Tuple) - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst Illustrates how to add standard proxy configuration when initializing `TelegramClient` by passing proxy details (type, address, port) as a tuple to the `proxy` parameter. This format is supported for backwards compatibility but the dictionary format is preferred. Requires either `python-socks[asyncio]` (Python >= 3.6) or `PySocks` (Python <= 3.5) library installed. ```python TelegramClient('anon', api_id, api_hash, proxy=("socks5", '127.0.0.1', 4444)) ``` -------------------------------- ### Configuring TelegramClient with MTProto Proxy (Concise) - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst A more concise example showing the essential parameters for configuring `TelegramClient` to use an MTProto proxy. It highlights setting the `connection` parameter to an MTProto type and providing the proxy details (host, port, secret) as a tuple to the `proxy` parameter, stripping away comments for clarity. Requires the Telethon library and MTProto proxy details. ```python from telethon import TelegramClient, connection client = TelegramClient( 'anon', api_id, api_hash, connection=connection.ConnectionTcpMTProxyRandomizedIntermediate, proxy=('mtproxy.example.com', 2002, 'secret') ) ``` -------------------------------- ### Configuring TelegramClient with Standard Proxy (Discouraged Tuple) - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst Shows the discouraged tuple format for defining standard proxy parameters, provided for backwards compatibility with `PySocks`. It includes details like proxy type, address, port, remote DNS flag, username, and password. The dictionary format is recommended instead. Requires the appropriate proxy library installed. ```python proxy = (socks.SOCKS5, '1.1.1.1', 5555, True, 'foo', 'bar') ``` -------------------------------- ### Handling Messages and Sending Photos with aiogram Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This snippet shows an aiogram bot example with handlers for the /start command, a regex pattern (`cat[s]?|puss`), and a catch-all for other messages. It demonstrates replying to text messages using `message.reply` and sending a photo with a caption using the `bot.send_photo` method. It requires the `aiogram` library and a bot token. ```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)') async 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() async def echo(message: types.Message): await bot.send_message(message.chat.id, message.text) if __name__ == '__main__': executor.start_polling(dp, skip_updates=True) ``` -------------------------------- ### Connecting and Logging In to Test Server Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/developing/test-servers.rst Initializes a Telethon client, sets the data center to a specific test DC (DC 2 in this case), and starts the client using a test phone number format (99966XYYYY) and a hardcoded code callback (repeating the DC ID five times). Requires the Telethon library and API credentials. ```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' ) ``` -------------------------------- ### Retrieving Entities using Telethon client.get_entity Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/entities.rst Illustrates various ways to retrieve entities using the `client.get_entity()` asynchronous method. It shows examples using usernames, t.me/telegram.dog links, chat/invite links, phone numbers (if in contacts), integer IDs, and explicitly specifying the entity type using Peer objects (`PeerUser`, `PeerChat`, `PeerChannel`). It also includes an example of `client.get_dialogs()` which populates the entity cache. ```python # (These examples assume you are inside an "async def") # # Dialogs are the "conversations you have open". # This method returns a list of Dialog, which # has the .entity attribute and other information. # # This part is IMPORTANT, because it fills the entity cache. dialogs = await client.get_dialogs() # 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') # Other kind of entities. channel = await client.get_entity('telegram.me/joinchat/AAAAAEkk2WdoDrB4-Q8-gg') contact = await client.get_entity('+34xxxxxxxxx') friend = await client.get_entity(friend_id) # Getting entities through their ID (User, Chat or Channel) entity = await client.get_entity(some_id) # You can be more explicit about the type for said ID by wrapping # it inside a Peer instance. This is recommended but not necessary. from telethon.tl.types import PeerUser, PeerChat, PeerChannel my_user = await client.get_entity(PeerUser(some_id)) my_chat = await client.get_entity(PeerChat(some_id)) my_channel = await client.get_entity(PeerChannel(some_id)) ``` -------------------------------- ### Manually Handling FloodWaitError with Custom Action (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/errors.rst Provides an example of explicitly catching `FloodWaitError` using `try...except` to perform a custom action, such as printing the wait time and terminating the program, rather than relying on Telethon's auto-sleep or simply letting the exception propagate. ```python from telethon.errors import FloodWaitError try: ... except FloodWaitError as e: print('Flood waited for', e.seconds) quit(1) ``` -------------------------------- ### Basic Telegram Interaction with Telethon Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/index.rst This snippet demonstrates fundamental Telegram interactions using the Telethon library. It covers connecting to the client, sending a message, downloading a profile photo, and setting up an event listener for new messages matching a pattern. It requires the Telethon library installed and valid API credentials (`api_id`, `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() ``` -------------------------------- ### Handling Messages and Sending Files with Telethon Python (aiogram Migration) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This snippet presents the Telethon equivalent of the aiogram example. It uses Telethon event decorators with pattern matching for the /start command and the 'cats' regex, along with a catch-all handler. It demonstrates replying to text messages and sending files more concisely using `event.reply` with the `file` parameter. It requires the `telethon` library, API ID, API hash, and a bot token. ```python from telethon import TelegramClient, events # Initialize bot and... just the bot! bot = TelegramClient('bot', 11111, 'a1b2c3d4').start(bot_token='TOKEN') @bot.on(events.NewMessage(pattern='/start')) async def send_welcome(event): await event.reply('Howdy, how are you doing?') @bot.on(events.NewMessage(pattern='(^cat[s]?$|puss)')) async def cats(event): await event.reply('Cats is here 🐱', file='data/cats.jpg') @bot.on(events.NewMessage) async def echo_all(event): await event.reply(event.text) if __name__ == '__main__': bot.run_until_disconnected() ``` -------------------------------- ### Using a Saved Telethon StringSession | Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/sessions.rst This snippet demonstrates how to initialize a `TelegramClient` by directly passing a saved `StringSession` string to the `StringSession()` constructor. This allows the client to log in instantly using the stored authorization key without requiring the phone number and code verification steps. It requires a valid session string, `api_id`, and `api_hash`. The example then sends a message using the client. ```Python string = '1aaNk8EX-YRfwoRsebUkugFvht6DUPi_Q25UOCzOAqzc...'\nwith TelegramClient(StringSession(string), api_id, api_hash) as client:\n client.loop.run_until_complete(client.send_message('me', 'Hi')) ``` -------------------------------- ### Handling TakeoutInitDelayError in Telethon (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/errors.rst Demonstrates how to catch the `TakeoutInitDelayError` which occurs when a takeout operation is attempted too soon. The required wait time is accessible via the `.seconds` attribute of the exception object. ```python from telethon import errors try: async with client.takeout() as takeout: ... except errors.TakeoutInitDelayError as e: # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ here we except TAKEOUT_INIT_DELAY print('Must wait', e.seconds, 'before takeout') ``` -------------------------------- ### Invoking SendMessageRequest with InputPeer Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/full-api.rst Shows how to invoke a raw API request, `SendMessageRequest`, by passing the request object instance to the client using the awaitable call `await client(request_object)`. This example uses a previously obtained `peer` object as one of the request parameters. ```python result = await client(SendMessageRequest(peer, 'Hello there!')) ``` -------------------------------- ### Handling Messages with Telethon Python (pyTelegramBotAPI Migration) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This snippet provides the Telethon version of the pyTelegramBotAPI echobot example. It uses Telethon's event decorators to register handlers for new messages and the /start command pattern, using the convenient `event.reply` method to respond. It requires the `telethon` library, API ID, API hash, and a bot token. ```python from telethon import TelegramClient, events bot = TelegramClient('bot', 11111, 'a1b2c3d4').start(bot_token='TOKEN') @bot.on(events.NewMessage(pattern='/start')) async def send_welcome(event): await event.reply('Howdy, how are you doing?') @bot.on(events.NewMessage) async def echo_all(event): await event.reply(event.text) bot.run_until_disconnected() ``` -------------------------------- ### Importing Telethon Errors in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/errors.rst This snippet shows the standard way to import the `errors` module from the `telethon` library, which contains the definitions for various RPC error classes that can be caught during API interactions. ```python from telethon import errors ``` -------------------------------- ### Updating Profile Photo Telethon Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/examples/users.rst This example shows how to set a new profile picture for the current user. It first uploads a file using client.upload_file and then uses the returned file object with UploadProfilePhotoRequest to set it as the profile photo. Requires an authenticated Telethon client and the path to the image file. ```python from telethon.tl.functions.photos import UploadProfilePhotoRequest await client(UploadProfilePhotoRequest( await client.upload_file('/path/to/some/file') )) ``` -------------------------------- ### Subclassing Bot and Handling Updates with dumbot Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This snippet shows a dumbot example using class inheritance. It defines a `Subbot` class that subclasses `Bot`, overrides the `init` method to fetch bot information (`self.me`), and the `on_update` method to handle incoming messages and reply with the bot's username. It requires the `dumbot` library and a bot token. ```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() ``` -------------------------------- ### Structuring Pytest Tests (Sync and Async) in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/developing/testing.rst This snippet shows examples of typical Pytest test functions in Python, covering both synchronous and asynchronous (`asyncio`) scenarios. It demonstrates importing functions to test, defining test functions (`test_*`), using fixtures (`fixture`, `event_loop`), asserting conditions, and applying the `pytest.mark.asyncio` decorator for async tests. ```python from module import my_thing, my_other_thing def test_my_thing(fixture): assert my_thing(fixture) == 42 @pytest.mark.asyncio async def test_my_thing(event_loop): assert await my_other_thing(loop=event_loop) == 42 ``` -------------------------------- ### Getting InputPeer using get_input_entity Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/full-api.rst Shows how to use the high-level `client.get_input_entity` method to retrieve the raw `InputPeer` object for a given entity represented by a string (username, phone, ID). This is the recommended and often more straightforward way to obtain the necessary input peer for raw API calls. ```python import telethon async def main(): peer = await client.get_input_entity('someone') client.loop.run_until_complete(main()) ``` -------------------------------- ### Calling a Raw Telethon API Function in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/quick-references/faq.rst Shows how to call a raw Telegram API function directly using the client object, passing the appropriate request object from `telethon.tl.functions`. The example calls `photos.GetUserPhotosRequest` to fetch user photos, demonstrating how to structure API calls that might require specific function objects. ```python result = await client(functions.photos.GetUserPhotosRequest( user_id='me', offset=0, max_id=0, limit=100 )) ``` -------------------------------- ### Sending Multiple Requests Ordered - Telethon - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/changelog.rst This example illustrates sending a list of `SendMessageRequest` objects using the client instance as a callable, combined with `ordered=True`. This allows executing multiple API calls in the specified order. Requires an active `TelegramClient` and the relevant request objects like `SendMessageRequest`. ```python from telethon.tl.functions.messages import SendMessageRequest client([SendMessageRequest(chat, 'Hello 1!'), SendMessageRequest(chat, 'Hello 2!')], ordered=True) ``` -------------------------------- ### Accessing Nested List Elements and Attributes in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/quick-references/faq.rst Demonstrates accessing data within complex, nested structures often returned by API calls. The example shows how to navigate through lists and objects (`result.photos[0].sizes[-1].type`) using indexing (`[0]`, `[-1]`) and the dot operator (`.`) to reach a specific attribute. ```python # Working with list is also pretty basic print(result.photos[0].sizes[-1].type) # ^ ^ ^ ^ ^ # | | | | \ type # | | | \ last size # | | \ list of sizes # access | \ first photo from the list # the... \ list of photos ``` -------------------------------- ### Accessing Migrated Channel Entity (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/chats-vs-channels.rst Illustrates how to retrieve the `Channel` entity that a `Chat` (small group) has been migrated to. By accessing the `migrated_to` property of the original `Chat` object, you get the new entity's ID or peer, which can then be used with `client.get_entity` to fetch the full `Channel` object. ```python # Assuming 'client' is an active Telethon client instance # and 'chat' is a Chat object that has been migrated # channel = await client.get_entity(chat.migrated_to) # channel is now a Channel ``` -------------------------------- ### Using Await for Asynchronous Methods in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/quick-references/faq.rst Illustrates the correct way to call an asynchronous method (`client.get_me()`) from within an asynchronous function (`async def handler`). The `await` keyword is essential for resolving the coroutine object and getting the actual result, addressing the "AttributeError: 'coroutine' object..." error. ```python async def handler(event): me = await client.get_me() # ^^^^^ note the await print(me.username) ``` -------------------------------- ### Specifying Telethon Dependency Version in Requirements.txt Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/changelog.rst Demonstrates the usage of the `~=` operator in a requirements file or pip command to specify a compatible version range for the `telethon` library. This ensures that pip installs any version within the `1.16` series, allowing patch releases but preventing major or minor version upgrades that might introduce breaking changes. ```text telethon~=1.16.0 ``` -------------------------------- ### Getting Full Entity using get_entity Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/full-api.rst Demonstrates using the high-level `client.get_entity` method to retrieve the complete entity object (User, Chat, Channel). While this returns a full object, not strictly an InputPeer, the library can automatically cast it to its input version when needed by raw API calls, or it can be manually converted using `telethon.utils.get_input_peer`. ```python entity = await client.get_entity('someone') ``` -------------------------------- ### Resolving Telegram Entities (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/entities.rst Provides multiple examples using the Telethon client to obtain entity objects (like users, groups, etc.) via various methods such as username, dialogs, participants lists, or messages. This is necessary to make the library 'see' the entity before its integer ID can be used reliably in subsequent operations. Requires an active Telethon client instance within an asynchronous context. ```python # (These examples assume you are inside an "async def") async with client: # Does it have a username? Use it! entity = await client.get_entity(username) # Do you have a conversation open with them? Get dialogs. await client.get_dialogs() # Are they participant of some group? Get them. await client.get_participants('username') # Is the entity the original sender of a forwarded message? Get it. await client.get_messages('username', 100) # NOW you can use the ID, anywhere! await client.send_message(123456, 'Hi!') entity = await client.get_entity(123456) print(entity) ``` -------------------------------- ### Initializing TelegramClient and Sending Message - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/modules/client.rst Demonstrates how to import and instantiate the `TelegramClient` using a session name, API ID, and API hash. It shows a basic asynchronous function `main` that sends a message and how to run this function using the client's context manager and event loop. ```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()) ``` -------------------------------- ### Handling Messages with python-telegram-bot Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This snippet shows a basic echobot implementation using the python-telegram-bot library. It sets up handlers for the /start command and all text messages, echoing the message back to the user. It requires the `python-telegram-bot` library and a bot token for initialization and polling. ```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() ``` -------------------------------- ### Disabling Telethon Flood Auto-Sleep (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/errors.rst Shows how to disable Telethon's default behavior of automatically sleeping when a `FloodWaitError` occurs. Setting the `flood_sleep_threshold` client attribute to 0 means the error will be raised immediately. ```python client.flood_sleep_threshold = 0 # Don't auto-sleep ``` -------------------------------- ### Handling FloodWaitError with Sleep in Telethon (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/errors.rst Illustrates how to catch `FloodWaitError`, which signifies that the request was repeated too frequently. The snippet accesses the required wait time using the `.seconds` attribute and pauses execution using `time.sleep` for that duration. ```python ... from telethon import errors import time try: messages = await client.get_messages(chat) print(messages[0].text) except errors.FloodWaitError as e: print('Have to sleep', e.seconds, 'seconds') time.sleep(e.seconds) ``` -------------------------------- ### Configuring TelegramClient with MTProto Proxy - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/signing-in.rst Demonstrates initializing `TelegramClient` to connect via an MTProto proxy. This requires explicitly setting the `connection` parameter to an MTProto connection type (like `ConnectionTcpMTProxyRandomizedIntermediate`) and passing the proxy details (host, port, secret) as a tuple to the `proxy` parameter. Requires the Telethon library and MTProto proxy details. ```python from telethon import TelegramClient, connection # we need to change the connection ^^^^^^^^^^ client = TelegramClient( 'anon', api_id, api_hash, # Use one of the available connection modes. # Normally, this one works with most proxies. connection=connection.ConnectionTcpMTProxyRandomizedIntermediate, # Then, pass the proxy details as a tuple: # (host name, port, proxy secret) # # If the proxy has no secret, the secret must be: # '00000000000000000000000000000000' proxy=('mtproxy.example.com', 2002, 'secret') ) ``` -------------------------------- ### Enabling Telethon Flood Auto-Sleep Always (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/errors.rst Demonstrates setting the `flood_sleep_threshold` client attribute to a large value (e.g., 24 hours). This configures Telethon to automatically sleep for almost any encountered `FloodWaitError`, letting the library handle the waiting. ```python client.flood_sleep_threshold = 24 * 60 * 60 # Sleep always ``` -------------------------------- ### Initializing Telethon Client for Test Server Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/developing/test-servers.rst Initializes a Telethon client with a new session (by passing None) and explicitly sets the data center to a test server IP and port. Requires the Telethon library and API credentials (api_id, api_hash). ```python client = TelegramClient(None, api_id, api_hash) client.session.set_dc(dc_id, '149.154.167.40', 80) ``` -------------------------------- ### Handling Emoji for Telethon Reaction Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/examples/working-with-messages.rst This snippet illustrates different valid ways to provide the emoji string needed for the `SendReactionRequest` in Telethon. It shows using the `emoji` library to get the emoji string, using the direct emoji character, and using its unicode escape sequence. ```python # All of these work exactly the same (you only need one): import emoji reaction = emoji.emojize(':red_heart:') reaction = '❤️' reaction = '\u2764' from telethon.tl.functions.messages import SendReactionRequest await client(SendReactionRequest( peer=chat, msg_id=42, reaction=reaction )) ``` -------------------------------- ### Handling Messages with pyTelegramBotAPI Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/botapi-vs-mtproto.rst This snippet demonstrates a simple echobot using the pyTelegramBotAPI library. It defines handlers using decorators for the /start command and all messages, replying to the user. It requires the `pyTelegramBotAPI` library and a bot token for initialization and polling. ```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() ``` -------------------------------- ### Updating Profile Name and Bio Telethon Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/examples/users.rst This example demonstrates how to modify the first name, last name, or 'about' (bio) section of the current user's profile using the UpdateProfileRequest. Any fields omitted in the request will remain unchanged. It requires an authenticated Telethon client. ```python from telethon.tl.functions.account import UpdateProfileRequest await client(UpdateProfileRequest( about='This is a test from Telethon' )) ``` -------------------------------- ### Initializing Telethon Client - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/basic/updates.rst This snippet shows the standard way to import the necessary classes from Telethon and create an instance of the TelegramClient, which is required to connect to the Telegram servers and interact with the API. Replace 'anon', api_id, and api_hash with your specific session name, API ID, and API hash. ```Python from telethon import TelegramClient, events client = TelegramClient('anon', api_id, api_hash) ``` -------------------------------- ### Using TelegramClient with context manager (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/changelog.rst Demonstrates how to use the TelegramClient within a Python 'with' block. This pattern automatically handles connecting the client when entering the block (calling `client.start()`) and disconnecting it when exiting the block (calling `client.disconnect()`). It requires importing `TelegramClient` and `sync` from the telethon library. ```python from telethon import TelegramClient, sync with TelegramClient(name, api_id, api_hash) as client: client.send_message('me', 'Hello!') ``` -------------------------------- ### Accessing Object Attributes in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/quick-references/faq.rst Illustrates how to access attributes (properties or fields) of an object returned by a Telethon method using the dot operator (`.`). The example shows accessing the `username` attribute from the user object returned by `client.get_me()`. Note the use of `await` as `get_me` is an asynchronous method. ```python me = await client.get_me() print(me.username) # ^ we used the dot operator to access the username attribute ``` -------------------------------- ### Configuring Basic Logging with Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/quick-references/faq.rst Configure the standard Python logging module to display messages from the Telethon library and your application. This helps in debugging and understanding the library's behavior by showing errors, warnings, or informational messages. ```python import logging logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING) ``` -------------------------------- ### Migrating Sync Telethon Connection Handling Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/compatibility-and-convenience.rst Demonstrates the migration from the older `try...assert client.connect()...finally client.disconnect()` pattern for connecting and disconnecting the Telethon client to the modern `with client:` context manager, which handles resource management automatically. ```python # 1. Import the client from telethon.sync from telethon.sync import TelegramClient # 2. Change this monster... try: assert client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) ... # REST OF YOUR CODE finally: client.disconnect() ``` ```python # ...for this: with client: ... # REST OF YOUR CODE ``` -------------------------------- ### Getting Input Sender via Event Method in Telethon Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/entities.rst Shows how to obtain the sender's InputPeer using the `event.get_input_sender()` *method*. Unlike the property, this method might perform a network request if necessary to resolve the entity. It is recommended when higher certainty is required or when reusing the sender entity multiple times in the same handler. ```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') ``` -------------------------------- ### Resolving Non-ID Identifier to Marked ID (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/chats-vs-channels.rst Shows how to use the client-specific `client.get_peer_id` method to resolve identifiers that are not simple numeric IDs, such as usernames ('me' in this example) or phone numbers. This method requires a connected client and may perform API calls to find the corresponding Telethon-formatted integer ID. ```python # Assuming 'client' is an active Telethon client instance # print(await client.get_peer_id('me')) # your id ``` -------------------------------- ### Using Telethon Sync Module for Convenience Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/compatibility-and-convenience.rst Demonstrates using the `telethon.sync.TelegramClient` wrapper for simplified scripting where explicit `async` and `await` keywords can often be omitted for API calls within a `with` block, while still allowing for asynchronous event handlers. ```python from telethon.sync import TelegramClient # ^~~~~ note this part; it will manage the asyncio loop for you with TelegramClient(...) as client: print(client.get_me().username) # ^ notice the lack of await, or loop.run_until_complete(). # Since there is no loop running, this is done behind the scenes. # message = client.send_message('me', 'Hi!') import time time.sleep(5) message.delete() # You can also have an hybrid between a synchronous # part and asynchronous event handlers. # from telethon import events @client.on(events.NewMessage(pattern='(?i)hi|hello')) async def handler(event): await event.reply('hey') client.run_until_disconnected() ``` -------------------------------- ### Sending Scheduled Messages using Telethon Client - Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/changelog.rst This snippet demonstrates how to send messages that are scheduled for a later time using the `schedule` parameter in the `client.send_message` method. It requires the `timedelta` class from the `datetime` module to specify the scheduling delay. Examples show scheduling messages for 10 minutes and 1 day in the future. ```python from datetime import timedelta # Remind yourself to walk the dog in 10 minutes (after you play with Telethon's update) await client.send_message('me', 'Walk the dog', schedule=timedelta(minutes=10)) # Remind your friend tomorrow to update Telethon await client.send_message(friend, 'Update Telethon!', schedule=timedelta(days=1)) ``` -------------------------------- ### Illustrating Telethon Sync Module Mechanism Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/compatibility-and-convenience.rst Provides a brief code snippet to illustrate the underlying mechanism of the `telethon.sync` module, which essentially runs synchronous-like calls by wrapping them within an asyncio loop using `asyncio.run()`, highlighting the source of its convenience and slight overhead. ```python asyncio.run(main()) ``` -------------------------------- ### Implementing Pure Asyncio Telethon Client Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/misc/compatibility-and-convenience.rst Shows the standard asyncio approach for using Telethon, which is recommended for performance-critical applications. It involves defining an `async def main` function, using `async with client:` for connection, awaiting all API calls, and running the main coroutine using `asyncio.run()`. ```python import asyncio from telethon import TelegramClient, events async def main(): async with TelegramClient(...) as client: print((await client.get_me()).username) # ^_____________________^ notice these parenthesis # You want to ``await`` the call, not the username. # message = await client.send_message('me', 'Hi!') await asyncio.sleep(5) await message.delete() @client.on(events.NewMessage(pattern='(?i)hi|hello')) async def handler(event): await event.reply('hey') await client.run_until_disconnected() asyncio.run(main()) ``` -------------------------------- ### Using async def, async with, and async for in Python Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/asyncio.rst This snippet demonstrates the advanced syntax features provided by the `async` keyword. It shows defining an asynchronous function (`async def`), using an asynchronous context manager (`async with`) for resource management, and iterating over an asynchronous generator (`async for`) for processing items like messages asynchronously. ```python import asyncio async def main(): # ^ this declares the main() coroutine function async with client: # ^ this is an asynchronous with block async for message in client.iter_messages(chat): # ^ this is a for loop over an asynchronous generator print(message.sender.username) asyncio.run(main()) # ^ this will create a new asyncio loop behind the scenes and tear it down # once the function returns. It will run the loop untiil main finishes. # You should only use this function if there is no other loop running. ``` -------------------------------- ### Handling Events with get_ Methods in Telethon Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/concepts/updates.rst Demonstrates the difference between accessing properties on event objects (which might be None) and using the corresponding async `get_` methods that ensure data is fetched. Also shows accessing properties on message objects obtained from client methods like `iter_messages`, where data is always available. Note that `get_` methods require `await`. ```python @client.on(events.NewMessage) async def handler(event): # event.input_chat may be None, use event.get_input_chat() chat = await event.get_input_chat() sender = await event.get_sender() buttons = await event.get_buttons() async def main(): async for message in client.iter_messages('me', 10): # Methods from the client always have these properties ready chat = message.input_chat sender = message.sender buttons = message.buttons ``` -------------------------------- ### Joining Private Chat/Channel via Invite Hash (Python) Source: https://github.com/hikariatama/hikka-tl/blob/v1/readthedocs/examples/chats-and-channels.rst Shows how to join a private Telegram chat or channel using an invite link hash via the `ImportChatInviteRequest` in Telethon. Requires a client object and the invite hash string. Returns updates upon successful import. ```python from telethon.tl.functions.messages import ImportChatInviteRequest updates = await client(ImportChatInviteRequest('AAAAAEHbEkejzxUjAUCfYg')) ```