为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

POPMUISE 2023-05-23 16:13:54
我正在尝试从网站获取一个 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.BytesIOThe 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如果不能这样,我如何打开文件并查看其内容?
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

该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']


查看完整回答
反对 回复 2023-05-23
  • 1 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信