我如何获得aiohttp以输出reddit图像

问题描述 投票:0回答:1
@commands.command(aliases=['gt'])
async def cat(self, ctx):
    """Outputs image from r/greentext"""

    async with ctx.typing():
        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://www.reddit.com/r/greentext/hot/.json") as r:
                data = await r.json()

                embed = discord.Embed(title = "r/greentext", color = 0xFF0000)
                embed.set_image(url = data["url"])
                embed.set_footer(text = "r/greentext")

                await ctx.send(embed = embed)

我知道数据[“ url”]应该是正确的,因为这就是图像文件在网站上的保存形式如此屏幕截图所示:https://imgur.com/a/kTl0BOW整个网站json位于此处:https://www.reddit.com/r/greentext/hot/.json如果有人可以帮助我,我将找不到aiohttp帮助服务器,而discord.py服务器根本无法帮助我,因为它们都使您觉得想要帮助很愚蠢

python reddit aiohttp discord.py-rewrite
1个回答
0
投票

reddit响应的顶层没有url键;您所指的图像是预览图像,它们是每个帖子的图像,因此您需要遍历帖子并提取图像:

data = await r.json()
for post in data["data"]["children"]:
    images = post.get("preview", {}).get("images", [])
    if not images:
        print("no preview images for %s..." % post["data"]["title"])
        continue
    image = images[0]  # grab the first image
    embed = discord.Embed(title = "r/greentext", color = 0xFF0000)
    embed.set_image(url = image["source"]["url"])
    embed.set_footer(text = "r/greentext")

为了使习惯于reddit返回的响应,您可以在JSON viewer中打开响应并进行分析。

© www.soinside.com 2019 - 2024. All rights reserved.