discord.py自定义Bot子类调用!hello触发CommandNotFound错误如何解决
问题根因
@command()装饰器默认仅对模块级别的全局函数生效,直接用在commands.Bot子类的内部方法上时,discord.py不会自动将该方法注册为可调用命令,所以触发“命令未找到”报错。- 类的实例方法第一个参数必须是实例本身
self,当前hello方法把ctx作为第一个参数,运行时参数传递逻辑完全错位。 - 方法定义了必填参数
arg,调用!hello时没有传参,即使命令注册成功也会触发参数缺失报错。
修复方案
直接替换MyBot.py为以下代码即可:
from discord.ext import commands from discord.ext.commands import command class MyBot(commands.Bot): def __init__(self): super().__init__(command_prefix="!") # 手动注册类内的hello命令 self.add_command(self.hello) async def on_ready(self): print("Bot ready.") @command(name="hello", help="Say hello") async def hello(self, ctx, *, arg=None): # self为首个必填参数,arg设置默认值None,支持不带参数调用 await ctx.send("Hello you!")
补充说明
如果不需要接收用户额外输入的参数,可以直接删除arg相关定义,方法签名改为async def hello(self, ctx):即可。如果后续有大量命令需要管理,推荐使用discord.py的cog(插件)体系组织代码,无需手动逐个注册命令。
内容的提问来源于stack exchange,提问作者Tanuki
相关产品推荐
相关产品推荐

