首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Alexa Intent Handler中进行API调用

在Alexa Intent Handler中进行API调用
EN

Stack Overflow用户
提问于 2018-05-28 08:25:37
回答 1查看 682关注 0票数 0

我正在尝试创建一个Alexa技能,它可以进行API调用来检索天气数据。无论我怎么尝试,我都不能让这段代码工作。这似乎不是很难的事情,我只是不知道如何将API调用放入意图处理程序中。我的节点技能也生疏了,这可能也无济于事。

代码语言:javascript
复制
/* 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);
}
EN

回答 1

Stack Overflow用户

发布于 2018-05-28 19:31:43

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

代码语言:javascript
复制
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);
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50557705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档