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

discord.py开发时为何无法将embed图片设置为用户上传的附件?

错误原因梳理
  • 你用来接收用户输入的bugReport是纯字符串类型,没有attachments属性,调用bugReport.attachments.url会直接抛出属性不存在异常,这是Embed发送失败的核心原因。用户上传的附件需要从消息对象ctx.message.attachments中读取。
  • 校验bugReport是否为空的逻辑位置错误,放在Embed构建之后,还没走到校验环节程序就会先报错,校验逻辑完全不生效。
  • ctx.message.attachments是列表类型,存储了用户上传的所有附件,不能直接调用url属性,需要先判断列表非空,再取对应附件的url。
修复后代码
@commands.command()
async def bug(self, ctx, *, bugReport=None):
    """允许用户上报bug的命令"""
    # 提前校验:文字描述和附件至少传一个
    if bugReport is None and not ctx.message.attachments:
        await ctx.send("你没有填写bug描述也没有上传附件!请重新提交。")
        return
    
    channel = self.client.get_channel(864211572218265610)

    bugEmbed = discord.Embed(
        title=f"Bug 上报",
        description=bugReport if bugReport else "用户未填写文字描述,仅上传了附件",
        color= 0xFFFF00
    )

    bugEmbed.add_field(
        name="上报人",
        value=f"<@{ctx.author.id}>"
    )

    bugEmbed.set_footer(
        text="",
        icon_url=ctx.author.avatar_url
    )
    # 存在附件时才给Embed设置图片,默认取第一个附件
    if ctx.message.attachments:
        bugEmbed.set_image(
            url=ctx.message.attachments[0].url
        )

    await channel.send(embed=bugEmbed)

内容的提问来源于stack exchange,提问作者goose.mp4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 00:36:02