2017-08-02 69 views
0

所以我讀過這篇文章:Adding session attributes in Python for Alexa skills它解決了我能夠存儲多個會話變量的問題。在Python中調用會話變量以獲得Alexa技能

但是,現在我的問題是回憶這些會話變量在另一個函數。這裏是什麼,我試圖做一個例子:

speech_output = "Your invoice for " + session['attributes']['invoiceAmount'] + \ 
       " dollars." 

我也試過這種代碼來設置本地變量session變量:

invoice_amount = int(session['attributes']['invoiceAmount']) 

我在做什麼錯?我之前從未使用Python進行過編程,所以我只是通過查看Amazon最喜歡的顏色示例代碼並根據自己的需要進行調整來教自己。我實際上有三個會話變量,但顯然如果我可以讓他們中的一個工作,我可以找出另一個。謝謝。

回答

0

您的問題很可能涉及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)) 
+0

我不知道,但我檢查了我的代碼,並且確實將session變量通過on_intent函數傳遞給每個函數,因爲我只是剪切並粘貼原始代碼並更改了意圖和函數的名稱。 但是,我鏈接到上面的其他文章最後有關於手動創建lambda處理程序的代碼。我不知道我應該在哪裏放置該代碼。這可能是問題嗎? –

1

我真的很抱歉,我終於明白了錯誤。我的會話變量存儲整數,但我試圖連接這些整數與文本。我沒有意識到我需要先將它們轉換爲字符串。我轉換爲一個字符串,並解決了我所有的問題。

+0

你可以刪除這個問題嗎? –

+0

它說我不應該刪除問題,當我點擊刪除。 –