首页 > 解决方案 > 尝试从 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)

标签: pythondiscord.py

解决方案


我不知道是否有更好的方法来做到这一点,但我会采取的一种方法是对 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 都指向视频实现逻辑。


推荐阅读