Discord.py Python 经济机器人有 mongodb "NoneType" 错误

Discord.py Python economy bot with mongodb "NoneType" error

(英语不好) 我想用 mongodb 创建一个经济机器人,它在 2 天前运行良好,但现在我有“NoneType”错误

来源代码来自main.py(在数据库中添加用户):

@client.event
async def on_ready():
    print(f'''
[*]BOT: ON
[*]BOT NAME : {client.user}
[*]BOT ID: {client.user.id}
        ''')
    for guild in client.guilds:
        for member in guild.members:
            post = {
                "_id": member.id,
                "balance": 10000000,
                "xp": 0,
                "level": 1
            }
            if collection.count_documents({"_id": member.id}) == 0:
                collection.insert_one(post)

该代码有效,因为我在 db

上看到了

来自 cog 的源代码有问题:

class Economic(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.cluster  = MongoClient(f"mongodb+srv://discord:{secret}@cluster403.xn9cm.mongodb.net/discord1?retryWrites=true&w=majority")
        cluster  = MongoClient(f"mongodb+srv://discord:{secret}@cluster403.xn9cm.mongodb.net/users?retryWrites=true&w=majority")
        self.collection = cluster.users.tutu
    @commands.command(
        name = "balance",
        aliases = ["ball","money"],
        brief = "User balance",
        usage = "balance <@user>",
        description = "none....."
    )
    async def user_balace(self, ctx, member: discord.Member = None):
        if member is None:
            embed = discord.Embed(
                title = f"__{ctx.author}__'s balance",
                description = f"Money: {self.collection.find_one({'_id': ctx.author.id})['balance']}"
            )
            await ctx.send(embed=embed)

当我在控制台中键入“>balance”命令时,出现错误:

Ignoring exception in command balance:
Traceback (most recent call last):
  File "D:\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Nick403\Desktop\Apps\PROJECTS\BOT\cogs\eco.py", line 22, in user_balace
    description = f"Money: {self.collection.find_one({'_id': ctx.author.id})['balance']}"
TypeError: 'NoneType' object is not subscriptable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "D:\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "D:\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable

有人可以帮助我吗? (抱歉我的英语不好)

错误信息本质上是说 self.collection.find_one({'_id': ctx.author.id}) 是 returning 为 None。在 PyMongo Documentation 中,我们可以看到当在集合中找不到这样的项目时,find_one() 将 return None。如果您的数据库中没有特定用户,我会重写您的代码以保证安全。

if self.collection.find({'_id': ctx.author.id}).count() == 0:
    self.collection.insert_one({USER OBJECT})

user = self.collection.find_one({'_id': ctx.author.id})