pythonpython-3.xredditpraw

How to fetch a random post from a subreddit (praw)


I have a question:

What would be an easy way to get a random post of a subreddit? Or best if I could get a random post made within 24 hours.

In older versions of praw, you could use

sub = r.get_subreddit('earthporn')
posts = sub.get_random_submission() 
print(posts.url)

However "get_random_submission" doesn't exist anymore. I know I could use something like

sub = r.subreddit('all')
    for posts in sub.hot(limit=20):
        random_post_number = random.randint(0,20)
        for i,posts in enumerate(sub.hot(limit=20)):
            if i==random_post_number:
                print(posts.score)

But this is very buggy and not power efficient. Plus I'm using this for a twitter bot, and I get an error after like 5 minutes with this code.

So I would really like to know if there's an easy way to get a random post of submission, and if I could get that random submission within a certain timeframe (such as the last 24 hours)?

Thanks!


Solution

  • You could simplify your code more than so and avoid the double loop.

    sub = r.subreddit('all')
    posts = [post for post in sub.hot(limit=20)]
    random_post_number = random.randint(0, 20)
    random_post = posts[random_post_number]