Tom
Tom

Reputation: 621

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!

Upvotes: 2

Views: 5007

Answers (3)

R9_
R9_

Reputation: 1

You can do this:

import random
posts = [post for post in subreddit.hot(limit=limit)]
random_post = random.choice(posts)

Upvotes: 0

PeskyPotato
PeskyPotato

Reputation: 712

You can get a random post by generating a number and then getting that post from a list. When it comes to selecting only posts from the last 24 hours you will need to fill an array with those posts first. I compare the current time with the time the post was submitted, if it is less than 24 hours I add it to the list posts.

It is from the list then that you can take a random submission out to do whatever you choose to do. This submission I have named random_post.

import praw
import time
import random


LIMIT_POST = 5

subreddit = reddit.subreddit('all')
new_submissions = subreddit.new(limit = LIMIT_POST)

current_time = int(time.time())

posts = []

for submission in new_submissions:
        sub_age = ((current_time - submission.created_utc) /60 /60 /24)
        if sub_age < 1:
                posts.append(submission)


random_number = random.randint(0,LIMIT_POST -1)
random_post = posts[random_number]

Upvotes: 0

Jonathan
Jonathan

Reputation: 8900

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]

Upvotes: 2

Related Questions