(不和谐机器人的异步Python内容)
通过asyncpraw使用reddit API
我正在调用reddit API并返回子reddit的十个热门帖子。
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)我想知道如何从这个生成器对象中选择一个随机提交。目标是让我的discord机器人发送一条消息来响应命令。该消息将包含一个链接,指向给定子subreddit上排名前十的热门帖子之一。
我尝试过通过索引访问它,例如抛出TypeError: 'ListingGenerator' object is not subscriptable的hot_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
发布于 2021-02-04 06:02:53
我已经解决了这个问题,可能非常不完美。上面问题的答案是让我自己了解生成器对象,它们如何使用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.")https://stackoverflow.com/questions/66029395
复制相似问题