Automatic replies for Telegram

Just like vacation emails, but for Telegram!

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.

“if(goingToCrashIntoEachOther) { dont(); }” — https://www.reddit.com/r/ProgrammerHumor/comments/5ylndv/so_thats_how_they_did_it_its_brilliant/

Getting started

We’ll use version 0.18.1 of Telethon, a Python 3 implementation of the Telegram API:

pip3 install telethon==0.18.1

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:

  • An api_id and api_hash for 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 username variable is the name of the file representing your saved session, and does not necessarily have to be your Telegram username.
from telethon import TelegramClient
client = TelegramClient(username, api_id, api_hash, update_workers=1, spawn_read_thread=False)
client.start(phone, password)

For more about Telethon, refer to the Telethon documentation or check out my previous post where I used (an older version of) it to perform some data analytics on my own Telegram conversations.

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:

@client.on(events.NewMessage(incoming=True))
def _(event):
if event.is_private:
client.send_message(event.message.from_id, "Sorry, I'll be away until next week!")

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.

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:

https://asciinema.org/a/170735

It works! 😄

Extensions

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.

Further thoughts

Deadlock avoidance

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.

Alternative solutions

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.

Security

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.

Further reading

Thanks for reading! If you want to find out more about the Telegram API or the Telegram Bot API, check out some of my previous blog posts:

  • 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 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:

Here’s the Telethon GitHub repository and documentation again:

You can find the source code for our autoreplier script as a Gist here: https://gist.github.com/yi-jiayu/acc31fbad5a25f746430428ce4d62c28

Acknowledgements

  • Ching Soon Tiac for the initial idea and comments
  • Wei Kiat for the additional insights and comments
  • Anh for helping me record a gif