def authenticate(): # Get client ID and secret from auth.ini config = get_config() # https://github.com/Imgur/imgurpython/blob/master/examples/auth.ini config.read('auth.ini') # this is the file that holds user credentials client_id = config.get('credentials', 'client_id') client_secret = config.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) # Authorization flow, pin example (see docs for other auth types) authorization_url = 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 = client.authorize(pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) config.set('credentials', 'refresh_token', credentials['refresh_token']) with open('auth.ini', 'w') as configfile: # save config.write(configfile) print ("Authentication successful! Here are the details:") print ((" Access token: {0}".format(credentials['access_token']))) print ((" Refresh token: {0}".format(credentials['refresh_token']))) return client
def get_all_image_data(config_file_path = CONFIG_FILE_PATH): """gets all the images for the given user from imgur""" """assumes you have a imgur api access""" images_all_data = [] with file(config_file_path, "r") as config_file: config_data = json.load(config_file) client_id = config_data["imgur"]["client_id"] client_secret = config_data["imgur"]["client_secret"] username = config_data["imgur"]["username"] client = ImgurClient(client_id, client_secret) images = client.get_account_images(username) for image in images: image_data = { "title":image.title, "link":image.link, "size":image.size } images_all_data.append(image_data) return images_all_data
async def imgur(message, client): """ Imgur stuff :param message: :param client: :return: """ im_client_id = "c8093a713f38daa" im_client_secret = "69a6863b617b86d562c6d45e45d9daf9134c283b" im_client = ImgurClient(im_client_id, im_client_secret) params = message.content.split() paramslength = int(len(params)) try: items = im_client.gallery(section='hot', sort='viral', page=0, window='day', show_viral=True) get = int(params[2]) for num in range(0, get): for item in items: await client.send_message(message.channel, item.link) except ImgurClientError as e: print(e.error_message) print(e.status_code)
def authenticate(): # Get client ID and secret from auth.ini config = get_config() config.read('auth.ini') client_id = config.get('credentials', 'client_id') client_secret = config.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) # Authorization flow, pin example (see docs for other auth types) authorization_url = 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: ") print type(pin) # ... redirect user to `authorization_url`, obtain pin (or code or token) ... credentials = client.authorize(pin, 'pin') 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'])) return client
def imgur_hon(): client = ImgurClient(ckey, csecret) window_list = ['month','year','all'] item_select = random.randint(0,10) items = client.subreddit_gallery('models', sort='top', window=random.choice(window_list), page=random.randint(0,5)) image = items[item_select].link return image
def main(argv): client_id = '.............' client_secret = '.............' pin = "" client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') usage = "usage : make_credentials.py -p <pin number>" usage += "\nauthorization url : \n\t" + authorization_url try: opts, args = getopt.getopt(argv, "hp:", ["pin="]) for opt, arg in opts: if opt == "-h": print(usage) sys.exit(2) elif opt in ("-p", "--pin"): pin = arg credentials = client.authorize(pin, 'pin') access_token = "access : " + credentials['access_token'] refresh_token = "refres : " + credentials['refresh_token'] print(access_token) print(refresh_token) keys = open("./token.txt", "w") keys.write(access_token + "\r\n") keys.write(refresh_token) keys.close() except getopt.GetoptError: print(usage)
def swapCodeForTokens(response): # takes dict of response parameters as input, like {'error':'blah blah'} or {'code':'blah blah','state':'blah blah'} db = app.connect_db() c=db.cursor() state = json.loads(response['state']) user_identifier = state['id'] redir = state['redir'] if 'error' in response: c.execute('UPDATE users SET imgur_json=NULL WHERE imgur_id='+app.app.sqlesc,(user_identifier,)) db.commit() return {'success':False} # called at the server redirect when imgur returns the code client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) credentials = client.authorize(response['code'],'authorization_code') # print credentials if 'access_token' in credentials.keys() and 'refresh_token' in credentials.keys(): db = app.connect_db() c = db.cursor() c.execute('UPDATE users SET imgur_json='+app.app.sqlesc+' WHERE imgur_id='+app.app.sqlesc,(json.dumps(credentials),user_identifier)) db.commit() db.close() return {'success':True,'redir':redir} else: c.execute('UPDATE users SET imgur_json=NULL WHERE imgur_id='+app.app.sqlesc,(user_identifier,)) db.commit() return {'success':False}
def main(): parser = argparse.ArgumentParser(description="Generate BBCode from an Imgur album") parser.add_argument("-c", "--clientid", help="Imgur client ID", required=True) parser.add_argument("-s", "--secret", help="Imgur secret", required=True) parser.add_argument("-a", "--album", help="Album ID", required=True) args = parser.parse_args() client = ImgurClient(args.clientid, args.secret) try: album = client.get_album(args.album) except ImgurClientError as e: print "Error fetching album - %s:" % (e.status_code) print e.error_message exit() print '[B][SIZE="4"]%s[/SIZE][/B]' % (album.title) thumb_regex = re.compile(r"^(.*)\.(.{3,4})$") for img in album.images: if img['title']: print '[SIZE="3"]%s[/SIZE]\n' % (img['title']) # Use "large thumbnail" size print '[IMG]%s[/IMG]' % (thumb_regex.sub("\\g<1>l.\\2", img['link'])) description = img['description'] if img['description'] else "" print description print
def download_albums(album_list, output_directory, num_threads, config_path): """ Download albums from album_list to output_directory. album_list: List containing album urls to download. output_directory: Directory in which to save the downloaded albums. num_threads: Number of concurrent downloads to perform. config_path: Path to an alternate config file. """ # Load the configuration from specified path if set. if config_path: config = load_config(config_path) else: config = load_config() logger.debug("Connecting to Imgur") imgur_client = ImgurClient(config['client_id'], config['client_secret']) pool = ThreadPool(num_threads) for album_url in album_list: logger.debug('Downloading images from %s' % (album_url)) album_id = re.match(r'.*\/a\/(?P<id>.*)', album_url).group('id') out_dir = os.path.join(output_directory, album_id) if not os.path.isdir(out_dir): os.makedirs(out_dir) logger.info('Downloading album %s' % (album_id)) images = imgur_client.get_album_images(album_id) for index, image in enumerate(images): pool.add_work({'index':index, 'url':image.link, 'directory':out_dir}) # Start the thread pool. Will block until all jobs are complete. pool.start()
def image_uploader(speech_text): if profile.data['imgur']['client_id'] == "xxxx" \ or profile.data['imgur']['client_secret'] == "xxxx": msg = 'upload requires a client id and secret' print msg tts(msg) return; words_of_message = speech_text.split() words_of_message.remove('upload') cleaned_message = ' '.join(words_of_message) if len(cleaned_message) == 0: tts('upload requires a picture name') return; image_listing = img_list_gen() client = ImgurClient(profile.data['imgur']['client_id'], profile.data['imgur']['client_secret']) for i in range(0, len(image_listing)): if cleaned_message in image_listing[i]: result = client.upload_from_path(image_listing[i], config=None, anon=True) conn = sqlite3.connect(profile.data['memory_db']) conn.execute("INSERT INTO image_uploads (filename, url, upload_date) VALUES (?, ?, ?)", (image_listing[i], result['link'], datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() print result['link'] tts('Your image has been uploaded')
def imgur_search(search=""): try: client = ImgurClient(imgur_id, imgur_secret) except ImgurClientError as e: if e.status_code == 403: return u'can i haz valid api keys?' else: return u'sorry i could not reach imgur :/ E_MSG: {0} E_CODE: {1}'.format(e.error_message, e.status_code) try: search_results = client.gallery_search(search, advanced=None, sort='time', window='all', page=0) except ImgurClientError as e: return u'derp, something bad happened: {0}'.format(e.error_message) if len(search_results) > 0: item = random.choice(search_results) if item.is_album: try: search_results = client.get_album_images(item.id) item = search_results[0] except ImgurClientError as e: return u'derp, something bad happened: {0}'.format(e.error_message) # gifs over 10mb get returned with an h appended to their id # shave it off to get the full animated gif if len(item.link) > 7 and item.link[-5] == 'h': gif_link = item.link[0:-5]+item.link[-4:] if DEBUG: print ("""[dankBot] [DEBUG] search="{0}" link="{1}" Large gif link found, modifying link.""").format(search, item.link) else: gif_link = item.link else: gif_link = None if DEBUG: print ("""[dankBot] [DEBUG] search="{0}" resource="{1}" No results found.""").format(search, "imgur") return gif_link
def feed_back(request): dict = {} user = check_auth(request) if user == None: return redirect("/login/") else : if request.method == "GET": form = Postform() return render(request,"post.html",{'form':form}) elif request.method == "POST": form = Postform(request.POST,request.FILES) if form : if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = Post_Model(user=user, image=image, caption=caption) post.save() image = post.image.url path = str(BASE_DIR +"\\"+ image) client = ImgurClient("9833d69a08cef7e", "f1603dd86bfe25b3f73427309b0561a92ff54262") post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() print(post.image_url) return redirect("/home/") else: dict['no_post'] = "Please choose a file , Caption is Mandatory...." return render(request,"post.html",dict)
async def imgur(self, *text): """Retrieves a picture from imgur imgur search [keyword] - Retrieves first hit of search query. imgur [subreddit section] [top or new] - Retrieves top 3 hottest or latest pictures of today for given a subreddit section, e.g. 'funny'.""" imgurclient = ImgurClient("1fd3ef04daf8cab", "f963e574e8e3c17993c933af4f0522e1dc01e230") if text == (): rand = randint(0, 59) #60 results per generated page items = imgurclient.gallery_random(page=0) await self.bot.say(items[rand].link) elif text[0] == "search": items = imgurclient.gallery_search(" ".join(text[1:len(text)]), advanced=None, sort='time', window='all', page=0) if len(items) < 1: await self.bot.say("Your search terms gave no results.") else: await self.bot.say(items[0].link) elif text[0] != (): try: if text[1] == "top": imgSort = "top" elif text[1] == "new": imgSort = "time" else: await self.bot.say("Only top or new is a valid subcommand.") return items = imgurclient.subreddit_gallery(text[0], sort=imgSort, window='day', page=0) if (len(items) < 3): await self.bot.say("This subreddit section does not exist, try 'funny'") else: await self.bot.say("{} {} {}".format(items[0].link, items[1].link, items[2].link)) except: await self.bot.say("Type help imgur for details.")
def checkApiAccess(userid): # something that checks whether we have api keys and whether they work; # if not, return False db = app.connect_db() c = db.cursor() c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,)) r = c.fetchone() if len(r) > 0: try: r = json.loads(r[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] except TypeError: return False else: return False client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token,refresh_token) try: client.get_account('me').url credits = client.credits # print(credits) if credits['ClientRemaining'] > 10 and credits['UserRemaining'] > 10: return True else: return None except ImgurClientError: return False
def main(s_argv): argv = s_argv argv["user"] = "******" argv["album"] = "youjung_ioi"#"chungha_ioi" argv["dump"] = "dump.txt" argv["save_path"] = "./save_list.txt" argv["complete_path"] = "./complete.txt" name_list = [] img_oriUrl_list = [] board_url = "" count = 1 name_flag = False #img_upload(access, refresh) _access_token, _refresh_token = get_access_token() print(_access_token) print(_refresh_token) client = ImgurClient(client_id, client_secret) client.set_user_auth(_access_token, _refresh_token) client.mashape_key = x_mash_key #print(client.credits["ClientLimit"]) #print("usr : %s, album : %s" % (argv["user"], argv["album"])) # album_id = get_album_id(client, argv["user"], argv["album"]) x_mash_info = get_x_mash_limit(client) remain = int(x_mash_info[0])
def pitstop(tripid, userid): if request.method == 'GET': tripdetails=[] for x in TripDetails.query.filter_by(tripsmaster=request.args.get('tripid')): tripdetails.append(dict(location=x.location, text=x.text, image=x.image)) return json.dumps(tripdetails) else: file = request.files['image'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) client = ImgurClient(client_id, client_secret) response = client.upload_from_path('/home/chakshu/WanderLust/Uploads/'+filename) tpid = TripsMaster.query.get(request.args.get('tripid')) tripdetails = TripDetails(tripsmaster = tpid,location=request.args.get('location'), timestamp=request.args.get('timestamp'), text=request.args.get('text'), image = str(response['link'])) db.session.add(tripdetails) # login_user(user) # return redirect(url_for('index')) db.session.commit() tripdetails=[] for x in TripDetails.query.filter_by(tripsmaster=request.args.get('tripid')): tripdetails.append(dict(location=x.location, text=x.text, image=x.image)) return json.dumps(tripdetails)
def upload_file(self): timestamp = datetime.fromtimestamp(self.img.time).strftime( self.conf.imgur.timestamp_format or "%Y-%m-%dT%H:%M:%S" ) config = dict( album=self.conf.imgur.album, name="{}_{}".format(timestamp, self.img.username).replace(":", "-"), title="{} (by {}; {})".format(self.img.caption or "No caption", self.img.username, timestamp), ) try: client = ImgurClient( self.conf.imgur.client_id, self.conf.imgur.client_secret, refresh_token=self.conf.imgur.refresh_token ) data = client.upload_from_path(self.img.local_path, config=config, anon=False) except ImgurClientError as e: msg = "Error uploading to imgur: {0.status_code} {0.error_message}".format(e) l.error(msg) self.reply(msg) raise l.info("uploaded image: {}", data) l.debug("X-RateLimit-ClientRemaining: {}", client.credits["ClientRemaining"]) self.img = self.img._replace(url=data["link"]) return True
def send_message(): image = Images.query.filter_by(is_sent=0).first() if image == None: imgur_client = ImgurClient(os.environ.get('IMGUR_CLIENT_ID'), os.environ.get('IMGUR_CLIENT_SECRET')) clarifai_api = ClarifaiApi() images = imgur_client.subreddit_gallery(subreddit='aww', page=0) for image in images: if image.is_album == False and ('jpeg' in image.type): try: result = clarifai_api.tag_image_urls(image.link) total_result = result['results'][0]['result']['tag']['classes'] if len(set(total_result).intersection(['dog', 'puppy', 'cat', 'kitten', 'bird'])) > 0: db.session.add(Images(image.link)) db.session.commit() except: pass image = Images.query.filter_by(is_sent=0).first() users = Users.query.filter_by(active=1).all() for user in users: try: client = TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'), os.environ.get('TWILIO_AUTH_TOKEN')) message = client.messages.create(to=user.number, from_="+19733214779", media_url=[image.link]) except: pass image.is_sent = 1 db.session.commit()
def index(): links = [] if request.method == 'POST': imgur_client_id = os.environ['imgur_client_id'] imgur_client_secret = os.environ['imgur_client_secret'] imgur_client = ImgurClient(imgur_client_id, imgur_client_secret) file_list = request.files.getlist('file') if not file_list: return jsonify({'ok': False}) file = file_list[0] filename = file.filename # If it's an accepted file if any(filename.lower().endswith(x) for x in ACCEPTED_EXTENSIONS): # Generate the path and save the file path = os.path.join(uploads_folder, secure_filename(filename)) file.save(path) # Upload the file to imgur res = imgur_client.upload_from_path(path) # Delete the local file os.remove(path) # Return the IMGUR link return jsonify({'ok': True, 'link': res['link']}) else: return jsonify({'ok': False}) return render_template('index.html', links=links)
def uploadToImgur(userid,url): db = app.connect_db() c = db.cursor() c.execute('SELECT map_url,name,farmname,date,imgur_json FROM playerinfo WHERE url='+app.app.sqlesc,(url,)) result = c.fetchone() if result[4] != None: previous_upload_properties = json.loads(result[4]) if time.time() < previous_upload_properties['upload_time']+(2*3600): return {'error':'too_soon','link':previous_upload_properties['imgur_url']} map_url = result[0] titlestring = u"{} Farm, {} by {}".format(result[2],result[3],result[1]) descriptionstring = u"Stardew Valley game progress, full summary at http://upload.farm/{}".format(url) # try: c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,)) r = json.loads(c.fetchone()[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token,refresh_token) # file = url_for('home',filename=map_url,_external=True) # print 'uploaded to',file # client.upload_from_url(file,config={'title':'uploaded from','description':'upload.farm'},anon=False) if app.app.config['IMGUR_DIRECT_UPLOAD'] == True: result = client.upload_from_path(map_url,config={'title':titlestring,'description':descriptionstring},anon=False) else: map_url = u"http://upload.farm/{}".format(map_url) result = client.upload_from_url(map_url,config={'title':titlestring,'description':descriptionstring},anon=False) print(result) imgur_json = json.dumps({'imgur_url':'http://imgur.com/'+result['id'],'upload_time':time.time()}) c.execute('UPDATE playerinfo SET imgur_json='+app.app.sqlesc+' WHERE url='+app.app.sqlesc,(imgur_json,url)) db.commit() try: return {'success':None,'link':result['link']} except: return {'error':'upload_issue','link':None}
def upload_img_from_url(url): imgur_api = ImgurClient(app.config['CLIENT_ID'], app.config['CLIENT_SECRET']) resp = imgur_api.upload_from_url(url) resp['link'] = normalize_url(resp['link']) return {u'link': resp['link']}
def download_album_images(aid, filename, postTitle): client = ImgurClient(im_client, im_secret) imgs = None try: imgs = client.get_album_images(aid) except Exception, e: return
def uploadGraffiti(self, filename): print 'hello upload' client = ImgurClient(self.clientId, self.clientSecret) uploadReturn = client.upload_from_path(self.fileUploadPath+filename, config=None, anon=True) print uploadReturn graffitiUploadLink = uploadReturn.get('link') return graffitiUploadLink
def get_imgur_links(client_id, client_secret): try: client = ImgurClient(client_id, client_secret) except ImgurClientError: get_imgur_links(client_id, client_secret) items = client.gallery() return [x.link for x in items if x is not None]
def authed(): config = get_config() config.read('auth.ini') client_id = config.get('credentials', 'client_id') access_token = config.get('credentials', 'access_token') client_secret = config.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
def get_random_caturday_image(): """Return url to random caturday image from album""" client = ImgurClient( CFG.get('imgur').get('clientid'), CFG.get('imgur').get('clientsecret') ) album = client.get_album(CFG.get('imgur').get('caturdayalbum')) return choice([image.get('link') for image in album.images])
def upload(path): CL_ID = '4b627183be928c7' CL_SEC = '606e73952395dd3d06f309c4ace529e5b1386525' client = ImgurClient(CL_ID,CL_SEC) print "Uploading image" image = client.upload_from_path("foo.png") return image['link']
def imgur_gifsearch (bot, msg): client = ImgurClient(imgur_client_id, imgur_client_secret) search = re.match('^!gif (.*)$', msg.text, re.I) items = client.gallery_search(search.groups()[0] + ' ext: gif AND animated: 1', advanced=None, sort='top', window='all', page=0) if not items: bot.say(msg.channel,":buch: No results for {0}".format("".join(search.groups()[0]))) else: item = random.choice(items) #item = items[0] bot.say(msg.channel,item.link)
class ImgurPostsProvider(RedditHandler, Generator): def __init__(self): super(ImgurPostsProvider, self).__init__(IMGUR) cm = ConfigManager() self.client = ImgurClient(cm.get('ImgrClientID'), cm.get('ImgrClientSecret')) self.toggled = set() def get_copies(self, url): search_request = "url:\'%s\'" % _get_post_id(url) return list(self.reddit.search(search_request)) def check(self, image): if not image.title or hash(normalize(image.title)) in self.toggled or \ image.height < 500 or image.width < 500: return False copies = self.get_copies(image.id) if len(copies) == 0: return True def process_title(self, title): #todo fix by re if isinstance(title,str): title.replace("my", "") title.replace("My", "") title.replace("MY", "") title.replace("me", "") title.replace("Me", "") title.replace("ME", "") return title def generate_data(self, subreddit, key_words): try:#todo fix rate limit #todo add posts statuses for page in xrange(MAX_PAGES): q = "tag:%s OR title:%s OR album:%s" % (subreddit, subreddit, subreddit) log.info("retrieve for %s at page %s" % (subreddit, page)) for entity in self.client.gallery_search(q=q, sort='time', page=page, window='week'): if entity.is_album: if entity.ups - entity.downs > 0 and entity.ups > MIN_UPS: images = [random.choice(self.client.get_album_images(entity.id))] else: images=[] else: images = [entity] for image in images: if self.check(image): self.toggled.add(hash(normalize(image.title))) yield PostSource(image.link, self.process_title(image.title)) except Exception as e: log.exception(e) return
def getAuthUrl(userid,target=None): db = app.connect_db() c = db.cursor() iuid = unicode(uuid.uuid4()) imgur_id = json.dumps({'id':iuid,'redir':target}) c.execute('UPDATE users SET imgur_id='+app.app.sqlesc+' WHERE id='+app.app.sqlesc,(iuid,userid)) db.commit() db.close() client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) authorization_url = client.get_auth_url('code')+'&state='+unicode(imgur_id) return authorization_url
def post_view(request): user = check_validation(request) if user: if request.method == "GET": form = PostForm() return render(request, 'post.html', {'form': form}) elif request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() path = str(BASE_DIR + '/' + post.image.url) client = ImgurClient("7c523b250772ade", "5307069c8ab8398c385cfbeacd51857ed22") post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() else: return redirect('/login/') return redirect('/feed/')
def post_view(request): user=check_validation(request) if user: if request.method=="POST": form=PostForm(request.POST, request.FILES) if form.is_valid(): print 'valid request' image=form.cleaned_data.get('image') caption=form.cleaned_data.get('caption') post=PostModel(user=user, image=image, caption=caption) path=str(BASE_DIR + '\\user_images\\' + post.image.url) print path client=ImgurClient('f0a596d7994e8f6','69e1ac90db848e9fca2fde987a3993ab5f725f5d') post.image_url=client.upload_from_path(path,anon=True)['link'] post.save() print 'Post saved' return redirect('/feed/') else: print 'invalid request' else: form=PostForm() return render(request,'post.html', {'form':form}) else: return redirect('/login/')
def main(tg): # Read keys.ini file at program start (don't forget to put your keys in there!) keyConfig = configparser.ConfigParser() keyConfig.read(["keys.ini", "config.ini", "..\keys.ini", "..\config.ini"]) chat_id = tg.message['chat']['id'] message = tg.message['text'] botName = tg.misc['bot_info']['username'] message = message.replace(botName, "") splitText = message.split(' ', 1) requestText = splitText[1] if ' ' in message else '' bot = telegram.Bot(keyConfig['BOT_CONFIG']['token']) client_id = keyConfig.get('Imgur', 'CLIENT_ID') client_secret = keyConfig.get('Imgur', 'CLIENT_SECRET') client = ImgurClient(client_id, client_secret) items = client.gallery_search(q=string.capwords(requestText), sort='top', window='all') if len(items) > 0: if items[0].link.endswith('.gif'): bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) return bot.sendDocument(chat_id=chat_id, filename=requestText, document=items[0].link) else: bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) return bot.sendPhoto(chat_id=chat_id, filename=requestText, photo=items[0].link)
def post_view(request): user = check_validation(request) if user: if request.method == 'GET': form = PostForm() elif request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) path = str(BASE_DIR + '/' + post.image.url) client = ImgurClient( '3bede51f2388c24', '3cf40459e88c26fab176f00a87e7cafb278c6bf4') post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect('/feed/') return render(request, 'post.html', {'form': form}) else: return redirect('/login/')
def post_view(request): user = check_validation(request) if user: print 'Authentic user' else: return redirect('/login/') if request.method == "GET": form = PostForm() return render(request , "post.html" , { "form" : form }) elif request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user = user , image = image , caption = caption) post.save() path = str(BASE_DIR + "\\" + post.image.url) client = ImgurClient("9b9be2f5fc6dc91", "073d8e90695a7c9b46fcc3c50e3e4b8d523c5b44") post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect("/feed/")
def post_view(request): user = check_user(request) if user == None: return redirect('/login/') elif request.method == 'GET': post_form = PostForm() return render(request, 'post.html', {'post_form': post_form}) elif request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() client = ImgurClient('005535c6f80c2dc', '2520684355b7cf9e0941c6d82bcf392af1807084') path = str(BASE_DIR + "\\" + post.image.url) post.image_url = client.upload_from_path(path, anon=True)['link'] post.save() return redirect("/feed/") else: return HttpResponse("Form data is not valid.") else: return HttpResponse("Invalid request.")
def post_view(request): user = check_validation(request) if user: if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') post = PostModel(user=user, image=image, caption=caption) post.save() path = str(post.image.url) client = ImgurClient("618bd3e5af61044", "a1e66dde5bb5b602df49616207d8c85e790e692f") post.image_url = client.upload_from_path(path, config=None, anon=True)['link'] post.save() return redirect('/feed/') else: form = PostForm() return render(request, 'post.html', {'form' : form}) else: return redirect('/login/')
def upload_image(image): """Uploads an image file to Imgur""" config = get_config() if not config: click.echo("Cannot upload - could not find IMGUR_API_ID or " "IMGUR_API_SECRET environment variables or config file") return client = ImgurClient(config["id"], config["secret"]) click.echo('Uploading file {}'.format(click.format_filename(image))) response = client.upload_from_path(image) click.echo('File uploaded - see your image at {}'.format(response['link'])) try: import pyperclip pyperclip.copy(response['link']) except ImportError: print("pyperclip not found. To enable clipboard functionality," " please install it.")
class UploadIM: def __init__(self): self.config = configparser.ConfigParser() self.config.read("config.ini") self.id = self.config["AUTH"]["IMGUR_ID"] self.secret = self.config["AUTH"]["IMGUR_SECRET"] self.client = ImgurClient(self.id, self.secret) def getLink(self, image_path): image = self.client.upload_from_path(image_path) return image['link']
def read_config(self): try: self.config = configparser.ConfigParser( ) # don't know what to do if this fails. configfiles = self.config.read( ['.imgursyncconfig', os.path.expanduser('~/.imgursyncconfig')]) # Save the name of the first file that was successfully read if len(configfiles) > 0: self.configfilename = configfiles[0] else: self.configfilename = '.imgursyncconfig' self.set_status('Successfully read config file. File is ' + self.configfilename) except: self.set_status('Failed to read config file.') print(sys.exc_info(), file=sys.stderr) return False # we need to make sure that the client is creatable using id and secret from configuration. complain if not. try: self.client = ImgurClient(self.config['client']['id'], self.config['client']['secret']) # enable re-authorize button except: self.set_status( 'Failed to create client using saved credentials. Run register script first.' ) print(sys.exc_info(), file=sys.stderr) return False # set access_token and refresh_token on screen try: self.string_access_token.set( self.config['credentials']['access_token']) self.string_refresh_token.set( self.config['credentials']['refresh_token']) except: self.set_status('Config did not contain tokens. Get a new PIN.') print(sys.exc_info(), file=sys.stderr) return False self.set_status('Tokens exist in config file. Try authorization now.') return True
def CreateAlbumAndUploadImages(albumName, albumDescription, images): access_token, refresh_token, client_id, client_secret = Config.getImgurKeys( ) client = ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) fields = {} fields['title'] = albumName fields['description'] = albumDescription fields['privacy'] = 'public' x = client.create_album(fields) y = client.album_add_images(x['id'], images) return x
def upload_images(album_title, paths): client = ImgurClient(client_id, client_secret) client.set_user_auth(imgur_access_token, imgur_refresh_token) fields = {'title': album_title} album = client.create_album(fields) for i, img in enumerate(paths): config = {'album': album['id'], 'name': str(i), 'title': str(i)} image = client.upload_from_path(img, config=config, anon=False) remove(img) return album
def authenticate(): #client_id = '854786241b5ff16' #client_secret = '90c6a5b0068fa60c3b6b047fffec2388fe6cd6c8' config = configparser.ConfigParser() config.read('auth.ini') client_id = config.get('credentials', 'client_id') client_secret = config.get('credentials', 'client_secret') imgur_username = config.get('credentials', 'imgur_username') imgur_password = config.get('credentials', 'imgur_password') client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') print("Go to the following URL: {0}".format(authorization_url)) browser = webdriver.Chrome() browser.get(authorization_url) username = browser.find_element_by_xpath('//*[@id="username"]') password = browser.find_element_by_xpath('//*[@id="password"]') username.clear() username.send_keys(imgur_username) password.send_keys(imgur_password) browser.find_element_by_name("allow").click() timeout = 2 try: element_present = EC.presence_of_element_located((By.ID, 'pin')) WebDriverWait(browser, timeout).until(element_present) pin_element = browser.find_element_by_id('pin') pin = pin_element.get_attribute("value") except TimeoutException: print("Timed out waiting for page to load") print("Your pin is : " + pin) # ... redirect user to `authorization_url`, obtain pin (or code or token) ... credentials = client.authorize(pin, 'pin') 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'])) browser.close() return client
def img_upload(_access_token, _refresh_token): client = ImgurClient(client_id, client_secret) client.set_user_auth(_access_token, _refresh_token) client.mashape_key = x_mash_key conf = {"album" : "JtebE", "description": "Hello World", "title" : "Hi"} res = client.upload_from_path("./image_1_2.gif", config = conf, anon = False) print(res) print(res["link"])
class Imgur: def __init__(self): client_id = os.getenv('IMGUR_CLIENT_ID') client_secret = os.getenv('IMGUR_CLIENT_SECRET') self.__fiat = os.getenv('FIAT_CURRENCY') if client_id == "" or client_secret == "": logger.warning('INVALID IMGUR CREDENTIALS') else: logger.warning('IMGUR INITIALIZED') self.client = ImgurClient(client_id, client_secret) def _create_graph(self, x, y): if len(x) == 0 or len(y) == 0: return "" start, end = date.fromtimestamp(x[0]), date.fromtimestamp(x[-1]) fig, ax = plt.subplots(1, dpi=300) ax.plot(x, y, alpha=0.5) ax.axes.xaxis.set_visible(False) ax.yaxis.set_major_formatter('${x:1.2f}') ax.yaxis.set_tick_params(which='major', labelleft=False, labelright=True) plt.title(f'Crypto Balance: {start} - {end}') plt.xlabel('Time') plt.ylabel(f'{self.__fiat} $') fig.savefig(temp_file_name) plt.close() return temp_file_name def send_graph(self, x, y, title=CRYPTO_BALANCE_CHECK, xlabel='Time', ylabel: str = '') -> str: if self.client is None: logger.warning('INVALID IMGUR CREDENTIALS') return "" if ylabel == '': ylabel = f'{self.__fiat} $' config = {'title': title, 'description': f'{x[0]} to {x[-1]}'} filename = self._create_graph(x, y) logger.warning('UPLOADING IMAGE') return self.client.upload_from_path(filename, config)['link']
def scrape(subreddit_name, backfill_to=None): """ Scrape a subreddit. :type subreddit_name: str :type backfill_to: datetime.datetime """ subreddit_name = subreddit_name.lower() imgur_client = ImgurClient( settings.IMGUR_CLIENT_ID, settings.IMGUR_CLIENT_SECRET) reddit = Reddit(user_agent=settings.REDDIT_USER_AGENT) subreddit = reddit.get_subreddit(subreddit_name) with session_manager() as session: if backfill_to is not None: _backfill( session, subreddit, subreddit_name, imgur_client, backfill_to) else: _scrape(session, subreddit, subreddit_name, imgur_client)
def imgur_login(): """Logins to Imgur""" config = get_config(True) if not config: click.echo("Cannot upload - could not find IMGUR_API_ID or " "IMGUR_API_SECRET environment variables or config file") return client = ImgurClient(config["id"], config["secret"]) authorization_url = client.get_auth_url('pin') click.echo("Please Go To {}".format(authorization_url)) login_pin = click.prompt('Please enter pin from the imgur login') credentials = client.authorize(login_pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) configvalues = ['access_token', 'refresh_token'] for value in configvalues: with open(os.path.expanduser( '~/.config/imgur_uploader/uploader.cfg')) as cf: lines = cf.readlines() ln = len(value) for ind, line in enumerate(lines): if value == line[:ln]: lines[ind:ind + 1] = [] break with open( os.path.expanduser( '~/.config/imgur_uploader/uploader.cfg'), "w") as out: out.writelines(lines) with open(os.path.expanduser('~/.config/imgur_uploader/uploader.cfg'), "a") as cf: cf.write("access_token=") cf.write(credentials['access_token']) cf.write("\nrefresh_token=") cf.write(credentials['refresh_token']) return { "access_token": credentials['access_token'], "refresh_token": credentials['refresh_token'] }
def authenticate(): client_id = '<REPLACE WITH YOUR IMGUR CLIENT ID>' client_secret = '<REPLACE WITH YOUR IMGUR CLIENT SECRET>' client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') print('Go to the following URL: {}'.format(authorization_url)) pin = get_input('Enter pin code: ') credentials = client.authorize(pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) return client
def imgur_upload(): client = ImgurClient(client_id, client_secret, access_token, refresh_token) albums = client.get_album_images("OKG9U3G") current_image_id = [image.id for image in albums] new_image_id = [] for file in file_list: # with open(os.devnull, "w") as f: # subprocess.call(["ect", file], stdout=f) # shutil.copy2(file, "/var/www/fgo.square.ovh/solomon-raid-stats/") id = client.upload_from_path(file, anon=False)["id"] new_image_id.append(id) print("{}: Uploaded to imgur".format(datetime.now())) for id in current_image_id: client.album_remove_images("OKG9U3G", id) for id in new_image_id: client.album_add_images("OKG9U3G", id) print("{}: Editted album".format(datetime.now()))
def add(self, client: ImgurClient, image_ids: list[int]) -> dict: """Add images to an album :param client: Imgur Client :type client: ImgurClient :param image_ids: list of image ids :type image_ids: list[int] :return: upload response :rtype: dict """ logging.info( 'Adding %d ids to album with deletehash "%s": %s', len(image_ids), self.deletehash, image_ids, ) if not self.deletehash: logging.debug("Creating album to add imgs to.") self.create(client) return client.album_add_images(self.deletehash, image_ids)
class Imgur(): imgur_client = ImgurClient('ad3227fae77dfb4', 'd8bdd43b496c945fd88858ebff4115088db6ebeb') def __init__(self, bot): self.bot = bot @commands.group(pass_context=True) async def imgur(self, context, search_term: str = None): """ Retrieve a random image from Imgur with or without keyword search. """ if search_term is None: todo = functools.partial(self.imgur_client.gallery_random, page=0) # Random entry from main gallery else: search_term = context.message.content.replace("!imgur ", "", 1) todo = functools.partial( self.imgur_client.gallery_search, search_term) # Search for results with keyword todo = self.bot.loop.run_in_executor(None, todo) # Perform imgur search try: results = await asyncio.wait_for(todo, timeout=20) # Too short? Long? except asyncio.TimeoutError: await self.bot.say("Timeout Error" ) # Took too long for server response else: if results: # We got a response img = results[0] # choice(results) link = img.gifv if hasattr( img, "gifv") else img.link # Check for gifv status await self.bot.say( link ) # Bot posts the imgur link (Can we post an embedded image?? w/o link??) else: await self.bot.say("No Results for %s" % search_term ) # Someone done goof'd return
class ImgurUploader(object): def __init__(self): self.client_id = settings.IMGUR_ID self.client_secret = settings.IMGUR_SECRET self.client = ImgurClient(self.client_id, self.client_secret) dispatcher.connect(self._handle_message, signal=Signals.PICTURE, sender=dispatcher.Any) self._run() def _post_image_from_file(self, filename, message): result = self.client.upload_from_path(filename) if 'link' in result: message += ": " + result['link'] print("Uploaded image to URL " + result['link'] + " at time %f" % time.time()) else: message += ": unable to upload image!" self._send_message(msg=message) def _handle_message(self, img=None, source=None): if img == None: return if source == "doorbell": message = "Doorbell ring [main]" else: message = source print("Got image from " + source + " at time %f" % time.time()) filename = "/tmp/DoorPicture-" + time.strftime("%Y%m%d-%H%M%S") + ".png" img.save(filename) print("Saved image to file " + filename +" at time %f" % time.time()) self._post_image_from_file(filename=filename, message=message) os.remove(filename) def _send_message(self, msg=None, img=None): dispatcher.send(signal=Signals.SLACK_MESSAGE, sender=self, msg=msg, img=img) def _run(self): while True: time.sleep(10)
def authenticate(): client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') pin = getPin(authorization_url) print("Get pin {0}".format(pin)) credentials = client.authorize(pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) print("Authentication finished.") return client
def authenticate(client_id: str, client_secret: str, refresh_token: str) -> ImgurClient: """Returns the ImgurClient associated with the given credentials :param client_id: The client ID :type client_id: str :param client_secret: The client secret :type client_secret: str :param refresh_token: The refresh token :type refresh_token: str :raises ValueError: Any of the credentials are invalid :return: The ImgurClient associated with the given tokens :rtype: ImgurClient """ try: client = ImgurClient(client_id, client_secret, refresh_token=refresh_token) except Exception: raise ValueError("Invalid credentials") return client
def get_imgur_client(client_id, client_secret): try: client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') imgur_pin = raw_input( 'Please visit %s and enter the pin given to you there: ' % authorization_url) credentials = client.authorize(imgur_pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) except ImgurClientError as e: print('Imgur error #%d: "%s"' % (e.status_code, e.error_message)) print('Proceeding without enabling Imgur integration.') client = False return client
class Imgur: client = None def _connect(self): if not self.client: try: self.client = ImgurClient(cfg['imgur.com']['id'], cfg['imgur.com']['secret']) except Exception as e: raise Exception('imgur連線錯誤: %s' % (str(e))) def upload(self, path, delete_on_uploaded=True): self._connect() for i in range(10): try: image = self.client.upload_from_path(path) break except Exception as e: sleep(1) else: raise Exception('imgur上傳錯誤: %s' % (str(e))) url = image['link'] if delete_on_uploaded: os.remove(path) return url def uploadByLine(self, bot, message_id): self._connect() tmp_file = '%s\%s.tmp' % (cfg['temp_dir'], message_id) message_content = bot.get_message_content(message_id) with open(tmp_file, 'wb') as f: for chunk in message_content.iter_content(): f.write(chunk) return self.upload(tmp_file)
class uploader(): def __init__(self): self.client_id = os.environ.get('Client_ID') self.client_secret = os.environ.get('Client_Secret') self.access_token = os.environ.get('access_token') self.refresh_token = os.environ.get('refresh_token') self.client = ImgurClient(self.client_id, self.client_secret, self.access_token, self.refresh_token) async def upload_photo(self, image_url, album): config = { 'album': album, } print(config) print("Uploading image... ") try: image = self.client.upload_from_url(image_url, config=config, anon=False) except Exception as e: print(e) print("Done")
def upload(self, client: ImgurClient) -> list[int]: """Upload images to Imgur :param client: imgur api client :type client: ImgurClient :return: list of uplaoded image ids :rtype: list[int] """ if self.image_id is None: logging.info('Uploading image to album "%s"', self.deletehash) print(self.status["twitter"]["media"], self.gen_config()) ret = client.upload_from_url( self.status["twitter"]["media"], config=self.gen_config(), anon=False ) self.image_id = ret["id"] else: logging.info( 'Image already uploaded to album "%s" with id "%s"', self.deletehash, self.image_id, ) return self.image_id
class SendImgur(Sender): def __init__(self, generate_img, name='img', position=1, app_url='http://localhost:3000/values'): super(SendImgur, self).__init__(name, position, app_url) self.client_secret = os.environ['IMGUR_SECRET'] self.client_id = os.environ['IMGUR_ID'] self.client = ImgurClient(self.client_id, self.client_secret) self.generate_img = generate_img def on_epoch_end(self, epoch=None, logs={}): img = self.generate_img() res = self.client.upload_from_path(img) return requests.patch(self.app_url, json={ 'name': self.name, 'type': 'img', 'value': res['link'], 'pos': self.position })
def _authenticate(self, settings): client_id = settings.get('credentials', 'client_id') client_secret = settings.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('pin') sys.stdout.write('\nGo to the following URL:\n >> {0}\n\n'.format(authorization_url)) sys.stdout.flush() pin = get_input('Enter pin code: ') credentials = client.authorize(pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) settings.set('credentials', 'refresh_token', credentials['refresh_token']) sys.stdout.write('\nAuthentication successful! Here are the details:\nAccess token: {0}\n' 'Refresh token: {1}\n** Configuration Updated **\n\n'.format( credentials['access_token'], credentials['refresh_token'])) sys.stdout.flush() self.save_settings() return client