JavaScript遍历命令文件夹制作Discord机器人帮助命令遇属性未定义问题
解决Discord机器人帮助命令中
i.name和i.description为undefined的问题 问题根源
你当前的代码里犯了一个关键错误:把commands变量赋值成了字符串形式的文件夹路径,然后直接遍历这个字符串。当你遍历字符串时,循环里的i其实是路径里的单个字符(比如'C'、':'、'/'这些),这些字符自然没有name和description属性,所以才会返回undefined。
正确解决方案
要实现遍历命令文件夹并获取每个命令的name和description,你需要借助Node.js的fs(文件系统)和path(路径处理)模块来读取并加载文件夹里的命令文件。下面是修改后的完整代码:
const fs = require('fs'); const path = require('path'); const Discord = require('discord.js'); module.exports = { name: 'help', description: 'Lists current commands.', execute(message) { // 获取命令文件夹的绝对路径(假设当前help.js在Bot根目录,commands是同级文件夹) const commandsPath = path.join(__dirname, 'commands'); // 读取文件夹里所有.js后缀的命令文件 const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); const helpEmbed = new Discord.MessageEmbed() .setTitle("Commands") .setColor(0x6e7175) .setFooter('Provided by Echo', 'https://cdn.discordapp.com/avatars/748282903997186178/6288e1f487e111b211aa9966c583d948.png?size=128') .setTimestamp(); // 遍历每个命令文件,加载模块并添加字段到Embed for (const file of commandFiles) { const command = require(path.join(commandsPath, file)); // 确保命令模块确实有name和description属性,避免报错 if (command.name && command.description) { helpEmbed.addField(command.name, command.description); } } message.channel.send(helpEmbed); } };
额外说明
- 使用
path.join(__dirname, 'commands')可以避免硬编码路径带来的跨平台问题(Windows用\,Linux/macOS用/),__dirname会自动指向当前help.js文件所在的目录。 - 添加了
if (command.name && command.description)的判断,防止某些命令文件没有正确导出name或description导致Embed构建报错。 - 原代码里的
if (message.content.toLowerCase() === '$help')其实可以移除——因为discord.js的命令系统通常是通过匹配命令名(也就是你导出的name: 'help')来触发的,这个判断属于重复校验。
内容的提问来源于stack exchange,提问作者iris87
相关产品推荐
相关产品推荐

