def corgi(): client = ImgurClient(client_id, client_secret) album = client.get_account_albums(album_id) images = client.get_album_images(album[0].id) index = random.randint(0, len(images) - 1) url = images[index].link return url
def handle_message(event): client_id = 'de5ecd12cacaf0a' client_secret = '3556bb208ceda936f8c53033b861041cb878d878 ' client = ImgurClient(client_id, client_secret) a = client.get_account_albums("kevin86117") images = client.get_album_images(a[0].id) index = random.randint(0, len(images) - 1) url = images[index].link if event.message.text == "corgi" or event.message.text == "柯基": message = ImageSendMessage(original_content_url=url, preview_image_url=url) elif event.message.text == "news": content = technews() line_bot_api.reply_message(event.reply_token, TextSendMessage(text=content)) else: message = TextSendMessage(text=event.message.text) line_bot_api.reply_message(event.reply_token, message)
class ImgurBot: def __init__(self): self.client = None self.authorized = False if (req_info.needToAddInfo(useImgur=True)): print( "Need to update required_info.py with correct credentials before running, see README for more info" ) super().__init__() def authenticate(self): self.client = ImgurClient(req_info.client_id_imgur, req_info.client_secret_imgur) authorization_url = self.client.get_auth_url('pin') print("Go to the following URL: {0}".format(authorization_url)) # Read in the pin, handle Python 2 or 3 here. pin = get_input("Enter pin code: ") # ... redirect user to `authorization_url`, obtain pin (or code or token) ... credentials = self.client.authorize(pin, 'pin') self.client.set_user_auth(credentials['access_token'], credentials['refresh_token']) print("Authentication successful! Here are the details:") print(" Access token: {0}".format(credentials['access_token'])) print(" Refresh token: {0}".format(credentials['refresh_token'])) self.authorized = True def getalbums(self): albums = self.client.get_account_albums(req_info.imgur_account, page=0) print("Done") print(albums) def upload_to_album(self, albumId, title, description, image_url): config = { 'album': albumId, 'name': title, 'title': title, 'description': description } self.client.upload_from_url(image_url, config=config, anon=False) pass
def photos(album=None): if album is None: return redirect(url_for('public.photos', album='63Tp6')) u = User.query.get(1) client = ImgurClient( current_app.config['IMGUR_CLIENT_ID'], current_app.config['IMGUR_CLIENT_SECRET'], access_token=u.access_token, refresh_token=u.refresh_token) albums = client.get_account_albums('timandmikaela') for a in albums: if a.id == album: break else: abort(404) a = client.get_album(album) if client.auth.current_access_token != u.access_token: u.access_token = client.auth.current_access_token db.session.add(u) db.session.commit() return render_template('photos.html', album=a, albums=albums)
class ImgurStorage(Storage): """ A storage class providing access to resources in a Dropbox Public folder. """ def __init__(self, location='/'): self.client = ImgurClient( CONSUMER_ID, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_REFRESH) logger.info("Logged in Imgur storage") self.account_info = self.client.get_account(USERNAME) self.albums = self.client.get_account_albums(USERNAME) self.location = location self.base_url = 'https://api.imgur.com/3/account/{url}/'.format(url=self.account_info.url) def _get_abs_path(self, name): return os.path.join(self.location, name) def _open(self, name, mode='rb'): remote_file = self.client.get_image(name, self, mode=mode) return remote_file def _save(self, name, content): name = self._get_abs_path(name) directory = os.path.dirname(name) logger.info([a.title for a in self.albums]) logger.info(name) logger.info(directory) if not self.exists(directory) and directory: album = self.client.create_album({"title": directory}) self.albums = self.client.get_account_albums(USERNAME) album = [a for a in self.albums if a.title == directory][0] #if not response['is_dir']: # raise IOError("%s exists and is not a directory." % directory) response = self._client_upload_from_fd(content, {"album": album.id, "name": name, "title": name}, False) return response["name"] def _client_upload_from_fd(self, fd, config=None, anon=True): """ use a file descriptor to perform a make_request """ if not config: config = dict() contents = fd.read() b64 = base64.b64encode(contents) data = { 'image': b64, 'type': 'base64', } data.update({meta: config[meta] for meta in set(self.client.allowed_image_fields).intersection(config.keys())}) return self.client.make_request('POST', 'upload', data, anon) def delete(self, name): name = self._get_abs_path(name) self.client.delete_image(name) def exists(self, name): name = self._get_abs_path(name) if len([a for a in self.albums if a.title == name]) > 0: return True try: album = [a for a in self.albums if a.title == os.path.dirname(name)][0] images = self.client.get_album_images(album.id) metadata = self.client.get_image(name) if len([im for im in images if im.name == name]) > 0: logger.info(dir(metadata)) return True except ImgurClientError as e: if e.status_code == 404: # not found return False raise e except IndexError as e: return False else: return True return False def listdir(self, path): path = self._get_abs_path(path) response = self.client.get_image(path) directories = [] files = [] for entry in response.get('contents', []): if entry['is_dir']: directories.append(os.path.basename(entry['path'])) else: files.append(os.path.basename(entry['path'])) return directories, files def size(self, path): cache_key = 'django-imgur-size:%s' % filepath_to_uri(path) size = cache.get(cache_key) if not size: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] size = self.client.get_image(image.id).size cache.set(cache_key, size) return size def url(self, path): cache_key = 'django-imgur-url:%s' % filepath_to_uri(path) url = cache.get(cache_key) if not url: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] url = self.client.get_image(image.id).link cache.set(cache_key, url) return url def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ #name = self._get_abs_path(name) #dir_name, file_name = os.path.split(name) #file_root, file_ext = os.path.splitext(file_name) ## If the filename already exists, add an underscore and a number (before ## the file extension, if one exists) to the filename until the generated ## filename doesn't exist. #count = itertools.count(1) #while self.exists(name): # # file_ext includes the dot. # name = os.path.join(dir_name, "%s_%s%s" % (file_root, count.next(), file_ext)) return name
class ImgurStorage(Storage): """ A storage class providing access to resources in a Dropbox Public folder. """ def __init__(self, location='/'): self.client = ImgurClient(CONSUMER_ID, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_REFRESH) logger.info("Logged in Imgur storage") self.account_info = self.client.get_account(USERNAME) self.albums = self.client.get_account_albums(USERNAME) self.location = location self.base_url = 'https://api.imgur.com/3/account/{url}/'.format( url=self.account_info.url) def _get_abs_path(self, name): return os.path.join(self.location, name) def _open(self, name, mode='rb'): remote_file = self.client.get_image(name, self, mode=mode) return remote_file def _save(self, name, content): name = self._get_abs_path(name) directory = os.path.dirname(name) logger.info([a.title for a in self.albums]) logger.info(name) logger.info(directory) if not self.exists(directory) and directory: album = self.client.create_album({"title": directory}) self.albums = self.client.get_account_albums(USERNAME) album = [a for a in self.albums if a.title == directory][0] #if not response['is_dir']: # raise IOError("%s exists and is not a directory." % directory) response = self._client_upload_from_fd(content, { "album": album.id, "name": name, "title": name }, False) return response["name"] def _client_upload_from_fd(self, fd, config=None, anon=True): """ use a file descriptor to perform a make_request """ if not config: config = dict() contents = fd.read() b64 = base64.b64encode(contents) data = { 'image': b64, 'type': 'base64', } data.update({ meta: config[meta] for meta in set(self.client.allowed_image_fields).intersection( list(config.keys())) }) return self.client.make_request('POST', 'upload', data, anon) def delete(self, name): name = self._get_abs_path(name) self.client.delete_image(name) def exists(self, name): name = self._get_abs_path(name) if len([a for a in self.albums if a.title == name]) > 0: return True try: album = [ a for a in self.albums if a.title == os.path.dirname(name) ][0] images = self.client.get_album_images(album.id) metadata = self.client.get_image(name) if len([im for im in images if im.name == name]) > 0: logger.info(dir(metadata)) return True except ImgurClientError as e: if e.status_code == 404: # not found return False raise e except IndexError as e: return False else: return True return False def listdir(self, path): path = self._get_abs_path(path) response = self.client.get_image(path) directories = [] files = [] for entry in response.get('contents', []): if entry['is_dir']: directories.append(os.path.basename(entry['path'])) else: files.append(os.path.basename(entry['path'])) return directories, files def size(self, path): cache_key = 'django-imgur-size:%s' % filepath_to_uri(path) size = cache.get(cache_key) if not size: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] size = self.client.get_image(image.id).size cache.set(cache_key, size) return size def url(self, path): cache_key = 'django-imgur-url:%s' % filepath_to_uri(path) url = cache.get(cache_key) if not url: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] url = self.client.get_image(image.id).link cache.set(cache_key, url) return url def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ #name = self._get_abs_path(name) #dir_name, file_name = os.path.split(name) #file_root, file_ext = os.path.splitext(file_name) ## If the filename already exists, add an underscore and a number (before ## the file extension, if one exists) to the filename until the generated ## filename doesn't exist. #count = itertools.count(1) #while self.exists(name): # # file_ext includes the dot. # name = os.path.join(dir_name, "%s_%s%s" % (file_root, count.next(), file_ext)) return name
if 'data' in response_data and isinstance( response_data['data'], dict) and 'error' in response_data['data']: raise ImgurClientError(response_data['data']['error'], response.status_code) return response_data['data'] if 'data' in response_data else response_data # check if finished folder exists if not os.path.exists('finished_uploads'): print("creating finished_uploads directory...") os.makedirs('finished_uploads') # check if album with today's date exists response = client.get_account_albums(get_username()) today_album_exists = False album_id = "" for item in response: if item.title == today: print(f"Found album: {item.title} - {item.id}") today_album_exists = True album_id = item.id break # otherwise create today's album if not today_album_exists: album_config = {'title': today, 'privacy': 'hidden'} response = client.create_album(album_config) album_id = response['id'] print(response)
class ImgurUtils: _ACCOUNT_NAME = "DermaGram" _CLIENT_ID = "74ab756d286b81b" _CLIENT_SECRET = "06e8cbd50c3388b95681efe0bf17e8578f72c8dd" _ACCESS_TOKEN = "7a58917273a8734cbbe6bc498d78e390b3c2e56e" _REFRESH_TOKEN = "463a35741a82af231b5d150deb7be5e69c48c386" def __init__(self): self._client = ImgurClient(ImgurUtils._CLIENT_ID, ImgurUtils._CLIENT_SECRET, ImgurUtils._ACCESS_TOKEN, ImgurUtils._REFRESH_TOKEN) ''' Takes a float value and converts to a formatted datetime string @param: 'epoch' is of type float (e.g. 123456789.0) @return: a formatted string (e.g. '2017-10-16 15:56:03') ''' def _get_local_time(self, epoch): logger = logging.getLogger(__name__) timestamp = str() try: timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch)) except Exception as error_msg: logger.error(error_msg) return timestamp ''' Retrieves all albums for a given account (e.g. DermaGram). For each album, checks if the title matches the current user's uuid. This is because we name albums based on the user's uuid. @return: a unique album.id if match exists; otherwise, None ''' def _get_album_id_by_title(self, username): album_id = None albums = self._client.get_account_albums(ImgurUtils._ACCOUNT_NAME) for album in albums: if (username == album.title): album_id = album.id break return album_id ''' Retrieves all albums for a given account (e.g. DermaGram). For each album, adds the 'title' property to a set. @return: a set of unique strings corresponding to album titles. ''' def _get_album_titles_as_set(self): album_titles = set() albums = self._client.get_account_albums(ImgurUtils._ACCOUNT_NAME) for album in albums: album_titles.add(str(album.title)) return album_titles ''' Retrieves images from Imgur using an album_id. The image's id, title, description and datetime are stored in an object 'image_info' and appended to a list 'image_history' @return: a list of objects containing info. about each image. ''' def get_images_from_album(self, album_id): logger = logging.getLogger(__name__) images_data = {"table": []} images = self._client.get_album_images(album_id) if images: # Sort images in descending chronological order images.sort(key=lambda x: x.datetime, reverse=True) for image in images: #Uncomment to list all properties that may be retrieved from an imgur Image object #print dir(image) info = self._parse_description(image.description) image_info = { 'id': str(image.id), 'title': str(image.title), 'link': str(image.link), 'location': info['location'], 'classification': info['classification'], 'datetime': self._get_local_time(float(image.datetime)), } images_data['table'].append(image_info) else: logger.warning('No images returned for album_id: {0}.' '\nget_album_images() response: {1}'.format( album_id, images)) return images_data def _parse_description(self, description): info = "" try: info = json.loads(description) except Exception as e: print "ERROR: ", e return info ''' Checks if album already exists for given uuid. Note: an album's title corresponds to the user's uuid. @return: boolean True if album exists; otherwise False ''' def _does_album_exist(self, username): album_titles = self._get_album_titles_as_set() return True if username in album_titles else False ''' Creates a new album where the album's title is the user's uuid. An new album id that is created in the process is returned. @return: a string variable corresponding to the album's unique id ''' def create_new_album(self, username): logger = logging.getLogger(__name__) new_album_id = None #TODO we need to do check if username already exists as album name if (False): existing_album_id = self._get_album_id_by_title(username) logger.error("The uuid {0} already has an album id: {1}".format( username, existing_album_id)) else: logger.info("Creating a new album for {0}".format(username)) album_info = {"title": username, "privacy": "public"} self._client.create_album(album_info) new_album_id = self._get_album_id_by_title(username) if new_album_id: logger.info("The new album id for user {0} is: {1}".format( username, new_album_id)) else: logger.error("There was an error getting the album_id.") return new_album_id #https://github.com/Imgur/imgurpython/blob/3a285f758bcb8a2ff6aa024b2944f464f50d87d0/examples/upload.py def add_image_to_album(self, album_id, title, location, classification, image_path): #TODO make this pull correct album and other data from user session description = {"location": location, "classification": classification} config = { 'album': album_id, 'title': title, 'description': json.dumps(description) } return self._client.upload_from_path(image_path, config=config, anon=False)
if __name__ == '__main__': client_dict = get_client_keys() print(client_dict) # If you already have an access/refresh pair in hand client_id = client_dict['client_id'] client_secret = client_dict['client_secret'] refresh_token = client_dict['refresh_token'] # Note since access tokens expire after an hour, only the refresh token is required (library handles autorefresh) client = ImgurClient(client_id, client_secret, refresh_token) big = open('..\\data\\bigcontent.html', mode='w') slider = open('..\\data\\slidercontent.html', mode='w') for i, album in enumerate(client.get_account_albums('NateRussell1')): album_title = album.title if album.title else 'Untitled' print('Album: {0} ({1})'.format(album_title, album.id)) for j, image in enumerate(client.get_album_images(album.id)): image_title = image.title if image.title else 'Untitled' image_link = image.link[0:4] + 's' + image.link[4:] big_image_link = image_link[:-4] + 'h' + image_link[-4:] small_image_link = image_link[:-4] + 's' + image_link[-4:] print('\t{0}: {1}'.format(big_image_link, small_image_link)) big.write( '<a class="%s"><img data-lazy="%s" class="bimg %s"/></a>' % (album.id, big_image_link, album.id)) slider.write( '<a class="%s"><img data-lazy="%s" class="simg %s"/></a>' % (album.id, small_image_link, album.id))