Skip to content

Instantly share code, notes, and snippets.

@TheEnigmaBlade
Created February 9, 2016 19:56
Show Gist options
  • Save TheEnigmaBlade/8e93087de8b82bea6b78 to your computer and use it in GitHub Desktop.
Save TheEnigmaBlade/8e93087de8b82bea6b78 to your computer and use it in GitHub Desktop.
import praw, requests
from requests.auth import HTTPBasicAuth
def connect_reddit(oauth_key, oauth_secret, username, password, useragent, oauth_scopes={}):
r = praw.Reddit(user_agent=useragent)
# Get oauth token
client_auth = HTTPBasicAuth(oauth_key, oauth_secret)
headers = {"User-Agent": useragent}
data = {"grant_type": "password", "username": username, "password": password}
response = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, headers=headers, data=data)
if not response.ok:
print("Received error code {}: {}".format(response.status_code, response.reason))
return None
response_content = response.json()
if "error" in response_content and response_content["error"] != 200:
print("Received error: {}".format(response_content["error"]))
return None
# Init praw oauth
token = response_content["access_token"]
r.set_oauth_app_info(oauth_key, oauth_secret, "http://example.com/unused/redirect/uri")
r.set_access_credentials(oauth_scopes | {"identity"}, access_token=token)
r.config.api_request_delay = 1
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment