discord.js中如何在单个变量中分配多个ActionRowBuilder对象
问题解决方法
你的代码存在几个关键问题,导致「Invalid Body Form」错误,以下是修正方案:
错误分析
- 错误将
ActionRowBuilder实例推送到了存储按钮文本的原始array数组,而非专门的组件数组 - 使用
buttons.join()会把对象数组转为字符串,Discord API要求components接收ActionRowBuilder对象数组,而非字符串 - 未将按钮组件添加到对应的
ActionRowBuilder实例中,创建的行是空的
修正后的代码
const array = ["button1", "button2", "button3", "button4", "button5", "button6", "button7", "button8", "button9", "button10"]; const buttonRow1 = new ActionRowBuilder(); const buttonRow2 = new ActionRowBuilder(); let components = []; // 生成按钮并分配到对应行 array.forEach((btnText, index) => { // 创建基础按钮(可根据需求调整样式、类型) const button = new ButtonBuilder() .setLabel(btnText) .setStyle(ButtonStyle.Primary) .setCustomId(`btn-${index}`); // 前5个按钮放入第一行,剩余放入第二行 index < 5 ? buttonRow1.addComponents(button) : buttonRow2.addComponents(button); }); // 根据按钮数量决定传入的行 components.push(buttonRow1); if (array.length > 5) { components.push(buttonRow2); } const embed = new EmbedBuilder().setDescription("This is a description."); message.channel.send({ embeds: [embed], components: components });
关键修正点
- 单独维护
components数组存储要发送的行实例,不修改原始按钮文本数组 - 直接将
ActionRowBuilder实例数组传入components,避免任何字符串转换操作 - 必须将每个按钮组件添加到对应的行实例中,确保行内有可渲染的按钮
内容的提问来源于stack exchange,提问作者user874737
相关产品推荐
相关产品推荐

