You need to enable JavaScript to run this app. Discord机器人开发:serverinfo指令中如何设置Embed服务器图标缩略图?
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人开发:serverinfo指令中如何设置Embed服务器图标缩略图?

服务器图标作为Embed缩略图的正确实现

代码无法运行的核心原因

  • API调用语法错误:ctx.guild.icon_url(format="png") 不符合discord.py的原生设计,icon_url是返回图标的属性而非可传参方法,强行对其加括号传参会直接触发运行时错误
  • 缺失空值判断:如果触发指令的服务器未设置自定义图标,服务器的图标属性会返回None,此时直接读取图标url会触发AttributeError导致指令崩溃

版本适配的正确取法

根据使用的discord.py版本,匹配对应的图标链接获取逻辑:

  • 1.7.x 旧版:指定PNG格式取图标链接需要调用icon_url_as()方法,写法为 ctx.guild.icon_url_as(format="png")
  • 2.0+ 新版:原icon_url属性已被弃用,新版将服务器图标封装为Asset对象,获取带格式的链接写法为 ctx.guild.icon.with_format("png").url

修正后的完整可运行代码

@bot.command(name='serverinfo', help='查看当前服务器信息')
async def serverinfo(ctx, *args, user: discord.Member = None):
    # 未传入查询用户时,默认使用指令触发者作为页脚展示对象
    if user is None:
        user = ctx.author

    embed = discord.Embed(title="服务器信息", color=0x0d48a6)
    # 仅当服务器存在自定义图标时,才设置Embed缩略图
    if ctx.guild.icon is not None:
        embed.set_thumbnail(url=ctx.guild.icon.with_format("png").url)
    # 对应原user参数的设计逻辑:在Embed页脚展示用户相关信息
    embed.set_footer(text=f"指令触发者:{user.name} | 用户ID:{user.id}")

    await ctx.send(embed=embed)

实用补充说明

  • 要支持服务器动态图标作为缩略图,只需将format参数替换为"gif",Discord会自动在Embed中渲染动态效果
  • 不需要手动拼接CDN链接的签名参数,discord.py返回的图标链接已经包含官方授权的访问凭证,可直接加载使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 11:54:02