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

如何根据变量加载JSON文件?discord.js问答游戏报错求助

解决discord.js问答游戏中'trivia未定义'的问题

以下是几个常见的问题原因及对应的解决方案,附代码示例:

1. 变量作用域错误

如果trivia变量定义在局部作用域(比如if分支、函数内部),外部访问时就会触发未定义错误。确保变量在需要使用它的作用域内定义。

2. JSON文件异步加载未处理

若使用fs.readFile异步读取文件,未等待文件加载完成就访问trivia,会导致变量未被赋值。可以改用同步读取或用async/await处理异步逻辑。

3. 随机数范围超出文件数量

如果随机生成的文件编号对应不存在的JSON文件,会导致读取失败,trivia无法被正常赋值。需确保随机数范围匹配现有文件数量。


正确代码示例(同步加载)

const fs = require('fs');
const path = require('path');
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', (message) => {
  if (message.content === '!trivia') {
    // 假设有2组问题文件(1.json、2.json),生成1-2之间的随机数
    const randomFileNum = Math.floor(Math.random() * 2) + 1;
    const triviaFilePath = path.join(__dirname, `${randomFileNum}.json`);

    try {
      // 同步读取并解析JSON文件
      const triviaData = fs.readFileSync(triviaFilePath, 'utf8');
      const trivia = JSON.parse(triviaData);

      // 从选中的文件中随机选一个问题
      const randomQIndex = Math.floor(Math.random() * trivia.length);
      const selectedQ = trivia[randomQIndex];
      
      message.channel.send(`问题:${selectedQ.question}`);
      // 后续可添加答案验证逻辑
    } catch (err) {
      console.error('加载问题文件失败:', err);
      message.channel.send('加载问题出错,请稍后再试');
    }
  }
});

client.login('你的Bot令牌');

正确代码示例(异步加载,async/await)

const fs = require('fs').promises;
const path = require('path');
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

async function getRandomTrivia() {
  const randomFileNum = Math.floor(Math.random() * 2) + 1;
  const triviaFilePath = path.join(__dirname, `${randomFileNum}.json`);
  
  try {
    const triviaData = await fs.readFile(triviaFilePath, 'utf8');
    const trivia = JSON.parse(triviaData);
    return trivia[Math.floor(Math.random() * trivia.length)];
  } catch (err) {
    console.error('读取文件失败:', err);
    return null;
  }
}

client.on('messageCreate', async (message) => {
  if (message.content === '!trivia') {
    const question = await getRandomTrivia();
    if (question) {
      message.channel.send(`问题:${question.question}`);
    } else {
      message.channel.send('无法获取问题,请检查文件是否存在');
    }
  }
});

client.login('你的Bot令牌');

额外检查项:

  • 确认JSON文件路径正确,可通过console.log(triviaFilePath)打印路径验证
  • 确保JSON文件格式无语法错误(比如逗号、引号遗漏)
  • 随机数范围要和实际文件数量对应(比如有3个文件就用Math.floor(Math.random() * 3) + 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:09:19