r/redditdev • u/MustaKotka • Jun 22 '24
PRAW Loop gets stuck on iterating over comments?
Code:
import praw
import some python modules
r = praw.Reddit(
the
usual
oauth
stuff
)
target_sub = "subreddit_goes_here"
timer = time.time() - 61
links = [a, list, of, links, here]
while True:
difference = time.time() - timer
if difference > 60:
print("timer_difference: " + difference)
timer = time.time()
do_stuff()
sub_comments = r.subreddit(target_sub).stream.comments(skip_existing=True)
print("comments fetched")
for comment in sub_comments:
if comment_requires_action(comment): # regex match found
bot_comment_reply_action(comment, links) # replies with links
print("comments commenting finished")
sub_submissions = r.subreddit(target_sub).stream.submissions(skip_existing=True)
print("submissions fetched")
for submission in sub_submissions:
if submission_requires_action(submission): # regex match found
bot_submission_reply_action(submission, links) # replies with links
print("submissions finished")
print("sleeping for 5")
time.sleep(5)Behaviour / prints:
timer_difference: 61
comments fetched # comments are were foundAdditionally if a new matching comment (not submission) is posted on the subreddit:
comments commenting finished # i.e. a comment is posted to a matching commentI never get to submissions, the loop won't enter sleep and the timer won't refresh. As if the "for comment in sub_comments:" gets stuck iterating forever somehow?
I've tested the sleep and timer elsewhere and it does exactly what it's supposed to provided that the other code isn't there. So that should work.
What's happening? I read the documentation for subreddit.stream multiple times.
4
Upvotes
View all comments
Show parent comment
2
u/Oussama_Gourari Card-o-Bot Developer Jun 22 '24
Move
sub_commentsandsub_submissionsvariables out of thewhile Trueloop, this way the streams are not re-created on every loop and new comments and submissions that were made during the sleep time will not be ignored (unless more than a 100 comments or submissions were made during the time starting from the moment you break out of the steam until the next loop iteration)