Discord.py编写AddRole/RemoveRole命令报CommandNotFound错误求助
问题现象
使用Python在PyCharm环境开发Discord机器人,实现addRole、removeRole角色管理命令时,调用addRole命令触发如下报错:
Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command "addRole" is not found
原实现代码如下:
@commands.command(pass_context = True) @commands.has_permissions(manage_roles = True) async def addRole(self, ctx, user : discord.Member, *, role : discord.Role): if role in user.roles: await ctx.send(f"{user.mention} already has that role! ({role})") else: await user.add_roles(role) await ctx.send(f"Added {role} to {user.mention}!") @addRole.error async def role_error(self, ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You need to have permissions to do this!") @commands.command(pass_context = True) @commands.has_permissions(manage_roles = True) async def removeRole(self, ctx, user : discord.Member, *, role : discord.Role): if role in user.roles: await user.remove_roles(role) await ctx.send(f"{user.mention} doesn't have that role! ({role})") else: await ctx.send(f"Removed {role} from {user.ention}!") @removeRole.error async def removeRole_error(self, ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You need to have permissions to do this!")
问题原因定位
- 直接触发CommandNotFound的核心原因:命令未注册到机器人实例。从代码带
self参数的写法能看出,这两个命令写在继承commands.Cog的功能类中,但没有执行Cog加载逻辑,机器人扫描不到这两个命令,因此判定命令不存在。 - 代码额外存在3处会导致功能异常的bug:
removeRole判断逻辑完全写反:检测到用户持有目标角色时执行移除,却返回“用户没有该角色”的提示;用户没有角色时反而走移除成功分支,会触发调用报错removeRole成功分支存在拼写错误:user.ention应为user.mention,执行时会触发属性不存在的报错- 代码中
pass_context = True是discord.py 1.0版本前的旧参数,新版本已经默认传递上下文,该参数属于冗余代码,不影响运行但无实际作用
修复方案
- 补全Cog注册逻辑
如果命令写在Cog类中(示例类名为RoleManage),需要在代码中添加Cog加载逻辑,将类实例注册到机器人:
# discord.py 2.0+ 版本用协程方式注册 async def setup(bot): await bot.add_cog(RoleManage(bot)) # discord.py 1.x 旧版本直接调用同步方法 # bot.add_cog(RoleManage(bot))
- 修正代码中的逻辑、拼写错误,移除冗余参数,修正后完整代码如下:
@commands.command() @commands.has_permissions(manage_roles = True) async def addRole(self, ctx, user : discord.Member, *, role : discord.Role): if role in user.roles: await ctx.send(f"{user.mention} already has that role! ({role})") else: await user.add_roles(role) await ctx.send(f"Added {role} to {user.mention}!") @addRole.error async def role_error(self, ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You need to have permissions to do this!") @commands.command() @commands.has_permissions(manage_roles = True) async def removeRole(self, ctx, user : discord.Member, *, role : discord.Role): # 修正反转的判断逻辑 if role not in user.roles: await ctx.send(f"{user.mention} doesn't have that role! ({role})") else: await user.remove_roles(role) # 修正拼写错误 await ctx.send(f"Removed {role} from {user.mention}!") @removeRole.error async def removeRole_error(self, ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You need to have permissions to do this!")
- 保存代码后重启机器人进程,命令即可正常识别调用。
内容的提问来源于stack exchange,提问作者Leon Warta
相关产品推荐
相关产品推荐

