如何用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
相关产品推荐
相关产品推荐

