def __init__(self, bot, id, secret): TextReader.__init__(self, bot) self.id = id self.secret = secret print("Logging in to Imgur") self.client = imgurpython.ImgurClient(self.id, self.secret) print("Done")
def initImgur(): """Initialize imgur api""" config = GLOBAL.config return imgurpython.ImgurClient( config["credentials"]['imgur_client_id'], config["credentials"]['imgur_client_secret'])
def get_content(url): split = urlsplit(url) path_elements = [x for x in split.path.split("/") if x] if len(path_elements) == 1: return retrieve_single(url) elif 1 < len(path_elements): client = imgurpython.ImgurClient(key_imgur.cred['client-id'], key_imgur.cred['client-secret']) particle, content_id = path_elements[:2] content_id = re.sub("[^A-Za-z0-9]+$", "", content_id) # removing dirt if particle == 'a': links = [x.link for x in client.get_album_images(content_id)] elif particle == 'gallery': g = client.gallery_item(content_id) if hasattr(g, 'images'): links = [x['link'] for x in g.images] else: links = [g.link] # we can have a gallery with only one item if len(links) > 200: return None rs = (grequests.get(x) for x in links) res = grequests.map(rs) f = sort_func(links) # for sorting res.sort(key=f) info = mk_pasteinfo(*[(x, u) for x, u in zip(res, rep(url))]) for paste, r in zip(info, res): paste['content'] = r.content return info
def __init__(self, client_id, client_secret, folder_path, refresh_token=None, single_images_folder=True): # Correcting refesh token if refresh_token == '': refresh_token = None # Storing refresh token self.refresh_token = refresh_token self.single_images_folder = single_images_folder # Creating ImgurClient self.client = ip.ImgurClient( client_id, client_secret, refresh_token=refresh_token) # Setting desired folder path self.desired_folder_path = self.check_folder_path(folder_path) self.check_if_folder_exists() # If refresh_token was given, set true if self.refresh_token is not None: self.is_authenticated = True else: self.is_authenticated = False
def login(self): """Attempt to log into the Imgur API.""" self.log.info('Logging into imgur...') self.client = imgurpython.ImgurClient(self.app_id, self.app_secret) self.log.debug(self.client.credits) if all(i is None for i in self.client.credits.values()): self.log.warning('Client returned no credits!') self.login()
def __init__(self, source, fetcher_host, fetcher_port, counters): super(Analyzer, self).__init__(source, fetcher_host, fetcher_port, counters) self._subdomains_pairs = [ tuple(s.split(':')) for s in source.subdomains ] self._page_uri_filter = set() self._client = imgur.ImgurClient(defines.IMGUR_CLIENT_ID, defines.IMGUR_CLIENT_SECRET)
def uploadGifToImgur(gif, clientId, clientSecret): # Uploading Gif to Imgur print("Uploading " + gif + " to imgur.") i = imgurpython.ImgurClient(clientId, clientSecret).upload_from_path(path=gif, config=None, anon=True) link = i.get('link') print("Gif can be found at: " + link) return link
def configure(self, *args, **kwargs): self.subreddit = kwargs['subreddit'] self.imgur_client = imgurpython.ImgurClient( client_id=IMGUR_CLIENT_ID, client_secret=IMGUR_CLIENT_SECRET) with shelve.open('decolorize_storage') as decolorize_storage: self.comments_done = decolorize_storage.get('comments_done', []) self.urls_done = decolorize_storage.get('urls_done', []) log.info('Loaded comments_done:{0}'.format(self.comments_done)) log.info('Loaded urls_done:{0}'.format(self.urls_done))
def get_imgur_client(max_attempts=10): """Wrap imgur client setup to make it more fault-tolerant""" attempt_counter = 0 while attempt_counter <= max_attempts: attempt_counter += 1 try: client = imgurpython.ImgurClient(config.imgur_client_id, config.imgur_client_secret) return client except ImgurClientError, err: logging.exception(err) logging.error("err:"+repr(err)) continue
async def imgur(cmd, message, args): if not args: return q = ' '.join(args) imgur_client = imgurpython.ImgurClient(ImgurClientID, ImgurClientSecret) gallery_items = imgur_client.gallery_search(q, advanced=None, sort='time', window='all', page=0) chosen_item = random.choice(gallery_items).link await message.channel.send(chosen_item)
def setup(bot): global imgur_client logging.basicConfig(level=logging.INFO) with open("secrets.yml", "r") as f: secrets = yaml.safe_load(f) imgur_client = imgurpython.ImgurClient(secrets["imgur_client_id"], secrets["imgur_client_secret"]) bot.add_cog(Archive(bot))
def run(): reload(sys) sys.setdefaultencoding('utf8') client_id = "" client_secret = "" client = imgurpython.ImgurClient(client_id, client_secret) items = client.gallery() array = [] counter = 0 for row in items: # Determine what image to show g_item = client.gallery_item(row.id) cover = "https://i.imgur.com/KjsT4r8.png" if type(g_item) is imgurpython.imgur.models.gallery_album.GalleryAlbum: cover = "https://i.imgur.com/%s.png" % g_item.cover elif type( g_item) is imgurpython.imgur.models.gallery_image.GalleryImage: cover = row.link # Make the dict subarray = { "description": str(row.description), "gallery": str(row.in_gallery), "postID": str(row.id), "link": str(row.link), "nsfw": str(row.nsfw), "points": str(row.points), "processedurl": str(cover), "time": str(row.datetime), "views": str(row.views) } # If nsfw easier for sql if subarray["nsfw"]: subarray['nsfw'] = "1" else: subarray['nsfw'] = "0" array.append(subarray) counter += 1 if counter > 4: break return array
def post_graph(impath, subreddit_name): subreddit.logging.info("Uploading to imgur...") client = imgurpython.ImgurClient(**database.CONFIG["imgurapi"]) info = "/r/%s statistics graph: %s" % (subreddit_name, str(datetime.datetime.now())) image = client.upload_from_path(impath, config={ "album": None, "name": info, "title": info, "description": info }) return image["link"]
def main(self, argv): self.generate_parser() if not argv: self.parser.print_help() return 0 args = self.parser.parse_args(argv) try: # Short-circuit and deal with help right away if args.func == self.cmd_help: self.cmd_help(args) return 0 credentials = imgur_credentials() self.client = imgurpython.ImgurClient(*credentials) args.func(self.client, args) except AttributeError: self.subparsers[argv[0]]['parser'].print_help()
def take_photo(self, bus): self.last_photo_upload = time.time() # Get flickr configuration. try: config = bus.command('get_status')['config'] webcam_host = config['data_measurement_host'] api = imgurpython.ImgurClient(config['private_imgur_id'], config['private_imgur_secret']) except KeyError: return album_id = config.get('private_imgur_album', None) if album_id is None: response = api.create_album({ 'title': "KORUZA (%s)" % config.get('name', 'koruza'), 'privacy': 'public', 'layout': 'grid', }) # Store album identifier. bus.command('set_config', config={ 'imgur_album': response['id'], 'private_imgur_album': response['deletehash'], }) album_id = response['deletehash'] try: data = requests.get('http://%s:8080/?action=snapshot' % webcam_host).content except (requests.HTTPError, requests.ConnectionError): return api.make_request( 'POST', 'upload', data={ 'type': 'base64', 'image': base64.b64encode(data), 'name': 'koruza', 'title': "Webcam Snapshot (%s)" % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), 'album': album_id, }, force_anon=True, )
def run(content_config, unused_env, variables): """ content_config schema: { "type": "random or query", "term": "query term if type is query", "max_count": 5, // max number of images to return "auth": { "client_id": "imgur client_id", "client_secret": "imgur client_secret" } } """ client = imgurpython.ImgurClient(content_config['auth']['client_id'], content_config['auth']['client_secret']) if content_config['type'] == 'random': images = [ x for x in client.gallery_random() if isinstance(x, GalleryImage) ] else: term = Resolve(content_config['term'], variables) images = [ x for x in client.gallery_search(term) if isinstance(x, GalleryImage) ] images = random.sample(images, int(content_config['max_count'])) m = Message() for i in images: c = Message.Bubble(i.title, i.link[:-4], i.link, i.description) c.add_button( Message.Button(Message.ButtonType.WEB_URL, 'Source', url=i.link[:-4])) c.add_button( Message.Button(Message.ButtonType.POSTBACK, 'Like', payload=TextPayload('like %s' % i.link))) m.add_bubble(c) return [Message('Here are the images you requested'), m]
async def imgurImg(search): config = configparser.ConfigParser() config.read('config.ini') client_id = config['Credentials']['imgur_client_id'] client_secret = config['Credentials']['imgur_client_secret'] imgur = imgurpython.ImgurClient(client_id, client_secret) galleryItems = imgur.gallery_search(search, window='all') images = [] for i in galleryItems: if type( i ) is imgurpython.imgur.models.gallery_image.GalleryImage and not i.link.endswith( ('.mp4', '.webm')) and not i.link.startswith("http://"): images.append(i) if len(images) > 0: url = images[random.randint(0, len(images) - 1)].link return url else: return None
def auth_imgur(client_id, client_secret): """Authenticating to imgur and returning ImgurClient to main, so we can use it to upload pictures. Arguments: client_id {string} -- [Client ID for creating Auth URL, by clicking this URL we can get access and refresh tokens from URL we get at Browser] client_secret {string} -- [Client secret for creating ImgurClient] Returns: [imgurpython.ImgurClient] -- [ImgurClient user, currently using for uploads.] """ #python module is not supported and it still works on pin #we use requests to get authentication link and we copy access and refresh tokens from site to our variables auth_string = string_builder_auth(client_id) print("Press the link and copy access&refresh tokens: {url}".format( url=auth_string)) access_token = input("enter access token: ") refresh_token = input("enter refresh token: ") #after that we use imgurpythons ImgurClient module to make a proper authentication client = imgurpython.ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) return client
async def imgurlink(cmd, message, args): if not args: await message.channel.send(cmd.help()) return if (ImgurClientID == '') or (ImgurClientSecret == ''): embed = discord.Embed(color=0xDB0000) embed.add_field( name='API key ImgurClientID and/or ImgurClientSecret not found.', value='Please ask the bot owner to add them.') await message.channel.send(None, embed=embed) return try: imgur_client = imgurpython.ImgurClient(ImgurClientID, ImgurClientSecret) except Exception as e: cmd.log.error(e) await message.channel.send('Something went wrong! Contact the bot dev.' ) return if message.attachments or args: if message.attachments: img_url = message.attachments[0].url else: img_url = ' '.join(args) if img_url.startswith('http'): upload_res = imgur_client.upload_from_url(img_url) response = discord.Embed(color=0x66CC66) response.add_field(name='✅ Image Uploaded', value=f'URL:\n```\n{upload_res["link"]}\n```') response.set_image(url=upload_res['link']) else: response = discord.Embed(color=0xDB0000, title='❗ Invalid URL') else: response = discord.Embed(color=0xDB0000, title='❗ Nothing Was Inputted') await message.channel.send(embed=response)
def clients(name, config=None): try: if not config: filename = os.path.abspath( os.path.join(os.path.dirname(__file__), '.gitignore', 'client_info.ini')) config = configparser.ConfigParser() config.read(filename) if name == 'reddit': reddit = praw.Reddit( client_id=config['reddit']['client_id'], client_secret=config['reddit']['client_secret'], user_agent=config['reddit']['user_agent']) return reddit elif name == 'imgur': imgur = imgurpython.ImgurClient( client_id=config['imgur']['client_id'], client_secret=config['imgur']['client_secret']) return imgur except Exception as e: print(f'Error: {e}') sys.exit()
def __init__(self, client_id, client_secret, folder_path, refresh_token=None, single_images_folder=True, overwrite=False, verbose=False, max_favorites=None): if verbose: ENABLE_LOGGING_DEBUG() self.max_favorites = max_favorites # Correcting refesh token if not refresh_token: refresh_token = None # Storing refresh token self.refresh_token = refresh_token self.single_images_folder = single_images_folder # Creating ImgurClient self.client = ip.ImgurClient(client_id, client_secret, refresh_token=refresh_token) # Setting desired folder path self.change_desired_folder_path(folder_path) # If refresh_token was given, set true if self.refresh_token is not None: self.is_authenticated = True else: self.is_authenticated = False self.overwrite = overwrite
async def imgur(cmd, message, args): q = ' '.join(args) try: imgur_client = imgurpython.ImgurClient(ImgurClientID, ImgurClientSecret) except imgurpython.helpers.error.ImgurClientError: cmd.log.error('Imgur ClientID + ClientSecret') return gallery_items = imgur_client.gallery_search(q, advanced=None, sort='time', window='all', page=0) try: chosen_item = random.choice(gallery_items).link except Exception as e: cmd.log.error(e) await cmd.bot.send_message(message.channel, 'No results...') return await cmd.bot.send_message(message.channel, chosen_item)
def convertImgurIndirectUrlToImg(submission, imgurAuth, url): # Login to imgur # This is required since they made NSFW images require login imgurClient = imgur.ImgurClient(imgurAuth.clientId, imgurAuth.clientSecret) if not checkImgurAPICredits(imgurClient): return None imageId = imgurIdFromUrl(url) if not imageId: logger.log("Failed to convert {} to image id".format(url)) try: return imgurClient.get_image(imageId).link except Exception as e: errorMessage = ( 'Failed to convert imgur to image link: ' '[ERROR] Exception: Url {} raised exception:\n\t {}'.format( url, e)) logger.log(errorMessage) LikedSavedDatabase.db.addUnsupportedSubmission(submission, errorMessage) return None
def run(self): global LinkList global stop global kill page = 0 client = imgurpython.ImgurClient(self.client_id, self.client_secret) while not kill: if stop: time.sleep(10) else: while LinkList.empty(): try: print "[*] Adding to queue from page:", str(page) content = client.gallery(section="user", sort="time", page=page, window="day", show_viral=False) for contents in content: LinkList.put(contents.link) page += 1 print "next page" except ImgurClientError as e: stop = True exit(e) else: quit("Quiting")
def _imgurify(self, url): client = imgurpython.ImgurClient( self.imgur_client_id, self.imgur_client_secret) replacement_values = list() if isinstance(url, list): for u in url: resp = client.upload_from_url(u) replacement_values.append(resp) else: try: resp = client.upload_from_url(url) replacement_values.append(resp) except imgurpython.helpers.error.ImgurClientError as e: self.bot.debug_print("ImgurClientError: ") self.bot.debug_print(str(e)) except UnboundLocalError as e: self.bot.debug_print("UnboundLocalError: ") self.bot.debug_print(str(e)) except requests.exceptions.ConnectionError as e: self.bot.debug_print("ConnectionError: ") self.bot.debug_print(str(e)) return replacement_values
async def imgur(cmd, message, args): if not args: await message.channel.send(cmd.help()) return if (ImgurClientID == '') or (ImgurClientSecret == ''): embed = discord.Embed(color=0xDB0000) embed.add_field( name='API key ImgurClientID and/or ImgurClientSecret not found.', value='Please ask the bot owner to add them.') await message.channel.send(None, embed=embed) return q = ' '.join(args) imgur_client = imgurpython.ImgurClient(ImgurClientID, ImgurClientSecret) gallery_items = imgur_client.gallery_search(q, advanced=None, sort='time', window='all', page=0) chosen_item = random.choice(gallery_items).link await message.channel.send(chosen_item)
async def get_imgurpic(imgur_album_id): """ Returns the URL of a random image from a given Imgur album :parameter imgur_album_id : The ID string for an Imgur album. (Ex: '8zcyw') :return String containing an image URL """ imgur_client = imgurpython.ImgurClient(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET) image_url_list = [] # Get a list of image objects from the album try: imgur_album_images = imgur_client.get_album_images(imgur_album_id) except ImgurClientError: print(str(ImgurClientError)) return 'The Imgur API returned an error. Please try again or wait a few minutes if this error happens again.' # extract a list of image links from the list of image objects, then return a random image link for image_url in imgur_album_images: image_url_list.append(image_url.link) return random.choice(image_url_list)
import pygame.camera import imgurpython import twilio.rest import os env = lambda s: os.environ[s] # get capture from video feed pygame.camera.init() cam_list = pygame.camera.list_cameras() camera = pygame.camera.Camera(cam_list[0], (640, 480)) camera.start() pygame.image.save(camera.get_image(), 'img.bmp') # upload to imgur imgur_client = imgurpython.ImgurClient(env('IMGUR_CLIENT_ID'), env('IMGUR_CLIENT_SECRET')) imgur_client.set_user_auth(env('IMGUR_ACCESS_TOKEN'), env('IMGUR_REFRESH_TOKEN')) imgur_url = imgur_client.upload_from_path('img.bmp', anon=False)['link'] print(imgur_url) # send image via text message res = twilio.rest.Client(env('TWILIO_ACCOUNT_SID'), env('TWILIO_AUTH_TOKEN')).messages.create( to='+16098656527', body='some shits goin down yo', from_='+17324106248', media_url=imgur_url, ) print(res)
def __init__(self, bot): self.bot = bot self.imgur = imgurpython.ImgurClient(config.IMGUR_CLIENT_ID, config.IMGUR_CLIENT_SECRET)
import random import imgurpython from config import ImgurClientID, ImgurClientSecret imgur_client = imgurpython.ImgurClient(ImgurClientID, ImgurClientSecret) async def imgur(cmd, message, args): if not args: return q = ' '.join(args) gallery_items = imgur_client.gallery_search(q, advanced=None, sort='time', window='all', page=0) chosen_item = random.choice(gallery_items).link await message.channel.send(chosen_item)