您的問題很可能涉及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處理程序的代碼。我不知道我應該在哪裏放置該代碼。這可能是問題嗎? –