Skip to content

Instantly share code, notes, and snippets.

Created December 22, 2010 03:04
Show Gist options
  • Save anonymous/751032 to your computer and use it in GitHub Desktop.
Save anonymous/751032 to your computer and use it in GitHub Desktop.
Helps to ensure your privacy on reddit by cleaning up your old posts and comments. Intended to be used with cron.
#!/usr/bin/env python
# put your username and password here
USERNAME = ""
PASSWORD = ""
import urllib, urllib2, cookielib, json, sys, datetime
from optparse import OptionParser
def read(fd):
data = fd.read()
fd.close()
return data
def should_delete(post, options):
if options.delete_all:
return True
if options.del_posts and 'num_comments' in post:
return True
if options.del_comments and 'num_comments' not in post:
return True
return False
# handle command line arguments
parser = OptionParser()
parser.add_option("-p", "--del-posts", help = "delete posts",
action="store_true", default = False)
parser.add_option("-c", "--del-comments", help = "delete comments",
action="store_true", default = False)
parser.add_option("-d", "--days", dest = "DAYS",
help = "delete posts after a number of days")
parser.add_option("-s", "--save", dest = "SAVE",
help = "save a certain number of items")
parser.add_option("-a", "--delete-all", action="store_true", default = False,
help = "delete everything, overriding all other settings")
options, args = parser.parse_args()
if options.delete_all:
print "Deleting everything."
elif options.del_posts or options.del_comments:
# print what we're deleting
print "Deleting",
if options.del_posts and options.del_comments:
print "posts and comments",
elif options.del_posts: print "posts",
else: print "comments",
# print when we are deleting things
if options.DAYS is not None:
if int(options.DAYS) == 1:
print "more than {0} day old".format(options.DAYS)
else:
print "more than {0} days old".format(options.DAYS)
else: print
# print how many posts we should save
if options.SAVE is not None:
if int(options.SAVE) == 1:
print "Saving {0} item".format(options.SAVE)
else:
print "Saving {0} items".format(options.SAVE)
else:
print "Deleting nothing, exiting..."
sys.exit()
# save us some cooookies
cookies = urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar())
opener = urllib2.build_opener(cookies)
# log in
params = urllib.urlencode({ 'user': USERNAME,
'passwd': PASSWORD,
'api_type': 'json' })
data = read(opener.open('http://www.reddit.com/api/login/', params))
# get the modhash
login_json = json.loads(data)
modhash = login_json['json']['data']['modhash']
# get user's posts
posts = []
data = read(opener.open('http://www.reddit.com/user/%s/.json' % USERNAME))
while True:
posts_json = json.loads(data)
# add each post to the list of posts
for post in posts_json['data']['children']:
posts.append(post['data'])
# when we run out of pages, stop
if posts_json['data']['after'] is None:
break
else:
data = read(opener.open('http://www.reddit.com/user/{0}.json?after={1}'.
format(USERNAME, posts_json['data']['after'])))
# delete however many posts we are going to save
if options.SAVE is not None:
if int(options.SAVE) >= len(posts):
sys.exit()
for i in range(0, int(options.SAVE)):
posts.pop(0)
if options.DAYS is not None:
# what time is it right now?
current_time = int(datetime.datetime(2000, 1, 1).utcnow().strftime("%s"))
# when should we delete posts after?
del_time = current_time - 24 * 60 * 60 * int(options.DAYS)
# trim posts that are not old enough from the start
while len(posts) > 0 and del_time < int(posts[0]['created_utc']):
print "{0} is not old enough".format(posts[0]['name'])
posts.pop(0)
# delete all posts
for post in posts:
if should_delete(post, options):
params = urllib.urlencode({ 'id': post['name'],
'executed': 'deleted',
'r': post['subreddit'],
'uh': modhash })
opener.open('http://www.reddit.com/api/del', params)
print "deleted {0} on {1}".format(post['name'], post['subreddit'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment