使用discord.py开发Discord机器人添加Cog功能报错,代码问题出在哪?
代码错误点及修复方案
存在的核心错误
- 函数归属错误:你定义的
on_message事件和命令逻辑完全写在了quotesCog类的外部,调用add_cog时只会加载类内部的逻辑,外部代码不会被Cog管理,自然不会生效。 - 装饰器使用错误:
on_message是消息监听事件,不能用@commands.command()装饰,Cog内的事件需要用@commands.Cog.listener()装饰。 - 逻辑冗余不符合框架规范:你已经使用了
commands.Bot框架,不需要手动在on_message里判断消息前缀触发命令,直接用框架提供的命令装饰器定义即可。 - Cog文件职责错误:如果你当前代码是单独的Cog扩展文件,不应该在文件内初始化
bot实例,bot实例需要在主入口文件中创建,再通过加载Cog的逻辑传入。
修正后的Cog文件代码(单独保存为quotes_cog.py)
import random from discord.ext import commands He_haram = [ "Do they not see the birds controlled in the atmosphere of the sky? none holds them up except Allah. Indeed in that are signs for a people who believe. Quran 16:79", "So be patient. Indeed, the promise of ALLAH is truth Quran 30:60", "our lord! Forgive me and my parents, and (all) the believers on the day when the reckoning will be established Quran 14:41", "And for those who fear Allah, he will make their path easy – Quran Al talak: 4" ] class quotes(commands.Cog): def __init__(self, bot): self.bot = bot # Cog内的事件监听器写法,如果你不需要额外的消息拦截逻辑可以直接删掉整个on_message方法 @commands.Cog.listener() async def on_message(self, message): if message.author == self.bot.user: return # 正确的Cog内命令写法 @commands.command(name="quotes") async def send_quotes(self, ctx): await ctx.send(f" {ctx.author.name}, {random.choice(He_haram)}") def setup(bot: commands.Bot): bot.add_cog(quotes(bot))
主入口文件加载Cog的示例(主文件保存为main.py)
import discord from discord.ext import commands # 注意必须显式声明Intents,同时需要在Discord开发者后台开启对应权限 bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.event async def on_ready(): print(f"登录成功,身份是{bot.user}") # 加载Cog,填写Cog文件的文件名,不需要带.py后缀 await bot.load_extension("quotes_cog") bot.run("你的机器人Token")
注意:discord.py v2.0及以上版本强制要求显式声明消息内容等Intents权限,未开启权限会导致机器人无法接收用户消息,也无法触发命令。
内容的提问来源于stack exchange,提问作者Pez
相关产品推荐
相关产品推荐

