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

Discord机器人开发:从JSON文件随机取语录并发送的命令实现

实现Discord机器人从JSON文件随机发送语录的命令

我来帮你搞定这个需求!其实从JSON文件读取和你之前用数组的逻辑几乎无缝衔接,Node.js本身就支持直接加载JSON文件,不用复杂的文件读取操作,下面一步步给你讲:

第一步:准备你的语录JSON文件

先创建一个quotes.json文件,和你的机器人脚本放在同一目录里。格式可以直接是一个数组,比如:

[
  "人生苦短,我用Python",
  "代码是写给人看的,顺便给机器运行",
  "Talk is cheap. Show me the code.",
  "调试代码的时间比写代码的时间还长"
]

如果之后你想给语录加更多信息(比如作者),也可以改成对象数组:

[
  {"text": "人生苦短,我用Python", "author": "Guido van Rossum"},
  {"text": "Talk is cheap. Show me the code.", "author": "Linus Torvalds"}
]

第二步:在机器人代码里读取并使用

假设你用的是最流行的discord.js库(v14版本),直接看完整示例代码:

const { Client, GatewayIntentBits, SlashCommandBuilder } = require('discord.js');
// 直接用require加载JSON文件,Node会自动把它解析成JS数组
const quotes = require('./quotes.json');

const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds, 
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent // 如果用前缀命令需要这个权限
  ] 
});

// 启动后注册一个slash命令(/quote)
client.on('ready', async () => {
  console.log(`Logged in as ${client.user.tag}!`);
  
  // 这里是给单个服务器注册命令,正式上线建议用官方的部署脚本
  const targetGuild = client.guilds.cache.get('你的服务器ID');
  if (targetGuild) {
    await targetGuild.commands.create(
      new SlashCommandBuilder()
        .setName('quote')
        .setDescription('随机发送一条语录')
    );
  }
});

// 处理slash命令交互
client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === 'quote') {
    // 和你之前用数组的随机逻辑完全一样
    const randomIndex = Math.floor(Math.random() * quotes.length);
    const selectedQuote = quotes[randomIndex];
    
    // 如果是对象数组,就调整成你想要的格式,比如`${selectedQuote.text} —— ${selectedQuote.author}`
    await interaction.reply(selectedQuote);
  }
});

// 如果你想用前缀命令(比如!quote),加这段监听
client.on('messageCreate', async message => {
  if (message.author.bot) return; // 忽略机器人自己的消息
  
  if (message.content === '!quote') {
    const randomIndex = Math.floor(Math.random() * quotes.length);
    await message.channel.send(quotes[randomIndex]);
  }
});

client.login('你的机器人令牌');

关键知识点说明

  1. JSON文件读取:Node.js的require可以直接加载JSON文件,自动完成解析,不用手动调用fs.readFile和JSON.parse,非常方便。如果你的JSON文件不在当前目录,记得写对相对路径(比如./data/quotes.json)。
  2. 随机选取逻辑:和你之前用数组的方法完全一致,Math.floor(Math.random() * quotes.length)会生成一个0到数组长度-1的随机整数,用它作为索引就能拿到随机语录。
  3. 动态文件的情况:如果你的语录文件需要经常修改(比如后台更新),那require就不太合适了(因为Node会缓存模块),这时候可以用fs.readFile异步读取并解析:
const fs = require('fs').promises;

// 在命令处理里读取
async function getRandomQuote() {
  const data = await fs.readFile('./quotes.json', 'utf8');
  const quotes = JSON.parse(data);
  return quotes[Math.floor(Math.random() * quotes.length)];
}

这样就能完美实现你想要的功能啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:43:53