与PRAW相比,如何正确处理异步PRAW中的多个流和异常?

2024-09-28 22:19:35 发布

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

我一直在我的Discord机器人中使用PRAW,使用subreddit流在subreddit中查找新帖子,并在出现新内容时将它们发布到Discord

Reddit有时会给出HTTP503错误,这用于完全中断流。通过一些研究,我发现我需要在异常发生后重新创建流对象以进行补偿。这是我的职能结构,运作良好:

async def post_reddit_to_discord(self):
    subreddit = self.reddit.subreddit("NameGoesHere")
    submissions = subreddit.stream.submissions(skip_existing=True, pause_after=0)

    while not self.bot.is_closed():
        try:
            submission = next(submissions)
            # If there are no submissions in the stream, wait for a new submission
            if submission is None:
                await asyncio.sleep(30)
            # Code to send the post to Discord goes here
        except Exception as e:
            # Code to send me notification about error goes here
            # Wait for reddit to recover
            await asyncio.sleep(60)
            # Recreate stream
            subreddit = self.reddit.subreddit("NameGoesHere")
            submissions = subreddit.stream.submissions(skip_existing=True, pause_after=0)

我最近搬到了asyncpraw,因为:

  • 异步有助于解决不协调机器人的问题
  • 我还想添加一个评论流到monitor,并在同一个bot中基于此进行操作,asyncpraw被推荐给我

下面是我为asyncpraw重写的相同函数:

async def post_reddit_to_discord(self):
    subreddit = await self.reddit.subreddit("NameGoesHere")
    while not self.bot.is_closed():
        try:
            async for submission in subreddit.stream.submissions(skip_existing=True, pause_after=0):
                # If there are no submissions in the stream, wait for a new submission
                if submission:
                    # Code to send the post to Discord goes here
                else:
                    asyncio.sleep(30)
        except Exception as e:
            # Code to send me notification about error goes here
            # Wait for reddit to recover
            await asyncio.sleep(60)

注意,我没有在异常中重新创建流

这也很有效,但是:

  1. 鉴于PRAW已经运行良好,我去asyncpraw的行动是否正确?它会处理多条流吗According to the author, it can.

  2. 建议如何添加第二个流(这次是评论)?相同功能/不同功能

  3. 自从移动到asyncpraw后,我没有遇到中断流的错误。它会像我的PRAW代码那样在异常情况下生存吗?这应该是因为流在while循环中,但我不知道如何测试它

  4. 有没有一种方法可以模拟HTTP 503错误之类的异常来测试函数,而不是在真实场景中等待它们发生,然后查看代码是否有效

如果你读到这里,非常感谢你抽出时间


Tags: thetoselfasynciosubmissionforstreamsleep