我檢查用戶是否在表中的代碼:@client.eventasync def on_message(ctx): id = ctx.author.id with open('coins.json') as coins: coinData = json.load(coins) with open('shop.json') as shop: shopData = json.load(shop) await client.process_commands(ctx) if id in coinData: print('exists') else: coinData["players"][id] = 0 with open('coins.json', 'w') as coins: json.dump(coinData, coins)它正在讀取的 JSON 文件:{"players": {"325616103143505932": 0}}當有人發送消息時會發生什么:{"players": {"325616103143505932": 0, "325616103143505932": 0}}而且它不會在控制臺中打印“存在”,無論該人發送了多少消息,但它只添加了兩次鍵值對。
1 回答

幕布斯7119047
TA貢獻1794條經驗 獲得超8個贊
在 python 中,字符串值和整數值是不同的。
>>> a = 1
>>> b = '1'
>>> a == b
False
因此,您應該將現有的 json 文件轉換為使用整數 ID(通過刪除引號)或使用str()將整數 ID 轉換為字符串。
這里使用的是字符串轉換(對于整數,您無需更改任何內容,只需更新您的文件):
@client.event
async def on_message(ctx):
id = str(ctx.author.id) # this line
with open('coins.json') as coins:
coinData = json.load(coins)
with open('shop.json') as shop:
shopData = json.load(shop)
await client.process_commands(ctx)
if id in coinData:
print('exists')
else:
coinData["players"][id] = 0
with open('coins.json', 'w') as coins:
json.dump(coinData, coins)
添加回答
舉報
0/150
提交
取消