Experience (XP) not working for all users JSON Discord.PY

会有一股神秘感。 提交于 2019-12-02 12:23:52

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!