您的问题很可能涉及session
变量的范围。
以下代码是来自颜色专家技能的意图调用。 正如您在第1行中看到的,变量session
被定义为参数。在第12行,该变量被传递给函数set_color_in_session(intent,session)
。
def on_intent(intent_request, session): # <-------------
""" Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# Dispatch to your skill's intent handlers
if intent_name == "MyColorIsIntent":
return set_color_in_session(intent, session) # <-------------
elif intent_name == "WhatsMyColorIntent":
return get_color_from_session(intent, session) # <-------------
elif intent_name == "AMAZON.HelpIntent":
return get_welcome_response()
else:
raise ValueError("Invalid intent")
从提供的信息,我相信你定义自己的功能通过定制意图被解雇,最容易忘记的session
变量传递给这些函数。再次,变量session
将只存在于你的函数中,如果它作为参数传入的话。以功能def get_color_from_session(intent, session):
为例。由于session
作为参数传入,因此它在第6行的此函数中可用,favorite_color = session['attributes']['favoriteColor']
。
如果您没有传入变量session
,那么您将引用一个名为session
的本地变量,该变量可能不存在。
def get_color_from_session(intent, session):
session_attributes = {}
reprompt_text = None
if "favoriteColor" in session.get('attributes', {}):
favorite_color = session['attributes']['favoriteColor'] #<-------------
speech_output = "Your favorite color is " + favorite_color + \
". Goodbye."
should_end_session = True
else:
speech_output = "I'm not sure what your favorite color is. " \
"You can say, my favorite color is red."
should_end_session = False
# Setting reprompt_text to None signifies that we do not want to reprompt
# the user. If the user does not respond or says something that is not
# understood, the session will end.
return build_response(session_attributes, build_speechlet_response(
intent['name'], speech_output, reprompt_text, should_end_session))
我不知道,但我检查了我的代码,并且确实将session变量通过on_intent函数传递给每个函数,因为我只是剪切并粘贴原始代码并更改了意图和函数的名称。 但是,我链接到上面的其他文章最后有关于手动创建lambda处理程序的代码。我不知道我应该在哪里放置该代码。这可能是问题吗? –