为什么我无法验证这些数字?

Why I can't verify these numbers?

我有一个问题:我想从 json 文件中获取一些整数,然后检查那里是否有等于当前 date/month 的整数。但是我有这个错误:

Unhandled exception in internal background task 'check_for_birthday'.
Traceback (most recent call last):
  File "C:\Users\baron_btjit4i\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\tasks\__init__.py", line 168, in _loop
    await self.coro(*args, **kwargs)
  File "c:\Users\baron_btjit4i\Desktop\Autrebot\Cogs\birthday.py", line 35, in check_for_birthday
    if member['month'] == curmonth:
TypeError: string indices must be integers

我的函数:

    @tasks.loop(seconds=1)
    async def check_for_birthday(self):
        now = datetime.datetime.now()
        curmonth = now.month
        curday = now.day
        guild = self.client.get_guild(guild_id)
        channel = self.client.get_channel(channel_id)
        
        with open(birthday_file, 'r') as f:
            var = jason.load(f)
            for member in var:
                if member['month'] == curmonth:
                    if member['day'] == curday:
                        try:
                            await self.client.get_user(member).send("Happy birthday!")
                        except:
                            pass
                        success = False
                        index = 0
                        while not success:
                            try:
                                await channel.send(f"Happy birthday to <@{member}>!")
                            except nextcord.Forbidden:
                                                    index += 1
                            except AttributeError:
                                index += 1
                            except IndexError:
                                # if the server has no channels, doesn't let the bot talk, or all vc/categories
                                pass
                            else:
                                success = True

我的 json 文件:

{
    "712319703602692117": {
        "month": 12,
        "day": 12
    }
}

你能帮帮我吗?

由于 var 是字典,for member in var: 将遍历其 。来自 the docs:

iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).

所以在你的情况下,member == "712319703602692117"。因此,member['month'] 是一个错误,因为字符串只能由整数和切片索引,不能 其他字符串。

您可以使用 dict.items:

迭代 key/value 对
for key, member in var.items():
    ...

这里,member == {"month": 12, "day": 12}.