concept state in category alexa

This is an excerpt from Manning's book Voice Applications for Alexa and Google Assistant.
Another approach is to use state management. If you come from a computer background, “state” is familiar to you. If you’re a self-trained developer, you may not know what a “state machine” refers to specifically, but you’ve likely worked with one in the past.
Figure 5.3 Handlers are mapped to request types, intents, and state.
![]()
To implement state handling in the skill, we need to first have the states in the code. A best practice is to define a top-level object that contains all of the states. This allows you to see and understand clearly all the states that are available and that might guide the user flow and the intent handling. State management in skills can be confusing with all the back and forth between states, so it’s best to do what you can to keep it simpler.
Listing 5.3 Handling an affirmative user response (./lambda/custom/index.js)
const TooMuchYesIntentHandler = { canHandle(handlerInput) { const intentName = "AMAZON.YesIntent"; const attributes = handlerInput.attributesManager.getSessionAttributes(); #1 return handlerInput.requestEnvelope.request.type === "IntentRequest" && #1 handlerInput.requestEnvelope.request.intent.name === intentName && #1 attributes.state === states.TOO_MUCH_CONFIRMATION; #1 }, handle(handlerInput) { const speech = "Okay, " + pluck(WellRestedPhrases.tooMuch); const attributes = handlerInput.attributesManager.getSessionAttributes(); #2 delete attributes.state; #2 handlerInput.attributesManager.setSessionAttributes(attributes); #2 return handlerInput.responseBuilder .speak(speech) .getResponse(); } }; exports.handler = Alexa.SkillBuilders.standard() .addRequestHandlers( TooMuchYesIntentHandler, #3 WellRestedIntentHandler, StopOrCancelIntentHandler, LaunchRequestHandler ) .lambda(); #1 Checks that all conditions are fulfilled #2 Resets the attributes to remove the state #3 Registers the new handlersThe first handler is for when users respond in the affirmative. Its
canHandlemethod requires that the intent isAMAZON.YesIntentand that the user is in the “too much sleep” state. Because the handler has this extra level of specificity arising from the state, we register the handler at the very beginning. In the fulfillment of the intent, we’ll create the response as normal and remove the state from the session attributes, because the user has now closed the conversation by saying that Alexa heard correctly.