discord.py中kick命令错误处理报错:'function'对象无'error'属性
问题:discord.py kick命令错误处理触发AttributeError
尝试为discord.py的kick命令添加错误处理时,出现报错:AttributeError: 'function' object has no attribute 'error',报错位置为@kick.error行。
完整代码
@client.command() @has_permissions(manage_roles=True, kick_members=True) async def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @kick.error async def kick_error(ctx, error): if isinstance(error, MissingPermissions): await ctx.send(f"Sorry you don't have permission to use that command{message.author.mention}")
报错代码段
@kick.error async def kick_error(ctx, error): if isinstance(error, MissingPermissions): await ctx.send(f"Sorry you don't have permission to use that command{message.author.mention}")
错误回溯信息
Traceback (most recent call last): File "c:\Users\Normal\Downloads\DiscordServer Bot\PaddsIslandServer.py", line 76, in <module> @kick.error AttributeError: 'function' object has no attribute 'error' Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x0000022572BA87C0>
解决方法
修正装饰器顺序
问题核心是装饰器顺序错误:@client.command()必须是最靠近函数的装饰器,权限检查装饰器@has_permissions要放在它的上方。原顺序中@has_permissions会把命令函数包装成普通函数,导致kick丢失了discord.py命令对象的error属性。修复错误处理中的变量问题
错误处理函数里的message.author.mention未定义,应替换为ctx.author.mention来获取命令调用者。
修正后的完整代码:
from discord.ext.commands import has_permissions, MissingPermissions @has_permissions(manage_roles=True, kick_members=True) @client.command() async def kick(ctx, member : discord.Member, *, reason=None): await member.kick(reason=reason) @kick.error async def kick_error(ctx, error): if isinstance(error, MissingPermissions): await ctx.send(f"抱歉,你没有使用该命令的权限 {ctx.author.mention}")
内容的提问来源于stack exchange,提问作者Github.io.user
相关产品推荐
相关产品推荐

