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.
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"Type "/newbot" to create a new bot
Choose the name of the bot
Choose the username of the bot
** This step will generate a TOKEN. Save this token for future
use.**Next click on the link for your new bot generated above (t.me/##yourbotname##) and start a conversation. Text "Hi"
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.
Replace your TOKENid below and call the below URL https://api.telegram.org/bot##yourTOKENid##/getUpdates
Extract the ChatID from the response. Look for the below tag in response: "chat":{"id": "xxxxxxx"
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 LambdaGo to AWS Console -> AWS Lambda -> Click on 'Create Function'
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
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.
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)
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.
Next, we will create a new layer, click on 'Create a New Layer'
Provide the required details, Upload the requests.zip file, click on 'Create'
Post creation, Go back to the Lambda function and click on Add a Layer to add the newly created layer, click 'Add'
- 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.
Top comments (4)
hey can you send me the zip file
hey can you send me the zip file
great tutorial. thank you
hey can you send me the zip file