【发布时间】:2021-04-22 17:57:10
【问题描述】:
我有一个命令,您可以在其中输入正确答案。如果正确,用户将获得 JSON 中的积分。但是我的更新功能似乎被破坏了,因为在再次正确执行之后,在 JSON 中再次为同一用户创建了一个条目。但是,我只想更新积分。此外,JSON 在关于用户的第二个条目之后停止。出了什么问题?
代码:
correct_answers = "A"
# Open the JSON after start
def json_open():
with open('users.json', 'r', encoding='utf-8') as f:
users = json.load(f)
return users
class Questions(commands.Cog, name='Question'):
"""Question bot"""
def __init__(self, bot):
super().__init__()
self.bot = bot
@commands.command()
async def question(self, ctx, answer):
self.question.enabled = False
global correct_answers
if correct_answers != answer:
await ctx.author.send(f"You guessed {answer} which is **wrong**. Good luck next time!")
await ctx.message.delete()
return
# OPEN JSON FILE, LOAD DATA
with open('users.json', 'r') as f:
users = json.load(f)
await self.update_data(users, ctx.message.author)
await self.add_experience(users, ctx.message.author, 10)
with open('users.json', 'w') as f:
json.dump(users, f)
await ctx.message.delete()
# UPDATE DATA
async def update_data(self, users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]['Points'] = 0
#users[user.id]['level'] = 1
async def add_experience(self, users, user, exp):
users[user.id]['Points'] += exp
看起来最后一个函数不起作用还是不需要add_experience 函数?
第二次执行后的 JSON 如下所示:
{"MYID": {"Points": 10}, "MYIDAGAIN": {"Points": 10}}
【问题讨论】:
标签: json discord discord.py