简体   繁体   中英

How to use session-specific variables in Alexa Skills?

I'm developing a fact skill for Alexa using their SpaceGeek template. The template itself is very straight forward, but I'm trying to improve it by making sure the facts used will not come up again in the same session. So I delete the element after it is used. However, now it comes to a problem that, those elements deleted in the session won't even come up in future sessions. So I assume the global variable stays in the backend and thus created a copy-array as below. But it still won't work. So after using all the facts once, I'll always get "That's all the facts we have for now". Even if I start a new session. Any help will be appreciated.

    function handleNewFactRequest(response) {
       var COPY_FACTS= SOME_FACTS.splice(0);
       if(COPY_FACTS.length>0){
           var factIndex = Math.floor(Math.random() * COPY_FACTS.length);
           var fact = COPY_FACTS[factIndex];

           // Create speech output
           var speechOutput = "Here's your random fact: " + fact + " would you like more?";
           var repromptOutput = "would you like more random facts?";
           COPY_FACTS.splice(factIndex, 1);
           response.ask(speechOutput, repromptOutput);
      }else{
           var speechOutput = "That's all the facts we have for now.";
           response.tell(speechOutput);
      }
    }

The correct way to handle this is to store your array as a session variable, rather than as a global object. An example which shows how to do this in detail would be the History Buff example skill , but generally speaking, the process is as follows:

When handling the user's first request, create an object which contains any variables you want to maintain throughout the session and assign it to session.attributes . You'd want to store your array as a property on that object.

Then, in future event handlers, you will be able to access those stored session-specific variables (ie your array) as properties of that session.attributes object.

In the linked example, in subsequent intent handlers they include the snippet sessionAttributes = session.attributes to provide a more convenient handle to access those variables.

Instead of using splice(0) to duplicate the array, use slice() .

The splice() function changes the original array, where as slice() does not. See Sirko's response on this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM