DEV Community

Cover image for Create a Telegram Bot with AWS Lambda Integration - Part 1

Create a Telegram Bot with AWS Lambda Integration - Part 1

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
    ** 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

  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
    Create Function2

  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

  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
    Set Env Variable2

  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

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

  1. Click on 'Layers' on the Lambda function
    Layers

  2. Click on 'Add a Layer'
    Add a Layer

  3. Next, we will create a new layer, click on 'Create a New Layer'
    Create a New Layer

  4. Provide the required details, Upload the requests.zip file, click on 'Create'
    Create Layer

  5. 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

Add Created Layer2

  1. 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!')
    }
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
aikleong7 profile image
Aikleong7

hey can you send me the zip file

Collapse
 
trycatch_z profile image
axl rose da deep web

hey can you send me the zip file

Collapse
 
alperinugur profile image
Alper Inugur

great tutorial. thank you

Collapse
 
cocodernero profile image
Cocodernero

hey can you send me the zip file