13

I am creating a custom skill for Alexa. I want to close the session on AMAZON.StopIntent. How can I achieve this with below code?

const ExitHandler = {
  canHandle(handlerInput) {
    const request = handlerInput.requestEnvelope.request;
    return request.type === 'IntentRequest'
      && (request.intent.name === 'AMAZON.StopIntent');
  },
  handle(handlerInput) {
    return handlerInput.responseBuilder
      .speak('bye!')
      .reprompt('bye!')
      .getResponse();
  },
};
Deepak Mankotia
  • 4,404
  • 6
  • 30
  • 55

2 Answers2

36

Alexa ends the session when shouldEndSession flag is set to true in the response JSON.

... 
"shouldEndSession": true
...

In your response builder can you try with the helper function withShouldEndSession(true)

 return handlerInput.responseBuilder
      .speak('bye!')
      .withShouldEndSession(true)
      .getResponse();

Response builder helper functions are listed here

johndoe
  • 4,387
  • 2
  • 25
  • 40
7

In your code snippet you would end the session just by removing the reprompt line:

return handlerInput.responseBuilder
  .speak('bye!')
  .getResponse();

so the suggested solution below works but it's redundant:

return handlerInput.responseBuilder
      .speak('bye!')
      .withShouldEndSession(true)
      .getResponse();

The code above is often used in the opposite scenario, when you want to keep the session open without a reprompt:

return handlerInput.responseBuilder
      .speak('bye!')
      .withShouldEndSession(false)
      .getResponse();
German
  • 10,263
  • 4
  • 40
  • 56
  • How long are the session attributes maintained when .withShouldEndSession(false) flag is used? – thedreamsaver Feb 10 '19 at 16:01
  • Until the session times out. In a real device a few seconds, 8 secs if I remember correctly. In the simulator (Test tab on developer.amazon.com/alexa) a very long long time (basically it does not time out unless you're logged out of the page) – German Feb 13 '19 at 22:22
  • 2
    So practically what is the use of .withShouldEndSession(false) on a real device? – thedreamsaver Feb 15 '19 at 13:26
  • 2
    It's the only way to keep a session open allowing the device to listen for a new utterance without providing a reprompt. Basically you use it when you don't want to insist on getting an answer (via reprompt) but allowing the user to say something once – German Feb 15 '19 at 19:44