我有2个独立的JSON文件,一个存储用户ID和“现金”,另一个存储用户ID和“城市”。我将它们存储在单独的JSON文件中的原因是为了防止错误,它只会丢失部分数据。
在排行榜上,我试图显示用户拥有的现金量以及他们来自哪个城市。现在,代码给了我一个关键错误:
File "c:\Users\test\Desktop\testclone\TESTCLONE.py", line 2411, in on_message
msg += '{0}. <@!{1}> {2} Dollars\n\n'.format(number +1, user, cash[user].get('dollars', 0)) + '\nCity: **{}**'.format(homecity[user].get('city',0))
KeyError: '244410964693221377'
此外,我尝试仅将城市显示为嵌入对象,并且我敢肯定,即使我没有遇到键盘错误,也不会抓住与现金最多的用户相关的城市。如果JSON文件“现金”也没有存储城市,是否可以做我想做的事?
try:
with open("homecity.json") as fp:
homecity = json.load(fp)
except Exception:
homecity = {}
def save_homecity():
with open("homecity.json", "w+") as fp:
json.dump(homecity, fp, sort_keys=True, indent=4)
def add_city(user: discord.User, city: str):
id = user.id
if id not in homecity:
homecity[id] = {}
homecity[id]["city"] = homecity[id].get("city", "") + city
print("{} is now in {}".format(user.name, homecity[id]["city"]))
save_homecity()
def get_city(user: discord.User):
id = user.id
if id in homecity:
return homecity[id].get("city", 0)
return 0
try:
with open("cash.json") as fp:
cash = json.load(fp)
except Exception:
cash = {}
def save_cash():
with open("cash.json", "w+") as fp:
json.dump(cash, fp, sort_keys=True, indent=4)
def add_dollars(user: discord.User, dollars: int):
id = user.id
if id not in cash:
cash[id] = {}
cash[id]["dollars"] = cash[id].get("dollars", 0) + dollars
print("{} now has {} dollars".format(user.name, cash[id]["dollars"]))
save_cash()
def get_dollars(user: discord.User):
id = user.id
if id in cash:
return cash[id].get("dollars", 0)
return 0
if message.content.startswith('!lb cash'):
cash_leaderboard = sorted(cash, key=lambda x : cash[x].get('dollars', 0), reverse=True)
msg = ''
for number, user in enumerate(cash_leaderboard) and enumerate(city_leaderboard):
msg += '{}. <@!{}> {} Dollars | **{}**\n\n'.format(number +1, user, cash[user].get('dollars', 0), homecity[user].get('city',0))
if number == 10:
break
else:
number += 1
embed = discord.Embed(
title="TOP LEADERBOARD\nLeaders:",
color=0x24d7cf,
description=msg
)
embed.set_author(name="BOT", icon_url="")
embed.set_thumbnail(url="")
embed.set_footer(text="BOT", icon_url="")
await client.send_message(message.channel, embed=embed)
答案 0 :(得分:0)
大脑炸完后,我意识到我一直都知道问题的答案。我改变了
msg += '{0}. <@!{1}> {2} Dollars\n\n'\n\n'.format(number +1, user, cash[user].get('dollars', 0)) + '\nCity:, **{}**'.format(homecity[user].get('city',0))
到
msg += '{}. <@!{}> {} Dollars | **{}**\n\n'.format(number +1, user, cash[user].get('dollars', 0), homecity[user].get('city',0))