Building Powerful Telegram Bots with Telethon in Python

KH Huang
3 min readAug 1, 2023

--

Telegram is a popular messaging platform known for its secure and feature-rich environment. As a developer, you can harness the power of Telegram’s Bot API to create interactive and dynamic bots that can perform a wide range of tasks. In this article, we’ll explore how to build powerful Telegram bots using Telethon, a powerful Python library that allows you to interact with Telegram’s API.

Introducing Telethon

Telethon is an asynchronous Python library that simplifies interacting with Telegram’s Bot API. It provides a user-friendly interface and handles all the complexities of making API calls and handling updates from Telegram. With Telethon, you can send messages, handle incoming messages, manage channels, and perform many other tasks with ease.

Installation

Before we dive into creating Telegram bots with Telethon, let’s start by installing the library. Open your terminal and use pip to install Telethon:

pip install telethon

Once installed, you’re ready to build your Telegram bot.

Creating a Telegram Bot

To create a Telegram bot, you first need to have a Telegram account. If you don’t have one, download the Telegram app and sign up.

Once you have your Telegram account, you can create a bot by following these steps:

  1. Open the Telegram app and search for the “BotFather” bot.
  2. Start a chat with the BotFather and use the “/newbot” command to create a new bot.
  3. Follow the instructions from the BotFather to choose a name and username for your bot.
  4. Once the bot is created, the BotFather will provide you with a unique API token for your bot. Make sure to keep this token safe, as it will be used to authenticate your bot when making API calls.

Connecting to Telegram API

With your bot’s API token in hand, you can now use Telethon to connect to the Telegram API and start interacting with your bot.

from telethon import TelegramClient, events

# Replace 'YOUR_API_ID', 'YOUR_API_HASH', and 'YOUR_BOT_TOKEN' with your actual values
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
bot_token = 'YOUR_BOT_TOKEN'
client = TelegramClient('bot_session', api_id, api_hash).start(bot_token=bot_token)

Replace 'YOUR_API_ID', 'YOUR_API_HASH', and 'YOUR_BOT_TOKEN' with your actual API ID, API hash, and bot token, respectively. The API ID and API hash are obtained by creating an application on the Telegram website (https://my.telegram.org/apps).

Sending Messages

To send a message from your bot to a user or a group, use the send_message method of the client object:

async def send_hello_message():
chat_id = 'USER_OR_GROUP_ID' # Replace with the chat ID of the user or group
message = 'Hello from your bot!'

await client.send_message(chat_id, message)


# Call the function to send the message
client.loop.run_until_complete(send_hello_message())

Replace 'USER_OR_GROUP_ID' with the chat ID of the user or group you want to send the message to.

Receiving Messages

To handle incoming messages, use the events.NewMessage event handler:

@client.on(events.NewMessage)
async def handle_new_message(event):
sender = await event.get_sender()
message = event.message.text

print(f"Received a message from {sender.username}: {message}")


# Run the event loop to start receiving messages
client.run_until_disconnected()

This code sets up an event handler to print any incoming messages from users or groups.

Responding to Commands

Telegram bots often respond to commands from users. To handle commands, use the events.NewMessage event handler with a filter for commands:

from telethon.tl.types import PeerUser, PeerChat, PeerChannel

@client.on(events.NewMessage(pattern='/start'))
async def handle_start_command(event):
sender = await event.get_sender()
chat_id = event.message.peer_id
if isinstance(chat_id, (PeerUser, PeerChat, PeerChannel)):
await client.send_message(chat_id, 'Welcome to the bot! How can I assist you?')

# Add more command handlers here for different commands

In this example, we respond to the “/start” command with a welcome message.

Conclusion

Telethon is a powerful Python library that makes it easy to build interactive and dynamic Telegram bots. With Telethon, you can connect to the Telegram API, send and receive messages, handle commands, and perform various other tasks with minimal effort.

In this article, we introduced Telethon and covered the basics of creating and using a Telegram bot. Armed with this knowledge, you can now explore more advanced features and build sophisticated bots to meet your specific needs. So go ahead, dive into the Telegram Bot API, and unleash the potential of your Telegram bot with Telethon!

Useful Links

--

--

KH Huang

Backend Software Engineer | Python & Golang | Crafting high-performance solutions for seamless experiences.