Discord Bot运行正常但不响应命令的问题及解决方法
Discord.py子类化commands.Bot后命令无法触发的问题解决
问题概述
基于commands.Bot实现自定义Bot类MyBot,在类内部通过@commands.command装饰器定义了hello命令,但发送$hello时命令始终无法触发。Bot能正常启动,on_ready事件可正常触发,所有消息(包括命令消息)都会进入on_message处理,且已在on_message中调用await self.process_commands(message),也尝试移除@commands.command的name参数,均未解决问题。
运行环境:Windows 10、Python 3.11、discord.py 2.2.2
原问题代码
from discord.ext import commands from discord import Intents class MyBot(commands.Bot): def __init__(self) -> None: intents = Intents.default() intents.message_content = True super().__init__( command_prefix='$', intents=intents ) @commands.command(name='hello') async def hello(self, ctx): await ctx.send('Hello!') async def on_ready(self): print(f'{self.user}<{self.user.id}> is now running') async def on_message(self, message): await self.process_commands(message) print(f'{self.user}<{self.user.id}> received a message')
问题原因
在commands.Bot的子类中直接使用@commands.command装饰类方法时,discord.py无法自动将这些命令注册到Bot实例。因为@commands.command装饰器默认会将命令注册到当前模块的全局Bot实例,子类内部的方法不会被自动识别和加载。
解决方法
方案一:使用Cog封装命令(已验证有效)
将命令逻辑封装到commands.Cog子类中,在Bot的on_ready事件中注册该Cog,即可正常触发命令。
修正后代码
from discord.ext import commands from discord import Intents class CommandCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def hello(self, ctx): await ctx.send('Hello!') class MyBot(commands.Bot): def __init__(self) -> None: intents = Intents.default() intents.message_content = True super().__init__( command_prefix='$', intents=intents ) async def on_ready(self): await self.add_cog(CommandCog(self)) # 注册Cog print(f'{self.user}<{self.user.id}> is now running') async def on_message(self, message): await self.process_commands(message) print(f'{self.user}<{self.user.id}> received a message')
方案二:手动注册命令(简化方案)
无需创建Cog,在Bot子类的__init__方法中手动将类方法添加为命令,放在super().__init__之后即可:
from discord.ext import commands from discord import Intents class MyBot(commands.Bot): def __init__(self) -> None: intents = Intents.default() intents.message_content = True super().__init__( command_prefix='$', intents=intents ) self.add_command(self.hello) # 手动注册命令 @commands.command(name='hello') async def hello(self, ctx): await ctx.send('Hello!') async def on_ready(self): print(f'{self.user}<{self.user.id}> is now running') async def on_message(self, message): await self.process_commands(message) print(f'{self.user}<{self.user.id}> received a message')
内容的提问来源于stack exchange,提问作者ndrey
相关产品推荐
相关产品推荐

