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

Discord.js开发:如何为menu.json每个元素在MessageEmbed中添加字段

可行性说明

这个需求完全可以实现,你现有代码仅存在几处语法和逻辑错误,修复后即可正常运行。

现有代码问题点

  • for循环语法错误:标准for循环结构为for(初始化; 循环条件; 步进逻辑),你的代码把条件和步进的位置写反了,同时遗漏了循环体的左大括号
  • 循环条件逻辑错误:menu是数组类型,不能直接和索引数值比较,需要读取数组的length属性判断边界,应改为x < menu.length
  • 可选优化点:你现在将embed初始化放在模块顶层,只会在机器人启动时生成一次,后续修改menu.json需要重启机器人才能生效,如果需要实时更新菜单,可以把embed生成逻辑挪到run方法内部

修复后完整代码

const Command = require("../Structures/Command.js");
const Discord = require("discord.js");
const { menu } = require("../data/menu.json");

// 要是需要实时更新菜单,就把下面embed生成的代码挪到run方法里
let menuEmbed = new Discord.MessageEmbed()
    .setColor("#FFA500")
    .setTitle("Menu")
    .setDescription("Here are the cool things you can order with an \"order\" command")

// 修复后的循环
for(let x = 0; x < menu.length; x++) {
    const itemName = menu[x].charAt(0).toUpperCase() + menu[x].slice(1).replace("_", " ");
    menuEmbed.addField(itemName, "```id:" + menu[x] + "```");
}

module.exports = new Command({
    name: "menu",
    description: "Gives you a menu",

    async run(message, args, client){
        // discord.js v13及以上版本需要用这个写法,旧版本可直接写message.reply(menuEmbed)
        message.reply({ embeds: [menuEmbed] });
    }
});

补充注意事项

单条MessageEmbed最多支持25个字段,要是你的菜单条目超过25个,需要拆分多个embed或者合并字段内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:18:00