Python开发Discord机器人时cog无报错但命令无法执行如何解决
Discord机器人Cog命令无法执行问题修复
存在的问题
- Cog文件代码结构错误:
help方法缩进错误,写在了setup函数内部,且不属于Help类,既不会被加载,也不符合类方法的书写规则。 - 装饰器使用错误:你要实现的是
!help前缀命令,错误使用了@commands.Cog.listener()事件监听装饰器,应该使用命令装饰器@commands.command()。 - 类方法参数缺失:Cog内的命令方法第一个参数必须是类实例自身
self,原有代码缺失该参数。 - 主文件命令处理拦截:重写
on_message事件后没有手动调用process_commands方法,所有前缀命令都会被该事件拦截,不会向下分发执行。 - 内置命令冲突:discord.py默认自带
help命令,和你自定义的命令重名会冲突,需要先移除默认的help命令。
修复方案
1. 修复cogs/help.py代码
from discord.ext import commands class Help(commands.Cog): def __init__(self, bot): self.bot = bot # 移到类内部,使用正确的命令装饰器,补全self参数 @commands.command() async def help(self, ctx, *, text=None): await ctx.send(f'**Help**\nno') def setup(bot): bot.add_cog(Help(bot))
2. 修复主文件代码
import discord from discord.ext import commands # 移除默认的help命令避免冲突 client = commands.Bot(command_prefix='!', help_command=None) @client.event async def on_ready(): print('Toh online {0.user}'.format(client)) await client.change_presence(activity=discord.Game(name="Cetriolino è un mega chaddone!")) @client.event async def on_message(message): if message.author == client.user: return if 'cetriolino' in message.content.lower() or 'emme'in message.content.lower(): await message.channel.send('🗿') if 'chad' in message.content.lower() or '🗿' in message.content.lower(): await message.channel.send('🗿') # 新增这行,处理前缀命令分发 await client.process_commands(message) initial_extensions = ['cogs.help'] if __name__ == '__main__': for extension in initial_extensions: client.load_extension(extension) client.run('你的机器人Token')
内容的提问来源于stack exchange,提问作者Cetriolino
相关产品推荐
相关产品推荐

