【问题标题】:Making API Calls Within Alexa Intent Handler在 Alexa Intent 处理程序中进行 API 调用
【发布时间】:2018-05-28 19:38:36
【问题描述】:

我正在尝试创建一个 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);
}

【问题讨论】:

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


    【解决方案1】:

    您的“结束”事件的事件处理程序位于错误的位置,这是您编写函数的一种方式(使用 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);
    })
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2023-03-22
      • 2020-04-24
      • 1970-01-01
      • 2020-02-26
      • 2019-09-17
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      相关资源
      最近更新 更多