python - 体验 (XP) 不适用于所有用户 JSON Discord.PY
问题描述
我正在尝试为在大约有 50-60 人输入的房间中输入的消息打分。它将第一次将用户添加到 JSON 文件中,但不会为他们键入的消息添加任何分数。我再次对其进行了测试,只有一个用户获得了他们输入的消息的积分,其余的保持不变。这是代码:
@client.event
async def on_message(message):
if message.content.lower().startswith('!points'):
await client.send_message(message.channel, "You have {} points!".format(get_points(message.author.id)))
user_add_points(message.author.id,1)
def user_add_points(user_id: int, points: int):
if os.path.isfile("users.json"):
try:
with open('users.json', 'r') as fp:
users = json.load(fp)
users[user_id]['points'] += points
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent=4)
except KeyError:
with open('users.json', 'r') as fp:
users = json.load(fp)
users[user_id] = {}
users[user_id]['points'] = points
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent = 4)
else:
users = {user_id:{}}
users[user_id]['points'] = points
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent=4)
def get_points(user_id: int):
if os.path.isfile('users.json'):
with open('users.json', 'r') as fp:
users = json.load(fp)
return users[user_id]['points']
else:
return 0
解决方案
我们应该只需要读取一次文件,然后在需要时将修改保存到文件中。我没有注意到任何会导致所描述行为的逻辑错误,因此这可能是关于允许您的机器人查看哪些消息的权限问题。为了便于调试,我简化了您的代码并添加了一些打印来跟踪正在发生的事情。我还添加了一个守卫on_message
来阻止机器人对自己做出响应。
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")
推荐阅读
- java - 如何在 JAVA 中将 excel/CSV 表转换为 JSON 对象?
- github - Github Actions:设置输出似乎不起作用
- java - java中获取String mongo字段数据类型
- docker - 警告:目录'/home/jovyan/.cache/pip'
- javascript - 如何使用 Svelte + Flask (Jinja2) 模板?
- powershell - System.DllNotFoundException:无法加载 DLL 'System.Data.SQLite.DLL':(来自 HRESULT 的异常:0x8007045A)
- python - 将列转换为相同的格式
- batch-file - 如何在批处理编程中替换字符串
- kubernetes - 列出过去 24 小时内新创建的 Kubernetes pod
- python - PyPDF2 提取空白文本