Telegram Bot for Free (AWS/Serverless)

In this Post, I am going to explain to you how to create your own Telegram Bot based on Serverless technology called Lambda in AWS. It is not difficult at all, I will explain all the necessary steps for your success. I already use Lambda in production and by the Post want to show advantages of Serverless Technologies. Before we go, let's create a plan for what we will do:

  1. Create AWS account (out of the scope, I hope you have one)
  2. Register Telegram Bot
  3. Create a Lambda function
  4. Create API Gateway
  5. Combine them all and make work together

A bit of theory before practice

Lambda - I would describe it in 3 words - forget about servers. For more information go to the AWS WebSite. A ChatBot is a perfect example for showing all the advantages of Lambda. So, why Serverless? A ChatBot is processing data only a short period of time and then answering to a client. Therefore you don't need computing resources all the time. With Lambda you will pay for only computing time and save money when you don't consume resources. The second benefit of using Lambda is zero efforts for maintenance. You can forget about updates, hardware, and other Servers' issues.

Register Telegram Bot

In your Telegram account find @BotFather, it is a bot for creating your Bots. Run /newbot and invent some name a unique username.  From @BotFather you will receive API key like this.

Telegram Bot

Create Lambda function

Login to AWS Console then go to Lambda and create a new Lambda Function. You need to define a name and runtime(Python 3.6).

Lambda Creating

Let's keep it simple and start from this function:

import json
def lambda_handler(event, context):
    print(event)
    return {'statusCode': 200}
Lambda Creating

Read more about Lambda syntax here

Create API Gateway

Go to API Gateway console and create a new API Gateway. You have to specify Protocol(REST) and Name. Then we have to create Method(ANY) and specify Integration type as  Lambda Function, Use Lambda Proxy integration and type Function Name in Lambda Function field. Farther, we have to deploy our API. 

Creating API Gateway

Combine them all and make work together

Now, we need to connect our Lambda Function with our Bot, we can do it by setting webhook for our Bot. It means that once we receive any data from Bot the data will forward to our AWS API and then to Lambda Function.  Just put your data to URL and open the URL via an Internet browser.

https://api.telegram.org/bot<Bot-Token>/setWebHook?url=<API-Invoke-URL>

We have used the simplest Lambda Function with just print(). Try to send something to your Bot and then open CloudWatch console for seeing print() output.

Check print() output
In CloudWatch Logs, we can see what data actually Lambda Function received.
Ok let's make it a bit more interesting, now we may change Lambda code and see errors or outputs in CloudWatch.

Here is a simple echo function, copy and past it to you Lambda console.

import os
import json
from botocore.vendored import requests
api_key = os.environ['api_key']
api_url = "https://api.telegram.org/bot{}/".format(api_key)
def lambda_handler(event, context):
    data = json.loads(event['body'])
    chat_id = data['message']['chat']['id']
    echo_text = data['message']['text']
    url = "{}sendMessage?text={}&chat_id={}".format(api_url, echo_text,chat_id)
    requests.get(url)
    return {'statusCode': 200}

And don't forget to define  api_key (Telegram API) in Environment variables.

Environment variables

Now, if you send anything to your Bot, it responds like an echo. Great! It was easy, you may start to play around with function and create your own logic. 

Scripts which  were shown above you can find on  GitHub