python - 尝试从 subreddit 返回随机照片,但机器人也会挑选出不适用于 set_image 的视频提交
问题描述
基本上,我想设置一个条件,只从 subreddit 的提交中挑选出 .jpeg 链接。因为否则,目前,如果提交的是视频,则机器人无法以不和谐的方式加载它。截至目前的代码 -
async def aww(self,ctx, *, subred = "aww"):
async with ctx.channel.typing():
reddit = praw.Reddit(
client_id ="",
client_secret ="",
username ="",
password ="",
user_agent ="")
subreddit = reddit.subreddit("aww")
all_subs = []
top = subreddit.top(limit = 50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(color=0xc81f9f,
title = "Stupid Aww Generator",
description =f"{ctx.author.mention} Here's your aww moment: \n\n{name}")
embed.set_image(url=url)
embed.set_footer(text=f"{ctx.guild.name}",)
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed)
解决方案
我不知道是否有更好的方法来做到这一点,但我会采取的一种方法是对 jpg 或 jpeg(或其他图像格式,就此而言)进行暴力检查
# This is assuming your URL is consistent.
url = "hxxp://www.someurl.com/someimage.jpg"
file_format = url.split(".")[-1]
if file_format in ["jpg", "jpeg", ...]:
# do embed
else:
# fetch another random and check again
或者您可以对您的 URL 字符串进行正则表达式匹配以查看它是否通过。
您可能希望为何时/是否所有 50 个 URL 都指向视频实现逻辑。
推荐阅读
- r - 从 R 中的文件夹中读取具有特定扩展名的文件
- angular - 如何将 setValue 和 getValue 与 ion-radio 一起用作组件
- java - Android Studio - 单元测试模拟应用重启
- lstm - 在 LSTM 单元中为不同的序列大小选择最佳的 num_units
- react-navigation - 使用类组件时的 React Navigation 5 深度链接
- sql - 从两个表中选择有限的结果
- angular-material - 当我尝试在 ionic 中打开带有 Angular Material 的 BottomSheet 时,this.bottomSheet.open 不是一个函数
- kuzzle - java.lang.RuntimeException: org.json.JSONException: JSONObject["_source"] 未找到。#Kuzzle
- python - 使用 tkinter 创建日历的最佳方法是什么?
- sql - 在显示其他列时选择一列中的最高值