Alexa Trivia Skill

时间:2018-01-24 10:41:51

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

早上好

我已经编写了一段时间的Alexa技能,我决定制作一个Trivia测验,我主要用 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));
}

}

希望你能帮助我,因为我把头发拉出来,看不出我哪里出错了。

感谢

2 个答案:

答案 0 :(得分:0)

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

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

中调用回调

答案 1 :(得分:0)

我解决了这个问题,谢谢

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

我还添加了一个回调以使其他功能正常工作,现在它正在工作,谢谢