【问题标题】:Check if image url is valid检查图片网址是否有效
【发布时间】:2021-07-31 02:37:24
【问题描述】:

您好,我正在用 Python 制作 Discord 机器人。我正在制作一个从 subreddit 随机提交的 meme 命令。那么它有一个小问题。当提交是视频或 Discord 不可用的格式时,embed 无法加载内容。所以我需要检查提交格式,当它是不可用的格式时,应该调用该功能或​​类似的东西。我无法弄清楚自己,所以我寻求帮助。代码如下:

@client.command()
async def meme(ctx):
    if not hasattr(client, 'nextMeme'):
        client.nextMeme = await getMeme()

    title, url, img_url, upvotes, comments = client.nextMeme

    embedVar = discord.Embed(title=title, url=url, color=discord.Color.random())
    embedVar.set_image(url=img_url)
    embedVar.set_footer(text=f"???? {upvotes} | ???? {comments}")

    await ctx.send(embed=embedVar)

    client.nextMeme = await getMeme()

async def getMeme():
    meme_subreddits = ['dankmemes', 'memes', 'jaharia', 'videoyun']
    subreddit = await reddit.subreddit(random.choice(meme_subreddits))
    all_subs = []

    top = subreddit.top(limit = 52)

    async for submission in top:
        all_subs.append(submission)
    
    random_sub = random.choice(all_subs)

    img_url = random_sub.url
    title = random_sub.title
    url = random_sub.shortlink
    upvotes = random_sub.score
    comments = random_sub.num_comments
    
    return title, url, img_url, upvotes, comments

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    您可以检查您获得的图片网址是否以受支持的文件扩展名结尾,如下所示:

    if img_url.endswith(('.jpg', '.png', '.gif', '.jpeg')):
    

    如果你想尝试直到你得到一个有效的,只要把它放在一个while循环中,这样的东西应该可以吗?我现在无法测试,抱歉

    img_url = ''
    while not img_url.endswith(('.jpg', '.png', '.gif', '.jpeg')):
        title, url, img_url, upvotes, comments = client.nextMeme
    #rest of your code
    

    您显然可以添加更多文件扩展名,这些只是我可以快速想到的。希望这至少对您有所帮助

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 2016-07-25
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2017-09-28
      • 2012-09-05
      相关资源
      最近更新 更多