Search code examples
aws-lambdaalexa-skills-kitvoice

How do I detect when a user ends interaction with alexa?


Title says it all. Is there a way for me to detect when a user ends interaction with Alexa? I'd like to save the user's configuration by this time. Instead of hitting the database per request.


Solution

  • You can do it by handling the SessionEndedRequest.

    These are snippets from https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs/wiki/Developing-Your-First-Skill, which will guide you in developing your first Alexa Skill.

    const SessionEndedRequestHandler = {
        canHandle(handlerInput) {
            return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';
        },
        handle(handlerInput) {
            //any cleanup logic goes here
            return handlerInput.responseBuilder.getResponse();
        }
    };
    
    'use strict';
    
    const Alexa = require('ask-sdk-core');
    // use 'ask-sdk' if standard SDK module is installed
    
    // Code for the handlers here
    
    let skill;
    
    exports.handler = async function (event, context) {
      console.log(`REQUEST++++${JSON.stringify(event)}`);
      if (!skill) {
        skill = Alexa.SkillBuilders.custom()
          .addRequestHandlers(
            SessionEndedRequestHandler,
          )
          .addErrorHandlers(ErrorHandler)
          .create();
      }
      
      return skill.invoke(event,context);
    }