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

为何我的Discord机器人Embed图标功能失效?代码求助

解决Discord Embed无法显示交互用户头像的问题

你代码里的核心问题出在set_author的icon_url参数上——你写的是字符串字面量"Interaction.user.avatar",这既不是有效的头像URL,大小写也错了(应该是小写的interaction),Discord解析不了这个无效的URL,导致Embed创建失败,所以命令执行不了。

正确的头像获取写法

要拿到交互用户的头像链接,需要调用interaction.user.avatar.url(avatar是Asset对象,必须通过.url获取实际的图片地址)。另外可以加个兜底逻辑,防止用户没设置自定义头像时出错:

embed.set_author(
    name=f"{interaction.user}",
    icon_url=interaction.user.avatar.url if interaction.user.avatar else interaction.user.default_avatar.url
)

修正后的完整代码

@client.tree.command(name="announce", description="used to announce messages into any channel of the server")
async def name(interaction: discord.Interaction, channel: discord.TextChannel, msg: str, title: str):
    embed = discord.Embed(title=f"**{title}**",
                      description=f"{msg}",
                      colour=0xf5d400)
    
    embed.timestamp = datetime.datetime.now()

    # 修正后的头像设置代码
    embed.set_author(
        name=f"{interaction.user}",
        icon_url=interaction.user.avatar.url if interaction.user.avatar else interaction.user.default_avatar.url
    )

    embed.set_thumbnail(url="https://static.vecteezy.com/system/resources/previews/021/282/254/original/be-careful-sign-symbol-exclamation-mark-in-yellow-free-png.png")

    embed.set_footer(text=f"Sent by {interaction.user}")

    await channel.send(embed=embed)
    await interaction.response.send_message(f"Your announcement has been sent to <#{channel.id}> successfully.",ephemeral=True)

关键说明

  • 必须用小写的interaction(和函数参数名一致),大写的Interaction是类名,不是当前的交互实例
  • avatar属性可能为None(用户未设置自定义头像),所以需要判断后用default_avatar.url作为备选

内容的提问来源于stack exchange,提问作者m2oneyy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:58:19