Automatic replies for Telegram

Just like vacation emails, but for Telegram!

Jiayu Yi
Jiayu Yi
Mar 19, 2018 · 6 min read

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.

“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 1.6.2 of Telethon, a Python 3 implementation of the Telegram API:

pip3 install telethon==1.6.2

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 session_file variable 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(phone, password)

After calling 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.

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))
async def handle_incoming_message(event):
if event.is_private:
await event.respond("Sorry, I'll be away until next week!")

Note that we have to use the async and 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:

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:

https://asciinema.org/a/170735

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.

Further thoughts

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.

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

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store