I am developing a telegram bot with python (telebot) , aws lambda and api gateway.
I have a problem in the lambda function and I can’t understand why I have this kind of problem.
My lambda is this:
import telebot
import datetime
TOKEN = 'xxx'
def lambda_handler(event, context):
bot = telebot.TeleBot(TOKEN)
# Extract the message key over payload's body
message = json.loads(event['body'])
print(message)
# Split between three variables bellow
chat_id = message['chat']['id'] # Chat ID will guide your chatbot reply
sender = message['from']['first_name'] # Sender's first name, registered by user's telegram app
text = message['text'] # The message content
if text.lower().strip() == "/time":
current_time = datetime.strftime(datetime.now(), "%H:%M:%S")
bot.send_message(chat_id, "Right now its {} UTC.".format(current_time))
else:
pass
The error I get, running the test is this:
Response
{
"errorMessage": "'body'",
"errorType": "KeyError",
"stackTrace": [
" File "/var/task/lambda_function.py", line 10, in lambda_handlern message = json.loads(event['body'])n"
]
}
The given json file:
{
"update_id": 0000000,
"message": {
"message_id": 000000,
"from": {
"id": 00000000,
"is_bot": false,
"first_name": "myname",
"last_name": "mysurname",
"username": "sursurname",
"language_code": "it"
},
"chat": {
"id": 000000,
"first_name": "myname",
"last_name": "mysurname",
"username": "sursurname",
"type": "private"
},
"date": 1654697178,
"forward_from": {
"id": 00000000,
"is_bot": false,
"first_name": "mysurname",
"last_name": "mysurname",
"username": "sursurname",
"language_code": "it"
},
"forward_date": 0000000000,
"text": "ciao"
}
}
I cannot understand why it is not able to read the body in any way, maybe I am in the wrong library? Do you have any suggestions to help me with this?
2
Answers
I solved it by doing this:
event['body']
is almost definitely not the correct key to access data passed through an event. The event passes information in a nested dictionary and you’ll need to figure out how to drill down to the correct key.