【问题标题】:how do i get aiohttp to output reddit images我如何让 aiohttp 输出 reddit 图片
【发布时间】:2020-08-12 11:20:01
【问题描述】:
@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)

我知道 data["url"] 应该是正确的,因为这就是图像文件在网站上保存的内容 如此屏幕截图所示:https://imgur.com/a/kTl0BOW 整个网站的json在这里:https://www.reddit.com/r/greentext/hot/.json 如果有人可以帮助我,我找不到 aiohttp 帮助服务器,而 discord.py 服务器根本没有帮助我,因为它们都让你觉得需要帮助很愚蠢

【问题讨论】:

  • 如果您的问题得到解答,请将其标记为solved

标签: python reddit aiohttp discord.py-rewrite


【解决方案1】:

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 中打开响应并分析它们。

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2016-12-17
    • 2013-02-11
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    相关资源
    最近更新 更多