discord.js v13如何收集用户提交的图片并在Embed中发送
discord.js v13 收集用户图片插入Embed功能修复方案
现有代码问题说明
- 过滤器逻辑错误
- 直接对消息对象
m调用startsWith方法不符合规范,判断文本内容需要读取m.content属性 m.attachments是固定存在的集合对象,无附件时也为真值,需要通过size属性判断是否存在附件- 未限制发送者身份,会误收集其他用户发送的内容
- 直接对消息对象
- 图片URL取值错误:消息对象本身没有
url属性,附件的URL存储在attachments集合的元素中,纯链接内容需要读取content属性 - 缺少超时处理逻辑,未收到用户消息时会卡住
修复后代码
interaction.reply({ content: '请发送一张图片...' }).then(async () => { const atch_filter = (m) => { // 仅响应触发交互的用户的消息 if (m.author.id !== interaction.user.id) return false; // 消息包含附件 或 消息内容为http/https开头的链接 return m.attachments.size > 0 || m.content.startsWith('http'); }; try { const collected = await interaction.channel.awaitMessages({ filter: atch_filter, max: 1, time: 30000, // 超时时间30秒,可按需调整 errors: ['time'] }); const receivedMsg = collected.first(); let imgUrl; // 优先读取附件地址 if (receivedMsg.attachments.size > 0) { imgUrl = receivedMsg.attachments.first().url; } else { // 无附件时读取消息内容作为图片链接 imgUrl = receivedMsg.content; } const embed = new MessageEmbed() .setTitle('图片已接收') .setImage(imgUrl) .setColor('BLUE'); await interaction.editReply({ content: '完成!', embeds: [embed] }); } catch (e) { // 超时兜底处理 await interaction.editReply({ content: '操作超时,未接收到有效图片' }); } });
注意事项
- 如果你需要接收用户发送的链接作为图片源,需要确保该链接是直接指向图片资源的直链(后缀通常为
.jpg/.png/.gif等),普通网页链接无法被Embed的setImage方法识别。
内容的提问来源于stack exchange,提问作者Negrura
相关产品推荐
相关产品推荐

