Chris Cazabon
Created December 9, 2016

Random Vocabulary

I like words, I like playing word games. This skill fetches random words with optional length parameter, reads and spells it out to you

46

Things used in this project

Hardware components

Echo Dot
Amazon Alexa Echo Dot
for testing
×1

Software apps and online services

Alexa Skills Kit
Amazon Alexa Alexa Skills Kit
for building the skill
AWS Lambda
Amazon Web Services AWS Lambda
for the backend code

Story

Read more

Code

lambda service code

JavaScript
this is the aws service that provides the service for the skill
'use strict';

/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
 * The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as
 * testing instructions are located at http://amzn.to/1LzFrj6
 *
 * For additional samples, visit the Alexa Skills Kit Getting Started guide at
 * http://amzn.to/1LGWsLG
 */

let http = require('http');
// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: 'SSML',
            ssml: '<speak>'+output.ssml+'</speak>',
        },
        card: {
            type: 'Simple',
            title: `${title}`,
            content: `${output.text}`,
        },
        reprompt: {
            outputSpeech: {
                type: 'PlainText',
                text: repromptText,
            },
        },
        shouldEndSession,
    };
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: '1.0',
        sessionAttributes,
        response: speechletResponse,
    };
}


// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    const sessionAttributes = {};
    const cardTitle = 'Welcome';
    const speechOutput = 'Welcome to the Alexa Skills Kit sample. ' +
        'Please tell me the length of a word to get by saying something like, get a 5 letter word';
    // If the user either does not reply to the welcome message or says something that is not
    // understood, they will be prompted again with this text.
    const repromptText = 'Please ask for a random word by saying, ' +
        'give me a random word';
    const shouldEndSession = false;

    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, {ssml:speechOutput, text:speechOutput}, repromptText, shouldEndSession));
}

function handleSessionEndRequest(callback) {
    const cardTitle = 'Session Ended';
    const speechOutput = 'Thank you for trying the Alexa Skills Kit sample. Have a nice day!';
    // Setting this to true ends the session and exits the skill.
    const shouldEndSession = true;

    callback({}, buildSpeechletResponse(cardTitle, {ssml:speechOutput, text:speechOutput}, null, shouldEndSession));
}

function handleUnauthorizedRequest(callback) {
    const cardTitle = 'Unauthorized';
    const speechOutput = 'This service is not authorized by this application, or is temporarily deactivated. Have a nice day!';
    // Setting this to true ends the session and exits the skill.
    const shouldEndSession = true;

    callback(null, buildSpeechletResponse(cardTitle, {ssml:speechOutput, text:speechOutput}, null, shouldEndSession));
}


function getRandomWord(intent, session, callback) {
    let favoriteColor;
    const repromptText = null;
    const sessionAttributes = {};
    let shouldEndSession = false;
    let speechOutput = '', cardText = '';
    let length = (intent.slots.Number.value !== undefined) ? intent.slots.Number.value : false;
    let url = 'http://www.setgetgo.com/randomword/get.php';
	let special = '';
	console.log(intent.slots.Number.value);
    console.log(length);
    if(length !== false){
        special = length+' letter';
        url += '?len='+length;
    }

    http.get(url, function(res){
    	res.setEncoding('utf8');
    	let rawData = "";
        
    	res.on('data', (chunk) => {
    		speechOutput = 'Your '+special+' word is '+chunk+'. <say-as interpret-as="spell-out">'+chunk+'</say-as>. '+chunk+'.';
    		cardText = 'Your '+special+' word is '+chunk+'.';
    		shouldEndSession = true;
    	});
	res.on('end', () => {
	  // Setting repromptText to null signifies that we do not want to reprompt the user.
	    // If the user does not respond or says something that is not understood, the session
	    // will end.
	    callback(sessionAttributes,
	         buildSpeechletResponse(intent.name, {ssml:speechOutput, text:cardText}, repromptText, shouldEndSession));	       	
	});


  
    });
}


// --------------- Events -----------------------

/**
 * Called when the session starts.
 */
function onSessionStarted(sessionStartedRequest, session) {
    console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}

/**
 * Called when the user launches the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);

    // Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    console.log(`onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId}`);

    const intent = intentRequest.intent;
    const intentName = intentRequest.intent.name;

    if (intentName === 'RandomVocab') {
        getRandomWord(intent, session, callback);
    } else if (intentName === 'AMAZON.HelpIntent') {
        getWelcomeResponse(callback);
    } else if (intentName === 'AMAZON.StopIntent' || intentName === 'AMAZON.CancelIntent') {
        handleSessionEndRequest(callback);
    } else {
        throw new Error('Invalid intent');
    }
}

/**
 * Called when the user ends the session.
 * Is not called when the skill returns shouldEndSession=true.
 */
function onSessionEnded(sessionEndedRequest, session) {
    console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
    // Add cleanup logic here
}


// --------------- Main handler -----------------------

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = (event, context, callback) => {
    let activated = true;
    try {
        console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);

        /**
         * Uncomment this if statement and populate with your skill's application ID to
         * prevent someone else from configuring a skill that sends requests to this function.
         */
        
        if (!activated || (event.session.application.applicationId !== 'amzn1.ask.skill.a4057d1f-b7bb-442e-9a8a-066f3c5628ea')) {
            console.log('unauthorized');
            handleUnauthorizedRequest(callback);
        }else{
        

            if (event.session.new) {
                onSessionStarted({ requestId: event.request.requestId }, event.session);
            }
    
            if (event.request.type === 'LaunchRequest') {
                onLaunch(event.request,
                    event.session,
                    (sessionAttributes, speechletResponse) => {
                        callback(null, buildResponse(sessionAttributes, speechletResponse));
                    });
            } else if (event.request.type === 'IntentRequest') {
                onIntent(event.request,
                    event.session,
                    (sessionAttributes, speechletResponse) => {
                        callback(null, buildResponse(sessionAttributes, speechletResponse));
                    });
            } else if (event.request.type === 'SessionEndedRequest') {
                onSessionEnded(event.request, event.session);
                callback();
            }
        }
    } catch (err) {
        callback(err);
    }
};

Credits

Chris Cazabon

Chris Cazabon

2 projects • 0 followers

Comments