Telegram auto reply bot in Yandex Cloud

2021-05-09, Anton Bakuteev

 

The purpose

At the moment telegram doesn't have a built-in option to do it. Since I am using telegram a lot at my job, it is very important to let colleagues know when I am not available. The most common scenario for me is when I am on vacation and have no access to the internet.

I've found some existing solutions, but they are hosted directly on your smartphone or there is no host proposed. This makes it useless when you have no access to the internet.

In this article I'll describe approach how to host auto responder in Yandex Compute Cloud and use it on demand via telegram bot based on serverless Yandex Cloud Functions.


The code

Code is here. The main idea is to have a serverless telegram bot as a trigger for another bot which is not serverless. The serverless bot is very cheap, since you only pay for each message and don't pay when you have no messages.

For the auto reply part I am using the smallest possible instance, which is also the cheapest. It has 2 cores (5% of performance for each core) and 512MB RAM. It costs about 2.88$ per month, which is quite cheap.


 


I was thinking of making it serverless too, but preferred  to save my time instead, since I already had a script non serverless auto reply script.

I've put the content of cloud_function/autoreplier_starter.py in the editor and initialized corresponding environment variables. This script uses Yandex Cloud API, it starts prepared instance, connects to it via ssh and starts autoreply.py script, which should be preliminary copied there with .env file which contains tokens. If the message in the trigger corresponds to the stop command it stops the instance to save money.


 


To make it run in telegram you should create a bot and bind it to cloud function via webhook.

curl -F "url=https://functions.yandexcloud.net/{secret_function_id}" \
https://api.telegram.org/bot{secret_bot_key}/setWebhook

That is basically all. For convenience  I added two commands to bot.


 


Pay attention, that autoreply will look like answers come directly from you.


Results and future plans

I find this bot very useful though it is not free, the price is worth it.

Copyright © SomeTech™ 2023