Skip to content

Instantly share code, notes, and snippets.

@gckrol
Forked from anonymous/reddit-privacy.py
Created June 29, 2012 19:39
Show Gist options
  • Select an option

  • Save gckrol/3020175 to your computer and use it in GitHub Desktop.

Select an option

Save gckrol/3020175 to your computer and use it in GitHub Desktop.

Revisions

  1. gckrol revised this gist Jun 29, 2012. 1 changed file with 49 additions and 52 deletions.
    101 changes: 49 additions & 52 deletions reddit-privacy.py
    Original file line number Diff line number Diff line change
    @@ -7,12 +7,26 @@
    import urllib, urllib2, cookielib, json, sys, datetime
    from optparse import OptionParser

    # 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("-a", "--delete-all", action="store_true", default = False,
    help = "delete everything, overriding all other settings")

    options, args = parser.parse_args()

    def read(fd):
    data = fd.read()
    fd.close()
    return data

    def should_delete(post, options):
    def should_delete_type(post):
    if options.delete_all:
    return True
    if options.del_posts and 'num_comments' in post:
    @@ -21,21 +35,27 @@ def should_delete(post, options):
    return True
    return False

    # handle command line arguments
    parser = OptionParser()
    def should_delete(post):
    if not should_delete_type(post): return False
    if options.DAYS is not None:
    # what time is it right now?
    current_time = int(datetime.datetime(2000, 1, 1).utcnow().strftime("%s"))

    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")
    # when should we delete posts after?
    del_time = current_time - 24 * 60 * 60 * int(options.DAYS)

    options, args = parser.parse_args()
    # trim posts that are not old enough from the start
    if int(post['created_utc']) < del_time:
    return True
    return False

    def delete_post(post):
    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'])

    if options.delete_all:
    print "Deleting everything."
    @@ -54,20 +74,14 @@ def should_delete(post, options):
    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)
    opener.addheaders = [('User-agent', 'Reddit-privacy/0.0')]

    # log in
    params = urllib.urlencode({ 'user': USERNAME,
    @@ -80,48 +94,31 @@ def should_delete(post, options):
    modhash = login_json['json']['data']['modhash']

    # get user's posts
    posts = []
    data = read(opener.open('http://www.reddit.com/user/%s/.json' % USERNAME))

    print("Reading posts...")
    num = 0
    todelete = []
    while True:
    posts_json = json.loads(data)
    for d in todelete:
    delete_post(d)
    todelete = []

    # add each post to the list of posts
    for post in posts_json['data']['children']:
    posts.append(post['data'])
    for p in posts_json['data']['children']:
    post = p['data']
    if should_delete(post):
    todelete.append(post)
    num += 1

    # 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'])))
    print("{0} posts read so far...".format(num))

    # 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'])
    for d in todelete:
    delete_post(d)
  2. @invalid-email-address Anonymous created this gist Dec 22, 2010.
    127 changes: 127 additions & 0 deletions reddit-privacy.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,127 @@
    #!/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'])