将 Alexa 与其他 API 一起使用

Using Alexa with other API

我正在尝试开发 Alexa 技能,该技能可以为用户所说的单词找到例句。我为此找到了 API (WordAPI),尽管当我打电话时,响应是不确定的。有人可以帮忙吗?

我的代码:

'use strict';
var Alexa = require('alexa-sdk');
var appId = 'this is valid';
var unirest = require('unirest');

var APP_STATES = {
    START: "_STARTMODE",
    TRANSLATE: "_TRANSLATE"
}

function getData(word){
    unirest.get("https://wordsapiv1.p.mashape.com/words/" + word)
    .header("X-Mashape-Key", "my key")
    .header("Accept", "application/json")
    .end(function (result) {
        return JSON.parse(result.body);
    });
}

exports.handler = function(event, context, callback){
    var alexa = Alexa.handler(event, context);
    alexa.appId = appId;
    alexa.registerHandlers(newSessionHandlers, startStateHandler, translateStateHandler);
    alexa.execute();
}

var newSessionHandlers = {
    'LaunchRequest': function(){
        this.handler.state = APP_STATES.START;
        this.emitWithState("BeginState", true);
    },

    'Unhandled': function () {
        this.emit(":tell", "Something went wrong");
    },
}

var startStateHandler = Alexa.CreateStateHandler(APP_STATES.START, {
    'BeginState': function(){
        var message = "You will say a word and I will give you facts about it, would you like to continue ?";
        this.emit(":ask", message, message);
    },

    'AMAZON.YesIntent': function(){
        this.handler.state = APP_STATES.TRANSLATE;
        this.emit(":ask", "Great, say a word !");
    },

    'AMAZON.NoIntent': function(){
        this.emit(":tell", "Ok, see you later !");
    },

    'Unhandled': function () {
        this.emit(":tell", "Something went wrong");
    },
});

var translateStateHandler = Alexa.CreateStateHandler(APP_STATES.TRANSLATE, {
    'GetWordIntent': function(){
        var word = this.event.request.intent.slots.word.value;
        console.log(getData(word));
        this.emit(":tell", "You said " + word);
    },

    'Unhandled': function () {
        this.emit(":tell", "Something went wrong");
    },

});

当我尝试 console.log 功能时出现问题。它 return 未定义。

    'GetWordIntent': function(){
      var word = this.event.request.intent.slots.word.value;
      console.log(getData(word));
      this.emit(":tell", "You said " + word);
    },

原始函数应该return从调用中解析数据。

function getData(word){
  unirest.get("https://wordsapiv1.p.mashape.com/words/" + word)
  .header("X-Mashape-Key", "my key")
  .header("Accept", "application/json")
  .end(function (result) {
    return JSON.parse(result.body);
  });
}

这确实处于开发的早期阶段,我正在尝试 console.log 输出。这可能是一些我看不到的愚蠢错误。我替换了 appId 和 API 键。 API有效,我在其他场景下检查过。

如有任何线索或提示,我们将不胜感激。

您 return 您的 getData 函数没有任何价值

尝试

function getData(word){
    return unirest.get("https://wordsapiv1.p.mashape.com/words/" + word)
    .header("X-Mashape-Key", "my key")
    .header("Accept", "application/json")
    .end(function (result) {
        return JSON.parse(result.body);
    });
}