My discord.py bot has an economy system in it, and you can get coins, but everyones balance(coin amount) connects to every server. Here is my code that deals with the .json
async def oAcc(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["bal"] = 100
with open("bank.json", "w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("bank.json", "r") as f:
users = json.load(f)
return users
How do I change this up so each server has a different "database".
CodePudding user response:
You could always just nest your users
dictionary within a server object and keep them all separate in the same file.
import json
# reading
def get_bank_data(server_name):
with open("bank.json", "r") as f:
database = json.load(f)
users = database.get(server_name, {})
return users
# writing
def put_bank_data(server_name, users):
with open("bank.json", "r") as f:
database = json.load(f)
database[server_name] = users
with open("bank.json", "w") as f:
json.dump(database, f)
server_name = "test_server"
server2_name = "test_server2"
user_id = '101'
users = get_bank_data(server_name)
users2 = get_bank_data(server2_name)
users[user_id] = {}
users[user_id]['bal'] = 100
users2[user_id] = {}
users2[user_id]['bal'] = 200
put_bank_data(server_name, users)
put_bank_data(server2_name, users2)
users_get = get_bank_data(server_name)
print(users_get[user_id]['bal'])
users2_get = get_bank_data(server2_name)
print(users2_get[user_id]['bal'])
Also, note I didn't use async
. There's not much reason to make a function asynchronous when you don't use await
within it. Check out this article if you want to see how you can speed up file io asynchronously, because as is you're not changing anything. https://www.twilio.com/blog/working-with-files-asynchronously-in-python-using-aiofiles-and-asyncio