Automatic replies for Telegram
Just like vacation emails, but for Telegram!
Update (2018–04–06): Updated code for Telethon 1.6.2
Recently, a friend told me that he wanted to go on a 10-day meditation retreat and asked if there was any way to automatically reply to people messaging him so that no one would think he was dead.
Indeed, this is possible in Telegram with the Telegram API! By the way, the Telegram API is not the same as the Telegram Bot API: the automatic replies will be sent by your own Telegram account, not from a bot.
How it works
Whenever you do something in the mobile app, web or desktop client, the client uses the Telegram API to make it happen. Incoming messages are received and replies are sent through the Telegram API. Creating a new group or changing your display picture is done using the Telegram API. Even your online status and “typing…” notifications and conveyed through the Telegram API.
Since the Telegram API is open, anyone can implement their own Telegram client and communicate with Telegram servers. With some coding and algorithms, we can make use of use the Telegram API to send automatic replies from our own Telegram account.
We’ll use version 1.6.2 of Telethon, a Python 3 implementation of the Telegram API:
pip3 install telethon==1.6.2
Authenticating to the Telegram API
To interact with the Telegram API using Telethon, we first need to create a Telethon
client object (docs). We’ll need several pieces of information to do this:
api_hashfor a Telegram application. Read about this here: https://core.telegram.org/api/obtaining_api_id
- Your phone number
- Your password if you have two-step verification turned on
- Telethon creates a local file to persist your session so you don’t have to keep authenticating; in the code fragment below, the
session_filevariable is the path to the file representing your saved session. You can name it after your username to remember which account it’s associated with.
from telethon import TelegramClient# load credentials hereclient = TelegramClient(session_file, api_id, api_hash)
client.start for the first time, you’ll be prompted to enter a login code that was sent to you on Telegram. After that, the session file will be created and as long as you use the same session file, you won’t have to authenticate again.
Listening to events
A Telethon client can listen and automatically respond to Telegram events such as incoming messages, contacts coming online or new members in group conversations (docs).
In this case, we want to automatically reply to incoming messages saying that we’ll be away for a while.
For example, the following code fragment will automatically reply to all incoming private messages, telling the sender that we’ll be away until the following week:
async def handle_incoming_message(event):
await event.respond("Sorry, I'll be away until next week!")
Note that we have to use the
await keywords because Telethon is asynchronous under the hood.
Putting things together
Let’s create a simple script by adding the Telegram authentication and a bit of logging:
Testing it out
Bus Eta Bot (@BusEtaBot) is a Telegram bot I made some time ago for checking bus arrival timings in Singapore. One of its features allows you to “bump” a message containing bus arrival times by asking the bot to send it to you again, putting it back at the bottom of the conversation.
(Note: the autoreplier script has been updated to ignore messages from bots, so the following doesn’t work anymore. You can still try out Bus Eta Bot though.)
We can use Bus Eta Bot’s resend feature to test our script is working, since the resend button causes the bot to send you a new private message, which our script is supposed to automatically reply to.
Here, our autoreplier script is immediately responding to every resent ETA query from Bus Eta Bot:
Our script also logs the incoming messages as they come in:
It works! 😄
In the script above, we automatically reply to all private messages. We could easily also decide to respond to all messages including those sent in groups, or instead use a whitelist or blacklist of chats which should or should not be replied to.
On the way home, I spoke to Wei Kiat about this post. He commented on the possibility that two users who were both using autorepliers could get stuck in an infinite loop automatically replying to each other. (This was the reason why Telegram bots originally were unable to receive messages from other Telegram bots.)
Wei Kiat proposed one way to avoid this by only auto-replying to the same chat a limited number of times. I also thought that introducing some rate-limits would help mitigate such a scenario.
When Soon Tiac asked about auto repliers, I immediately jumped to this solution using the Telegram API. However, Wei Kiat also pointed out that there were other ways to convey information to other parties in an unattended way, such as putting it in your display picture, your bio or even your name.
This was a reminder for me about what we learn in design thinking: start with a problem, not a solution. Sometimes when we immediately zero-in on the first solution which comes to our mind, we may lose sight of the big picture and get stuck in a local minimum.
It’s easy to use Telethon to automate things we want to do with the Telegram API. Someone might conceivably think, “Cool, let’s make this into a service so that anyone can set up automatic replies for their Telegram account, maybe through a Telegram bot.”
However, authenticating to the Telegram API is an all-or-nothing action: after authentication, the new session has full control over your Telegram account. It can read all your messages, send messages to anyone, change your phone number and password, and even delete your account. This should not be something to be taken lightly.
If someone does create such a service, some possible concerns could be whether this service should be trusted with this level of control, the risks of such control falling into unauthorised hands, or whether users would even understand the implications of using such a service, and the ethics of it all.
Would this work with WhatsApp?
WhatsApp does not have an API for developers, however should be technically possible to reverse-engineer the web client code to register a handler on incoming messages and look for the appropriate functions to use to send messages. Such an implementation would necessarily require one to have a web browser running and their phone continuously connected to the internet.
- In Introduction to the Telegram API, we explore how to understand the Telegram API and what we can do with it, and use it to analyse our Telegram chat history:
Introduction to the Telegram API
Analyse your conversation history on Telegram programatically
- Introduction to the Telegram Bot API is a 3-part series going through how the Telegram Bot API works and showing how to build a working inline-mode Pokédex bot:
Introduction to the Telegram Bot API, Part 1
Make an inline Telegram bot in 100 lines of code
Here’s the Telethon GitHub repository and documentation again:
Welcome to Telethon's documentation! - Telethon 0.18.1 documentation
Telegram is a popular messaging application. This library is meant to make it easy for you to write Python programs…
You can find the source code for our autoreplier script as a Gist here: https://gist.github.com/yi-jiayu/acc31fbad5a25f746430428ce4d62c28
- Ching Soon Tiac for the initial idea and comments
- Wei Kiat for the additional insights and comments
- Anh for helping me record a gif