I've a problem: I want to get some integers from a json file and then check there if there are equals to the current date/month. But I've this error:
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
My function:
@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
My json file:
{
"712319703602692117": {
"month": 12,
"day": 12
}
}
Can you help me ?
CodePudding user response:
Since var is a dictionary, for member in var: will iterate over its keys. From the docs:
iter(d)Return an iterator over the keys of the dictionary. This is a shortcut for
iter(d.keys()).
So in your case, member == "712319703602692117". Thus, member['month'] is an error because strings can only be indexed by integers and slices, not other strings.
You can iterate over key/value pairs using dict.items:
for key, member in var.items():
...
Here, member == {"month": 12, "day": 12}.
