Created
October 8, 2012 20:28
-
-
Save aperson/3854774 to your computer and use it in GitHub Desktop.
Quick script to ban a user from every subreddit you moderate (use wisely!)
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
#!/usr/bin/env python3 | |
import json | |
import urllib.request | |
import time | |
import re | |
import signal | |
import sys | |
from urllib.parse import urlencode | |
import http.cookiejar | |
from contextlib import contextmanager | |
def p(data, end='\n'): | |
print(time.strftime( | |
'\r\033[K\033[2K[\033[31m%y\033[39m/\033[31m%m\033[39m/\033[31m%d' | |
'\033[39m][\033[31m%H\033[39m:\033[31m%M\033[39m:\033[31m%S\033[39m] ') + data, end=end) | |
def sigint_handler(signal, frame): | |
'''Handles ^c''' | |
p('Recieved SIGINT! Exiting...') | |
sys.exit(0) | |
class Reddit(object): | |
"""Base class to perform the tasks of a redditor.""" | |
def __init__(self, username, password): | |
self.username = username | |
self.password = password | |
self.cj = http.cookiejar.CookieJar() | |
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj)) | |
self.opener.addheaders = [('User-agent', 'ban-all.py v0')] | |
self._login() | |
def _request(self, url, body=None): | |
if body is not None: | |
body = urlencode(body).encode('utf-8') | |
with self.opener.open(url, data=body) as w: | |
time.sleep(2) | |
return json.loads(w.read().decode('utf-8')) | |
def _login(self): | |
p("Logging in as {}.".format(self.username)) | |
body = {'user': self.username, 'passwd': self.password, 'api_type': 'json'} | |
resp = self._request('https://www.reddit.com/api/login', body) | |
self.modhash = resp['json']['data']['modhash'] | |
def post(self, url, body): | |
"""Sends a POST to the url and returns the json as a dict.""" | |
if 'api_type' not in body: | |
body['api_type'] = 'json' | |
body['uh'] = self.modhash | |
return self._request(url, body) | |
def get(self, url): | |
"""Sends a GET to the url and returns the json as a dict.""" | |
if '.json' not in url: | |
url += '.json' | |
return self._request(url) | |
def main(USERNAME, PASSWORD, users): | |
r = Reddit(USERNAME, PASSWORD) | |
reddits = [i['data']['display_name'] for i in r.get( | |
'http://www.reddit.com/reddits/mine/moderator.json')['data']['children']] | |
for reddit in reddits: | |
for user in users: | |
p('Banning {} from /r/{}'.format(user, reddit)) | |
body = { | |
'action': 'add', 'type': 'banned', 'name': user, 'id': '#banned', 'r': reddit} | |
r.post('http://www.reddit.com/api/friend', body) | |
if __name__ == '__main__': | |
signal.signal(signal.SIGINT, sigint_handler) | |
args = sys.argv[1:] | |
main(args[0], args[1], args[2:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment