You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:45:08