Last active
December 14, 2015 03:49
-
-
Save Garciat/5023987 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tempfile, os, requests, json, webbrowser | |
import pyscreenshot as pyscr | |
from base64 import b64encode | |
# required modules: pyscreenshot, PIL, requests | |
__client_id__ = '...' | |
__client_secret__ = '...' | |
__cred_keys__ = ['access_token', 'refresh_token', 'token_type', 'expires_in'] | |
def valid_credentials(creds): | |
for k in __cred_keys__: | |
if k not in creds: | |
return False | |
return True | |
def refresh(creds): | |
params = { | |
'client_id': __client_id__, | |
'client_secret': __client_secret__, | |
'grant_type': 'refresh_token', | |
'refresh_token': creds['refresh_token'] | |
} | |
r = requests.post('https://api.imgur.com/oauth2/token', verify = False, data = params) | |
return r.json() | |
def authorize(): | |
cred_file = os.path.expanduser(os.path.join('~', '.imgur_credentials')) | |
if os.path.exists(cred_file): | |
with file(cred_file) as f: | |
creds = json.loads(f.read()) | |
if valid_credentials(creds): | |
return refresh(creds) | |
auth_url = 'https://api.imgur.com/oauth2/authorize?client_id=%s&response_type=%s' % (__client_id__, 'pin') | |
webbrowser.open_new_tab(auth_url) | |
print 'Enter PIN:', | |
pin = raw_input() | |
params = { | |
'client_id': __client_id__, | |
'client_secret': __client_secret__, | |
'grant_type': 'pin', | |
'pin': pin | |
} | |
r = requests.post('https://api.imgur.com/oauth2/token', verify = False, data = params) | |
creds = r.json() | |
with file(cred_file, 'w') as f: | |
f.write(r.text) | |
return creds | |
def capture_upload(): | |
creds = authorize() | |
_, filepath = tempfile.mkstemp(suffix = '.jpg') | |
pyscr.grab_to_file(filepath) | |
with file(filepath, 'rb') as f: | |
image = b64encode(f.read()) | |
params = { | |
'image': image | |
} | |
headers = { | |
'Authorization': 'Bearer %s' % creds['access_token'] | |
} | |
r = requests.post('https://api.imgur.com/3/image', verify = False, data = params, headers = headers) | |
res = r.json() | |
if r.status_code == 200: | |
pass | |
else: | |
print res['data']['error'] | |
exit(1) | |
webbrowser.open_new_tab(res['data']['link']) | |
#os.unlink(filepath) | |
if __name__ == '__main__': | |
capture_upload() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment