Выполнение вызовов API в обработчике Alexa - PullRequest
0 голосов
/ 28 мая 2018

Я пытаюсь создать навык Alexa, который выполняет вызов API для получения данных о погоде.Независимо от того, что я пробовал, я не могу заставить этот код работать.Это похоже на то, что не сложно, я просто не могу понять, как встроить вызов API в обработчик намерений.Вероятно, не поможет, что мои навыки на Node тоже ржавые ...

/* 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 голосов
/ 28 мая 2018

Ваш обработчик события 'end' находится в неправильной позиции, так что вы могли бы написать свою функцию (чтение буфера из https.get с помощью JSON.parse и вызов обратного вызова с результатом):

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);
})
...