You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py机器人设置服务器前缀出现Config无prefixes属性MongoDB错误

问题定位与修复方案

错误根因定位

  • 报错明确指向Config cog类实例不存在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:36:04