【问题标题】:Choose a random post from an asyncpraw subreddit generator object?从 asyncpraw subreddit 生成器对象中选择一个随机帖子?
【发布时间】:2021-05-07 19:05:22
【问题描述】:

(用于不和谐机器人的异步 Python 内容)

通过asyncpraw使用reddit API

我正在调用 reddit API 并返回 subreddit 的十个热门帖子。

hot_posts = returned_subreddit.hot(limit=10)

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

这个对象可以被迭代,并且可以使用不同的属性。例如:

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

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

我尝试通过索引访问它,例如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

【问题讨论】:

    标签: python random generator python-asyncio praw


    【解决方案1】:

    我已经解决了这个问题,可能非常不完美。上述问题的答案是让自己了解生成器对象,它们如何使用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.")
    

    【讨论】:

    • 非常感谢!这行:submission_list = [submission async for submit in sub.hot(limit=20) if not submit.stickied and not submit.over_18 and not submit.spoiler] 是非常需要的,因为我从没想过异步
    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多