discord.py中能否在Cog内使用多个监听器?同名监听器仅最后一个生效问题的解决方法
解决discord.py Cog中多个on_message监听器仅最后一个生效的问题
你遇到的问题根源很直白——Python类里同名的方法会被后面的定义直接覆盖。你在test类里写了两个on_message方法,第二个方法会完全替换掉第一个,所以只有最后一个会被注册为消息监听器,第一个相当于从来没存在过。
下面给你两种可行的解决方案:
方案1:合并逻辑到同一个监听器
把两个on_message里的代码合并到同一个方法中,这样所有逻辑都会被执行:
class test(commands.Cog): @commands.Cog.listener() async def on_message(self, message): # 第一个监听器的原有代码 if message.content.startswith("!greet"): await message.channel.send("Hello there!") # 第二个监听器的原有代码 if message.content.startswith("!farewell"): await message.channel.send("Goodbye!") def setup(bot): bot.add_cog(test(bot))
方案2:拆分逻辑到独立函数(保持代码整洁)
如果不想把所有代码堆在一个方法里,可以把不同的逻辑拆成单独的辅助函数,然后在on_message里统一调用:
class test(commands.Cog): @commands.Cog.listener() async def on_message(self, message): # 调用拆分后的逻辑函数 await self.handle_greeting(message) await self.handle_farewell(message) # 注意:如果你的监听器需要兼容bot的命令,记得加上这句 await self.bot.process_commands(message) # 第一个逻辑的独立函数 async def handle_greeting(self, message): if message.content.startswith("!greet"): await message.channel.send("Hello there!") # 第二个逻辑的独立函数 async def handle_farewell(self, message): if message.content.startswith("!farewell"): await message.channel.send("Goodbye!") def setup(bot): bot.add_cog(test(bot))
额外注意点
如果你的on_message监听器处理了消息(比如删除消息、拦截内容),一定要加上await self.bot.process_commands(message),否则bot的命令会被监听器拦截,无法正常触发。
内容的提问来源于stack exchange,提问作者ClawX69
相关产品推荐
相关产品推荐

