Search code examples
pythonredditprawdiscord.py

Discordpy, praw, blocking


So i'm writing discord bot on python, and i want to make background task which would check subreddit for new submissions and post it if there's certain flair. But when i'm trying to start my bot, which worked perfect before, it just wait for something and doesn't start. What should i do?

async def reddit_task():
        await bot.wait_until_ready()
        start_time = time.time()
        reddit = praw.Reddit(different keys)
        subreddit = reddit.subreddit('certain subreddit')
        for submission in subreddit.stream.submissions():
            if submission.created_utc > start_time:
                if submission.link_flair_text == 'certain flair':
                    em = discord.Embed(title=submission.title+'\n'+submission.shortlink)
                    if len(submission.preview) > 1:
                            em.set_image(url=submission.preview['images'][0]['source']['url'])
                    await bot.send_message(discord.Object(id='my channel id'), embed=em)

            else:
                pass

if __name__ == "__main__":
    for extension in startup_extensions:
        try:
            bot.load_extension(extension)
        except Exception as e:
            exc = '{}: {}'.format(type(e).__name__, e)
            print('Failed to load extension {}\n{}'.format(extension, exc))
    bot.loop.create_task(reddit_task())
    bot.run(config.bot_beta_token)

Solution

  • I ran into this problem as well since subreddit.stream.submissions() is blocking the for loop. So I solved it by using an infinite loop and subreddit.stream.submissions(pause_after=0) so it returns None if there are no new posts then waits 60 seconds before checking again.

    async def reddit_task():
        await client.wait_until_ready()
        start_time = time.time()
    
        reddit = praw.Reddit("<client_stuff>")
        subreddit = reddit.subreddit("<some_subreddit>")
        submissions = subreddit.stream.submissions(pause_after=0)
    
        while not client.is_closed:
            submission = next(submissions)
    
            if submission is None:
                # Wait 60 seconds for a new submission
                await asyncio.sleep(60)
    
            elif submission.created_utc > start_time:
                <do_stuff_with_submission>