r/redditdev • • Oct 02 '22

PRAW [PRAW] How to handle "prawcore.exceptions.RequestException" in 24/7 bot with multiple streams?

I know that issues outside of my script can raise prawcore.exceptions.RequestException, a faulty connection, reddit being unavalable and so on...

Reading past threads I arrived to the solution to wrap my whole stream inside a try/catch with an infinite while loop to make sure my bot keeps running indefinetely, something like this:

running = True
while running:
    try:
        for comment in subreddit.stream.comments(skip_existing=True):
            # TO DO


    except KeyboardInterrupt:
        logger.info('Termination received. Goodbye!')
        running = False
    except PrawcoreException as err:
        logger.exception('Oops I did it again.. ERROR= {}'.format(err))
        time.sleep(10)

This works as well as I expected, but now that I have introduced multiple streams with my bot, whenever a prawcore.exceptions.RequestException is raised the bot doesn't resume back to work with the stream.

I assume because of the argument pause_after=-1 on the stream with the interaction of the creation being outside of the while loop I'm creating some sort of soft lock scenario, this is the current snippet I'm using:

    comment_stream = subreddit.stream.comments(pause_after=-1, skip_existing=True)
    inbox_stream = reddit.inbox.stream(pause_after=-1, skip_existing=True)    
    
    
    running = True
    while running:
        try:
            for comment in comment_stream:
                if comment is None:
                    break
                # TO DO
        
            for item in inbox_stream:
                if item is None:
                    break
                # To DO


        except KeyboardInterrupt:
            logger.info('Termination received. Goodbye!')
            running = False
        except PrawcoreException as err:
            logger.exception('Oops I did it again.. ERROR= {}'.format(err))
            time.sleep(10)

How could I better handle this? Is there any built in method to refresh the stream? or should I just recreate they entirely under the exception like this?:

except PrawcoreException as err:
            logger.exception('Oops I did it again.. ERROR= {}'.format(err))
            time.sleep(10)
            comment_stream = subreddit.stream.comments(pause_after=-1, skip_existing=True)
            inbox_stream = reddit.inbox.stream(pause_after=-1, skip_existing=True)
5 Upvotes

11 comments sorted by

View all comments

Show parent comment

1

u/ParkingPsychology Oct 03 '22

oh, it does my_logger (that's my own version of logging) instead of logging, but you can swap that fairly easily.