Create Telegram bot in Python using Telethon

Telegram is a popular messaging application. This library is meant to make it easy for you to write Python programs that can interact with Telegram. Think of it as a wrapper that has already done the heavy job for you, so you can focus on developing an application.

If you are the owner of the Telegram channel/group, you can use BotFather to create a bot. However, if you are not the admin of the channel/group, you can use Telethon to create Telegram bot

Telethon is an asyncio Python 3 MTProto library to interact with Telegram's API as a user or through a bot account (bot API alternative).

Install Telethon #

The first thing is install Telethon

pip install telethon

Create Application #

Before working with Telegram’s API, you need to get your own API ID and hash:

  1. Login to your Telegram account with the phone number of the developer account to use.
  2. Click under API Development tools.
  3. A Create new application window will appear. Fill in your application details. There is no need to enter any URL, and only the first two fields (App title and Short name) can currently be changed later.
  4. Click on Create application at the end. Remember that your API hash is secret and Telegram won’t let you revoke it. Don’t post it anywhere!

Creating a client and sign in #

from telethon import TelegramClient, events, sync
# These example values won't work. You must get your own api_id and
# api_hash from, under API Development.
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

client = TelegramClient('session_name', api_id, api_hash)

In the first line, we import the class name so we can create an instance of the client. Then, we define variables to store our API ID and hash conveniently. At last, we create a new TelegramClient instance and call it client. We can now use the client variable for anything that we want, such as sending a message to ourselves.

Interact with Telegram API #


client.send_message('username', 'Hello! Talking to you from Telethon')
client.send_file('username', '/home/myself/Pictures/holidays.jpg')

messages = client.get_messages('username')

async def handler(event):
    await event.respond('Hey!')