anytarsier67
anytarsier67

Reputation: 33

unable to randomize submissions coming from reddit

i am trying to make my discord bot grab images from the r/memes subreddit.

here is my code the interfaces with the reddit api

subreddit = reddit.subreddit('memes')
hot_python = subreddit.hot(limit=100)

for submission in hot_python:
    print(submission.title)

async def meme():
    memes_submissions = reddit.subreddit('memes').hot()
    post_to_pick = random.randint(1, 10)
    for i in range(0, post_to_pick):
        submission = next(x for x in memes_submissions if not x.stickied)

here is my code to send the selected post

elif message.content == "!meme":
        channel = message.channel
        await message.channel.send(submission.url)

when ever i run the command it send the same meme over and over instead of choosing a random one. any idea on how to fix this?

Upvotes: 1

Views: 137

Answers (1)

jarhill0
jarhill0

Reputation: 1629

Getting a random post from a subreddit is a Reddit feature which PRAW supports.

Here's a function that gets a random post from a specified subreddit:

def random_post(subreddit):
    return reddit.subreddit(subreddit).random()

And if you want the post not to be stickied, use this:

def random_nonsticky_post(subreddit):
    while True:
        post = reddit.subreddit(subreddit).random()
        if not post.stickied:
            return post

As discussed in your followup question, it's important to note that some subreddits do not permit getting a random post.

Upvotes: 1

Related Questions