Skip to content

Instantly share code, notes, and snippets.

@d-schmidt
Last active November 15, 2021 04:51
Show Gist options
  • Save d-schmidt/d79bf351a9c63872507aceea5cfae34c to your computer and use it in GitHub Desktop.
Save d-schmidt/d79bf351a9c63872507aceea5cfae34c to your computer and use it in GitHub Desktop.
request a praw reddit oauth authcode and refresh token
#!/usr/bin/env python3
import sys
import http.server
from urllib.parse import urlparse
import praw
import time
"""
https://github.com/reddit/reddit/wiki/API
http://praw.readthedocs.io/en/latest/getting_started/authentication.html
to get a refresh_token
- create an app at reddit https://www.reddit.com/prefs/apps/
- create a praw.ini:
[bot]
client_id=clientIdFromPrefsApps
client_secret=clientSecretFromPrefsApps
user_agent=praw:yourbotname:1.0 (by /u/yourusername)
- python refreshToken.py
- copy refreshToken and update praw.ini
"""
redirect_is_local = True
redirect_uri = 'http://127.0.0.1:65010/authorize_callback'
r = praw.Reddit('bot', redirect_uri=redirect_uri)
oauthState = str(int(time.time()))
url = r.auth.url(('submit', 'privatemessages', 'read', 'identity'),
oauthState, 'permanent')
print("copy, call url and confirm, copy code from redirected url")
print(url)
if redirect_is_local:
import webbrowser
webbrowser.open(url)
# start local http server for callback, prints refreshToken
if redirect_is_local:
class CallbackHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
query = urlparse(self.path).query
queryParts = dict(qc.split("=") for qc in query.split("&"))
if oauthState != queryParts['state']:
print('wrong state')
self.wfile.write(bytes('wrong state', "utf8"))
return
code = queryParts['code']
refreshToken = r.auth.authorize(code)
text = "authCode:" + code + '\nrefreshToken:' + refreshToken
print(text)
self.wfile.write(bytes(text, "utf8"))
server = http.server.HTTPServer(("127.0.0.1", 65010), CallbackHandler)
server.timeout = None
server.handle_request()
server.server_close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment