Intent Schema
{
  "intents": [
     {
      "intent": "TimeIntent"
     },
    {
      "intent": "AMAZON.StopIntent"
    }
    ]
}
Sample Utterances
TimeIntent How much time has passed
I only have one intent that I use to ask for the elapsed time.  And the StopIntent just helps me quit the skill.  All of the work happens in the Lambda function.
var tickingClockMP3 = 
    "https://alexafiles.blob.core.windows.net/demo/ticking-clock.mp3";
exports.handler = function (event, context) {
    var attributes = {};
    if (event.session.new) {
        attributes = { startTime: event.request.timestamp };
    }
    else {
        attributes = 
        { 
            startTime: event.session.attributes.startTime,
            timeDiff: (new Date(event.request.timestamp) - 
                       new Date(event.session.attributes.startTime)) / 1000
        };
    }
    try {
        if (event.request.type === "SessionEndedRequest") {
                    onSessionEnded(event.request, event.session);
                    context.succeed();
        }
        else if(event.request.type === "LaunchRequest")
            context.succeed(buildTickerResponse(attributes, false));
        else if(event.request.type === "IntentRequest") {
            var output = "" + (attributes.timeDiff || 0)  
                       + " seconds have past.
            context.succeed(buildTickerResponse(attributes, false, output));
        }
        else
            context.succeed(buildTickerResponse(attributes, false));
    } catch (e) {
        context.fail("Exception: " + e);
    }
};
function buildTickerResponse(attributes, shouldEndSession, output) {
    return {
        version: "1.0",
        sessionAttributes: attributes,
        response: {
            outputSpeech: {
                type: "SSML",
                ssml: output || " "
            },
            reprompt: {
                outputSpeech: {
                    type: "SSML",
                    ssml: "At anytime you can say... " +  
                          "Alexa, how much time has past?
"
                }
            },
            shouldEndSession: false
        }
    };
}
A few things to note here.  
- When creating MP3s, make sure you follow the rules about where they can be hosted and the allowed format. I used FFMPEG to fix it up: ffmpeg -i input.mp3 -b:a 48k -ar 16000 output.mp3.
 - While the SSML is playing the audio, the only way to get Alexa to hear you again, you have to say her name.
 - I store the startTime as an attribute. I have to copy that value over to the new attributes object I send back each time.
 
That's it!  You can now keep track of how much time has past since your skill started.

No comments:
Post a Comment