DEV Community

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

Create a Telegram Bot with AWS Lambda Integration - Part 2

Hello and welcome back to the Part -2 of the AWS Lambda and Telegram Bot interaction. For the next step, I was exploring on the integration options that can be trialled for taking this a step further. Below are the use cases for which this integration can be used.

  1. Serverless Notifications: By integrating Telegram with AWS Lambda, you can create a serverless notification system that sends messages to Telegram whenever certain events occur in your AWS infrastructure. For example, you could set up a Lambda function to send a message to a Telegram group whenever a new EC2 instance is launched.
  2. Chatbot: You can use AWS Lambda to build a chatbot that responds to user queries in Telegram. For example, you could create a Lambda function that uses natural language processing to answer questions about your products or services, and then integrate it with Telegram so that users can interact with the chatbot through the Telegram app.
  3. Content Distribution: By integrating Telegram with AWS Lambda, you can create a system for distributing content to users through Telegram. For example, you could set up a Lambda function to generate daily news summaries or weather updates, and then use Telegram to distribute them to subscribers.
  4. Event Monitoring: You can use AWS Lambda to monitor events in your Telegram groups or channels. For example, you could create a Lambda function that analyzes messages in a Telegram group and sends an alert to a designated user if certain keywords or phrases are detected.
  5. Analytics: By integrating Telegram with AWS Lambda, you can create a system for analyzing user behavior in Telegram. For example, you could set up a Lambda function to track how often users interact with your Telegram bot, what kinds of questions they ask, and how long they spend chatting. This data can then be used to optimize your chatbot and improve user engagement.

Firstly, I tried to create a chatbot which will respond to commands typed on telegram and for now it is sending a sample response back for acknowledgement

Assuming you have followed all the required steps from Part - 1, below is the code that you will be required to update in the lambda handler for this

import json
import os
import requests
def lambda_handler(event, context):
request_body = json.loads(event['body']) # EXtract the Body from the call
request_msg = json.dumps(request_body['message'])#['chat']['id'] # Extract the message object which contrains chat id and text
chat_id = json.dumps(request_body['message']['chat']['id']) # Extract the chat id from message
command = json.dumps(request_body['message']['text']).strip('"') # Extract the text from the message
# TODO implement
BOT_TOKEN = os.environ.get('TOKEN')
BOT_CHAT_ID = os.environ.get('CHATID')
BOT_CHAT_ID = chat_id # Updating the Bot Chat Id to be dynamic instead of static one earlier
command = command[1:] # Valid input command is /start or /help. however stripping the '/' here as it was having some conflict in execution.
if command == 'start':
message = "Welcome to my bot! How can I help you today?" # Sample Response on start command
elif command == 'help':
message = "Here are the available commands: /start, /help"
else:
message = "I'm sorry, I didn't understand that command. Please try again."
send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage?chat_id=' + BOT_CHAT_ID + \
'&parse_mode=HTML&text=' + message
response = requests.get(send_text)
print(send_text)
print(response)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}

For the above chatbot to work, we need to have an active connection between Telegram and Lambda. For this, we need to set a webhook. Below is the command to set webhook

https://api.telegram.org/bot<>/setWebhook?url=<>

  1. Here the BOT ID is your Bot ID
  2. The Lambda Function URL is the URL obtained from the Lambda description page.

Image description

After updating the above code, below is the result that I have got

Image description

That's it for the Part 2.
Next I want to try the below for Part 3.
a. Create a chatbot quiz which will have questions from Dynamo DB and scorecard in DynamoDB and hosted via Telegram.
b. Some live score or ticker updates via Telegram. This will involve in CORS functionality and https calls via Lambda.

Top comments (1)

Collapse
 
estiercooooool profile image
Estiercol 2.0 • Edited

Hello HardikJoshi !!

I found this tutorial very useful. Im a very beginner, and im making my first steps on aws infrastructure.
A little suggestion, could you insert the block code, on some snippet or text box? As it is right now, the indentation is completely lost. And I had to correct it manually, trial and error:

import json
import os
import requests
def lambda_handler(event, context):
    request_body = json.loads(event['body']) # EXtract the Body from the call
    request_msg = json.dumps(request_body['message'])#['chat']['id'] # Extract the message object which contrains chat id and text
    chat_id = json.dumps(request_body['message']['chat']['id']) # Extract the chat id from message
    command = json.dumps(request_body['message']['text']).strip('"') # Extract the text from the message
    # TODO implement
    BOT_TOKEN = os.environ.get('TOKEN')
    BOT_CHAT_ID = os.environ.get('CHATID')
    BOT_CHAT_ID = chat_id # Updating the Bot Chat Id to be dynamic instead of static one earlier
    command = command[1:] # Valid input command is /start or /help. however stripping the '/' here as it was having some conflict in execution.
    if command == 'start':
        message = "Welcome to my bot! How can I help you today?" # Sample Response on start command
    elif command == 'help':
        message = "Here are the available commands: /start, /help"
    else:
        message = "I'm sorry, I didn't understand that command. Please try again."
    send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage?chat_id=' + BOT_CHAT_ID + '&parse_mode=HTML&text=' + message
    response = requests.get(send_text)
    print(send_text)
    print(response)
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
Enter fullscreen mode Exit fullscreen mode

Thanks again for this guide!
Regards.