Discord.js v13 如何发送数量动态未知的消息按钮
问题根源
原代码的错误逻辑有两点:
- 遍历数组的每一次循环都新建了独立的
MessageActionRow,且单独执行了ch.send()发送操作,循环跑几次就会发几条消息 - 模板字符串写法错误,
setURL(${user.id})漏了包裹的反引号,会直接报语法错误
另外注意Discord交互组件的官方限制:单个MessageActionRow最多放置5个按钮,单条消息最多携带5个MessageActionRow(总计25个按钮),你最多10个按钮的场景完全在限制范围内。
修正代码
核心逻辑调整为先统一生成所有按钮、按每行5个的规则拆分按钮行,最后只执行一次消息发送:
// 批量生成所有链接按钮实例 const buttonList = array.map(user => { return new client.discord.MessageButton() .setLabel(user.type) .setURL(`${user.id}`) // 补全模板字符串反引号 .setEmoji('979681456781635700') .setStyle('LINK') }) // 按每行最多5个按钮拆分,生成ActionRow数组 const components = [] for (let i = 0; i < buttonList.length; i += 5) { const actionRow = new client.discord.MessageActionRow() .addComponents(buttonList.slice(i, i + 5)) components.push(actionRow) } // 单次发送消息,携带所有按钮行 const targetChannel = client.channels.cache.get('998376140326256158') targetChannel.send({ embeds: [embed], components: components })
适配效果
- 数组长度为1-5时,所有按钮自动排列在同一行
- 数组长度为6-10时,自动拆分为2行,第一行放5个按钮,第二行放剩余按钮
- 不需要提前固定数组长度,支持1-10范围内任意长度的按钮配置数组,全程仅发送1条消息
内容的提问来源于stack exchange,提问作者TheGloriesVe
相关产品推荐
相关产品推荐

