Discord.js斜杠命令如何读取txt文件随机行作为回复内容
Discord斜杠指令从指定txt文件随机取一行回复实现方案
你现有代码已经引入了文件操作需要的fs依赖,不需要额外引入readline就能实现需求,注意你代码里有个拼写错误:临时消息配置项是ephemeral,你写的emphemral是错的,会导致配置不生效。
实现逻辑
核心逻辑分三步:
- 读取目标txt文件的全部文本内容
- 按换行符拆分内容为行数组,过滤空行、兼容Windows(
\r\n)和Unix(\n)的换行格式 - 生成数组长度范围内的随机整数,取对应下标的文本作为回复内容
可直接用的代码版本
版本1:每次触发指令读文件(适合频繁修改txt内容、不想重启机器人的场景)
直接替换你原有的execute方法即可,文件体积在10MB以内都可以用这个方案:
async execute(interaction) { // 读取文件、拆分有效行 const allLines = fs.readFileSync(file, 'utf8') .split(/\r?\n/) .filter(line => line.trim().length > 0); // 异常兜底:文件为空的时候返回提示 if (allLines.length === 0) { return interaction.reply({ content: '消息库为空,请检查meow.txt文件', ephemeral: true }); } // 随机取一行回复 const randomReply = allLines[Math.floor(Math.random() * allLines.length)]; interaction.reply({ content: randomReply, ephemeral: true }); }
版本2:启动时缓存文件内容(性能最优,推荐日常使用)
把文件读取逻辑放到模块加载阶段,机器人启动时一次性把所有内容读到内存,后续触发指令不需要重复读硬盘,响应速度更快:
const { SlashCommandBuilder } = require(`@discordjs/builders`); const fs = require("fs"); const path = require("path"); // 用绝对路径定位文件,避免启动目录不同导致找不到文件 const file = path.join(__dirname, './texts/meow.txt'); // 启动时加载所有消息到内存 let replyPool = []; try { replyPool = fs.readFileSync(file, 'utf8') .split(/\r?\n/) .filter(line => line.trim().length > 0); } catch (err) { console.error('加载meow.txt失败,请检查路径和文件权限:', err); } module.exports = { data: new SlashCommandBuilder() .setName(`meow`) .setDescription(`meoww??`), async execute(interaction) { if (replyPool.length === 0) { return interaction.reply({ content: '消息库加载失败,请检查控制台报错', ephemeral: true }); } const randomMsg = replyPool[Math.floor(Math.random() * replyPool.length)]; interaction.reply({ content: randomMsg, ephemeral: true }); }, };
注意事项
- 保存
meow.txt时请选择UTF-8无BOM编码,否则第一行可能出现乱码 - 如果需要修改txt里的消息内容,用版本2的话改完要重启机器人才会生效
- 不要用这个方法加载超过100MB的超大型txt文件,会占用过多内存,这种场景再考虑用readline逐行读取做随机
内容的提问来源于stack exchange,提问作者FluffyWasTaken
相关产品推荐
相关产品推荐

