Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
speechAssets
src
tests
LICENSE.txt
README.md
publish.sh

README.md

Alexa Cookbook

Hello World


Intro

This is a simple tutorial to introduce a simple Alexa skill and code.

Pre-requisites:

Tutorial Steps

Code

  1. Login to AWS and verify the region at the top right is set to the Ireland or N. Virginia Region region.
  2. Click Lambda and then Create a Lambda function Do not select the default Blank blueprint.
  3. Locate and click on the alexa-skill-kit-sdk-factskill skill template (hint: search for fact )
  4. Click in the empty square and choose the trigger Alexa Skills Kit and click Next.
  5. Give your function the name HelloWorld
  6. Paste in the source code from src/index.js :
        var Alexa = require('alexa-sdk');
    
        exports.handler = function(event, context, callback) {
            var alexa = Alexa.handler(event, context);
            alexa.registerHandlers(handlers);
            alexa.execute();
        };
    
        var handlers = {
            'LaunchRequest': function () {
                this.emit('MyIntent');
            },
    
            'MyIntent': function () {
                this.emit(':tell', 'Hello World from Alexa!');
            }
        };
    
  7. Just below the code editor, create or re-use an execution role, such as lambda_basic_execution
  8. Click Next and create the function.
  9. Make note of the Lambda ARN, shown near the top right, such as
  • arn:aws:lambda:us-east-1:333304287777:function:HelloWorld

Skill

  1. Login to [developer.amazon.com] and click Alexa, then Alexa Skills Kit
  2. Create a new Skill called HelloWorld with invocation name hello world.
  3. Paste in the IntentSchema.json :
    {
      "intents": [
        {
          "intent": "MyIntent",  "slots":[]
        },
    
        {
          "intent": "AMAZON.HelpIntent"
        },
        {
          "intent": "AMAZON.StopIntent"
        },
        {
          "intent": "AMAZON.CancelIntent"
        }
      ]
    }
    
  4. Paste in the SampleUtterances.txt :
    MyIntent hello
    
  5. Configure the skill endpoint with the AWS Lambda ARN previously created.

Test

  • Type or say "open hello world" and Alexa should reply with "hello world from Alexa"
  • Modify code within the Lambda function editor to have Alexa say something besides Hello World.
  • Test and hear Alexa say the new response.

Lab 1

This lab will have you extend your skill by adding new Intents. First we will add the intent to the skill definition.

  1. Within the Dev Portal skill definition, click on the Interaction Model page.
  2. Review the Intent Schema panel, notice the three lines that define the MyIntent schema.
  3. Create a new intent definition, similar to MyIntent called WhatsUpIntent
  4. Within the Sample Utterances box, add a sample for the new intent, such as WhatsUpIntent what is up

Next, we will add a handler to the AWS Lambda function

  1. Within the AWS Lambda Console console, review your function code
  2. Within the handlers section, notice the three lines of code that handle the MyIntent event.
  3. Create a new handler function for the WhatsUpIntent (hint: copy & paste the MyIntent function and change MyIntent to WhatsUpIntent)
  4. Customize the message Alexa will say
  5. Change the emit from a :tell to an :ask. This :ask will keep the session open after Alexa responds.
  6. Test your new skill by opening the skill and saying "what is up"

Finally, we will add handlers for default requests such as Help, Stop, and Cancel

  1. Within the Lambda code, add handlers for the following events:
  • AMAZON.HelpIntent AMAZON.StopIntent AMAZON.CancelIntent
  1. Customize the message in each handler
  2. Ensure the Help handler action is :ask, while the Cancel and Stop handlers are :tell.

Feel free to add additional intents and handlers to make your skill unique.

Lab 2

This lab will have you add Intents with Slots. Click to your skill's Interaction Model, Intent Schema box. Review your existing Intent Schema. The final two characters in this JSON are ] } Click your cursor just before these two characters. Type a comma, then press Enter three times.

We will add a new Intent called MyNameIsIntent; and define a slot with the intent.

Copy and paste in the following new Intent definition:

    {
      "intent": "MyNameIsIntent",
      "slots":[
        {
          "name":"firstname",
          "type":"AMAZON.GB_FIRST_NAME"
        }
      ]
    }

Also add the following line to your Sample Utterances: MyNameIsIntent my name is {firstname}

  • Create another handler within your AWS Lambda function for MyNameIsIntent that stores the firstname slot value in a local variable:
  • Be sure this line of code exists inside the scope of this new Intent Handler.

var myName = this.event.request.intent.slots.firstname.value;

  • Repeat the name back to the user as part of the MyNameIsIntent handler.

For example, you could have the MyNameIsIntent handler do this :

