首页 > 解决方案 > discord.ext.commands.errors.CommandInvokeError:命令引发异常:KeyError:'514026847680593922'

问题描述

所以我试图为用户创建一个查看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}}

标签: pythondiscord.py

解决方案


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

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

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


推荐阅读