【问题标题】:How do I print out an"AttributeError" error with my Discord bot?如何使用我的 Discord 机器人打印出“AttributeError”错误?
【发布时间】:2020-12-17 23:44:37
【问题描述】:

我使用一个命令来检查我的机器人在哪个频道中。如果它在频道中,那么一切都会很好地输出。但如果机器人不在频道中,我会得到控制台条目: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的下部。这里什么都没有发生,只有输出显示在控制台中。这里的正确方法是什么?

【问题讨论】:

    标签: python discord bots discord.py


    【解决方案1】:

    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
    

    【讨论】:

    • 感谢解释,第一种方法很好用!
    猜你喜欢
    • 2022-12-07
    • 2021-02-24
    • 2019-01-12
    • 1970-01-01
    • 2021-09-02
    • 2021-01-11
    • 2021-08-14
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多