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

Discord.py实现服务器图标旁置服务器名称的问题求助

解决Discord Embed标题添加服务器图标问题

问题出在你直接使用ctx.guild.icon,它是一个Asset对象,并非可直接显示的图片链接。要在Embed标题里显示服务器图标,需要调用它的url属性获取完整图片地址,再用Discord支持的Markdown图片语法嵌入。

修改后的代码如下:

@bot.command(name='mc', brief='Displays member count')
async def member_count(ctx):
    # 处理服务器无图标的情况,避免报错
    guild_icon = f"![Server Icon]({ctx.guild.icon.url}) " if ctx.guild.icon else ""
    
    embed = discord.Embed(
        title=f"{guild_icon}{ctx.guild.name}",
        color=discord.Colour(int(0x7889da))
    )
    embed.add_field(name="Users", value=ctx.guild.member_count, inline=True)
    # 优化人类成员统计的写法,更高效
    human_count = sum(1 for m in ctx.guild.members if not m.bot)
    embed.add_field(name="Humans", value=human_count, inline=True)
    embed.add_field(name="Bots", value=ctx.guild.member_count - human_count, inline=True)

    await ctx.send(embed=embed)

关键说明:

  • ctx.guild.icon.url:获取服务器图标的直接访问链接,Discord会自动处理不同尺寸的图标请求
  • 增加了无图标判断:如果服务器没有设置图标,就只显示服务器名称,避免抛出异常
  • 优化了人类成员的统计方式,用生成器表达式替代列表推导,节省内存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:22:08