this.emit(':ask', 'hello, ' + myName, 'try again');

Lab 3

Add short MP3 audio clips to your output via SSML.

SSML markup tags can be interspersed directly within normal speech output text.

You can test these within the Voice Simulator textbox, just above the Service Simulator textbox on the skill TEST page.

Examples:

There is a three second pause here <break time="3s"/>  then the speech continues.

<audio src='https://s3.amazonaws.com/my-ssml-samples/Flourish.mp3' />
<audio src='https://s3.amazonaws.com/my-ssml-samples/cheap_thrills.mp3' />
<audio src='https://s3.amazonaws.com/my-ssml-samples/this_is_what_you_came_for.mp3' />

For example, you could make Alexa say words and sound effects by preparing an output string like this:

var say = " hello <audio src='https://s3.amazonaws.com/my-ssml-samples/Flourish.mp3' /> world";
this.emit(':ask',say, 'try again');

Read the documentation page on how to prepare and host MP3 audio clips in the required format. You can use a tool such as "ffmpeg" or "vlc" to down-sample your existing MP3 content. You can host the MP3s on your own website, or within the AWS S3 service. Simply create an S3 bucket, upload your files, and set the files to be public, and note file properties which contain the public URL to the file.

Lab 4

Your skill code can create a custom response based on the geographic region of the user, whether they are in US, GB, or DE.

You can add conditional logic like this:

    var locale = this.event.request.locale;

    var say = "";

    if (locale == 'en-GB'){
            say = 'hiya';

    } else if (locale == 'de-DE') {
            say = 'guten tag';

    } else {
            say = 'hello';
    }
    this.emit(':ask', say, 'try again');

Based on Dean Bryen's post How to Build a Multi-Language Alexa Skill

Lab 5

Add session attributes to your skill to remember things.

Based on your work in Lab 2, your lambda function now has a MyNameIsIntent handler.

Add the following line of code after you have retrieved the firstname slot value into the myName variable:

this.attributes['name'] = myName;

Now, locate the handler for the AMAZON.StopIntent that you defined in Lab 1. Within this handler, replace the code with the following:

var myName = '';
if (this.attributes['name']) {
    myName = this.attributes['name'];
}
this.emit(':tell', 'goodbye, ' + myName, 'try again');

Test your skill. Say "my name is sam". Then say "stop". You should hear a personalized goodbye message.

Lab 6

Add DynamoDB to your skill. Within your exports.handler, add one new line:

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);


    alexa.dynamoDBTableName = 'YourTableName'; // creates new table for userid:session.attributes

    alexa.registerHandlers(handlers);
    alexa.execute();
};

Add permissions for your Lambda function to access DynamoDB:

  1. From within AWS Console, click on IAM, then Roles, then lambda_basic_execution:
  2. Click "Attach Policy" and select a DynamoDB policy such as AmazonDynamoDBFullAccess
  3. Test your skill by executing a unit test from the AWS Lambda console.
  4. You may see an error such as "errorMessage": "Requested resource not found". This is okay.
  5. Wait 60 seconds, then navigate to AWS DynamoDB and click on Tables.
  6. You should see a table called YourTableName.
  7. Return to the Lambda console, and test your function again. It should now succeed.
  8. Return to DynamoDB, and click on Tables, then YourTableName
  9. Click on Items and you should now see a record that has "amzn1.ask.account" in the userId column
  10. Click on this record to review the data stored for this userId. You should see a mapAttr object that stores the state of your session.attributes.

Note:

  • The session.attribute state is persisted in Dynamo only when your skill ends.
  • The previous session.attributes is loaded again when the user starts the skill again.
  • The first 25GB of data stored in DynamoDB is always free.

Lab 7

Controlling IOT Devices

Following the blog post, setup a virtual device called waterPump, and build a skill to turn the pump desired state to 1 or 0 based on a slot value.

Lab 8

Account Linking allows your users to enable your skill, and then enter their credentials to your existing website or directory. This is how Uber and Domino's Pizza links an Alexa user to a user within their service. The skill can gain access to user attributes, and the skill can make authenticated calls into the service using an OAuth token that is automatically kept for the user with their enabled skill.

Account linking is required as a component of a Smart Home skill.

Setup Account Linking to "Login with Amazon" as in the blog post. Welcome the user by saying their full name.

Lab 9

Using the alexa-sdk

  1. Search the internet for npm alexa sdk
  2. Click the first link to open the alexa-sdk node module project page
  3. Read and scroll through the documentation and try out the code snippets in your skill.

Back to the Workshop Folder - Cookbook Home Page

You can’t perform that action at this time.