discord.js v13 如何编写代码从MessageCollector中收集首个图片/视频附件
问题诊断
- 附件长度判断逻辑错误:
Collected.attachments.values()返回的是迭代器对象,直接用方括号包裹只会得到包含单个迭代器的数组,length永远为1,无法正确判断是否存在附件。需要用Array.from()将迭代器转换为真实的附件数组再计算长度。 - 链接前缀匹配逻辑错误:
startsWith(https://||http://)写法不符合语法逻辑,JS会先运算||表达式,结果永远返回https://,导致所有http://开头的链接都无法被匹配。需要拆分为两个独立的startsWith判断再用逻辑或连接。 - 代码结构不完整:你提供的代码片段缺失了多层闭合的大括号和圆括号,实际运行会直接抛出语法错误,需补全所有闭合标签。
修复后代码
Message.author.send({ embeds: [AttachmentEmbed] }).then(Msg => { var Collector = Msg.channel.createMessageCollector({ MessageFilter, max: 1, time: 300000 }); Collector.on(`collect`, Collected => { if (Collected.content.toLowerCase() !== `cancel`) { // 迭代器转数组后计算长度 const attachments = Array.from(Collected.attachments.values()); console.log(attachments.length); if (attachments.length > 0) { var Attachment = attachments[0]; var AttachmentType = `Image`; PostApproval(false, Mode, Title, Description, Pricing, Contact, Attachment, AttachmentType); // 修正链接前缀判断逻辑 } else if ((Collected.content.startsWith(`https://`) || Collected.content.startsWith(`http://`)) && !Collected.content.startsWith(`https://cdn.discordapp.com/attachments/`)) { var Attachment = Collected.content.split(/[ ]+/)[0]; var AttachmentType = `Link`; PostApproval(false, Mode, Title, Description, Pricing, Contact, Attachment, AttachmentType); console.log(Attachment) } else if (Collected.content.startsWith(`https://cdn.discordapp.com/attachments/`)) { var Attachment = Collected.content.split(/[ ]+/)[0]; var AttachmentType = `ImageLink`; PostApproval(false, Mode, Title, Description, Pricing, Contact, Attachment, AttachmentType); console.log(Attachment) } } }) })
内容的提问来源于stack exchange,提问作者DbkboxiMoldoxjZfmebo
相关产品推荐
相关产品推荐

