Chris Cazabon
Created December 6, 2016 © GPL3+

Chuck Norris Jokes

Immediate access to random Chuck Norris jokes...what else needs to be said

Beginner2 hours70

Things used in this project

Story

Read more

Code

aws lambda

JavaScript
Ask Chuck Norris a joke
'use strict';

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

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

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

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 Chuck Norris fan DB. ' +
        'You can ask me a joke';
    // 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 me a joke by saying, ' +
        'tell me a joke';
    const shouldEndSession = false;

    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

function handleSessionEndRequest(callback) {
    const cardTitle = 'Session Ended';
    const speechOutput = 'Thank you for playing with the Chuck Norris fan. Have a nice day!';
    // Setting this to true ends the session and exits the skill.
    const shouldEndSession = true;

    callback({}, buildSpeechletResponse(cardTitle, 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, speechOutput, null, shouldEndSession));
}

function GetJoke(intent, session, callback) {
    let favoriteColor;
    const repromptText = null;
    const sessionAttributes = {};
    let shouldEndSession = false;
    let speechOutput = '';
    var url = 'http://api.icndb.com/jokes/random';

    http.get(url, function(res){
    	res.setEncoding('utf8');
    	let rawData = "";
    	let processedData = "";
    	res.on('data', (chunk) => {
    		console.log(chunk);
    		try{
    			chunk = JSON.parse(chunk);
    			processedData += chunk.value.joke;
    		}
    		catch(e){
    			console.log(e);
    		}
    	});
	res.on('end', () => {
	    speechOutput = processedData;
    		shouldEndSession = true;
	    callback(sessionAttributes,
	         buildSpeechletResponse("Joke", speechOutput, 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 === 'GetJoke') {
        GetJoke(intent, session, callback);
    } else if (intentName === 'AMAZON.HelpIntent') {
        getWelcomeResponse(callback);
    } else if (intentName === 'AMAZON.StopIntent' || intentName === 'AMAZON.CancelIntent') {
        console.log('stop intent');
        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 authorized = 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 (!authorized || event.session.application.applicationId !== 'amzn1.ask.skill.ae6967fd-f7e6-4972-8bba-652a368b9617') {
            //callback('Invalid Application ID');
            handleUnauthorizedRequest(callback);
        }
        

        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);
    }
};

Alexa Skill Utterances

Plain text
how to invoke the skill
GetJoke a joke
GetJoke a random joke
GetJoke a chuck norris joke
GetJoke a random chuck norris joke

Credits

Chris Cazabon

Chris Cazabon

2 projects • 0 followers

Comments