添加Cog时触发AttributeError:'Misc'对象无'bot'属性
Discord机器人Cog初始化AttributeError问题解决
在开发Discord机器人时,Misc.py这个Cog触发了AttributeError,错误提示'Misc' object has no attribute 'bot',以下是相关代码和错误信息:
主Discord机器人文件代码
import discord from discord.ext import commands import random import json import os import asyncio def get_prefix(bot, message): with open("jsonfiles/prefixes.json", "r") as f: prefixes = json.load(f) return prefixes[str(message.guild.id)] bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all()) with open("textfiles/keys.txt", "r") as f: lines = f.readlines() bot_token = lines[0] bot_invite_url = lines[1] @bot.event async def on_ready(): print("Successfully connected to Discord.") print("To invite, copy and paste this link into url and go from there. ", bot_invite_url) @bot.event async def on_guild_join(guild): with open("jsonfiles/prefixes.json", "r") as f: prefixes = json.load(f) prefixes[str(guild.id)] = "=" with open("jsonfiles/prefixes.json", "w") as f: json.dump(prefixes, f, indent=4) @bot.event async def on_guild_remove(guild): with open("jsonfiles/prefixes.json", "r") as f: prefixes = json.load(f) prefixes.pop(str(guild.id)) with open("jsonfiles/prefixes.json", "w") as f: json.dump(prefixes, f, indent=4) async def load(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") async def main(): async with bot: await load() await bot.start(bot_token) asyncio.run(main())
出现问题的Cog代码(Misc.py)
import discord from discord.ext import commands import random class Misc(commands.Cog): def __init__(self, bot): bot = self.bot @commands.Cog.listener() async def on_ready(self): print("Misc.py is online.") @commands.command(aliases=["8ball", "eightball"]) async def magic_eight_ball(self, ctx, *, question): with open("textfiles/responses.txt", "r") as f: random_responses = f.readlines() response = random.choice(random_responses) await ctx.send(response) #the error occurs here (i at least think) async def setup(bot): await bot.add_cog(Misc(bot))
触发的错误信息
File "d:\DiscordBot\cogs\misc.py", line 7, in __init__ bot = self.bot ^^^^^^^^ AttributeError: 'Misc' object has no attribute 'bot'
问题原因与解决方案
这是代码疏漏,不是bug。问题出在Misc类的__init__方法里,赋值语句写反了:
- 错误写法:
bot = self.bot,试图将未定义的self.bot赋值给局部变量bot,但此时self.bot还不存在,直接触发AttributeError。 - 正确写法:将传入的bot实例绑定到类的属性上,即:
def __init__(self, bot): self.bot = bot
修改后,Cog就能正确接收并持有机器人实例,错误即可解决。
内容的提问来源于stack exchange,提问作者Paradoxial
相关产品推荐
相关产品推荐

