如何使用我的 Discord 机器人打印出"AttributeError"错误?



我使用一个命令来检查我的机器人在哪个通道中。如果它在一个通道中,一切都会很好地输出。但如果机器人不在通道中,我会得到控制台条目:AttributeError: 'NoneType' object has no attribute 'channel'。我的代码如下:

@commands.command()
@commands.is_owner()
async def channel(self, ctx):
bot_channel = ctx.guild.voice_client.channel
await ctx.send(embed=discord.Embed(
title=f":eyes:  Ich befinde mich hier: {bot_channel}",
color=self.bot.get_embed_color(ctx.guild)))
if bot_channel is None:
await ctx.message.add_reaction("❌")

这是关于if bot_channel is None的下部。这里什么也没发生,只有输出显示在控制台中。这里的正确方法是什么?

NoneType没有任何属性

>>> foo = None
>>> print(foo.value)
AttributeError: 'NoneType' has no attribute 'value'

我告诉你,因为如果机器人没有连接到任何语音频道,ctx.guild.voice_client可以是None,有两种方法可以逃脱惩罚。

  1. 使用try/except
try:
bot_channel = ctx.guild.voice_client.channel
except AttributeError:
return await ctx.send('Bot is not in a voice channel')
  1. 首先检查voice_client是否为None
voice_state = ctx.guild.voice_client
if voice_state is None:
return await ctx.send('Bot is not in a voice channel')
bot_channel = voice_state.channel