discord.py机器人Cogs文件加载失败报AttributeError错误求助
问题修复方案
核心错误点
- 监听器装饰器拼写错误:报错明确提示
discord.ext.commands没有Cogs属性,你代码中写的@commands.Cogs.listener()是错误写法,正确为单数形式@commands.Cog.listener() - 类构造方法格式错误:
UpdateCode类的初始化方法用了单下划线包裹的_init_,Python中类构造方法必须用双下划线包裹,即__init__,否则不会在类实例化时自动执行,会触发属性缺失报错 - 隐性语法问题:你定义的status循环列表里,
" Schrodinger's cat ???"行末尾缺少逗号,会导致该行字符串和下一行的十六进制字符串自动拼接,不符合你预期的状态切换效果
修改后的Cogs文件代码
import discord from discord.ext import commands, tasks from itertools import cycle class UpdateCode(commands.Cog): # 修正构造方法双下划线 def __init__(self, client): self.client = client # 建议把status初始化移到构造方法里,避免on_ready重复调用时重复生成cycle实例 self.status = cycle([ " Unanswered Question of Life", " Self - Referential Paradox", " Near-infinite density?", " Dark matter ?", " Measurement of the speed of light in one straight line", " Schrodinger's cat ???", # 补全缺失的逗号 "436c69636b2074686973206c696e6b20666f72206672656520766275636b7320212121212121203a200a68747470733a2f2f7777772e796f75747562652e636f6d2f77617463683f763d6451773477395767586351 (try to decrypt this)", "The light side of Discord is the path of many unnatural abilities" ]) # 修正装饰器为单数Cog @commands.Cog.listener() async def on_ready(self): print("We have logged in as {0.user}".format(self.client)) # 避免重复启动任务,先判断是否已运行 if not self.status_swap.is_running(): self.status_swap.start() @tasks.loop(minutes = 5) async def status_swap(self): await self.client.change_presence(activity = discord.Game(next(self.status))) def setup(client): client.add_cog(UpdateCode(client))
可选优化(针对主文件)
- 权限限制:给
load、unload指令增加管理员权限校验,避免普通用户随意操作Cog加载:
@client.command() @commands.has_permissions(administrator=True) async def load(ctx, extension): client.load_extension(f"cogs.{extension}") await ctx.send(f"已加载{extension}") @client.command() @commands.has_permissions(administrator=True) async def unload(ctx, extension): client.unload_extension(f"cogs.{extension}") await ctx.send(f"已卸载{extension}")
- 意图配置:如果使用的是discord.py v2.x版本,需要显式配置网关意图,否则指令无法正常触发:
# 主文件初始化Bot前添加 intents = discord.Intents.default() intents.message_content = True # 开启消息内容读取权限,需要在Discord开发者后台也开启对应开关 client = commands.Bot(command_prefix = "!", intents=intents)
- v2.x适配:discord.py v2.x中
add_cog为异步方法,需要修改Cogs的setup方法为异步写法:
# Cogs文件中的setup方法修改为 async def setup(client): await client.add_cog(UpdateCode(client))
内容的提问来源于stack exchange,提问作者Daniesh Rieza
相关产品推荐
相关产品推荐

