我从博客中获得了以下代码,该代码获取了今天的比特币价格。我可以从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”函数,“事件”和“上下文”的格式是什么?另外,这里的“背景”是什么?
在我的情况下,我应该通过什么作为“事件”和“上下文”?
答案 0 :(得分:2)
您的代码失败,因为event
对象用{'Date': 'Feb 22'}
填充,但是您的代码期望的远远超过此。因此,当您尝试通过尝试访问currentIntent
来解析此JSON时,它将失败:
date_input = event['currentIntent']['slots']['Date']
从控制台进行测试时,您无法将任何context
传递给Lambda,因为它是由AWS自动填充的。另外,上下文仅在非常特定的情况下使用,因此我现在不必担心。
但是,您可以将event
作为参数传递,并且有很多方法可以使用。手动执行此操作最简单的方法是转到AWS的Lambda控制台,单击“测试”,如果尚未配置任何“测试事件”,则会弹出以下屏幕
现在,您可以在下拉菜单中选择您的事件,AWS将为您填写事件,如下所示:
您现在可以按照自己的方式自定义事件。
保存并单击“测试”后,event
对象将使用提供的JSON填充。
另一种选择是检查Sample Events Published By Event Sources,这样您就可以简单地捕获想要的任何JSON事件并相应地对其进行定制。
我为您获取了Lex Sample Event,它看起来像这样:
{
"messageVersion": "1.0",
"invocationSource": "FulfillmentCodeHook or DialogCodeHook",
"userId": "user-id specified in the POST request to Amazon Lex.",
"sessionAttributes": {
"key1": "value1",
"key2": "value2",
},
"bot": {
"name": "bot-name",
"alias": "bot-alias",
"version": "bot-version"
},
"outputDialogMode": "Text or Voice, based on ContentType request header in runtime API request",
"currentIntent": {
"name": "intent-name",
"slots": {
"slot-name": "value",
"slot-name": "value",
"slot-name": "value"
},
"confirmationStatus": "None, Confirmed, or Denied
(intent confirmation, if configured)"
}
}
将其用作您的活动,就可以相应地对其进行测试。