我从博客中获得了以下代码,该代码获取了今天的比特币价格。我可以从 AWS Lex 控制台访问这个 Lambda 函数并测试机器人以获得今天的价格。
"""
Lexbot Lambda handler.
"""
from urllib.request import Request, urlopen
import json
def get_bitcoin_price(date):
print('get_bitcoin_price, date = ' + str(date))
request = Request('https://rest.coinapi.io/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/latest?period_id=1DAY&limit=1&time_start={}'.format(date))
request.add_header('X-CoinAPI-Key', 'E4107FA4-A508-448A-XXX')
response = json.loads(urlopen(request).read())
return response[0]['price_close']
def lambda_handler(event, context):
print('received request: ' + str(event))
date_input = event['currentIntent']['slots']['Date']
btc_price = get_bitcoin_price(date_input)
response = {
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "SSML",
"content": "Bitcoin's price was {price} dollars".format(price=btc_price)
},
}
}
print('result = ' + str(response))
return response
但是当我从 AWS Lex 控制台测试该函数时,我收到以下错误:
Response:
{
"errorMessage": "'currentIntent'",
"errorType": "KeyError",
"stackTrace": [
[
"/var/task/lambda_function.py",
18,
"lambda_handler",
"date_input = event['currentIntent']['slots']['Date']"
]
]
}
Request ID:
"2488187a-2b76-47ba-b884-b8aae7e7a25d"
Function Logs:
START RequestId: 2488187a-2b76-47ba-b884-b8aae7e7a25d Version: $LATEST
received request: {'Date': 'Feb 22'}
'currentIntent': KeyError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 18, in lambda_handler
date_input = event['currentIntent']['slots']['Date']
KeyError: 'currentIntent'
如何在 AWS Lambda 控制台中测试该函数?'lambda_handler' 函数,'event' 和 'context' 的格式是什么?另外,这里的“背景”是什么?
在我的情况下,我应该将什么作为“事件”和“上下文”传递?