discord.ext.commands.errors.CommandInvokeError:命令引发异常:KeyError:'514026847680593922'

时间:2021-03-30 15:39:35

标签: python discord.py

所以我试图创建一个命令来查看用户的 lvl 和 xp,这就是我编码的内容

@client.command(aliases = ['rank','lvl'])
async def level(ctx,member: discord.Member = None):

    if not member:
        user = ctx.message.author
        with open('level.json','r') as f:
            users = json.load(f)
        lvl = users[str(user.id)]['level']
        exp = users[str(user.id)]['experience']

        embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP " ,color = discord.Color.green())
        embed.set_author(name = ctx.author, icon_url = ctx.author.avatar_url)
        await ctx.send(embed = embed)
    else:
      with open('level.json','r') as f:
          users = json.load(f)
      lvl = users[str(member.id)]['level']
      exp = users[str(member.id)]['experience']
      embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP" ,color = discord.Color.green())
      embed.set_author(name = member, icon_url = member.avatar_url)

      await ctx.send(embed = embed)

但是总是报错

Ignoring exception in command level:
    ret = await coro(*args, **kwargs)
  File "d:\shit_2.py", line 65, in level
    lvl = users[str(user.id)]['level']
KeyError: '514026847680593922'

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

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '514026847680593922'

有人请帮忙

编辑:- 这是我的 json 文件的样子

{"<@514026847680593922>": {"experience": 95, "level": 3}}

1 个答案:

答案 0 :(得分:0)

我不知道您在 json 中是否在代码的某个地方编写了一个新用户,例如当有人加入服务器时。

回溯只是说 Python 在您的用户变量(即来自 json 的数据)中找不到条目 '514026847680593922'

发生这种情况时,也许您应该users[str(member.id)] = {"level": 0, "experience": 0} 并将其保存到 json 文件中,然后重试