Paul Langdon
Published © CC BY-NC-SA

Alexa: The English Major (Thesaurus Skill)

Ask Alexa what another word for cow is and she will tell you. Alexa will make you sound smarter as you broaden your vocabulary.

IntermediateFull instructions provided1 hour2,069

Things used in this project

Hardware components

Amazon Echo
Amazon Alexa Amazon Echo
×1

Software apps and online services

Alexa Skills Kit
Amazon Alexa Alexa Skills Kit

Story

Read more

Schematics

Flow

Code

Alexa Intent Schema

JSON
{
  "intents": [
    {
      "intent": "SynonymIntent",
      "slots": [
        {
          "name": "queryword",
          "type": "AMAZON.LITERAL"
        }
      ]
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}

Sample Uterances

Tex
SynonymIntent what is another word for {flat|queryword}
SynonymIntent how else would I say {tired|queryword}
SynonymIntent what's a smart way to say {happy|queryword}
SynonymIntent what's another word for {car|queryword}
SynonymIntent how would an english major say {boat|queryword}
SynonymIntent {run|queryword}
SynonymIntent a word for {cow|queryword}
SynonymIntent how else would I say {cat|queryword}
SynonymIntent how would an english major say {dog|queryword}
SynonymIntent what is a synonym for {sad|queryword}
SynonymIntent what's a synonym for {patient|queryword}
SynonymIntent a synonym for {exhaustive|queryword}
SynonymIntent for a synonym for {ended|queryword}
SynonymIntent for a good synonym for {plan|queryword}
SynonymIntent to tell me a synonym for {hope|queryword}
SynonymIntent to give me a synonym for {slow|queryword}
SynonymIntent about a synonym for {smart|queryword}
SynonymIntent for another word for {brilliant|queryword}

AMAZON.HelpIntent help
AMAZON.HelpIntent help me
AMAZON.StopIntent stop
AMAZON.CancelIntent cancel

Lambda Service

JavaScript
// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.

var http = require('http');

exports.handler = function (event, context) {
    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 (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.[unique-value-here]") {
             context.fail("Invalid Application ID");
        }
        */

        if (event.session.new) {
            onSessionStarted({requestId: event.request.requestId}, event.session);
        }

        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,
                event.session,
                function callback(sessionAttributes, speechletResponse) {
                    context.succeed(buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === "IntentRequest") {
            onIntent(event.request,
                event.session,
                function callback(sessionAttributes, speechletResponse) {
                    context.succeed(buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request, event.session);
            context.succeed();
        }
    } catch (e) {
        context.fail("Exception: " + e);
    }
};

/**
 * 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);

    var intent = intentRequest.intent,
        intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    if ("SynonymIntent" === intentName) {
        getSyn(intent, session, callback);
    } else if ("AMAZON.HelpIntent" === intentName) {
        getHelpResponse(callback);
    } else if ("AMAZON.StopIntent" === intentName || "AMAZON.CancelIntent" === intentName) {
        handleSessionEndRequest(callback);
    } else {
        throw "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
}

// --------------- 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.
    var sessionAttributes = {};
    var cardTitle = "Welcome";
    var speechOutput = "Welcome to Thesaurus Rex. " +
        "I can find synonyms for words. Please use only single words, for example car, but not race car.";
    // 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.
    var repromptText = "You can get help by saying, help.";
    var shouldEndSession = false;

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

function getHelpResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.
    var sessionAttributes = {};
    var cardTitle = "Help";
    var speechOutput = "To use Thesaurus Rex you say a word you would like a synonym for. Only single words, for example car, but not race car.";
    // 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.
    var repromptText = "Go ahead, say a word.";
    //    "synonym for little";
    
    var shouldEndSession = false;

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

function handleSessionEndRequest(callback) {
    var cardTitle = "Session Ended";
    var speechOutput = "Thank you for using Thesaurus Rex to make yourself look smart. Have a nice day!";
    // Setting this to true ends the session and exits the skill.
    var shouldEndSession = true;

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




function makeTheoRequest(word, theoResponseCallback) {
    
   if (word===undefined) {
     theoResponseCallback(new Error('undefined'));
   }
   
  console.log(`Got word: ${word}`);

  var query_url ='http://words.bighugelabs.com/api/2/c/' + word + '/json';
  var body = '';
  var jsonObject;

  http.get(query_url, (res) => {
    console.log(`Got response: ${res.statusCode}`);
    if (res.statusCode==200) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
          body += chunk;
        });
        res.on('end', () => {
          console.log("RequestBody: " + body);
          jsonObject = JSON.parse(body);
          
           theoResponseCallback(null, body);
       
        });
    }
    else if (res.statusCode==303) {
        console.log("RequestBody: " + res.statusMessage);
        query_url ='http://words.bighugelabs.com/api/2/yourkey/' +res.statusMessage + '/json';
        console.log("url: " + query_url);
        http.get(query_url, (res2) => {
            console.log(`Got response: ${res2.statusCode}`);
            res2.setEncoding('utf8');
            res2.on('data', function (chunk) {
              body += chunk;
            });
            res2.on('end', () => {
              console.log("RequestBody: " + body);
              jsonObject = JSON.parse(body);
              
               theoResponseCallback(null, body);
            
            });
        });
    }
    else {
      console.log(`Got error: ${res.statusCode}`);
      theoResponseCallback(new Error(res.statusCode));
    }
  }).on('error', (e) => {
    console.log(`Got error: ${e.message}`);
     theoResponseCallback(new Error(e.message));
  });
}




function getSyn(intent, session, callback) {
    var repromptText = null;
    var sessionAttributes = {};
    var shouldEndSession = true;
    var speechOutput = "";
    var maxLength = 0;


   


    makeTheoRequest( intent.slots.queryword.value, function theoResponseCallback(err, theoResponseBody) {
        var speechOutput;

        if (err) {
            if (err=='undefiend'){
                 speechOutput = "Sorry, the Thesaurus service can only handle single word, for example car. Multiple words such as race car, marching band, tuna fish and golden retriever will not work.";
            }
            else {
                speechOutput = "Sorry, the Thesaurus service is experiencing a problem with your request. Try again or try a different singular word.";
            }
            
        } else {
            
            var theoResponse = JSON.parse(theoResponseBody);
            
            speechOutput = "Here's what I found: ";
            
            if (theoResponse.hasOwnProperty('noun')) {
                speechOutput += intent.slots.queryword.value + ', used as a noun, ';
                maxLength = Object.keys(theoResponse.noun.syn).length;
                if (Object.keys(theoResponse.noun.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theoResponse.noun.syn[i];
                
                }
                speechOutput += '. '
            }
            
            if (theoResponse.hasOwnProperty('verb')){
                speechOutput += intent.slots.queryword.value + ', used as a verb, ';
                maxLength = Object.keys(theoResponse.verb.syn).length;
                if (Object.keys(theoResponse.verb.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theoResponse.verb.syn[i];
                
                }
                speechOutput += '. '
            }
            
            if (theoResponse.hasOwnProperty('adverb')){
                speechOutput += intent.slots.queryword.value + ', used as an adverb, ';
                maxLength = Object.keys(theoResponse.adverb.syn).length;
                if (Object.keys(theoResponse.adverb.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theoResponse.adverb.syn[i];
                
                }
                speechOutput += '. '
            }
            
            if (theoResponse.hasOwnProperty('adjective')){
                speechOutput += intent.slots.queryword.value + ', used as an adjective, ';
                maxLength = Object.keys(theoResponse.adjective.syn).length;
                if (Object.keys(theoResponse.adjective.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theoResponse.adjective.syn[i];
                
                }
                speechOutput += '. '
            }
            
        }

        callback(sessionAttributes,
             buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
    });
    
}


// --------------- Helpers that build all of the responses -----------------------

function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",
            text: output
        },
        /*
        card: {
            type: "Simple",
            title: "SessionSpeechlet - " + title,
            content: "SessionSpeechlet - " + output
        },
        */
        reprompt: {
            outputSpeech: {
                type: "PlainText",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    };
}

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

Credits

Paul Langdon

Paul Langdon

49 projects • 316 followers
Working as a cloud architect for an IoT hardware company

Comments