Dominik
Dominik

Reputation: 3592

How do I print out an"AttributeError" error with my Discord bot?

I use a command to check which channel my bot is in. If it is in a channel, everything is output nicely. But if the bot is not in a channel I get the console entry: AttributeError: 'NoneType' object has no attribute 'channel'. My code looks like this:

@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("❌")

This is about the lower part with if bot_channel is None. Nothing happens here and only the output is shown in the console. What would be the correct method here?

Upvotes: 0

Views: 123

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

A NoneType doesn't have any attributes

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

I'm telling you this, cause ctx.guild.voice_client can be None if the bot isn't connected to any voice channel, there are two ways you can get away with that.

  1. Using try/except
try:
    bot_channel = ctx.guild.voice_client.channel
except AttributeError:
    return await ctx.send('Bot is not in a voice channel')
  1. Checking first if voice_client is 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

Upvotes: 1

Related Questions