mercredi 3 février 2021

Choose a random post from an asyncpraw subreddit generator object?

(asynchronous Python stuff for a discord bot)

Using the reddit API via asyncpraw

I am making a call to the reddit API and returning a subreddit's ten hot posts.

hot_posts = returned_subreddit.hot(limit=10)

Which prints <asyncpraw.models.listing.generator.ListingGenerator object at 0x0000021B3CC1A3A0>

This object can be iterated through and different attributes can be used. e.g.:

async for submission in hot_posts:
    print(submission.title)
    print(submission.score)
    print(submission.id)
    print(submission.url)

I would like to know how to choose a random submission from this generator object. The goal is for my discord bot to send a message in response to a command. The message would include a link to one of top ten hot posts on a given subreddit.

I've tried accessing it via an index e.g. hot_posts[3] which threw TypeError: 'ListingGenerator' object is not subscriptable

Tried so far using random library:

choice(hot_posts) Result: TypeError: object of type 'ListingGenerator' has no len()

random.sample(hot_posts, k=1) Result: TypeError: Population must be a sequence. For dicts or sets, use sorted(d).

Docs:

https://asyncpraw.readthedocs.io/en/latest/code_overview/models/subreddit.html

https://asyncpraw.readthedocs.io/en/latest/code_overview/other/listinggenerator.html#asyncpraw.models.ListingGenerator




Aucun commentaire:

Enregistrer un commentaire