首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从asyncpraw subreddit生成器对象中选择随机发布?

从asyncpraw subreddit生成器对象中选择随机发布?
EN

Stack Overflow用户
提问于 2021-02-03 22:21:10
回答 1查看 298关注 0票数 0

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

通过asyncpraw使用reddit API

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

hot_posts = returned_subreddit.hot(limit=10)

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

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

代码语言:javascript
复制
async for submission in hot_posts:
    print(submission.title)
    print(submission.score)
    print(submission.id)
    print(submission.url)

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

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

到目前为止,我尝试使用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

EN

回答 1

Stack Overflow用户

发布于 2021-02-04 06:02:53

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

代码语言:javascript
复制
    @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.")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66029395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档