OAuth 2 login support. see get_secret.py and praw.ini.example

pull/38/head
David Trail 10 years ago
parent f016d95783
commit 2e9beb1d91

@ -10,7 +10,8 @@ from simpleconfigparser import simpleconfigparser
from datetime import datetime, timedelta from datetime import datetime, timedelta
import praw import praw
from praw.errors import InvalidUser, InvalidUserPass, RateLimitExceeded from praw.errors import InvalidUser, InvalidUserPass, RateLimitExceeded, \
HTTPException
from praw.objects import Comment, Submission from praw.objects import Comment, Submission
try: try:
@ -67,28 +68,34 @@ save_directory = config.get('main', 'save_directory')
_user = config.get('main', 'username') _user = config.get('main', 'username')
_pass = config.get('main', 'password') _pass = config.get('main', 'password')
r = praw.Reddit(user_agent="shreddit/3.3") r = praw.Reddit(user_agent="shreddit/4.0")
if save_directory: if save_directory:
r.config.store_json_result = True r.config.store_json_result = True
def login(user=None, password=None): def login(user=None, password=None):
try: try:
if user and password: # This is OAuth 2
r.login(_user, _pass) r.refresh_access_information()
else: if verbose:
r.login() # Let the user supply details print("Logged in with OAuth.")
except InvalidUser as e: except HTTPException:
raise InvalidUser("User does not exist.", e) try:
except InvalidUserPass as e: if user and password:
raise InvalidUserPass("Specified an incorrect password.", e) r.login(_user, _pass)
except RateLimitExceeded as e: else:
raise RateLimitExceeded("You're doing that too much.", e) r.login() # Let the user supply details
except InvalidUser as e:
raise InvalidUser("User does not exist.", e)
except InvalidUserPass as e:
raise InvalidUserPass("Specified an incorrect password.", e)
except RateLimitExceeded as e:
raise RateLimitExceeded("You're doing that too much.", e)
if not r.is_logged_in(): if not r.is_logged_in():
login(user=_user, password=_pass) login(user=_user, password=_pass)
if verbose: if verbose:
print("Logged in as {user}".format(user=r.user)) print("Logged in as {user}.".format(user=r.user))
if verbose: if verbose:
print("Deleting messages before {time}.".format( print("Deleting messages before {time}.".format(
@ -103,78 +110,83 @@ if verbose and whitelist:
subs=', '.join(whitelist)) subs=', '.join(whitelist))
) )
things = [] def get_things(after=None):
if item == "comments": if item == "comments":
things = r.user.get_comments(limit=None, sort=sort) return r.user.get_comments(limit=None, sort=sort)
elif item == "submitted": elif item == "submitted":
things = r.user.get_submitted(limit=None, sort=sort) return r.user.get_submitted(limit=None, sort=sort)
elif item == "overview": elif item == "overview":
things = r.user.get_overview(limit=None, sort=sort) return r.user.get_overview(limit=None, sort=sort)
else: else:
raise Exception("Your deletion section is wrong") raise Exception("Your deletion section is wrong")
for thing in things: def remove_things(things):
# Seems to be in users's timezone. Unclear. for thing in things:
thing_time = datetime.fromtimestamp(thing.created_utc) # Seems to be in users's timezone. Unclear.
# Exclude items from being deleted unless past X hours. thing_time = datetime.fromtimestamp(thing.created_utc)
after_time = datetime.now() - timedelta(hours=hours) # Exclude items from being deleted unless past X hours.
if thing_time > after_time: after_time = datetime.now() - timedelta(hours=hours)
if thing_time + timedelta(hours=nuke_hours) < datetime.utcnow(): if thing_time > after_time:
pass if thing_time + timedelta(hours=nuke_hours) < datetime.utcnow():
continue pass
# For edit_only we're assuming that the hours aren't altered. continue
# This saves time when deleting (you don't edit already edited posts). # For edit_only we're assuming that the hours aren't altered.
if edit_only: # This saves time when deleting (you don't edit already edited posts).
end_time = after_time - timedelta(hours=hours) if edit_only:
if thing_time < end_time: end_time = after_time - timedelta(hours=hours)
continue if thing_time < end_time:
continue
if str(thing.subreddit).lower() in whitelist or \
thing.id in whitelist_ids: if str(thing.subreddit).lower() in whitelist or \
continue thing.id in whitelist_ids:
continue
if whitelist_distinguished and thing.distinguished:
continue if whitelist_distinguished and thing.distinguished:
if whitelist_gilded and thing.gilded: continue
continue if whitelist_gilded and thing.gilded:
if max_score is not None and thing.score > max_score: continue
continue if max_score is not None and thing.score > max_score:
continue
if trial_run: # Don't do anything, trial mode!
if verbose: if trial_run: # Don't do anything, trial mode!
print("Would have deleted {thing}: '{content}'".format( if verbose:
thing=thing.id, content=thing)) print("Would have deleted {thing}: '{content}'".format(
continue thing=thing.id, content=thing))
continue
if save_directory:
if not os.path.exists(save_directory): if save_directory:
os.makedirs(save_directory) if not os.path.exists(save_directory):
with open("%s/%s.json" % (save_directory, thing.id), "w") as fh: os.makedirs(save_directory)
json.dump(thing.json_dict, fh) with open("%s/%s.json" % (save_directory, thing.id), "w") as fh:
json.dump(thing.json_dict, fh)
if clear_vote:
thing.clear_vote() if clear_vote:
thing.clear_vote()
if isinstance(thing, Submission):
if verbose: if isinstance(thing, Submission):
print('Deleting submission: #{id} {url}'.format( if verbose:
id=thing.id, print('Deleting submission: #{id} {url}'.format(
url=thing.url.encode('utf-8')) id=thing.id,
) url=thing.url.encode('utf-8'))
elif isinstance(thing, Comment): )
replacement_text = get_sentence() elif isinstance(thing, Comment):
if verbose: replacement_text = get_sentence()
msg = '/r/{3}/ #{0} with:\n\t"{1}" to\n\t"{2}"'.format( if verbose:
thing.id, msg = '/r/{3}/ #{0} with:\n\t"{1}" to\n\t"{2}"'.format(
sub(b'\n\r\t', ' ', thing.body[:78].encode('utf-8')), thing.id,
replacement_text[:78], sub(b'\n\r\t', ' ', thing.body[:78].encode('utf-8')),
thing.subreddit replacement_text[:78],
) thing.subreddit
if edit_only: )
print('Editing {msg}'.format(msg=msg)) if edit_only:
else: print('Editing {msg}'.format(msg=msg))
print('Editing and deleting {msg}'.format(msg=msg)) else:
print('Editing and deleting {msg}'.format(msg=msg))
thing.edit(replacement_text)
if not edit_only:
thing.delete()
things = get_things()
remove_things(things)
thing.edit(replacement_text)
if not edit_only:
thing.delete()

Loading…
Cancel
Save