Simple Telegram Bot with Python and AWS Lambda

6 min read Original article ↗

Daniils Petrovs

Press enter or click to view image in full size

Python is a fantastic language for simple automation tasks. It is one of the most popular languages in the world thanks to its easy and beginner-friendly syntax, and giant ecosystem of tools and libraries. Combined with server-less services like AWS Lambda, you can make very cost-effective and useful automations with it. In this article, I will show you how I built a simple Python bot that extracts radar imagery and data and posts it to Telegram. We are using a weather radar image generated on the website lietus.lv and sending it to Telegram using a bot.

Telegram setup

The first thing we will do is create a Telegram bot. All Telegram bots use the publicly available Bot API. This is how our Lambda will communicate with the Telegram API servers to actually execute commands in Telegram, like sending messages. Bots are created in the messenger itself using a bot called BotFather.

Using the BotFather bot right in Telegram to create the bot and get our API token.

We need to use BotFather to actually register our bot with Telegram and get an API token. This is the primary authorisation mechanism of the API. Make sure not to leak this token anywhere public! Otherwise, someone can easily take control of your bot. If this happens or you just forget the token, don’t worry — you can always change it later by using BotFather again.

Now that we are armed with an API token, we can already start sending messages to Telegram using our bot! Technically, a proper Telegram bot app does 2-way communication with the Telegram API, and there are 2 ways of doing it:

  • Long-polling (polling the Telegram API in a loop for updates)
  • Web-hook (registering the app’s request endpoint that is called on new updates)

However, we don’t need either of these since our bot will only send messages. Instead we can simply use Telegram APIs sendPhoto method. We don’t even need to process the file at all — we will just send the URL of the radar image directly to Telegram.

Next, we are going to create a channel for the bot to post in. Make sure to add the bot as an admin.

Now here is a small tricky part. All chat interaction methods in the API identify the Telegram chats by a specific signed integer ID. There isn’t really a straightforward way to get it, however one way is to send a test message to the chat, then forward it to a very useful bot called Telegram Bot Raw. It will print out the raw metadata of the message.

We are interested in the id in the“forward_from_chat” key. That is our chat_id.

Setting up AWS Lambda

Now it is time to create our Lambda. Lambda is a very powerful and cheap AWS service that, plainly put, allows you to run some code on demand, without having to worry about hosting virtual servers. This means that you are charged only when your code runs. With the current pricing model, Lambda is actually free for a large number of initial executions and runtime. At this point I assume you have an AWS account. First thing we do is head to the AWS Console and head over to the Lambda section.

Press enter or click to view image in full size

Hit “Create function”, you will be presented with a form. We are interested in a Python 3.8 runtime environment (the latest stable version of Python as of the time of writing), and giving it a meaningful name.

Press enter or click to view image in full size

Our Lambda is created! Now we need to do some more setup. Like I said before, you should never put sensitive credentials or tokens in plaintext in your code. Instead we can load the Telegram API token from an environment variable. Setting one up is easy:

Press enter or click to view image in full size

By default, the environment variable will be encrypted at rest with a new symmetric key. In production, it is strongly advised to also encrypt the keys in transit. You can read more about it here.

Press enter or click to view image in full size

We can write the code directly in the Lambda editor this time, as we won’t need anything external libraries and we are keeping it simple this time.

Writing the code

We are using the built-in http.client module for our HTTP requests this time. We construct the endpoint by attaching the telegram_token that we get from the previously defined environment variable. lambda_handler is our handler function — it is the function that will be called when the Lambda is triggered. Another option could be to use the requests library, but this time we are keeping it barebones. I just used a REST client like Insomnia, which allows you to test an API before writing any code, as well as generate code in most languages and libraries. The source I am using keeps a list of generated radar images in a sub-resource, that looks like so:

Press enter or click to view image in full size

Luckily, we don’t even need to use any libraries, because Python already comes with the html.parse module built-in.

Get Daniils Petrovs’s stories in your inbox

Join Medium for free to get updates from this writer.

Remember me for faster sign in

After writing our own little parser and trying it all together, the final result will look like this:

We can test our Lambda by sending some dummy payload:

Press enter or click to view image in full size

Final steps: AWS EventBridge

The final step is to execute our Lambda according to some schedule. The typical way to do this is to create an EventBridge trigger. You can use either a rate or a typical cron schedule.

Press enter or click to view image in full size

That’s it! You should see the connector in the Lambda designer.

Press enter or click to view image in full size

Final result:

Thanks for reading!

I hope you learned something new. Next time we can try something a bit more advanced — creating an interactive bot, that will serve an image/response on user commands. If you have any extra questions, ping me on Twitter