Skip to content

Instantly share code, notes, and snippets.

@ty-porter
Created April 15, 2020 07:04
Show Gist options
  • Save ty-porter/bfbefcd134c96cbb33a118d29a22d429 to your computer and use it in GitHub Desktop.
Save ty-porter/bfbefcd134c96cbb33a118d29a22d429 to your computer and use it in GitHub Desktop.
A Reddit script to continuously count similar posts you've made in the past

Usage

python post_count_bot.py

Exports data to post_counts.csv, and overwrites the file every time you make a post on Reddit.

import csv
import praw
import sys
import traceback
# Reddit client configuration:
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'
# Reddit username to follow
REDDIT_USERNAME = 'REDDIT_USERNAME'
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)
def run(self):
user = self.reddit.redditor(REDDIT_USERNAME)
user_comment_stream = praw.models.util.stream_generator(
lambda **kwargs: self.user_comments(user, **kwargs))
count_cache = {}
for comment in user_comment_stream:
sliced_comment = comment.body.split('\n')[0]
if sliced_comment in count_cache:
count = count_cache[sliced_comment] + 1
else:
count = 1
count_cache[sliced_comment] = count
with open('post_counts.csv', 'w') as f:
for item in sorted(count_cache.items(), key=lambda item: item[1], reverse=True):
f.write("%s,%s\n"%(item))
def user_comments(self, user, **kwargs):
results = []
results.extend(user.comments.new(**kwargs))
results.sort(key=lambda post: post.created_utc)
return results
if __name__ == '__main__':
while True:
try:
Bot().run()
except KeyboardInterrupt:
print('Exiting')
sys.exit(0)
except Exception:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment