Things used in this project

Hardware components:
Echo
Amazon Alexa Amazon Echo
×1
Amazon echo dot
Amazon Alexa Echo Dot
×1
Software apps and online services:
Dp image kit 02
Amazon Alexa Alexa Skills Kit
Screen%20shot%202015 07 20%20at%206.10.26%20pm
Amazon Web Services AWS Lambda

Schematics

Voice User Interface
VUI for the skill
Untitled diagram 9jmppmgtax

Code

Intent SchemaJSON
The schema of user intents in JSON format.
{
  "intents": [
    {
      "slots": [
        {
          "name": "queryword",
          "type": "WORDS"
        }
      ],
      "intent": "SynonymIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}
Sample UtterancesTex
These are what people say to interact with your skill.
SynonymIntent what is a synonym for {queryword}
SynonymIntent a synonym for {queryword}
SynonymIntent for a synonym for {queryword}
SynonymIntent for a good synonym for {queryword}
SynonymIntent to tell me a synonym for {queryword}
SynonymIntent to give me a synonym for {queryword}
SynonymIntent about a synonym for {queryword}
SynonymIntent what is another word for {queryword}
SynonymIntent how else would I say {queryword}
SynonymIntent {queryword}
SynonymIntent a word for {queryword}
SynonymIntent how else would I say {queryword}
SynonymIntent for another word for {queryword}
AMAZON.HelpIntent help
AMAZON.StopIntent stop
AMAZON.CancelIntent cancel
AWS Lamda FunctionJavaScript
The mind of the project
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.9f977b1d-591f-4672-8341-60e2bed5a428") {
             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 = "Hi! I am Synonimi. I can find synonyms for words that you say to me. I accept only single words, for example morning, but not good morning.";
    // 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 = "I can help you if you just say, 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 = "Say a word you would like a synonym for and I will find it for you. Only single words please, for example morning, but not good morning.";
    // 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 = "Don't be shy, I don't bite , say a word.";
    
    var shouldEndSession = false;

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

function handleSessionEndRequest(callback) {
    var cardTitle = "Session Ended";
    var speechOutput = "It was my pleasure to be of your help!";
    // Setting this to true ends the session and exits the skill.
    var shouldEndSession = true;

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




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

  var query_url ='http://words.bighugelabs.com/api/2/01e7c1ef2013fa9cd27667fb3796914b/' + word + '/json'; //Add your api key here
  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);
          
           theResponseCallback(null, body);
       
        });
    }
    else if (res.statusCode==303) {
        console.log("RequestBody: " + res.statusMessage);
        query_url ='http://words.bighugelabs.com/api/2/01e7c1ef2013fa9cd27667fb3796914b/'+res.statusMessage+'/json'; //Put your api key here
        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);
              
               theResponseCallback(null, body);
            
            });
        });
    }
    else {
      console.log(`Got error: ${res.statusCode}`);
      theResponseCallback(new Error(res.statusCode));
    }
  }).on('error', (e) => {
    console.log(`Got error: ${e.message}`);
     theResponseCallback(new Error(e.message));
  });
}




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


   


    makeaRequest( intent.slots.queryword.value, function theResponseCallback(err, theResponseBody) {
        var speechOutput;

        if (err) {
            if (err=='undefiend'){
                 speechOutput = "Sorry, I can only handle single word, for example morning. Multiple words will not work.";
            }
            else {
                speechOutput = "Sorry, I am experiencing some problem with your request. Try again or try a different singular word.";
            }
            
        } else {
            
            var theResponse = JSON.parse(theResponseBody);
            
            speechOutput = "I got this for you: ";
            
            if (theResponse.hasOwnProperty('noun')) {
                speechOutput += intent.slots.queryword.value + ', used as a noun, ';
                maxLength = Object.keys(theResponse.noun.syn).length;
                if (Object.keys(theResponse.noun.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theResponse.noun.syn[i];
                
                }
                speechOutput += '. '
            }
            
            if (theResponse.hasOwnProperty('verb')){
                speechOutput += intent.slots.queryword.value + ', used as a verb, ';
                maxLength = Object.keys(theResponse.verb.syn).length;
                if (Object.keys(theResponse.verb.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theResponse.verb.syn[i];
                
                }
                speechOutput += '. '
            }
            
            if (theResponse.hasOwnProperty('adverb')){
                speechOutput += intent.slots.queryword.value + ', used as an adverb, ';
                maxLength = Object.keys(theResponse.adverb.syn).length;
                if (Object.keys(theResponse.adverb.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theResponse.adverb.syn[i];
                
                }
                speechOutput += '. '
            }
            
            if (theResponse.hasOwnProperty('adjective')){
                speechOutput += intent.slots.queryword.value + ', used as an adjective, ';
                maxLength = Object.keys(theResponse.adjective.syn).length;
                if (Object.keys(theResponse.adjective.syn).length>5)
                {
                    maxLength = 5;
                }
                
                for(var i=0;i<maxLength;i++) {
                if (i>0){
                    speechOutput += ", or ";
                }
                speechOutput +=  theResponse.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

8e87e99a3dbe904aea6e86228f33f803
Hannan Satopay
1 project • 3 followers
I am doing electronics engineering and I am interested in both hardware and software development.
Contact

Replications

Did you replicate this project? Share it!

I made one

Love this project? Think it could be improved? Tell us what you think!

Give feedback

Comments

Add projectSign up / Login