[英]KeyError in Discord.PY when the key exists
因此,我目前正在为我的 Discord 机器人创建一种货币,并且我正在尝试发出一个 give 命令,以便用户可以将货币提供给其他用户。 我不断收到 KeyError,但用户 ID 已经在 json 文件中。 有人可以看看,看看有什么可以做的吗? 我已经看到了很多关键错误问题的解决方案,但没有一个有用。
def addCoins(users, member, amount):
try:
users[member.mention] += amount
except KeyError:
users[member.mention] = amount
with open('user_coins.json', 'w') as f:
json.dump(users, f)
`@bot.command()
async def mycoins(ctx):
user = ctx.author
with open('user_coins.json', 'r') as f:
userCoinDic = json.load(f)
users = userCoinDic.keys()
if user.mention in users:
embcoins = discord.Embed(title=f"Your Coins, {user}", description=f"You have {userCoinDic[user.mention]} coins.", color=0xFF8300, inline=False)
await ctx.send(embed=embcoins)
else:
await ctx.send("You don't seem to have any coins...")
def giveCoins(users, member, amount):
try:
users[member] += int(amount)
except KeyError:
users[member] = int(amount)
@bot.command()
async def give(ctx, amount, userToGive):
user = ctx.author
with open('user_coins.json', 'r') as f:
userCoinDic = json.load(f)
giveCoins(userCoinDic, userToGive, amount)
userCoinDic[user.mention] -= int(amount)
await ctx.send(f"Successfully given {userToGive} {amount} lasagna coins")
with open('user_coins.json', 'w') as f:
json.dump(userCoinDic, f)
json 文件:
{"<@800485638583091210>": 130, "<@496433501751607316>": 35, "<@805067781769789482>": 30, "<@266012778358243339>": 5, "<@747549629335339149>": 35, "<@761003497239609354>": 100, "<@!878371788852166697>": 55}
和错误:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 189, in mycoins
embcoins = discord.Embed(title=f"Your Coins, {user}", description=f"You have {userCoinDic[user.mention]} coins.", color=0xFF8300, inline=False)
KeyError: '<@878371788852166697>'
正如我在 json 文件中注意到的那样(最后一个)给出的 id 和错误中有一个错字而不是
"<@!878371788852166697>": 55
它一定要是
"<@878371788852166697>": 55
当在 JSON 中时, member.mention
返回<@878371788852166697>
,它被存储为<@!878371788852166697>
,因此 KeyError ...
为避免此类错误,请勿使用提及作为键,因为返回的提及可能会更改; 它通常是<@id>
但有时可能是<@!id>
(这意味着用户的显示名称与其实际用户名不同)因此存在不一致。 我强烈建议不要使用提及作为关键,而是使用ids
,因为 Discord ID 永远不会改变,因此变得更可靠且更易于使用。
您可以使用.id
属性(例如member.id
)访问成员/用户 Object 的 ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.