Lou*_*ing 6 python alexa-skills-kit alexa-slot
我试图正确理解插槽如何以编程方式工作。在编写任何代码之前,我会通过查看适用于python的alexa sdk 的示例来尝试很好地理解它。
具体来说,我试图理解ColorPicker示例中插槽中的基础知识(我正确理解了hello_world,并通过自己添加一些东西进行了一些编码。工作正常)。
我很难理解如何访问这些插槽值(因为我看到它是通过两种不同的方式完成的)。
def whats_my_color_handler(handler_input):
"""Check if a favorite color has already been recorded in
session attributes. If yes, provide the color to the user.
If not, ask for favorite color.
"""
# type: (HandlerInput) -> Response
if color_slot_key in handler_input.attributes_manager.session_attributes:
fav_color = handler_input.attributes_manager.session_attributes[
color_slot_key]
speech = "Your favorite color is {}. Goodbye!!".format(fav_color)
handler_input.response_builder.set_should_end_session(True)
else:
speech = "I don't think I know your favorite color. " + help_text
handler_input.response_builder.ask(help_text)
handler_input.response_builder.speak(speech)
return handler_input.response_builder.response
Run Code Online (Sandbox Code Playgroud)
我在此功能中了解的是color_slot_keyAlexa(前端,Alexa Developer)插槽中变量的名称。但是handler_input.attributes_manager.session_attributes,据我所知,通常是插槽,通过其键访问handler_input.attributes_manager.session_attributes['color_slot_key']将获得具有该键的插槽的值。
如果我正确理解这一点,那对我来说很有意义。如果有颜色,Alexa会说出来。如果不是,则不是。
现在:
@sb.request_handler(can_handle_func=is_intent_name("MyColorIsIntent"))
def my_color_handler(handler_input):
"""Check if color is provided in slot values. If provided, then
set your favorite color from slot value into session attributes.
If not, then it asks user to provide the color.
"""
# type: (HandlerInput) -> Response
slots = handler_input.request_envelope.request.intent.slots
if color_slot in slots:
fav_color = slots[color_slot].value
handler_input.attributes_manager.session_attributes[
color_slot_key] = fav_color
speech = ("Now I know that your favorite color is {}. "
"You can ask me your favorite color by saying, "
"what's my favorite color ?".format(fav_color))
reprompt = ("You can ask me your favorite color by saying, "
"what's my favorite color ?")
else:
speech = "I'm not sure what your favorite color is, please try again"
reprompt = ("I'm not sure what your favorite color is. "
"You can tell me your favorite color by saying, "
"my favorite color is red")
handler_input.response_builder.speak(speech).ask(reprompt)
return handler_input.response_builder.response
Run Code Online (Sandbox Code Playgroud)
我不明白为什么在此函数中通过以下方式访问颜色的值:
handler_input.request_envelope.request.intent.slots[color].value
而不是像第一个函数那样(类似这样):
handler_input.attributes_manager.session_attributes[color_slot_key]
我猜想,第一个只是检查会话属性中是否存在(我不太了解这些属性),而另一个则与Alexa请求有关。但是为什么格式不同?
你混合两种不同的东西。会话属性与槽值无关。您可以通过以下方式检索插槽:
handler_input.request_envelope.request.intent.slots
Run Code Online (Sandbox Code Playgroud)
为了方便起见,该示例将检索到的颜色存储在会话属性中,以便在整个技能会话期间保存它。将会话属性视为在技能会话中持续存在的持久属性(键+值)(它们可以是您想要的任何属性)。
此处解释了会话属性的颜色选择器示例使用:
(你甚至有一个选项卡来选择 python)
在测试选项卡中,测试技能并查看传入和传出的 json。事情将会变得清晰!