Raj Bhanushali
Published © GPL3+

PokéType: An Alexa Skill

PokéType tells the user what type the pokémon that they specify is. Simple as that.

BeginnerShowcase (no instructions)1 hour1,450
PokéType: An Alexa Skill

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

Pokemon Server for Alexa

JavaScript
A node.js web server using the express library that listens for any calls from alexa and returns the appropriate response
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var verifier = require('alexa-verifier');
var app = express();

//check if request has a signaturecertchainurl (this is all for authentication)
app.use(function(req, res, next) {
  if (!req.headers.signaturecertchainurl) {
    return next();
  }
 
  // mark the request body as already having been parsed so it's ignored by 
  // other body parser middlewares 
  req._body = true;
  req.rawBody = '';

  //once we get data, add it on to our body
  req.on('data', function(data) {
    return req.rawBody += data;
  });

  //once its all over
  req.on('end', function() {

    var cert_url, er, error, requestBody, signature;

    //parse the raw body
    try {
      req.body = JSON.parse(req.rawBody);
    } catch (error) {
      er = error;
      req.body = {};
    }

    //get the information needed to verify the request
    cert_url = req.headers.signaturecertchainurl;
    signature = req.headers.signature;
    requestBody = req.rawBody;

    //verify the request
    verifier(cert_url, signature, requestBody, function(er) {

      if (er) {
        //if it fails, throw an error and return a failure
        console.error('error validating the alexa cert:', er);
        res.status(401).json({ status: 'failure', reason: er });
      } else {
        //proceed
        console.log("verified!")
        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
		},
		"sessionAttributes": {}
	}

	var info = req.body.request;

    console.log(info.type)

    //handle different types of requests
    if(info.type == 'LaunchRequest'){
        data.response.outputSpeech.text = "Alright. You can ask me the type of any Generation one pokemon. What pokemon's type would you like to know?"
        data.response.shouldEndSession = false;
        res.send(data);
    }

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

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

	var pokemon = info.intent.slots.pokemon.value; //retrieve the pokemon name sent with the alexa post request
	var sentenceBuild = pokemon + "\'s type is ";

	//make a request to the pokeapi
	request('http://pokeapi.co/api/v2/pokemon/' + pokemon, function(error, response, body){

		//check if the request was successful
		if (!error && response.statusCode == 200) {

			//parse the JSON string returned by the request
    		body = JSON.parse(body);
    		
    		var pokemon = body.name;
    		var sentence = pokemon + " is type ";

    		var typesarray = [];

    		//populate the array of types the pokemon is (can be more than one)
    		for(var i = 0;i<body.types.length;i++){
    			typesarray.push(body.types[i].type.name)
    		};

    		//check if there is more than one type 
    		if(typesarray.length > 1){

    			//iterate through the array of types to build the sentence
    			for(var n=0;n<typesarray.length;n++){

    				//check if this is the last type to display
    				if(n+1 == typesarray.length){

    					sentence += " and " + typesarray[n]
    					console.log(sentence);

    					//modify the sample data so Alexa can return our response
    					data.response.outputSpeech.text = sentence;

    					//send the data back to the echo
    					res.send(data);

    				}//if we're at the last type
    				else{
    					//build the sentence if there are more types left to display
    					sentence += typesarray[n], ", "
    				}//if there are more types to show

    			}//iterate through allt ypes

    		}//if there's more than one type
    		else{
    			console.log("one type");
    			sentence += typesarray[0];
    			data.response.outputSpeech.text = sentence;
    			res.send(data);
    		}//if theres only one type

    }//if the response was successful
    else if(response.statusCode == 404){
        console.log("there was a problem", response.statusCode)
        console.log("triggered");
        data.response.outputSpeech.text = "Sorry, I didn't quite get what pokemon's type you wanted. Could you repeat that again for me?"
        data.response.shouldEndSession = false;
        res.send(data);
    }
    		 
	}) //end of request to pokeapi

} //if its an intent request

})
var port = process.env.PORT || 3000;
app.listen(port, function () {

    console.log('Pokemon Server is up!');

});

Credits

Raj Bhanushali

Raj Bhanushali

2 projects • 0 followers

Comments