Skip to content

Instantly share code, notes, and snippets.

@crash-horror
Last active May 1, 2018 19:15
Show Gist options
  • Save crash-horror/b6ebd6064a72984032e5b685a6a603b4 to your computer and use it in GitHub Desktop.
Save crash-horror/b6ebd6064a72984032e5b685a6a603b4 to your computer and use it in GitHub Desktop.
A simple script to get a subreddit's comments in realtime
#!/usr/bin/env python3
# gist-reddit-feeder.py
# github.com/crash-horror
"""
A simple script to get a subreddit's comments in realtime.
You will need these modules:
* praw
* colorama
(pip install praw colorama)
Also you need to have a reddit account and a registered application as described here:
https://praw.readthedocs.io/en/latest/getting_started/authentication.html#script-application
You register the app in reddit here:
https://www.reddit.com/prefs/apps/
(select script for personal use)
"""
import shutil
import textwrap
import time
from colorama import *
import praw
from prawcore import NotFound
init(autoreset=True)
myindent = 8
# Set your creds here (read above)
reddit = praw.Reddit(client_id='*****',
client_secret='*****',
password='*****',
user_agent='*****',
username='*****')
def sub_exists(sub):
exists = True
try:
reddit.subreddits.search_by_name(sub, exact=True)
except NotFound:
exists = False
return exists
def ask_me():
while True:
answer = input('Enter subreddit: ')
if sub_exists(answer):
return answer
else:
print('Subreddit does not exist, try again.')
print(reddit.user.me(), end=' ')
mysreddit = ask_me()
subreddit = reddit.subreddit(mysreddit)
start_time = time.time()
print('Listening...')
for comment in subreddit.stream.comments():
if comment.created_utc < start_time:
continue
width = shutil.get_terminal_size((80, 20)).columns
w = width-1
try:
print(' '*myindent + Back.RED + str(comment.submission.num_comments))
print(Style.BRIGHT + Fore.GREEN + textwrap.indent(textwrap.fill(comment.submission.title, w-myindent), ' '*myindent))
try:
print(textwrap.indent(textwrap.fill(Fore.YELLOW + comment.parent().body.replace('\n\n', '\n'), w-myindent), ' '*myindent))
except AttributeError: # this means there is no parent comment
pass
print(textwrap.fill(comment.body.replace('\n\n', '\n'), w))
except praw.exceptions.PRAWException as e:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment