You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord JS机器人答题Collector异常:超时无响应无法切换问题

Discord问答机器人超时无响应问题修复

问题说明

我开发的Discord问答机器人,在设置10秒答题时限后,若无人在规定时间内答对,机器人没有任何反馈,停留在当前问题。相关代码如下:

问题数组

const questions = [
  {
    question: "What is the capital of France?",
    answer: "Paris",
  },
  {
    question: "Who is the best barcelona player of all history?",
    answer: "Messi",
  },
];

现有脚本

client.on('messageCreate', async message => {
//...

const handleQuestion = () => {
if (i >= questions.length) {
  return;
}
channel.send(questions[i].question);

// Create a collector to get the answers from users
const filter = m => !m.author.bot;
const collector = channel.createMessageCollector(filter, { time: 10000 });

collector.on('collect', message => {
  if (message.content === questions[i].answer) {
    channel.send(`${message.author} a trouvé la bonne réponse!`);
    collector.stop();
  }
});

collector.on('end', collected => {
  i++;
  if (i >= questions.length) {
    channel.send('Toutes les questions ont été posées!');
    return;
  }
  if (!collected.size) {
    channel.send(`Aucune réponse n'a été trouvée pour la question "${questions[i].question}"`);
  }
  handleQuestion();
});
};

handleQuestion();
}
});

client.login('Token_discord');

问题根源

  1. 在collector.end回调中,先执行了i++,导致发送超时提示时引用的是下一题的问题,而非当前超时的题目,逻辑混乱
  2. 用户无法得到明确的超时反馈,误以为机器人未响应

修复代码

client.on('messageCreate', async message => {
//...
let i = 0;
const channel = message.channel;

const handleQuestion = () => {
  if (i >= questions.length) {
    return;
  }
  // 保存当前问题,避免索引变动导致引用错误
  const currentQuestion = questions[i];
  channel.send(currentQuestion.question);

  const filter = m => !m.author.bot;
  const collector = channel.createMessageCollector(filter, { time: 10000 });

  collector.on('collect', msg => {
    // 忽略大小写,提升用户体验
    if (msg.content.toLowerCase() === currentQuestion.answer.toLowerCase()) {
      channel.send(`${msg.author} 答对了!`);
      collector.stop();
    }
  });

  collector.on('end', collected => {
    // 先处理当前题的超时反馈
    if (collected.size === 0) {
      channel.send(`无人在10秒内答对问题:"${currentQuestion.question}"`);
    }
    // 再递增索引
    i++;
    if (i >= questions.length) {
      channel.send('所有问题已完成!');
      return;
    }
    // 进入下一题
    handleQuestion();
  });
};

handleQuestion();
});

client.login('Token_discord');

关键修改点

  • 用currentQuestion变量保存当前题目,避免因i递增导致的引用错误
  • 调整end回调逻辑顺序:先发送超时提示,再递增索引,最后触发下一题
  • 新增大小写忽略判断,降低用户答题门槛
  • 明确i和channel的作用域,避免未定义错误

内容的提问来源于stack exchange,提问作者oxem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 03:20:52