Last active
February 21, 2020 08:33
-
-
Save tripulse/88c2fc37008d1778d18bffb15623d9c9 to your computer and use it in GitHub Desktop.
Simple script for uploading images onto Imgur.
This file contains hidden or 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
"Uploads an image to imgur.com using the Imgur API." | |
import argparse | |
import requests | |
import re | |
import sys | |
import os | |
class ImgurInvalidScheme(ValueError): pass | |
class ImgurUpload(argparse.ArgumentParser): | |
__doc__ = __doc__ | |
IS_URL = re.compile(r"(?P<scheme>[a-z]+)://.") | |
SUPPORTED_URL_SCHEMES = ('http', 'https', 'ftp', 'ftps') | |
def __init__(self): | |
argparse.ArgumentParser.__init__(self, | |
prog= self.__class__.__name__, | |
description= self.__doc__) | |
self.add_argument('PATH', | |
help= "a path-like object, resembles a URL or file-path", | |
default= '-') | |
self.add_argument('--title', | |
dest='TITLE', | |
help= "title of the image to be posted") | |
self.add_argument('--description', | |
dest= 'DESC', | |
help= "description of the image") | |
self.params = vars(self.parse_args()) | |
def main(self, client_id= None): | |
path = self.IS_URL.search(self.params['PATH']) | |
infile = None | |
if path is None: | |
if self.params['PATH'] == '-': | |
infile = sys.stdin.buffer | |
else: | |
infile = open(self.params['PATH'], 'rb', buffering= 0) | |
else: | |
if not path.groupdict()['scheme'] in self.SUPPORTED_URL_SCHEMES: | |
raise ImgurInvalidScheme("specified URL scheme isn't supported by Imgur") | |
imgur_resp = requests.post("https://api.imgur.com/3/image", data= { | |
# read 10000000 bytes which is 10 MB (that's the upper limit) | |
# sometimes can corrupt the stuff if incomplete. | |
'image': self.params['PATH'] if path else infile.read(10000000), | |
'type': 'URL' if path else 'file', | |
'title': self.params['TITLE'], | |
'description': self.params['DESC'] | |
}, headers= { | |
'Authorization': f'Client-ID {client_id}' | |
}).json() | |
if imgur_resp['status'] != 200: | |
raise Exception(f"Imgur responded with a non-OK status ({imgur_resp['status']})") | |
else: | |
print(imgur_resp['data']['link']) | |
if __name__ == "__main__": | |
imgup = ImgurUpload() | |
imgup.main(os.getenv("IMGUR_CLIENT_ID")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the OAuth2 authentication "Client ID" is required.
IMGUR_CLIENT_ID
environment variable.