Search code examples
discorddiscord.pyprawasyncpraw

Discord.py meme command takes a lot of time


I am making a bot in discord.py and have a fully working meme command using asyncpraw (praw did not work). But it takes a lot of time around 8-10 seconds for the meme to appear. Is there any way to reduce the time? Here is the code :-

@client.command(aliases=['memes'])
async def meme(ctx):
    subreddit = await reddit.subreddit("memes")
    all_subs = []
    top = subreddit.top(limit = 200)
    async for submission in top:
      
      all_subs.append(submission)
    
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    ups = random_sub.score
    link = random_sub.permalink
    comments = random_sub.num_comments
    embed = discord.Embed(title=name,url=f"https://reddit.com{link}", color=ctx.author.color)
    embed.set_image(url=url)
    embed.set_footer(text = f"👍{ups} 💬{comments}")
    await ctx.send(embed=embed)
    

Solution

  • It takes a while because everytime you execute the command, it'll always generate a list of submissions to pick from but then the list just disappears after the command executes which means that you generate 200 posts every command execution just to pick from one

    If you want a more efficient, faster way, make it a separate function!

    all_subs = []
    
    
    async def gen_memes():
        subreddit = await reddit.subreddit("memes")
        top = subreddit.top(limit = 200)
        async for submission in top:
          all_subs.append(submission)
    
    
    @client.event
    async def on_ready():
        await gen_memes()  # generate memes when bot starts
    
    @client.command(aliases=['memes'])
    async def meme(ctx):
        random_sub = random.choice(all_subs)
        all_subs.remove(random_sub)
        name = random_sub.title
        url = random_sub.url
        ups = random_sub.score
        link = random_sub.permalink
        comments = random_sub.num_comments
        embed = discord.Embed(title=name,url=f"https://reddit.com{link}", color=ctx.author.color)
        embed.set_image(url=url)
        embed.set_footer(text = f"👍{ups} 💬{comments}")
        await ctx.send(embed=embed)
        
        if len(all_subs) <= 20:  # meme collection running out owo
            await gen_memes()
    

    of course this is not the most efficient way, if you want to refill your memes in a certain interval, you can use discord.ext.tasks!