删除对我不起作用的高级命令

时间:2021-07-05 04:07:26

标签: python discord discord.py

import os
import discord
import json
from discord.ext import commands, check

@bot.command()
async def removepremium(ctx, user : discord.Member):
    if ctx.author.id != 475975102576590849: #put your user id on discord here
        return

    with open("premium_users.json") as f:
        premium_users_list = json.load(f)

    if user.id in premium_users_list:
      premium_users_list.pop(user.id)
    else:
        await ctx.send(f"{user.mention} is not in the list, so they cannot be removed!")
        return

    with open("premium_users.json", "w+") as f:
        json.dump(premium_users_list, f)

    await ctx.send(f"{user.mention} has been removed!")

removepremium 不起作用,我收到此错误 -

忽略命令 removepremium 中的异常: 文件“main.py”,第 247 行,在 removepremium 中 premium_users_list.pop(user.id) 索引错误:弹出索引超出范围

1 个答案:

答案 0 :(得分:0)

list.pop(N) method 从列表中删除第 N 个元素。

a = ["a","b","c"]
a.pop(1)
print(a)
<块引用>

['a', 'c']

当您尝试 premium_users_list.pop(user.id) 时,您实际上是要删除具有精确 ID 的用户还是删除列表中位置为 ID 的用户?

我不知道你的 JSON 数据是什么,所以试着用我的例子解释你的代码行为:

>>> users = [{"id": 100, "name": "A"}, {"id": 101, "name": "A"}, {"id": 102, "name": "A"}]
>>> 
>>> users.pop(101)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> 
>>> users.pop(1)
{'id': 101, 'name': 'A'}
>>> 
>>> print(users)
[{'id': 100, 'name': 'A'}, {'id': 102, 'name': 'A'}]

如果您想使用 ID = 101 删除用户,您应该执行以下操作:

>>> users = [{"id": 100, "name": "A"}, {"id": 101, "name": "A"}, {"id": 102, "name": "A"}]
>>> 
>>> users_without_101 = [i for i in users if not i['id'] == 101]
>>> 
>>> print(users_without_101)
[{'id': 100, 'name': 'A'}, {'id': 102, 'name': 'A'}]