Discord斜杠命令能否支持单次上传多张图片作为附件?
问题:Discord.js 斜杠命令实现多图批量上传
我正在基于Discord JS搭建一个艺术服务器机器人,开发了/submitref斜杠命令,用于让用户将参考图片上传至指定的#references频道(该频道仅机器人可发言)。当前已实现单次上传一张图片的功能,但希望能在一个斜杠命令中接受多张图片。
现有SlashCommandBuilder代码如下:
module.exports = { data: new SlashCommandBuilder() .setName('submitref') .setDescription('Submit a reference photo to the server.') .addAttachmentOption(option => option .setName('ref') .setDescription('Reference Photo') .setRequired(true) ) }
尝试通过Ctrl+点击多选本地图片上传,但该参数仅能接收一张图片。虽可通过添加多个可选参数支持多图,但从用户体验出发,更希望实现单次多选上传的方案。
解决方案
Discord.js v14.7.0及以上版本支持为附件参数设置最大/最小接收数量,直接通过setMaxValue()和setMinValue()方法就能实现单次多选上传的需求,无需添加多个参数。
修改后的命令构建代码
module.exports = { data: new SlashCommandBuilder() .setName('submitref') .setDescription('Submit reference photos to the server.') .addAttachmentOption(option => option .setName('refs') .setDescription('Reference Photos (multiple allowed)') .setRequired(true) .setMinValue(1) // 要求至少上传1张图片 .setMaxValue(10) // 限制最多上传10张,可按需调整 ) }
处理多附件的交互逻辑
在命令执行的回调函数中,需要注意此时获取到的附件是一个数组,而非单个对象:
async execute(interaction) { // 获取所有上传的附件(数组形式) const attachments = interaction.options.getAttachment('refs'); const referencesChannelId = '你的#references频道ID'; const referencesChannel = interaction.guild.channels.cache.get(referencesChannelId); if (!referencesChannel) { return interaction.reply({ content: '未找到指定的参考图片频道!', ephemeral: true }); } // 将附件转换为Discord消息支持的文件格式 const files = attachments.map(attachment => ({ attachment: attachment.url, name: attachment.name })); // 批量发送到目标频道 await referencesChannel.send({ files }); // 回复用户上传结果 await interaction.reply({ content: `成功上传${attachments.length}张参考图片!`, ephemeral: true }); }
注意事项
- 必须使用Discord.js v14.7.0或更高版本,否则
setMinValue()和setMaxValue()方法不可用 - 调整
setMaxValue()时,要兼顾Discord的单条消息附件总大小限制(最大25MB) - 参数名称改为
refs并更新描述,能让用户更清晰地知道该参数支持多选
内容的提问来源于stack exchange,提问作者Audrey Publicover
相关产品推荐
相关产品推荐

