我正在嘗試創建一個不和諧的機器人,讓人們獲勝,然后將其存盤到一個 json 檔案中。當我運行命令 ?win @ 時,我遇到了一個錯誤,在錯誤中顯示了他們的 id。我相信這是因為他們的 id 不在 json 檔案中。但是,我希望我的代碼為他們的 id 創建一個條目,如果它不在 json 檔案中,則獲勝。這是我的功能和命令。
公開勝利
async def open_wins(user):
users = await get_win_data()
if str(user.id) in users:
return False
users[str(user.id)] = {"Wins": 0}
with open('leaderboard.json',"w") as f:
json.dump(users,f)
return True
獲取中獎資料
async def get_win_data():
with open("leaderboard.json", "r") as f:
users = json.load(f)
return users
贏碼
@client.command()
@commands.has_role("Draft Manager")
async def win(ctx,member: discord.Member = None ):
if not member:
member = ctx.author
await open_wins(member)
users = await get_win_data()
user = member
onewin = 1
await ctx.send(f"You just gained {onewin} win ")
users[str(user.id)]["Wins"] = onewin
with open("leaderboard.json", "w") as f:
json.dump(users, f, indent=4)
這是我的 json 檔案
{
"325837218222440460": {
"Wins": 1
}
}
我想注意 win 命令僅在我執行 "?win" 時才有效,但是當我執行 "?win <@user>" 時,就會出現錯誤。
uj5u.com熱心網友回復:
await open_wins(member)僅當member為 None時才使用。但是如果你使用“?win <@user>”,@user可能仍然沒有記錄到你的檔案中。因此,您需要await open_wins(member)在所有情況下都使用函式。
@client.command()
@commands.has_role("Draft Manager")
async def win(ctx,member: discord.Member = None ):
if not member:
member = ctx.author
await open_wins(member)
users = await get_win_data()
user = member
onewin = 1
await ctx.send(f"You just gained {onewin} win ")
users[str(user.id)]["Wins"] = onewin
with open("leaderboard.json", "w") as f:
json.dump(users, f, indent=4)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376091.html
