Create a Telegram Bot with AWS Lambda Integration - Part 1
Tags: awslambda, aws, python, telegram
Published: 2023-01-16 19:05:06

Hi all, recently over the Christmas break, I wanted to explore a telegram bot automation for a personal project. As part of that, I went through learning all the steps required and going over multiple iterations to optimize the code and also get it working.

And with the this post, I want to share my learning with you all. Below is the step by step guide to create a Telegram Bot with AWS Lambda Integration.

This will be a multi-part blog. Part 1 below is focusing on getting the basics done and then Part 2 will go for advanced interactions.

I hope this helps you.

1. Firstup, we will create a bot in Telegram. All conversations will be done via this bot over telegram.
For creating bot, telegram has this really cool feature @BotFather, Search for botfather and you can start interacting to create new bot
"Seach BotFather and message /start"

2. Type "/newbot" to create a new bot
3. Choose the name of the bot
4. Choose the username of the bot
   ![Telegram Bot Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rehx86fq770xb5b9kpf.JPG)
   ** This step will generate a TOKEN. Save this token for future 
  use.**

5. Next click on the link for your new bot generated above (t.me/##yourbotname##) and start a conversation. Text "Hi"

6. Once you send a message to the bot, the chat will get an ID which will be used for the conversation. To retrieve the ChatID, we will use the Telegram API.

7. Replace your TOKENid below and call the below URL https://api.telegram.org/bot##yourTOKENid##/getUpdates 

8. Extract the ChatID from the response. Look for the below tag in response: "chat":{"id": "**xxxxxxx**"

9. Now send a sample message to this chat with Web (Later on we will do it via AWS Lambda) https://api.telegram.org/bot##yourTOKENid##/sendMessage?chat_id=##yourChatID##&text=Hello
  **HURRAY.. You should have got a text from the Bot already. Now lets build the integration with AWS Lambda** 

10. Go to AWS Console -> AWS Lambda -> Click on 'Create Function'
  ![Create Function Help](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8993v9yrizjhpjbeexuq.JPG)

11. Now, give a valid function name and select the suitable runtime, then go to advance setting and select the checkbox of 'Enable Function URL' and 'None' for the IAM setting (This is great feature and elimiates API Gateway setting altogether), keep rest settings as default and click on 'Create Function'. I chose python in this case
  ![Create Function1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbmmrstymtkzn4difq27.JPG)
  ![Create Function2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kmp4vmdr0n1bqr8yv0my.JPG)

12. When the sample function is created. Copy the Function URL and open it in a new tab. You should get a response as below.
If you are getting unauthorize error, then recheck if you had selected 'None' in function URL which ensures unathenticated access. 
  ![Function URL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wybprqrrqa12oq220945.JPG)

13. It's best practice to define the secure information as Environment Variable (or for advanced uses you can use other secure stores). Go to 'Configuration' tab and click on 'Environment Variables' and add 2 variables
'TOKEN' = Value is ##yourTOKENid##
'CHATID' = Value is ##yourCHATid## (In future, we can retrieve chatid from request to make it dynamic) 
  ![Set Env Variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7lbpbsgui2qze9bh5liz.JPG)
  ![Set Env Variable2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9kviia3dau3z46cs0wr6.JPG)

14. Now we will add the functionality to send the message via Lambda. For python, this usually requires importing 'requests' module which is not available out of the box.
Hence, for this, we will choose to create a layer in Lambda which will host this library.
  Download the Requests tar from https://github.com/TryNErr/TryNErr/blob/main/requests.zip

  **Once downloaded tar will have to be convered to ZIP with below folder structure**

  For Python, create the below folder structure + download required libraries 
  python / 
         certifi-2021.10.8.dist-info
         certifi
         charset_normalizer
         charset_normalizer-2.0.12.dist-info
         idna
         idna-3.3.dist-info
         requests
         requests-2.27.1.dist-info

  [](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)

  you can alternately take it from your python project libraries and zip these files OR contact me and I can send it to you.

15. Click on 'Layers' on the Lambda function
  ![Layers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0n09r6r31en0pgme0m2.JPG)


16. Click on 'Add a Layer'
  ![Add a Layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1oli2xq3y4uczl6nqooa.JPG)



17. Next, we will create a new layer, click on 'Create a New Layer'
  ![Create a New Layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6f45q0escodt50mnyib.JPG)



18. Provide the required details, Upload the requests.zip file, click on 'Create'
  ![Create Layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/krzb26mszay6154crkqu.JPG)



19. Post creation, Go back to the Lambda function and click on Add a Layer to add the newly created layer, click 'Add'
  ![Add Created Layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zd6bw1tws4z6dztawo7.JPG)

  ![Add Created Layer2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a37mu7ev1l3nh4o5qh7m.JPG)

20. Now, update your lambda function with the below code:


```
import json
import os
import requests

def lambda_handler(event, context):
    # TODO implement
    BOT_TOKEN = os.environ.get('TOKEN')
    BOT_CHAT_ID = os.environ.get('CHATID')
    #BOT_CHAT_ID = chat_id
    bot_message = "Hello, this is the bot from telegram"
    send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage?chat_id=' + BOT_CHAT_ID + \
                '&parse_mode=HTML&text=' + bot_message
    response = requests.get(send_text)
    print(response)    
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
```


## This should send a message to your telegram chat...

**Thats the end of Part 1.
For Part 2, I will try to a) add more functionality to the bot and b) schedule the bot to trigger message in set frequency.**