python - 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}}
解决方案
我不知道您的代码中的某个地方是否在 json 中编写了一个新用户,例如当有人加入服务器时。
回溯只是说 Python 在您的用户变量中找不到条目“514026847680593922”(即来自 json 的数据)
发生这种情况时,也许您应该users[str(member.id)] = {"level": 0, "experience": 0}
将其保存到 json 文件中,然后重试
推荐阅读
- react-native - React-Native-Expo 在 iOS 中再次询问相机和相机胶卷权限?
- flutter - Flutter SQFlite 多对多关系设置
- javascript - javascript:新关键字在内部做什么
- r - 用红色填充值 = 0 的单元格
- javascript - Js:如何复制/粘贴文本,包括从网页到我的 html 页面的超链接
- android - android kotlin java.io.FileNotFoundException:/storage/emulated/0/number.txt:打开失败:EACCES(权限被拒绝)
- sql-server - 减少 CASE 表达式 SQL Server 的冗余
- python - 有没有办法在python中刮掉没有硒的JavaScript页面
- apache-kafka - minikube 上的 Kafka 控制台生产者/消费者 ERROR 向主题发送消息时出错
- node.js - 为什么承诺不返回?