我将占用 2 个插槽,并在代码中处理空插槽(python)。
所以首先你必须在你的意图中定义2个插槽city和country,机器人将检查DialogCodeHook中的插槽值是否已填充,如果验证成功,它将调用FulfillmentCodeHook调用天气 api 将结果返回给用户。
注意:您必须检查Initialization and validation code hook,以便它转到DialogCodeHook
def build_response(message):
return {
"dialogAction":{
"type":"Close",
"fulfillmentState":"Fulfilled",
"message":{
"contentType":"PlainText",
"content":message
}
}
}
def elicit_slot(intent_name, slots, slot_to_elicit, message):
return {
'dialogAction': {
'type': 'ElicitSlot',
'intentName': intent_name,
'slots': slots,
'slotToElicit': slot_to_elicit,
'message': message
}
}
def delegate(session_attributes, slots):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate',
'slots': slots
}
}
def perform_action(intent_request):
source = intent_request['invocationSource'] # DialogCodeHook or FulfillmentCodeHook
slots = intent_request['currentIntent']['slots'] # your slots city and country
if source == 'DialogCodeHook':
# Perform basic validation on the supplied input slots.
if slots['city'] is None: # or any other validation that you want to perform
return elicit_slot(
intent_request['currentIntent']['name'], # current intent name
slots, # current intent slots
'city', # slot name
'Please enter city name' # prompt the user to enter city name
)
if slots['country'] is None:
return elicit_slot(
intent_request['currentIntent']['name'], # current intent name
slots, # current intent slots
'country', # slot name
'Please enter country name' # prompt the user to enter country name
)
# delegate means all slot validation are done, we can move to Fulfillment
return delegate(output_session_attributes, slots)
if source == 'FulfillmentCodeHook':
result = your_api_call(slots['city'], slots['country'])
return build_response(result) # display the response back to user
def dispatch(intent_request):
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot's intent handlers
if intent_name == 'GetWeather':
return perform_action(intent_request)
raise Exception('Intent with name ' + intent_name + ' not supported')
def lambda_handler(event, context):
logger.debug(event)
return dispatch(event)
希望对你有帮助。