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

discord.js开发机器人help命令时Embed添加字段无效果且无报错如何解决

问题原因
  • 核心问题是fs.readdir为异步执行方法,你当前的代码在文件读取操作还未完成、还没给Embed添加任何字段时,就已经执行了message.channel.send(embed)发送了还没修改完的Embed对象,所以看不到字段内容,且语法层面没有错误所以不会报错。
  • 次要问题:discord.js的MessageEmbed.addField()方法要求至少传入字段名、字段值两个必填参数,你只传了命令名作为第一个参数,缺少第二个值也会导致字段添加失败。
修复方案

将发送Embed的逻辑移动到fs.readdir的回调函数内部,同时补全addField的参数即可,修正后的代码如下:

exports.run = (client, message, args) => {
    const Discord = require("discord.js");
    const fs = require('fs');
    // Help command
    let embed = new Discord.MessageEmbed()
      .setTitle("Help")
      .setDescription("Availible commands are listed here");
    fs.readdir("./commands/", (err, files) => {
      if (err) return console.error(err);
      files.forEach(file => {
        if (!file.endsWith(".js")) return;
        let commandName = file.split(".")[0];
        // 补全addField的第二个参数,这里可以自定义命令说明内容
        embed.addField(commandName, "可输入 !help [命令名] 查看详细用法");
      });
      // 把发送逻辑移到回调内部,等所有字段添加完成后再发送
      message.channel.send(embed);
    });
};
可选优化

如果你不想用回调嵌套,也可以改用fs.readdirSync同步读取方法,代码逻辑更直观:

exports.run = (client, message, args) => {
    const Discord = require("discord.js");
    const fs = require('fs');
    // Help command
    let embed = new Discord.MessageEmbed()
      .setTitle("Help")
      .setDescription("Availible commands are listed here");
    // 同步读取文件列表,会阻塞直到读取完成再执行后续代码
    const files = fs.readdirSync("./commands/");
    files.forEach(file => {
      if (!file.endsWith(".js")) return;
      let commandName = file.split(".")[0];
      embed.addField(commandName, "可输入 !help [命令名] 查看详细用法");
    });
    message.channel.send(embed);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:18:04