【问题标题】:User XP Data Isn't Being Written To JSON File用户 XP 数据未写入 JSON 文件
【发布时间】: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


【解决方案1】:

你的代码很好,除了一行

except:
    with open('users.json', 'w', encoding = 'utf8') as f:
        user = {} # This empties your dictionary whenever a new user has sent a message
        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)

只需删除该行,您的代码就可以正常工作了。

下一次,请尝试从教程中了解更多代码,以了解如何将它们应用到您的用例中。

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 2015-07-21
    • 2018-05-26
    • 1970-01-01
    • 2022-06-29
    • 2016-03-07
    • 2019-12-20
    • 2017-04-15
    • 2021-11-11
    相关资源
    最近更新 更多