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 (i.e. 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.