Reputation: 3
My code to check whether a user is in the table or not:
@client.event
async 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)
The JSON file it is reading:
{"players": {"325616103143505932": 0}}
What happens when someone sends a message:
{"players": {"325616103143505932": 0, "325616103143505932": 0}}
And it doesn't print 'exists' in console, no matter how many messages the person sends, but it adds the key value pair only twice.
Upvotes: 0
Views: 276
Reputation: 3924
In python, a string value and an integer value are different.
>>> a = 1
>>> b = '1'
>>> a == b
False
So you should either convert your existing json file to using integer IDs (by removing the quotes) or by using str()
to convert the integer ID to a string.
Here's using a string conversion (with integers you don't have to change anything, only update your file):
@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)
Upvotes: 1