Last active
June 10, 2020 03:16
-
-
Save ty-porter/ded04a3b28e37e43aeb2d17f139e8247 to your computer and use it in GitHub Desktop.
Voting bot that removes posts if threshold is not met
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 praw | |
from datetime import datetime | |
class Bot: | |
REDDIT = praw.Reddit(username='REDDIT_USERNAME', | |
password='REDDIT_PASSWORD', | |
client_id='REDDIT_CLIENT_ID', | |
client_secret='REDDIT_CLIENT_SECRET', | |
user_agent='REDDIT_USER_AGENT') | |
SUBREDDIT = 'TrueUnpopularOpinion' | |
THRESHOLD_PCT = 60 | |
TIME_LIMIT = {"days": 0, | |
"hours": 6, | |
"minutes": 0, | |
"seconds": 0} | |
REMOVAL_MSG = 'This post has been removed due to community votes after 6 hours.' | |
TRACKED_POSTS = [] # No need to edit this, it is built by the bot as it's needed | |
def run(self): | |
self.AGE_CUTOFF = self.build_age_cutoff() | |
self.append_new_submissions() | |
self.check_tracked_submissions() | |
def append_new_submissions(self): | |
for submission in self.REDDIT.subreddit(self.SUBREDDIT).stream.submissions.new(): | |
if submission.created_utc < self.AGE_CUTOFF: | |
break | |
if submission.id not in [submission.id for submission in self.TRACKED_POSTS]: | |
self.TRACKED_POSTS.append(submission) | |
def check_tracked_submissions(self): | |
untracked_submissions = [] | |
for submission in self.TRACKED_POSTS: | |
if submission.created_utc > AGE_CUTOFF: | |
continue | |
untracked_submissions.append(submission.id) | |
upvotes, downvotes = self.count_votes(submission) | |
ratio = self.guarded_ratio(upvotes, downvotes) | |
if ratio < float(self.THRESHOLD_PCT) / 100: | |
submission.remove(mod_note=self.REMOVAL_MSG) | |
self.cull_untracked(untracked_submissions) | |
def cull_untracked(self, untracked_submissions): | |
self.TRACKED_POSTS = [submission for submission in self.TRACKED_POSTS if submission.id not in untracked_submissions] | |
def count_votes(self, submission): | |
submission.comments.replace_more(limit=None) | |
votes = (0, 0) | |
for top_level_comment in submission.comments | |
if top_level_comment.body.lower() == 'yes': | |
votes[0] += 1 | |
elif top_level_comment.body.lower() == 'no': | |
votes[1] += 1 | |
return votes | |
def build_age_cutoff(self): | |
days = self.TIME_LIMIT['days'] * 86400 | |
hours = self.TIME_LIMIT['hours'] * 3600 | |
minutes = self.TIME_LIMIT['minutes'] * 60 | |
seconds = self.TIME_LIMIT['seconds'] | |
return days + hours + minutes + seconds | |
def guarded_ratio(self, up, down): | |
try: | |
return float(up) / float(up + down) | |
except ZeroDivisionError: | |
return 1.0 | |
if __name__ == '__main__': | |
bot = Bot() | |
while True: | |
bot.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment