我如何让 aiohttp 输出 reddit 图像
how do i get aiohttp to output reddit images
@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 服务器根本帮不了我,因为它们都让你觉得寻求帮助很愚蠢
reddit 回复顶层没有url
键;您所指的图像是预览图像,这些是每个 post,因此您需要遍历 post 并提取图像:
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 中打开回复并分析它们。
@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 服务器根本帮不了我,因为它们都让你觉得寻求帮助很愚蠢
reddit 回复顶层没有url
键;您所指的图像是预览图像,这些是每个 post,因此您需要遍历 post 并提取图像:
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 中打开回复并分析它们。