在Alexa Intent Handler中进行API调用

时间:2018-05-28 00:25:37

标签: node.js alexa alexa-skills-kit alexa-skill

我正在尝试创建一个Alexa技能,进行API调用以检索天气数据。无论我尝试过什么,我都无法使用此代码。这似乎是一件不会很难的事情,我只是无法弄清楚如何将API调用放入intent处理程序中。我的节点技能也生锈也许没有帮助......

/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/
/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills
 * nodejs skill development kit.
 * This sample supports multiple lauguages. (en-US, en-GB, de-DE).
 * The Intent Schema, Custom Slots and Sample Utterances for this skill, as well
 * as testing instructions are located at https://github.com/alexa/skill-sample-nodejs-fact
 **/

'use strict';
const Alexa = require('alexa-sdk');

//Replace with your app ID (OPTIONAL).  You can find this value at the top of your skill's page on http://developer.amazon.com.
//Make sure to enclose your value in quotes, like this: const APP_ID = 'amzn1.ask.skill.bb4045e6-b3e8-4133-b650-72923c5980f1';
const APP_ID = undefined;

const SKILL_NAME = 'Space Facts';
const GET_FACT_MESSAGE = "Here's your fact: ";
const HELP_MESSAGE = 'You can say tell me a space fact, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';

const handlers = {
    'LaunchRequest': function () {
        this.emit('GetWeatherIntent');
    },
    'GetWeatherIntent': function () {
        var mythis=this;
        var city=this.event.request.intent.slots.city.value;

        var weather='{"coord":{"lon":-104.98,"lat":39.74},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":300.92,"pressure":1012,"humidity":23,"temp_min":297.15,"temp_max":303.15},"visibility":16093,"wind":{"speed":4.1,"deg":360},"clouds":{"all":75},"dt":1527451080,"sys":{"type":1,"id":539,"message":0.0055,"country":"US","sunrise":1527420953,"sunset":1527473936},"id":5419384,"name":"Denver","cod":200}';

        getWeather(city, function (output) {
            weather=output;
            var speechText = 'The temperature in ';
            speechText += mythis.event.request.intent.slots.city.value;
            speechText += ' is ';
            speechText += toFahrenheit(JSON.parse(weather).main.temp);
            speechText += ' degrees ';
            speechText += 'Fahrenheit'; //TODO: add Celsius capability
            mythis.response.cardRenderer(SKILL_NAME, speechText);
            mythis.response.speak(speechText);
            mythis.emit(':responseReady');
            mythis.emit(output);
        });



    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = HELP_MESSAGE;
        const reprompt = HELP_REPROMPT;

        this.response.speak(speechOutput).listen(reprompt);
        this.emit(':responseReady');
    },
    'AMAZON.CancelIntent': function () {
        this.response.speak(STOP_MESSAGE);
        this.emit(':responseReady');
    },
    'AMAZON.StopIntent': function () {
        this.response.speak(STOP_MESSAGE);
        this.emit(':responseReady');
    },
};

exports.handler = function (event, context, callback) {
    const alexa = Alexa.handler(event, context, callback);
    alexa.APP_ID = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var getTemp = function (city) {
    return getWeather(city).main.temp;
}

var getWeather = function(city, callback) {
    var URL='https://api.openweathermap.org/data/2.5/weather?q='+city+'&APPID=[MY API KEY]';
    const https = require('https');

    https.get(URL, (res, callback) => {
        console.log('statusCode:', res.statusCode);
        console.log('headers:', res.headers);

        var output='';

        res.on('data', (d) => {
            output += d;
        });

        res.on('end', callback(output));

    }).on('error', (e) => {
      console.error(e);
    });
}

var toFahrenheit = function(kelvins) {
    return Math.round(9.0/5.0*(kelvins-273)+32);
}

1 个答案:

答案 0 :(得分:0)

'结束'您的事件处理程序事件处于错误的位置,一种可以编写函数的方法(使用JSON.parse从https.get读取缓冲区并使用结果调用回调函数):

var getWeather = function(city, callback) {
  const url='https://api.openweathermap.org/data/2.5/weather?q='+city+'&APPID=<your api key>';
  const https = require('https');

  https.get(url, res => {
    var output='';

    res.on('data', d => {
      output += d;
    });
    res.on('error', console.error);
    res.on('end', () => {
      callback(JSON.parse(output))
    });
  });
}


// example usage: 
getWeather('london', res => {
  console.log(res);
})