Experience (xp) Not Working For All Users Json Discord.py
I'm trying to give points for messages typed in a room that has around 50-60 people that type in it. It will add the user to the JSON file the first time, but it won't add any more
Solution 1:
We should only need to read the file once, and then just save our modifications to the file when we need to. I didn't notice any logical errors that would lead to the behavior described, so it may be a permissions issue regarding what messages your bot is allowed to see. To facilitate debugging, I've simplified your code and added some prints to track what's going on. I also added a guard in on_message to stop the bot from responding to itself.
import json
import discord
client = discord.Client()
try:
with open("users.json") as fp:
users = json.load(fp)
except Exception:
users = {}
def save_users():
with open("users.json", "w+") as fp:
json.dump(users, fp, sort_keys=True, indent=4)
def add_points(user: discord.User, points: int):
id = user.id
if id not in users:
users[id] = {}
users[id]["points"] = users[id].get("points", 0) + points
print("{} now has {} points".format(user.name, users[id]["points"]))
save_users()
def get_points(user: discord.User):
id = user.id
if id in users:
return users[id].get("points", 0)
return 0
@client.event
async def on_message(message):
if message.author == client.user:
return
print("{} sent a message".format(message.author.name))
if message.content.lower().startswith("!points"):
msg = "You have {} points!".format(get_points(message.author))
await client.send_message(message.channel, msg)
add_points(message.author, 1)
client.run("token")
Post a Comment for "Experience (xp) Not Working For All Users Json Discord.py"