Created
May 26, 2016 10:18
-
-
Save 1995eaton/83790b5e3ad2f001560ac4bbca1ba35b to your computer and use it in GitHub Desktop.
Reddit Subreddit Completion
This file contains hidden or 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 uuid | |
import re | |
import json | |
import urllib.request | |
import urllib.parse | |
subreddit_rx = re.compile(r'\A[A-Za-z0-9][A-Za-z0-9_]{,20}\Z') | |
subreddit_url = 'https://www.reddit.com/api/search_reddit_names.json' | |
def is_valid_subreddit_prefix(prefix: str) -> bool: | |
return re.match(subreddit_rx, prefix) is not None | |
def subreddit_search(prefix: str) -> [str]: | |
if not is_valid_subreddit_prefix(prefix): | |
raise Exception('Invalid subreddit name: {}'.format(prefix)) | |
post_data = urllib.parse.urlencode({ | |
'query': prefix, | |
'include_over_18': 'true', | |
'renderstyle': 'html', | |
}).encode('ascii') | |
opener = urllib.request.build_opener() | |
opener.addheaders = [('User-Agent', 'Search-Subreddits-Python-' + | |
str(uuid.uuid4()))] | |
with opener.open(subreddit_url, post_data) as f: | |
data = f.read().decode('utf-8') | |
data = json.loads(data) | |
return data['names'] | |
if __name__ == '__main__': | |
import os | |
if len(sys.argv) != 2: | |
print('Usage: {} {} SUBREDDIT_PREFIX'.format( | |
os.path.split(sys.executable)[-1], | |
sys.argv[0], | |
)) | |
sys.exit(-1) | |
try: | |
names = subreddit_search(sys.argv[1]) | |
except Exception as ex: | |
print(ex) | |
sys.exit(-1) | |
if len(names) == 0: | |
print('{}: No subreddit matches'.format(sys.argv[1])) | |
else: | |
print(sys.argv[1] + ':') | |
for sr in names: | |
print((' ' * 4) + sr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment