【发布时间】:2021-07-18 06:17:56
【问题描述】:
这是我第一次使用 JSON,所以这可能是显而易见的。我正在尝试制作一个 Discord Bot,为用户提供 XP 和消息传递级别,为此我需要将数据写入外部 JSON 文件。我无法让它工作,所以我按照教程,完美地复制了它,但它仍然没有写入 JSON 文件,所以我处于死胡同。
我的路径:/Desktop/TGFY Bot/cogs
/TGFY Bot 保存我的主要机器人文件 /cogs 保存我的 leveling.py cog 和我的 users.json 文件
leveling.py 在下面
import discord
from discord.ext import commands
import json
class leveling(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
with open('users.json', 'r', encoding = 'utf8') as f:
user = json.load(f)
try:
with open('users.json', 'w', encoding = 'utf8') as f:
user[str(message.author.id)]['exp'] = user[str(message.author.id)]['exp'] + 1
lvl_start = user[str(message.author.id)]['level']
lvl_end = user[str(message.author.id)]['exp'] ** (1.5/4)
if lvl_start < lvl_end:
user[str(message.author.id)]['level'] = user[str(message.author.id)]['level'] + 1
lvl = user[str(message.author.id)]['level']
await message.channel.send(f'{message.author.name} has reached level {lvl}')
json.dump(user, f, sort_keys = True, indent = 4, ensure_ascii = False)
return
json.dump(user, f, sort_keys = True, indent = 4, ensure_ascii = False)
except:
with open('users.json', 'w', encoding = 'utf8') as f:
user = {}
user[str(message.author.id)] = {}
user[str(message.author.id)]['level'] = 0
user[str(message.author.id)]['exp'] = 0
json.dump(user, f, sort_keys = True, indent = 4, ensure_ascii = False)
def setup(bot):
bot.add_cog(leveling(bot))
我的 users.json 文件中只有 {}
当我运行我的机器人时,我没有收到任何错误,但是当我发送消息时,没有信息存储到 users.json
【问题讨论】:
-
您的问题中的缩进关闭了吗?还是 on_message 监听器实际上在 init 函数中?
-
在打开要写入的 json 文件之前尝试打印一些东西
-
@Kelo 缩进关闭了,但我修复了它,这给了我一个新问题。它在文件路径中找不到 users.json,所以我将其移至
/TGFY Bot。这行得通,并且得到了认可,但我仍然遇到同样的问题,即没有写入 users.json
标签: json discord.py bots