Reputation: 1557
My code:
@bot.command()
async def delwarn(ctx, member: discord.Member = None, warnid = None):
if member:
with open('warns.json', 'r') as fcheckifthere:
checkifthere = json.load(fcheckifthere)
if f'{member.id}' in checkifthere.keys():
amount = len(checkifthere[f'{member.id}'])
if f'{warnid}' in checkifthere[f'{member.id}']:
if not amount == 1:
# i want to delete the value f"{warnid}"
del checkifthere[f'{member.id}'][f'{warnid}']
with open('warns.json', 'w+') as fcheckifthere:
json.dump(checkifthere, fcheckifthere, sort_keys=True, indent=4)
Error:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str
I want to delete the specific value f"{warnid}", but I don't know how and I get this error.
Here is an example how the json file looks like:
{
305354423801217025: [
0145324124,
2142141244
]
{
Upvotes: 0
Views: 956
Reputation: 3994
Your error is in this line, where you try to delete the warn ID:
del checkifthere[f'{member.id}'][f'{warnid}']
checkifthere[f'{member.id}']
is a list and the index you're giving is a string. List indeces must be integer so you have an error.
The simplest way to delete list elements is to use list.remove(element)
:
checkifthere[str(member.id)].remove(warnid)
Also, you don't need f strings
, you can use str()
to convert integers and floats to strings.
With a bit of refactoring, here's how your command would look like:
from discord import Member
from discord.ext import commands
from json import load, dump
@bot.command()
async def delwarn(ctx, member: Member = None, warn_id: str = None):
if not member:
return
with open('warns.json', 'r') as file:
data = load(file)
member_id = str(member.id)
if not member_id in data.keys():
return
if warn_id in data[member_id] and not len(data[member_id]) == 1:
with open('warns.json', 'w') as file:
data[member_id].remove(warn_id)
dump(data, file, sort_keys=True, indent=4)
Upvotes: 1