您的问题很可能涉及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))