If you’re looking to integrate Telegram functionality into your Python applications, Telethon is the library you need. This article provides a concise guide along with examples to get you started.
Installation:
To begin, install Telethon using pip:
pip install telethon
Setting up API Credentials:
Obtain your API ID and Hash from Telegram’s website.
Basic Usage:
Initialize Telethon by creating a client instance:
from telethon.sync import TelegramClient
api_id = 'your_api_id'
api_hash = 'your_api_hash'
client = TelegramClient('session_name', api_id, api_hash)
Connecting and Logging in:
Connect to the Telegram servers and log in:
client.start()
Sending a Message:
Send a message to a user or a channel:
target_entity = 'username or chat_id'
message = 'Hello, Telethon!'
client.send_message(target_entity, message)
Receiving Messages:
Retrieve and print messages from a chat:
messages = client.get_messages(target_entity, limit=5)
for message in messages:
print(message.text)
Downloading Media:
Download media files (photos, videos, documents) from messages:
message = client.get_messages(target_entity, limit=1)[0]
if message.media:
message.download_media()
Working with Events:
Use events to handle incoming messages or updates:
from telethon.sync import events
@client.on(events.NewMessage)
async def handle_new_message(event):
print(event.message.text)
client.run_until_disconnected()
Handling Errors:
Implement error handling for robustness:
from telethon import errors
try:
# Your code here
except errors.RPCError as e:
print(f"Error: {e}")
Disconnecting:
Logout and disconnect when done
client.disconnect()
This brief guide should get you started with Telethon. Explore further and customize according to your project’s needs. Happy coding! 🚀
#telegram #bot #telegrambot #python #automation #telethon #pythonprogramming