(用于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
我已经解决了这个问题,可能非常不完善。以上问题的答案是让我了解生成器对象,它们如何使用
yield
,以及它们如何不可编辑,应该使用到随机停止点,或者使用到一个列表中,然后从中随机选择相关问题 更多 >
编程相关推荐