Discord.py机器人设置服务器前缀出现Config无prefixes属性MongoDB错误
问题定位与修复方案
错误根因定位
- 报错明确指向
Configcog类实例不存在prefixes属性,你贴出的代码里写的是self.bot.prefixes.find,但错误日志显示实际运行的代码是self.prefixes.find,说明本地运行的代码漏写了.bot前缀,没有从bot实例上调用MongoDB集合 - 存在隐藏错误:
deleteprefix方法里写了self.bot.bot.prefixes,多了一层.bot,后续运行也会触发属性不存在错误 - 大概率存在主文件配置问题:你初始化MongoDB的prefixes集合后,没有将集合绑定到bot实例上,导致就算写对了
self.bot.prefixes也会找不到属性 - 额外语法问题:MongoDB查询单条数据应该用
find_one方法而非find,且参数需要传查询字典,不能直接传入服务器ID
修复步骤
1. 修正主文件MongoDB绑定配置
在主文件初始化bot后,必须将MongoDB的prefixes集合绑定到bot实例,示例代码(如果用异步驱动motor写法一致):
# 主文件示例 from pymongo import MongoClient from discord.ext import commands import discord mongo_client = MongoClient("你的MongoDB连接串") db = mongo_client["你的数据库名称"] bot = commands.Bot(command_prefix="默认前缀", intents=discord.Intents.all()) # 关键:把prefixes集合绑定到bot实例,cog里才能通过self.bot.prefixes调用 bot.prefixes = db["prefixes"]
2. 修正Config cog代码
首先确保Config类的初始化方法正确接收并绑定bot实例,再修正两个命令的调用逻辑:
class Config(commands.Cog): # 必须有初始化方法绑定bot实例 def __init__(self, bot): self.bot = bot @commands.command() @commands.has_permissions(manage_guild=True) async def prefix(self, ctx, prefix=None): if prefix is None: return await ctx.send("Put in a prefix for me to change to!") # 修正查询方法和参数 data = await self.bot.prefixes.find_one({"_id": ctx.guild.id}) if data is None or "prefix" not in data: data = {"_id": ctx.guild.id, "prefix": prefix} data["prefix"] = prefix # 修正upsert写法 await self.bot.prefixes.replace_one({"_id": ctx.guild.id}, data, upsert=True) await ctx.send("I have changed the server's prefix to {}".format(prefix)) @commands.command(aliases=["dp"]) @commands.has_permissions(manage_guild=True) async def deleteprefix(self,ctx): # 修正多余的.bot层和unset写法 await self.bot.prefixes.update_one({"_id": ctx.guild.id}, {"$unset": {"prefix": ""}}) await ctx.send("The server's prefix has been set to default") def setup(bot): bot.add_cog(Config(bot))
注意:如果使用的是同步pymongo驱动,不需要加
await关键字,只有异步驱动motor才需要加await调用方法。
内容的提问来源于stack exchange,提问作者aDorzz
相关产品推荐
相关产品推荐

