Last active
March 14, 2020 18:31
-
-
Save ty-porter/2af63b3245a7ce63763d3f232fc35ff5 to your computer and use it in GitHub Desktop.
Reddit bot for updating flair to top commenter's username after 48 hours
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import traceback | |
import datetime | |
import praw | |
BOT_USERNAME = 'BOT_USERNAME' | |
BOT_PASSWORD = 'BOT_PASSWORD' | |
BOT_CLIENT_ID = 'BOT_CLIENT_ID' | |
BOT_CLIENT_SECRET = 'BOT_CLIENT_SECRET' | |
BOT_USER_AGENT = 'BOT_USER_AGENT' | |
TARGET_SUBREDDIT = 'TARGET_SUBREDDIT' | |
FLAIR_CSS_CLASS = '' | |
FLAIR_MSG = 'Questioned by: /u/' | |
class Bot(): | |
def __init__(self): | |
self.reddit = praw.Reddit(username=BOT_USERNAME, | |
password=BOT_PASSWORD, | |
client_id=BOT_CLIENT_ID, | |
client_secret=BOT_CLIENT_SECRET, | |
user_agent=BOT_USER_AGENT) | |
self.new_submissions = [] | |
def botcode(self): | |
try: | |
for submission in self.reddit.subreddit(TARGET_SUBREDDIT).stream.submissions(skip_existing=True): | |
self.new_submissions.append(submission) | |
carryover_submissions = [] | |
for submission in self.new_submissions: | |
if self.date_diff_in_hours(submission.created_utc) < 48: | |
carryover_submissions.append(submission) | |
continue | |
submission.comment_sort = 'best' | |
top_comment = [ comment for comment in submission.comments ][0] | |
top_commenter = top_comment.redditor.name | |
flair_id = [ choice['id'] for choice in submission.link_flair.choices() if choice['css_class'] == FLAIR_CSS_CLASS ][0] | |
submission.flair.select(flair_id, FLAIR_MSG + top_commenter) | |
self.new_submissions = carryover_submissions | |
except BaseException as e: | |
if type(e) == KeyboardInterrupt: | |
sys.exit(0) | |
else: | |
traceback.print_exc() | |
def date_diff_in_hours(self, epoch_time): | |
date = datetime.datetime.utcfromtimestamp(epoch_time) | |
diff = datetime.datetime.utcnow() - date | |
return diff.seconds / (3600) | |
if __name__ == '__main__': | |
while True: | |
Bot().botcode() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment