将Alexa与其他API一起使用

问题描述 投票:0回答:1

我正在尝试开发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函数时出现问题。它返回undefined。

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

原始函数应该从调用中返回已解析的数据。

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工作,我在其他场景中检查过它。

任何线索或提示将非常感激。

node.js api alexa
1个回答
0
投票

你没有从你的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);
    });
}

© www.soinside.com 2019 - 2024. All rights reserved.