You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

求助:Python开发Discord机器人Meme命令如何过滤无效格式投稿并重新获取有效内容

解决Discord机器人Meme命令的格式兼容问题

我完全懂你遇到的麻烦——随机抓到视频或者Discord不支持的媒体格式时,Embed直接加载失败,体验特别差。其实只需要给getMeme函数加个格式校验的循环逻辑,让它自动跳过无效投稿,直到拿到能正常显示的图片就行。下面是具体的修改方案:

首先明确一下,Discord的Embed支持的图片格式有这些:.jpg.jpeg.png.gif.webp,我们就基于这个列表做校验。

修改后的完整代码

import random
import discord
# 假设你已经正确初始化了client和reddit实例

@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']
    # 定义Discord支持的图片扩展名
    supported_formats = ('.jpg', '.jpeg', '.png', '.gif', '.webp')
    max_attempts = 20  # 防止无限循环的最大尝试次数
    attempts = 0
    
    while attempts < max_attempts:
        attempts += 1
        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
        
        # 检查链接是否以支持的格式结尾
        if img_url.lower().endswith(supported_formats):
            # 额外处理:排除imgur的视频链接(这类链接常伪装成图片)
            if '/video/' not in img_url.lower():
                title = random_sub.title
                url = random_sub.shortlink
                upvotes = random_sub.score
                comments = random_sub.num_comments
                return title, url, img_url, upvotes, comments
    
    # 如果多次尝试都没找到有效投稿,返回一个友好的默认内容
    return "哎呀!没找到合适的meme 😅", "https://reddit.com", "https://via.placeholder.com/500", 0, 0

关键修改点说明

  • 格式校验逻辑:通过endswith(supported_formats)检查投稿链接的扩展名,只保留Discord能正常加载的图片格式
  • 防无限循环:添加max_attempts限制尝试次数,避免遇到某个子版块全是视频的极端情况时程序卡死
  • 额外兼容处理:针对imgur这类平台的视频链接(比如https://i.imgur.com/xxx/video),额外排除包含/video/的链接,进一步降低无效投稿的概率
  • 容错返回:如果多次尝试都没找到有效投稿,返回一个友好的默认内容,避免命令直接报错崩溃

这样修改后,你的meme命令就会自动跳过无效格式的投稿,每次发送的Embed都能正常显示图片啦。

内容的提问来源于stack exchange,提问作者MekroKnight

火山引擎 最新活动