【问题标题】:Alexa Trivia SkillAlexa琐事技巧
【发布时间】:2018-01-24 10:41:51
【问题描述】:

早安

我已经编写 Alexa 技能有一段时间了,我决定做一个琐事测验,我主要用 Javascript 编写它,并使用测验模板来帮助我进行一些修改。

我已经设置了所有的 Intent,代码正在做我需要的事情,我需要做的最后一点是用来自外部 API 的数据填充一个数组,我相信我已经正确设置了 API 请求,因为我以前用过同样的代码。

但是,当我运行该技能时,它一直提示说填充数据时出错,当我查看日志时,我的 API 代码没有显示,是我做错了什么吗?

我希望你能看看我有什么,看看我做错了什么,问题填充在我的名为填充数据的函数中。

function populateData()
{   
    if(difficulty == "")
    {
        questions = [];
        var i =0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50',
            method: 'GET'
        };

        var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            console.log(qdata);

            questions.push(qdata);

            }

        });

    });
    req.end();

    if(i == 50)
    {
        return true;
    }

    }
    else if(difficulty == "easy")
    {
        questions = [];
        var i =0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50&difficulty=easy',
            method: 'GET'
        };

        var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            questions.push(qdata);

            }

        });

    });
    req.end();

    if(i == 50)
    {
        return true;
    }

    }
    else if(difficulty == "medium")
    {
        questions = [];
        var i=0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50&difficulty=medium',
            method: 'GET'
        };

        var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            questions.push(qdata);

            }

        });

    });
    req.end();

    if(i == 50)
    {
        return true;
    }

    }
    else if(difficulty == "hard")
    {
        questions = [];
        var i=0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50&difficulty=hard',
            method: 'GET'
        };

    var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            questions.push(qdata);

            }
        });

    });
    req.end();

    }

    if(i == 50)
    {
        return true;
    }
}

当用户要求开始测验时调用此函数

function getWelcomeResponse(callback) 
{

var populated = populateData();

if(populated)
{
var sessionAttributes = {},
    speechOutput = "I will ask you " + GAME_LENGTH.toString()
        + " questions, try to get as many right as you can. Just say the number of the answer. Let's begin. ",
    shouldEndSession = false,

    gameQuestions = populateGameQuestions(),
    correctAnswerIndex = Math.floor(Math.random() * (ANSWER_COUNT)), // Generate a random index for the correct answer, from 0 to 3
    roundAnswers = populateRoundAnswers(gameQuestions, 0, correctAnswerIndex),

    currentQuestionIndex = 0,
    spokenQuestion = Object.keys(questions[gameQuestions[currentQuestionIndex]])[0],
    repromptText = "Question 1. " + spokenQuestion + " ",

    i, j;

for (i = 0; i < ANSWER_COUNT; i++) {
    repromptText += (i+1).toString() + ". " + roundAnswers[i] + ". "
}
speechOutput += repromptText;
var sessionAttributes = {
    "speechOutput": repromptText,
    "repromptText": repromptText,
    "currentQuestionIndex": currentQuestionIndex,
    "correctAnswerIndex": correctAnswerIndex + 1,
    "questions": gameQuestions,
    "score": 0,
    "correctAnswerText":
        questions[gameQuestions[currentQuestionIndex]][Object.keys(questions[gameQuestions[currentQuestionIndex]])[0]][0]
};
callback(sessionAttributes,
    buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, shouldEndSession));
}
else
{
    callback(sessionAttributes,
    buildSpeechletResponseWithoutCard("There has been an error while populating data", "There has been an error while populating data", false));
}

}

希望你能帮助我,因为我正在拔头发,看不到哪里出错了。

谢谢

【问题讨论】:

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


    【解决方案1】:

    这里发生了很多事情,但从这里追踪来看,似乎可能发生的是 node.js 回调计时问题的经典案例 - 更具体地说,您的 Lambda 函数在您的 API 调用完成之前返回(您可能还有一些变量范围问题 - 从这里很难说)。

    如果您的响应取决于 API 调用的结果,您需要等待返回响应,直到该响应完成。在您的情况下,我会尝试将回调函数传递给您的 populateData 方法,然后构建您的响应并在 res.on('end'... 中调用回调

    【讨论】:

      【解决方案2】:

      我解决了这个问题,谢谢

      我使用了 https.get 请求,然后使用 Json.Parse 来获取结果,我现在已将它们添加到我需要的数组中。

      我还添加了一个回调来让其他函数工作,现在可以工作了,谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-05
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多