不会用 json.load 加载 json 文件

Will not load json file with json.load

使用我的 discord 机器人,我试图在 json 文件中存储对一堆不同命令的一堆响应。这个命令只是一组 dares,键为“dare”,值是一个包含不同字符串的列表。当我使用 with open() 函数时,它会将其注册为一个目录,您可以打印原始文件,但是当您尝试使用 var = json.load 时,它什么也做不了。该行之后的任何代码都不会 运行.

我使用 shell 命令直接进入该文件并打开它。这完全没问题。文件打印正常。

    @commands.command()
    async def dare(self, ctx):
        """Gives the user a dare to do"""
    
        with open("cogs/docs/json/responses.json") as f:
            print(-1)
            print(f)
            data = json.load(f)
            print(0)
            dares = data["dare"]
            print(1)
            selectedDare = random.choice(dares)

        await ctx.reply(selectedDare)

上面的代码只打印到-1f。没有什么比这更重要的了。 f 只是打印对象。我也试过 json.loads 等等,没有任何效果。 JSON 已正确安装。我完全迷路了。

所有响应都存储在一个列表中,这是仅针对此命令的响应。

// this is all the responses for the dares
    {
        "dare":[
            "Dare #1",
            "Dare #2",
            "Dare #3"
        ]
    }

我的机器人处理错误有一个 CommandError,但没有进一步的。


# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
        return

如评论中所述,问题来自作者定义的 on_command_erroron_error 函数 ( https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=on_command_error#discord.ext.commands.Bot.on_command_error )

在 bot/cog 中的任何位置引发时,将与 exception/error 一起调用。

-> 该定义的函数应该始终有一个默认情况,例如,如果您写几个 if isinstance(e, SomeException): ...,您将需要一个 else: raise eelse: super().on_command_error(e) 来确保默认情况会进一步处理,以防出现您未计划的异常或您无需在 bot/cog

中担心的情况

你可以把你的函数改成这个

# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
        return
    super().on_command_error(ctx, error)

或这个

# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
        return
    raise error

但我认为最好的方法是

# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
    else:
        super().on_command_error(ctx, error)

并且在添加其他条件时,例如其他错误,您将不得不使用 elif