Add custom skill to amazon Alexa using lambda function

Posted By :Arun Singh |25th March 2019

Create a name that identifies the skill. This name customer will see in the skill store. We can modify this name before publish is necessary.
You can add multiple additional languages later. Amazon Alexa custom skill has interaction modal that defines how the user interacts with your skill. 

Interaction Models                                                                       

The request the skill can handle your request and give you an answer. The words the user can say like "Alexa: tell me the cricket score", "Alexa: play the latest Bollywood songs" etc.

In the custom model, you can define the requests and the words yourself. Your code will complete how your skill responds to those requests.

In pre-defined models, the possible requests and the utterances are already defined for you.  

Create Alexa Custom Skill

First, you have to need to log in to your Amazon developer portal https://developer.amazon.com/. If you don't have Amazon developer account you can create one free account. Now navigate to Alexa.
Now you can create new Alexa skill by using the Create Skill button. You have to insert the skill name and select the preferred language as well. Now select the custom tab and creates skill.

                                                                       

After that, you will navigate to the skill page.

                       

Alexa custom skill contains the following main features.

Invocation: Now select the Invocation tab, you can give the command in skill innovation name section which you start your custom skill.

Intents: In this tab section you can provide individual commands that you should provide within the skill to trigger different events. by default, you can see there are 3 Intents already defined like AMAZON.CencelIntent , AMAZON.HelpIntent and AMAZON.StopIntent.

Slots: You can add multiple slots for identified as the parameter to intents where you can pass in different values.

Endpoint: Endpoint section tab used for integrating newly build skills. Two options are there as AWS Lambda ARN and HTTPS. In this blog, we are going to use the AWS Lambda ARN option.

Create A New Intent

Click on Add button to create new Intent.

                                       

You have to give a proper name for your intent and create the custom intent. Next, we have to provide the sample utterance for this intent. This utterance decides the actual voice commands that the user would provide to execute this intent.

                                         

Click on add button inside slot type section.

                                                           

Now we have to build the lambda function that needs to integrate with this skill.

Develop the Lambda function 

First, you have to login into the AWS console and search the Lambda in the AWS service search bar. You can make a function by using the create function button. 

                                                         

I am using the author from scratch option with NodeJs. If you don't want an existing role, select the create a custom role or create a new role from the template. This AWS would create a default role for your lambda function. It will create default file index.js and provide you with a default code.

First I am creating one helper function as follows:

// These are the helper functions 
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,
    };
}
function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: '1.0',
        sessionAttributes,
        response: speechletResponse,
    };
}

Now the next function supports the session start and the skill launch.

function onSessionStarted(sessionStartedRequest, session) {
    console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}

function onLaunch(launchRequest, session, callback) {
    console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);
// Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

function getWelcomeResponse(callback) {
    const sessionAttributes = {};
    const cardTitle = 'Welcome';
    const speechOutput = 'Welcome to the light demo ' ;
   
    const repromptText = 'You can say: what switch to control ' ;
    const shouldEndSession = false;
callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

In this function, you can specify the welcome message and the re-prompt messages if the user does not give any voice input. It will use a helper function in the callback function. The lambda code creates a session for the current instance of the custom skill.

Now we specify the session end request onSessionEnded event:

function handleSessionEndRequest(callback) {
    const cardTitle = 'Session Ended';
    const speechOutput = 'Thank you for using light control , have a great day!';
    const shouldEndSession = true;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}


function onSessionEnded(sessionEndedRequest, session) {
    console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
    // Add cleanup logic here
}

The intent handler function is the most important function. In this function, we are mapping the Alexa custom skill's intents, into the lambda function.

function onIntent(intentRequest, session, callback) {
    console.log(`onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId}`);
const intent = intentRequest.intent;
    const intentName = intentRequest.intent.name;
// Dispatch to your skill's intent handlers
    if (intentName === 'AMAZON.HelpIntent') {
        getWelcomeResponse(callback);
    } else if (intentName === 'AMAZON.StopIntent') {
        handleSessionEndRequest(callback);
    } else if (intentName === 'lightcontrol') {
        var color = intent.slots.color.value;
        var lightstatus = intent.slots.lightstatus.value;
        lights(callback,color,lightstatus);
    }
}

Now we have to need to build the lights function where are going to interface with our IoT server.

function lights(callback,color,lightstatus) {
    
   var _switch = "";
   var _status = "";
   
   if(color == "red")
        _switch = "V1";
   else if(color == "green")
        _switch = "V2";
   else if(color == "orange")
        _switch = "V0";
   else
        _switch = "error";
        
    if(lightstatus == "on")
        _status = "1";
    else if(lightstatus == "off")
        _status = "0";
    
   var endpoint = "http://<myip>:8080/<myport>/update/"+_switch+"?value="+_status;
            var status ="offline";
            var body = "";
            http.get(endpoint, (response) => {
              console.log("Got response: " + response.statusCode)
              response.on('data', (chunk) => { body += chunk })
              response.on('end', () => {
              })
            });
   
    const sessionAttributes = {};
    
    //Get card title from data
    const cardTitle = 'device status';
    
    //Get output from data
    const speechOutput = 'The  ' + color + '  light is turned '+ lightstatus;
    const repromptText = '' ;
    const shouldEndSession = false;
callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

You can get the source code from this git repo http://https://github.com/priyalwalpita/alexa_lambda

Lambda function link with the custom skill and copy the ARN value of lambda function.

                                                            

Now go to your custom skill and select EndPoint section and paste the lambda function ARN value.

                                                          

Next step you have to need to copy the skill id and enter in your lambda function

Go to the lambda configuration section of the Alexa skill kit and add your customer skill id.

                                                        

Now save both the custom skill and lambda function. Next click on build model button to make a new build.

Alexa Custom Skill Testing

For custom, skill testing clicks on Test model button to enable the test of your skill.

      

For more information please visit here https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-an-aws-lambda-function.html.

Thanks for reading!


About Author

Arun Singh

Arun is a MEAN stack developer. He has a fastest and efficient way of problem solving techniques. He is very good in JavaScript and also have a little bit knowledge of Java and Python.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us