从asyncpraw subreddit生成器对象中选择随机帖子?

2024-09-28 22:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

(用于discord机器人的异步Python内容)

通过asyncpraw使用RedditAPI

我正在调用RedditAPI并返回subreddit的十篇热门帖子

hot_posts = returned_subreddit.hot(limit=10)

它打印<asyncpraw.models.listing.generator.ListingGenerator object at 0x0000021B3CC1A3A0>

可以迭代该对象,并可以使用不同的属性。e、 g:

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

我想知道如何从这个生成器对象中选择随机提交。目标是让我的discord bot发送消息以响应命令。该消息将包括一个链接,指向给定子Reddit上十大热门帖子之一

我尝试通过一个索引来访问它,例如hot_posts[3],它抛出 TypeError: 'ListingGenerator' object is not subscriptable

迄今为止已尝试使用random库:

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

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

文件:

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


Tags: 对象submissionobjectmodels帖子postsprint热门
1条回答
网友
1楼 · 发布于 2024-09-28 22:26:10

我已经解决了这个问题,可能非常不完善。以上问题的答案是让我了解生成器对象,它们如何使用yield,以及它们如何不可编辑,应该使用到随机停止点,或者使用到一个列表中,然后从中随机选择

    @commands.command()
    async def r(self, ctx, subreddit: str=""):
        async with ctx.channel.typing():
            if self.reddit:
                chosen_subreddit = REDDIT_ENABLED_MEME_SUBREDDITS[0]
                if subreddit:
                    if subreddit in REDDIT_ENABLED_MEME_SUBREDDITS:
                        chosen_subreddit = subreddit
                sub = await self.reddit.subreddit(chosen_subreddit)
                submission_list = [submission async for submission in sub.hot(limit=20) if not submission.stickied and not submission.over_18 and not submission.spoiler]
                selector = randint(0, len(submission_list) - 1)
                post = submission_list[selector]
                await ctx.send(f"{post.url}\n<https://www.reddit.com{post.permalink}>")
            else:
                await ctx.send("This is not working.")

相关问题 更多 >