如何让Kahoot机器人随机答题?kahoot.js-updated报错排查
Kahoot机器人无法随机答题:TypeError异常分析与修复
问题重现
使用kahoot.js-updated编写的Kahoot机器人成功加入房间,但触发QuestionStart事件时抛出如下错误:
Math.random() * question.quizQuestionAnswers[question.questionIndex] ^ TypeError: Cannot read properties of undefined (reading '0')
原代码如下:
const Kahoot = require("kahoot.js-updated"); var kahoots = [] for (var i = 0; i < bot_count; i++) { kahoots.push(new Kahoot); kahoots[i].join(pin, name+" "+String(i)).catch(error => { console.log("join failed " + error.description + " " + error.status) }); kahoots[i].on("QuestionStart", (question) => { question.answer( Math.floor( Math.random() * question.quizQuestionAnswers[question.questionIndex] ) ); });
错误原因
错误出在question.quizQuestionAnswers[question.questionIndex]这一行:
quizQuestionAnswers是存储所有问题选项的数组,每个元素对应一道题的选项集合question.questionIndex是当前题的索引,但用它索引quizQuestionAnswers得到的是当前题的选项数组,而非选项数量。你试图用随机数乘以这个数组,导致计算逻辑错误,最终触发undefined读取异常。
修复方案
要获取当前题的选项数量,需取quizQuestionAnswers对应索引元素的长度。修正后的代码如下:
const Kahoot = require("kahoot.js-updated"); const kahoots = []; for (let i = 0; i < bot_count; i++) { const client = new Kahoot(); kahoots.push(client); client.join(pin, `${name} ${i}`).catch(error => { console.log(`join failed ${error.description} ${error.status}`); }); client.on("QuestionStart", (question) => { // 获取当前题的选项总数 const optionCount = question.quizQuestionAnswers[question.questionIndex].length; // 生成0到选项数-1的随机索引(符合答题参数要求) const randomAnswer = Math.floor(Math.random() * optionCount); question.answer(randomAnswer); }); }
额外优化
- 用
let替代var,避免循环变量作用域泄漏问题 - 使用模板字符串提升代码可读性
内容的提问来源于stack exchange,提问作者Shan
相关产品推荐
相关产品推荐

