Writing simple Telegram bot with Telethon
In this article I will quickly create a showcase of using Telethon Python library in order to make a simple Telegram bot. Our bot will be a member of a group/channel and once someone changes group’s description bot will post that about information as a separate message.
We need a couple of things in order to get started
- Register a new bot with a help of BotFather
- Create new API application to obtain
APP_HASHvariables. Follow the steps here
- Install Telethon library. Both regular
pip install telethonand modern
poetry add telethonwill work.
- Make sure you are familiar with asyncio and how asynchronous programming works in Python.
We can listen to any event that happens in a chat. For example when a title/description has been changed we will receive ChatAction event. In the example below we will listen to any incoming message in the group responding with an updated description. First we need to create a bot instance
from telethon.sync import TelegramClient
Once done we need to create a handler responsible of dealing with the specific kind of the events
from telethon.sync import events
Now let’s run execution loop and add the bot to any test group we already have
You will see logging in your console after any new message arrives into the channel.
The one most important thing left is to implement the main application logic
from telethon import functions
As you can see we store current topic in a global variable, so once process restarts we would loose latest topic. You can use Sqlite to have a simple persistent storage or just write it to the file. The only trick here is to obtain ChatFull instance otherwise we will not be able to get the description.
That’s it, now you are able to enhance it with any custom features you want. Happy coding!