读取内存中的一个json文件discord.py

我正在尝试从网站获取一个 jsonfile 到内存中,然后读取其中的内容。但我不太清楚该怎么做......这就是我所做的


@bot.command(name="meme")

async def memcommand(ctx, type: str = None):

    if type is None:

        subreddit = reddit.subreddit("memes")

        submission = subreddit.random()

        posturl = f"https://www.reddit.com/r/memes/comments/{submission}/.json"

        try:

            # urllib.request.urlretrieve(posturl, f'reddit_jsons/{submission}.json')

            r = requests.get(posturl)

            inmemoryfile = io.BytesIO(r.content)

        except Exception:

            await ctx.send(f"Seems like reddit doesn't like this many requests... Let's wait a bit....")

            return

        with open(inmemoryfile) as f: # This throws the error

            actualfile = json.load(f)

        imgurl = actualfile[0]['data']['children'][0]['data']['url']

错误是


Ignoring exception in command meme:

Traceback (most recent call last):

  File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped

    ret = await coro(*args, **kwargs)

  File "D:/Ficheiros/Pastas/Tudo/Coding/Python/Projects/Server-Utils/bot.py", line 958, in memcommand

    with open(inmemoryfile) as f:

TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO


The above exception was the direct cause of the following exception:


Traceback (most recent call last):

  File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke

    await ctx.command.invoke(ctx)

  File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke

    await injected(*ctx.args, **ctx.kwargs)

  File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped

    raise CommandInvokeError(exc) from exc

如果不能这样,我如何打开文件并查看其内容?


POPMUISE
浏览 134回答 1
1回答

慕无忌1623718

该requests.Response对象有一个json方法可以为您读取 json。请注意,对于async函数,您不应该进行阻塞requests.get。本回答重点关注json部分。@bot.command(name="meme")async def memcommand(ctx, type: str = None):    if type is None:        subreddit = reddit.subreddit("memes")        submission = subreddit.random()        posturl = f"https://www.reddit.com/r/memes/comments/{submission}/.json"        try:            # urllib.request.urlretrieve(posturl, f'reddit_jsons/{submission}.json')            r = requests.get(posturl)        except Exception:            await ctx.send(f"Seems like reddit doesn't like this many requests... Let's wait a bit....")            return        actualfile = r.json()        imgurl = actualfile[0]['data']['children'][0]['data']['url']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python