首页 > 解决方案 > 如何处理自定义 NoneType 错误?

问题描述

我已经在我的机器人中实现了我自己的功能/检查。反正控制台中没有正常AttributeError的 as 输出,但是例如: 'NoneType' object has no attribute 'requested_by', 所以没有AttributeError, 因为是我自己的函数。

有没有办法通过机器人输出这个错误并可能用try/except语句处理它?(我确实尝试过但没有成功)

这是一个例子:

    @commands.command(aliases=["disconnect"])
    @commands.guild_only()
    @commands.check(is_audio_requester) # check what it is about
    async def leave(self, ctx):
        """Leaves the voice channel, if currently in one."""
        client = ctx.guild.voice_client
        state = self.get_state(ctx.guild)
        if client and client.channel:
            await client.disconnect()
            del self.states[ctx.guild.id]
        else:
            raise commands.CommandError("Not in a voice channel.")
        await ctx.send(
            embed=discord.Embed(title=":wave::skin-tone-3: I left the voice channel.",
                                color=self.bot.get_embed_color(ctx.guild)))

部分我仍然得到,无论出于何种原因:

'NoneType' object has no attribute 'requested_by'

导致错误的函数:

async def is_audio_requester(ctx):
    """Checks that the command sender is the song requester."""
    music = ctx.bot.get_cog("Music")
    state = music.get_state(ctx.guild)
    permissions = ctx.channel.permissions_for(ctx.author)
    if permissions.administrator or state.is_requester(ctx.author):
        return True
    else:
        raise commands.CommandError(
            "You need to be the song requester to do that.")

这些都没有打印出来!)

我无法处理此错误,然后我可能必须从频道中删除机器人或重新启动它。leave如果我在没有它的情况下执行命令,commands.check它当然可以工作。有没有什么办法解决这一问题?

我已经通过 尝试了我自己的自定义错误leave.error,但这似乎不起作用。正如预期的那样,即使通过类似的东西if XXX is None也不起作用。在这种情况下,我也不能使用Cog.cog.command_error文档,至少看起来是这样。

标签: pythondiscord.pynonetype

解决方案


推荐阅读