Siddharth Bhanushali
Created November 22, 2016

Cat Facts!

Want to know more about your feline friend? Look no further. This skill returns a random cat fact once invoked.

152
Cat Facts!

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

Code

The Server

JavaScript
this is the main server code that you can deploy on a cloud hosting service. be sure to install all the dependencies!
var express = require('express');
var bodyParser = require('body-parser');
var verifier = require('alexa-verifier');
var request = require('request');
var app = express();
 
 //make sure to verify the request
app.use(function(req, res, next) {
  if (!req.headers.signaturecertchainurl) {
    return next();
  }

  req._body = true;
  req.rawBody = '';
  req.on('data', function(data) {
    return req.rawBody += data;
  });
  req.on('end', function() {
    var cert_url, er, error, requestBody, signature;
    try {
      req.body = JSON.parse(req.rawBody);
    } catch (error) {
      er = error;
      req.body = {};
    }
    cert_url = req.headers.signaturecertchainurl;
    signature = req.headers.signature;
    requestBody = req.rawBody;
    verifier(cert_url, signature, requestBody, function(er) {
      if (er) {
        console.error('error validating the alexa cert:', er);
        res.status(401).json({ status: 'failure', reason: er });
      } else {
        next();
      }
    });
  });
});


app.use(bodyParser.json());

app.get('/', function(req, res){
	res.send("hello");
})

app.post('/', function(req, res){

	//sample data to make alexa return a response
	var data = {
		"version": "1.0",
		"response": {
			"outputSpeech": {
				"type": "PlainText",
				"text": "Please work!"
			},
			"shouldEndSession": true
		},
        "reprompt": {
              "outputSpeech": {
                "type": "PlainText",
                "text": "Want another fact?"
              }
            },
		"sessionAttributes": {}
	}

	var info = req.body.request;

    //handle different types of requests
    if(info.type == 'LaunchRequest'){
         data.response.outputSpeech.text = "Hey! Ask me for a cat fact."
         data.response.shouldEndSession = false;
         res.send(data);
         
    }

    else if(info.type=='SessionEndedRequest'){}

    else if(info.type=='IntentRequest'){


    if(info.intent.name == "AMAZON.HelpIntent"){
        console.log("help intent");
        data.response.outputSpeech.text = "You can ask me for a random cat fact."
        data.response.shouldEndSession = false;
        res.send(data);
    }

    else if(info.intent.name == "AMAZON.CancelIntent" || info.intent.name == "AMAZON.StopIntent"){
        console.log("cancel intent");
        data.response.outputSpeech.text = "Good-bye."
        data.response.shouldEndSession = true;
        res.send(data);
    }

    else if(info.intent.name == "GetFact"){

        //use request, an HTTP library to send an HTTP request to the cat facts api
        request('http://catfacts-api.appspot.com/api/facts?number=1',   function (error, response, body) {
          if (!error && response.statusCode == 200) {
            console.log(JSON.parse(body).facts[0]) 
            //send the fact after retrieving it from the api
            var fact = JSON.parse(body).facts[0];
            data.response.outputSpeech.text = fact
            data.response.shouldEndSession = true;
            res.send(data);
          }
          else{
            data.response.outputSpeech.text = fact
            data.response.shouldEndSession = true;
            res.send("whoops! there was a problem getting the fact.");
          }
        });

    }

}

})
var port = process.env.PORT || 3000;
app.listen(port, function () {
  
    console.log('cat server is up!');

});

Credits

Siddharth Bhanushali

Siddharth Bhanushali

1 project • 0 followers

Comments