Discord.js实现!inspire随机图命令时图片显示在embed外部问题
故障原因
你当前代码将图片放在send()方法的files参数中,该参数会把文件作为消息独立附件上传,不会自动关联到MessageEmbed结构内,因此图片会显示在embed消息外部。
另外原有命令触发判断逻辑有误:startsWith()方法仅接收一个前缀匹配参数,你传入prefix和'inspire'两个参数时,实际仅会匹配prefix的内容,无法正确识别!inspire触发指令。
修复方法
要让图片嵌入到MessageEmbed内部,需要在构造embed时通过.setImage()方法显式引用图片资源:
- 如果使用本地图片文件,需要给上传的附件设置和embed引用一致的文件名,通过
attachment://文件名格式关联附件和embed - 如果使用公网可直接访问的图片链接,可直接将图片URL传入
.setImage(),无需额外上传附件
修复后可运行代码
bot.on("messageCreate", message => { // 过滤机器人自身消息,避免循环触发指令 if (message.author.bot) return; const targetChannel = message.guild.channels.cache.find(channel => channel.name === '🤖-bot-chat'); // 修正命令匹配规则,正确识别!inspire指令 if (message.content.startsWith(`${prefix}inspire`)) { // 延迟1秒删除用户触发指令的消息,加catch捕获权限不足等异常 setTimeout(() => message.delete().catch(err => console.log('删除消息失败:', err)), 1000); const getRandomIndex = (length) => Math.floor(Math.random() * length); const imageFiles = fs.readdirSync('/images/'); const randomImage = imageFiles[getRandomIndex(imageFiles.length)]; const responseEmbed = new Discord.MessageEmbed() .setTitle("Just a test") // 关联附件为embed内嵌图片 .setImage(`attachment://${randomImage}`); targetChannel.send({ embeds: [responseEmbed], files: [{ attachment: `/images/${randomImage}`, name: randomImage }] }); } })
注意事项
- 确认运行机器人的进程对
/images/目录有读取权限,路径配置和实际存放图片的路径一致 message.delete(1000)的延迟删除写法在discord.js v13及以上版本已废弃,使用setTimeout包裹delete()方法兼容性更好- 如果不需要自定义频道发送,可以直接用
message.channel.send()替代手动查找频道的逻辑,减少权限判断问题
内容的提问来源于stack exchange,提问作者Joe_42o
相关产品推荐
相关产品推荐

