Many of us now have some kind of voice assistant around the home, whether it be an Amazon Echo, Apple HomePod or a Google Home. It seems that voice is going to have a huge impact on the way we go about our daily lives, and as web developers we need to ask ourselves, what are the ways we can improve user experience by implementing voice into our websites and web applications?

In this tutorial, we are going to be building a simple Alexa skill that updates the news content on a website. The category type will depend on the voice input by the user. It would help if you have some experience with AWS already, but there is a lot of documentation out there to help you out if you get in a pickle.

What will I need?

First, find the files for this tutorial on GitHub.

You will also need to register for an Amazon Developer account and an AWS account.

Firebase will be used to store our user input, so make sure you sign up for a Firebase account. We will also be using the News API to get the latest news stories, so get yourself a free API key at newsapi.org.

Intents, utterances and slots

Here are the utterances we have setup inside the Alexa Developer Console for our skill. Feel free to add more

Once you are set up, navigate to developer.amazon.com/alexa/console/ask and click on Create Skill. The first thing we need to do is set up Intents, Utterances and Slot Types inside the Alexa Developer Console. An intent is what the user of the skill is trying to achieve. Utterances are specific phrases that users will say when talking to Alexa, for example: ‘What day is it?’. A slot is a variable that relates to an utterance, for example: ‘What time is it in {place}?’. This would make {place} the custom slot.

Select Intents from the left-hand side of the dashboard and click Add Intent. Make sure Create Custom Intent is selected and type ContentUpdate in the text box: this will now become our function name later on.

We now move on to utterances, which is where we are going to need to take the category of the news that the user wants to update to. We will be using category as our slot name and then set up the following utterances:

"Update {category}"
"{category} stories"
"Update to {category}"
"Set stories to {category}"

Finally, we need to create a slot type, where we will write out a couple of inputs that we expect to get from the user. From the left-hand side of the dashboard, click Add next to Slot Types. Type in ‘NewsType’ and click the ‘Create custom slot type’ button. Under Slot Values, you will need to add in some news categories. We will use Sport, Business, Technology and Politics. Once you are finished, make sure you have selected NewsType from the dropdown as the slot type for category.

AWS Lambda function

We will now head over to Lambda inside AWS. Select Create Function and then select the Blueprints radio box. Make sure you select the alexa-skill-kit-sdk-factskill from the list and click Configure. Give your function a name and then create a new role. When finished, click Create Function at the bottom of the page. You will need to select Alexa Skills Kit as a trigger for your function, then we can move onto the function itself. We won’t be using the built-in code editor for this project; instead we will be writing out the functions locally and then uploading a zip file. Make sure you copy the contents of the index.js file inside the Lambda editor, as we will paste this inside our local project.

Create a local project

We will start by creating a new Node project locally. Inside our own index.js file, we will paste the contents we just took from Lambda. We need to import Firebase and the Alexa SDK using NPM.

npm install alexa-sdk
npm install firebase

Make sure you include the references at the top of your index.js file.

const Alexa = require('alexa-sdk'); 
var Firebase = require("firebase");

You should have some default code already there, one of which is called ‘LaunchRequest‘. This is used to welcome the user to the skill. All you need to do here is change the welcome message to ‘Welcome to website update’.

    'LaunchRequest': function () {
        this.emit(':ask', 'welcome to website update');
    },

If you use the :tell command then Alexa will end the skill after the message, whereas if you use :ask then Alexa will listen for eight seconds for the next prompt. We will be using :ask, so that Alexa is ready to listen for our update prompt.

Firebase configuration

Next, we need to add our Firebase configuration details at the top of the index.js file.

  var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    projectId: "<PROJECT_ID>",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>"
  };
Firebase.initializeApp(config);

ContentUpdate function

Alexa skill: Simulator

The Alexa simulator is a great way of testing your skill on your machine without needing an Amazon Echo device

Earlier in the tutorial, we created an intent called ‘ContentUpdate’. This means we need to create a ContentUpdate function, where we will respond to the user input based on the Utterances we created. So, if the user said ‘Update to sport’, then this function would be called. We begin by creating a variable called categoryType, which takes the voice input of the user. We then store the category type inside the Firebase database and get Alexa to tell us the name of the category we updated to.

   'ContentUpdate': function() {
    var categoryType = this.event.request.intent.slots.category.value;
    if(Firebase.apps.length === 0) {
      Firebase.initializeApp(config);
    }
         Firebase.database().ref('/').set({
            preference: categoryType
            }).then((data)=>{
            Firebase.app().delete().then()
            }).catch((err) => {
            console.log(err);
            })
        this.emit(':ask', 'you updated to ' + categoryType);
},

After you save your index.js file, you will need to zip up the project. Navigate to the project folder from the command line and type the following command.

zip -r index.zip *

Head back to your function inside Lambda and scroll down to the Function Code section. From the drop-down box for code entry type, select ‘Upload a .zip file’. You will now be able to upload your zip file.

Before you test your project inside the Alexa simulator, take the ARN on the top right of the Lambda page and input this inside the Endpoint section of the Alexa console. To test your skill, all you need to say is ‘Open web update’ and Alexa will respond with ‘Welcome to web update’. If you now say ‘Update to sport’, Alexa should say ‘you updated to sport’. The word ‘sport’ should also appear under preference inside your Firebase database.

News page

Alexa skill: Final page

Here is what the final HTML page will look like. It will display the category that you requested through Alexa

Finally, download the news page I created (index.html) from the Alexa Project – HTML folder on GitHub.

Open up the main.js file and enter in your own Firebase configuration details on lines 1-8, like we did earlier in the tutorial.

You will also need to enter your News API key from newsapi.org on line 11 of the main.js file.

var myAPIKey = "<YourAPIKey">;

If you now open the index.html file, it should load in some news stories from your chosen category. Every time you tell Alexa to update with a new category (sport, technology, business or politics), the news story category on the page will change.

Alexa, onwards!

This is only a small example of what you could achieve with Alexa and hopefully gives you a good foundation for any future voice projects. You could always add in more slot values to get more categories from the API or even update the project so that it pulls in your own website news/posts. I can’t wait to see how web and app developers will include Alexa in their projects. 

This article was originally published in issue 313 of net, the world’s best-selling magazine for web designers and developers. Buy issue 313 here or subscribe here.

Related articles: