Skip to content

Commit

Permalink
Make it so bot doesn't crash on network or reddit api error (#5)
Browse files Browse the repository at this point in the history
* try/except to keep connected on error

* fix loop
  • Loading branch information
JeffP07 authored Mar 5, 2024
1 parent 9d2c672 commit b1e485b
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import ast
import time
from dotenv import load_dotenv
import praw
from sqlitedict import SqliteDict
Expand Down Expand Up @@ -33,6 +34,11 @@

# Subreddit to monitor
subreddit_name = os.environ["SUBREDDIT"]
subreddit = reddit.subreddit(subreddit_name)
stream = subreddit.stream.comments(skip_existing=True)

print(f"Bot connected and listening in r/{subreddit_name}")
print(f"Whitelisted users: {whitelisted_users_lower}")

# The text for the sticky comment
sticky_comment_text = """
Expand All @@ -41,10 +47,7 @@
"""

def sticky_comment_on_whitelisted_user_post():
print(f"Bot started and listening in r/{subreddit_name}")
print(f"Whitelisted users: {whitelisted_users_lower}")
subreddit = reddit.subreddit(subreddit_name)
for comment in subreddit.stream.comments(skip_existing=True):
for comment in stream:
# Check if new comment is from a whitelisted username
if comment.author and (comment.author.name.lower() in whitelisted_users_lower):
print(f"Found a post by whitelisted user: {comment.author.name}")
Expand Down Expand Up @@ -85,5 +88,13 @@ def sticky_comment_on_whitelisted_user_post():
bot_sticky_comment.mod.distinguish(how='yes', sticky=True)
print(f"Stickied a comment on post: {submission.title}\nPost id: {submission.id}\nComment id: {bot_sticky_comment.id}")

# Run the bot
sticky_comment_on_whitelisted_user_post()
while True:
try:
# Run the bot
stream = subreddit.stream.comments(skip_existing=True)
sticky_comment_on_whitelisted_user_post()
print(f"[{time.asctime()}] Retrying connection in 60 seconds...\n")
except Exception as error:
print(f"[{time.asctime()}] ERROR: {error}\n")
print(f"[{time.asctime()}] Retrying connection in 60 seconds...\n")
time.sleep(60)

0 comments on commit b1e485b

Please sign in to comment.