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

如何用discord.py实现profile查询命令 解决NoneType属性报错问题

错误原因
  • 代码中没有先判断user参数是否为空,就预先初始化了两个Embed对象,当无用户被@时,user为None,此时构造otherProfileEmbed调用user.display_name属性就会触发空对象属性报错。
修复方案

将Embed构造逻辑移到参数判断分支内,仅当需要用到对应Embed时才初始化,同时可以提取共用的随机色变量减少重复代码,修复后代码如下:

@bot.command(name = "profile", help = "View someone's profile")
async def profile(ctx, user: discord.User = None):
    colorOne = random.randint(0, 255)
    colorTwo = random.randint(0, 255)
    colorThree = random.randint(0, 255) 
    random_color = discord.Colour.from_rgb(colorOne, colorTwo, colorThree)
    
    if user is None:
        # 无指定用户时返回发送者自身的资料
        embed = discord.Embed(
            title = f"{ctx.message.author.display_name}'s profile",
            description = f"**Username:** {str(ctx.message.author)}\n**User ID:** {str(ctx.message.author.id)}",
            color = random_color
        )
    else:
        # 有指定用户时返回被@用户的资料
        embed = discord.Embed(
            title = f"{user.display_name}'s profile",
            description = f"**Username:** {str(user)}\n**User ID:** {str(user.id)}",
            color = random_color
        )
    await ctx.send(embed = embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:06:04