簡體   English   中英

不會使用 json.load 加載 json 文件

[英]Will not load json file with json.load

使用我的 discord 機器人,我試圖在 json 文件中存儲一堆不同命令的響應。 該命令只是一組膽量,鍵為“膽量”,值是一個包含不同字符串的列表。 當我使用with open() function 時,它會將其注冊為一個目錄,您可以打印原始文件,但是當您嘗試使用var = json.load時,它什么也不做。 該行之后的任何代碼都不會運行。

我已經使用 shell 命令到 go 直接進入該文件並打開它。 這完全沒問題。 文件打印正常。

    @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只打印 object。 我也嘗試過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

As stated in comments, the issue comes from the author's defining a on_command_error or on_error function ( https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=on_command_error#discord.ext.commands. bot.on_command_error )

當它在 bot/cog 中的任何地方引發時,將使用異常/錯誤調用它。

-> 對於定義的 function,應該總是有一個默認情況,例如,如果你寫了一些if isinstance(e, SomeException): ... ,你將需要一個else: raise eelse: super().on_command_error(e)確保進一步處理默認情況,以防出現您未計划或您不需要在機器人/cog 中擔心的異常情況

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM