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) |