尝试使用意外的mimetype:text/html解码JSON

2024-09-30 03:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的discord机器人中的meme命令以前可以工作,但它突然停止工作。。。。 这是密码

@commands.command(name = 'meme')
@commands.cooldown(1, 2, BucketType.user)
async def meme(self,ctx):
    '''get a random meme from reddit!'''
    subreddits = ['dankmemes', 'memes','meme', 'wholesomememes', 'comedyheaven','pewdiepiesubmissions', 'KidsAreFuckingStupid','cursedcomments','HolUp','blursedimages','rareinsults']
    subreddit = random.choice(subreddits)
    async with aiohttp.ClientSession() as cs:
        async with cs.get(f'https://www.reddit.com/r/{subreddit}/new.json?sort=hot') as r:
            res = await r.json()
            post=res['data']['children'][random.randint(0, 25)]
            url = post['data']['url']
            title= post['data']['title']
            embed = discord.Embed(title = title,description=f"Meme for {ctx.author}")
            embed.set_image(url=url)
            embed.set_footer(text = f'Image from r/{subreddit}')
            await ctx.send(embed=embed)

它几天前停止工作了。。我一直试图找到一个解决方案,但很长一段时间都没有成功 我试过这个: https://stackoverflow.com/a/48841071/16390831

但我尝试的每个解决方案都会出现以下两个错误之一: aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://www.reddit.com/r/meme/new.json?sort=hot')

File "C:\Users\dhrav\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped ret = await coro(*args, **kwargs) File "c:\Users\dhrav\Documents\Python Projects\SpaceBot\SpaceBot\commands.py", line 565, in meme res = json.loads(rs) File "C:\Users\dhrav\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Users\dhrav\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\dhrav\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

怎么了?这与RedditAPI有关吗? 我试着打印cs,它给出了一个关于服务器和其他东西的奇怪输出

同样,它在几天前确实工作了,但突然停止工作,似乎没有任何原因。 任何帮助都将不胜感激。 提前谢谢


Tags: inpyjsonurltitlelocallineembed
2条回答

API正在返回Content-Type: text/html头,您可以将content_type=None传递到r.json以忽略头:

res = await r.json(content_type=None)

似乎Reddit发送了错误的内容类型。您可以将所需的内容传递给json()方法

res = await r.json(content_type='text/html')

相关问题 更多 >

    热门问题