def _handle_instagram(url): """http*://instagram.com/p/*""" from instagram.client import InstagramAPI CLIENT_ID = '879b81dc0ff74f179f5148ca5752e8ce' api = InstagramAPI(client_id=CLIENT_ID) # todo: instagr.am m = re.search('instagram\.com/p/([^/]+)', url) if not m: return shortcode = m.group(1) r = bot.get_url("http://api.instagram.com/oembed?url=http://instagram.com/p/%s/" % shortcode) media = api.media(r.json()['media_id']) print(media) # media type video/image? # age/date? -> media.created_time # (datetime object) # full name = username for some users, don't bother displaying both if media.user.full_name.lower() != media.user.username.lower(): user = "******" % (media.user.full_name, media.user.username) else: user = media.user.full_name if media.caption: return "%s: %s [%d likes, %d comments]" % (user, media.caption.text, media.like_count, media.comment_count) else: return "%s [%d likes, %d comments]" % (user, media.like_count, media.comment_count)
def inst2sina(userid): """ 同步最新一条instagram状态到微博 """ api = InstagramAPI(access_token=INST_CONF['access_token']) recent_media, next = api.user_recent_media(user_id=userid, count=1) # 验证request返回值正常,如果不正常,可能是access_token过期 if recent_media['meta']['code'] == 200: s = Sina(SINA_CONF['app_key'], SINA_CONF['app_secret'], SINA_CONF['redirect_uri'], SINA_CONF['access_token']) if recent_media['data'][0]['location'] != None: if recent_media['data'][0]['caption']: id = s.postTweet(' '.join([recent_media['data'][0]['caption']['text'], recent_media['data'][0]['link']]), recent_media['data'][0]['images']['standard_resolution']['url'], lat=str(recent_media['data'][0]['location']['latitude']), long=str(recent_media['data'][0]['location']['longitude'])) else: id = s.postTweet(recent_media['data'][0]['link'], recent_media['data'][0]['images']['standard_resolution']['url'], lat=str(recent_media['data'][0]['location']['latitude']), long=str(recent_media['data'][0]['location']['longitude'])) else: if recent_media['data'][0]['caption']: id = s.postTweet(' '.join([recent_media['data'][0]['caption']['text'], recent_media['data'][0]['link']]), recent_media['data'][0]['images']['standard_resolution']['url']) else: id = s.postTweet(recent_media['data'][0]['link'], recent_media['data'][0]['images']['standard_resolution']['url']) else: return None return id
def myInfo(): #written by Tim content = "<h2>User's Information</h2>" access_token = request.session['access_token'] if not access_token: return 'Missing Access Token' try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) myUser = api.user() #makes an API call content += "<img src="+myUser.profile_picture+" alt='Profile Picture' >" content +="<p>Username : "******"</p>" content +="<p>Full Name: "+myUser.full_name+"</p>" content +="<p>ID number: "+myUser.id+"</p>" content +="<p>Biography: "+myUser.bio+"</p>" content +="<h3>Counts:</h3>" content +="<ul><li>Posts: "+ str(myUser.counts.get('media'))+"</li>" content +="<li><a href='/myFollowers'>Followers: </a>"+ str(myUser.counts.get('followed_by'))+"</li>" content +="<li><a href='/myFollowing'>Following: </a>"+ str(myUser.counts.get('follows'))+"</li></ul>" except Exception as e: print(e) return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
def get_medias(user_id, all=False): print('get_medias user_id=%s, all=%s' % (user_id, all)) api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET) medias = [] # media_urls = [] more_medias, _ = api.user_recent_media() # media_urls.extend(get_media_urls(more_medias)) if more_medias: medias.extend(more_medias) loop = 100 if all else 1 while more_medias and loop > 0: try: print('get_medias max_id=%s' % more_medias[-1].id) more_medias, _ = api.user_recent_media(max_id=more_medias[-1].id) if not more_medias: print('get_medias no more data, break') break print('get_medias new medias count: %s' % len(more_medias)) medias.extend(more_medias) # media_urls.extend(get_media_urls(more_medias)) time.sleep(3) except Exception, e: print("error:%s on get_medias:%s" % (e, loop)) time.sleep(10) loop -= 1
def instagram(): results = [] api = InstagramAPI(client_id=app.config['CLIENT_ID'], client_secret=app.config['CLIENT_SECRET']) data = json.loads(request.data.decode()) lat = data["lat"] lng = data["lng"] dist = data["dist"] min_tstmp = data["min_timestamp"] your_location = api.media_search(count=100, lat=lat, lng=lng, distance=dist, min_timestamp=min_tstmp) for media in your_location: url = media.images['standard_resolution'].url pid = media.id img_paths = detect_faces(url, pid) if not img_paths == []: for img_path in img_paths: results.append(img_path) results = json.dumps(results) print "****** RESULTS ******" print " " print results return results
def instagram(key): api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92') for item in api.user_recent_media(user_id=key, count=20, max_id=100): photo = item.images print dp, username, did,web, bio lol = "text" return lol
def book(book_id): form = SearchForm() book = Book.query.filter_by(id = book_id).first() pics = Picture.query.filter_by(book_id = book_id).order_by(Picture.order) if book == None: flash('Book not found') return redirect(url_for('index')) if form.validate_on_submit(): api = InstagramAPI(client_id=app.config['INSTAGRAM_ID'], client_secret = app.config['INSTAGRAM_SECRET']) # if max_tag_id > 0: # if request.args['query']: # tag_name = request.args['query'] # tag_media, next = api.tag_recent_media(count = 20, max_id = max_tag_id, tag_name = request.args['query']) # else: tag_media, next = api.tag_recent_media(count = 20, tag_name = form.query.data) instagram_results = [] for media in tag_media: instagram_results.append(media.images['thumbnail'].url) try: max_tag_id = next.split('&')[2].split('max_tag_id=')[1] except: max_tag_id = None return render_template('book.html', query = form.query.data, instagram_results = tag_media, pics = pics, form = form, next = max_tag_id, book = book) return render_template('book.html', book = book, pics = pics, form = form)
def populate(access_token): 'Populate database with default data' user_id = app.config.get('INSTAGRAM_USER_ID') api = InstagramAPI(access_token=access_token) feed = api.user_recent_media(user_id=user_id, max_pages=2000, as_generator=True) all_tags = {} for media in get_media(feed): # Add photos caption = media.caption.text if media.caption else None photo = Photo( instagram_id=media.id, caption=caption, created_time=media.created_time, link=media.link) db.session.add(photo) # Add tags, ensure we do not duplicate tags if hasattr(media, 'tags'): tags = {t.name: all_tags.get(t.name, Tag(name=t.name)) for t in media.tags} all_tags.update(tags) photo.tags.extend(tags.values()) # Add images images = [Image(height=i.height, width=i.width, url=i.url, type=i_type) for i_type, i in media.images.iteritems()] db.session.add_all(images) photo.images.extend(images) # TODO: Locations. db.session.add_all(all_tags.values()) db.session.commit()
def print_pics_dict1(yelp_id): api = InstagramAPI(client_id=client_id, client_secret=client_secret) recent_photos = {} instapics = [] instalinks = [] instalocations = read_csv_insta(yelp_id) # print instalocations.values() for location_id in instalocations.values(): recent_media, next = api.location_recent_media(location_id=location_id) for media in recent_media: # print media.location.name # if recent_photos[media.location.name] # recent_photos[media.location.name] = {'instalocation': infos[8]} # print media.link if len(instapics) < 5: pic = media.images[u'standard_resolution'].url.encode('ascii', 'ignore') link = media.link instapics.append([pic, link]) # print media.images[u'standard_resolution'].url.encode('ascii', 'ignore') place_name = media.location.name.encode('ascii', 'ignore') recent_photos[location_id] = { place_name: instapics } instapics = [] instalinks = [] # print recent_photos.keys() return recent_photos
def get_conference_pictures(self, keyword): json_data = [] # Cassandra initialization cluster = Cluster([config.get("cassandra.host1"), config.get("cassandra.host2")]) session = cluster.connect('insight') # Instagram initialization instagram_api = InstagramAPI(client_id=config.get("instagram.client_id"), client_secret=config.get("instagram.client_secret")) yymmdd = datetime.utcnow().strftime('%y') + datetime.utcnow().strftime('%m') + datetime.utcnow().strftime('%d') rows = session.execute(self.TOP_10_QUERY % (yymmdd)) for (yymmdd, count, word) in rows: img_arr = [] popular_media = instagram_api.media_popular(count=20) for media in popular_media: img_arr.append(media.images['standard_resolution'].url) json_data.append({"word": word, "count": count, "pic_url": img_arr}) return json_data
def _init(self, *args, **kwargs): """ start the ball a rolling with a request to instagram API open a csv file and output the headers and rows based on results """ api = InstagramAPI( client_id = INSTAGRAM_CLIENT_ID, client_secret = INSTAGRAM_CLIENT_SECRET ) instagram_media = api.tag_recent_media(IMAGE_COUNT, 0, IMAGE_HASHTAG) # open the csv file with open(CSV_FILENAME, "wb") as csv_file: csv_output = csvkit.py2.CSVKitWriter(csv_file, delimiter=",", encoding="utf-8") # write the header row to the csv file csv_output.writerow(["hashtag", "local_date_time", "user_name", "image_link", "image_caption", "like_count", "comment_count", "post_link", "post_type", "post_tags", "post_likes", "utc_date_time"]) # loop through the results for item in instagram_media[0]: # build a new csv row csv_row = self.build_csv_row_from(item) # write the new csv row csv_output.writerow(csv_row)
def myFollowing(): #written by Tim content = "<h2>Accounts I Follow</h2>" access_token = request.session['access_token'] if not access_token: return 'Missing Access Token' try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) follow_list, next_ = api.user_follows() counter =0 content+="<ul>" for user in follow_list: content+="<li><em>"+user.getName()+"</em></li>" counter = counter +1 content+="</ul>" content+="</h2>Total following count: "+str(counter)+"</h2><p></p><p></p>" except Exception as e: print(e) return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
class client_packet: def __init__(self, client_id, client_secret, redirect_uri, begin_user_id): self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.begin_user_id = begin_user_id print('creating new client...') def Access_token(self, flag): if flag: scope = [] self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri) redirect_uri = self.api.get_authorize_login_url(scope=scope) print("Visit this page and authorize access in your browser:\n", redirect_uri) code = input("Paste in code in query string after redirect: ").strip() print('client_id: ' + self.api.client_id) print('client_secret: ' + self.api.client_secret) self.access_token = self.api.exchange_code_for_access_token(code) print(self.access_token) else: self.access_token = 'Insert Your actual Client Access token to not repeath this again and again' return self.access_token
def slideshow(request, timeout=4, speed=1, tag='nofilter'): show_message = True if request.GET.get('message') == 'false': show_message = False if not request.session.get('token'): return redirect('totem.views.auth') token = request.session.get('token') output = {} api = InstagramAPI(access_token=token) medias, pagination = api.tag_recent_media(count=30, tag_name=tag) refresh_time = (speed + timeout) * len(medias) output['medias'] = medias output['timeout'] = timeout output['speed'] = speed output['tag'] = tag output['refresh_time'] = refresh_time output['show_message'] = show_message return render_to_response('totem/slideshow.html', output, context_instance=RequestContext(request))
def mappa(request): latitudine = request.GET.get('lat') longitudine = request.GET.get('lng') instance = UserSocialAuth.objects.get(user=request.user, provider='instagram') access_token = instance.tokens['access_token'] api = InstagramAPI( access_token = access_token, client_ips = MIOIP, client_secret = CLIENT_SECRET ) media_vicini = api.media_search(lat = latitudine, lng = longitudine, count = 100, distance = 5000) #for media in media_vicini: #print media.user.username # point_obj = media.location.point # latitude = point_obj.latitude # longitude = point_obj.longitude template = loader.get_template('map.html') context = RequestContext(request, { 'media_vicini': media_vicini, "centroLat" : latitudine, "centroLng" : longitudine, }) return HttpResponse(template.render(context))
def tag_search(): api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92') tag_search, next_tag = api.tag_search(q="thefuturepark") tag_recent_media, next = api.tag_recent_media(count=1000,tag_name="thefuturepark") photos = [] content = "<h2>Media Search</h2>" for tag_media in reversed(tag_recent_media): # print tag_media res = tag_media.caption.text retweet = 0 favorites = tag_media.like_count name = tag_media.user.username real = tag_media.user.full_name pic = tag_media.user.profile_picture followers = 0 # date = unicode(tag_media.created_time.replace(microsecond=0)) date = tag_media.created_time print date embed = tag_media.get_standard_resolution_url() enable = True photos.append('<img src="%s"/>' % tag_media.get_standard_resolution_url()) photos.append(tag_media.caption.text) data = models.Trace.query.filter(models.Trace.key==res, models.Trace.name ==name) if data.count() > 0: print "kaparehas" else: print "wala" t = models.Trace(tweet='thefuturepark', key=res, retweet=retweet, favorites=favorites, name=name, real=real, pic=pic, followers=followers, date=date,embed=embed,enable=enable) db.session.add(t) db.session.commit() content += ''.join(photos) return content
def index(request): success = False if request.method == 'POST': form = contactForm(request.POST) if form.is_valid(): success = True cd = form.cleaned_data asunto = u'Por: %s mail: %s Tipo de servicio: %s Plan: %s' % (cd['nombre'], cd['email'], cd['tipoServicio'], cd['planes']) content = u'Email contacto: %s \nAsunto: %s \nTelefono: %s \nDescripcion: %s' % (cd['email'], asunto, cd['telefono'], cd['texto']) send_mail(asunto, content, cd['email'], ['*****@*****.**']) else: form = contactForm() api = InstagramAPI(client_id='e78042ef1e834e75a28291aee734d615', client_secret='a299e7f23d0840f9b473417ea7c38c33') recent_media, next = api.user_recent_media(user_id="621890719", count=6) lista_media_url = [] #lista_media_texto = [] lista_media_likes = [] lista_media_link = [] for media in recent_media: lista_media_link.append(media.link) lista_media_url.append(media.images['standard_resolution'].url) #lista_media_texto.append(media.caption.text) lista_media_likes.append(str(media.like_count)) zip_media = zip(lista_media_link, lista_media_url, lista_media_likes) logos = LogoEmpresa.objects.all() ctx = {'form': form, 'success': success, 'zip_media': zip_media, 'logos': logos} return render_to_response('homepage/index.html', ctx, context_instance=RequestContext(request))
def run(self): # Instantiates an Instagram API object using the python-instagram library api = InstagramAPI(client_secret=self.client_secret,access_token=self.access_token) # Get the recent #capitalone tags recent_tags, next = api.tag_recent_media(tag_name="CapitalOne", count=MAX_COUNT) nextCounter = math.ceil(MAX_COUNT/20.0)+1 temp, max_tag = next.split("max_tag_id=") # Initialize variables to track number of positive, negative, and neutral posts # that load recent posts return positivePosts = 0 negativePosts = 0 neutralPosts = 0 counter = 1 while next and counter < nextCounter: # First run through the recent tags if counter == 1: self.loadRecentPosts(recent_tags,api) # Use pagination to run through more than 20 tags else: recent_tags, next = api.tag_recent_media(tag_name='CapitalOne', max_tag_id=max_tag) temp, max_tag = next.split('max_tag_id=') self.loadRecentPosts(recent_tags,api) counter+=1 self.calculateCaptionAndImageSentimentAverage() self.makeGraphs()
def tag(request, tag): api = InstagramAPI(client_id='53ff568efcd6492eb9b88c7b92a615b4', client_secret='3649d3a0675647b1839a5aa580a10dbc') photos = [] tag_m, next = api.tag_recent_media(tag_name=tag.encode('utf-8'), count=16) photos = photos + tag_m pages = [] next_url = [] if next != None: ind = next.find('max_tag_id=') ind += 11 nm = next[ind:] pages.append(nm) next_url = "http://" + str(request.META['HTTP_HOST']) + "/tag/" + tag.encode('utf-8') + "/" + max(pages) for photo in photos: photo.created_time = photo.created_time + timedelta(hours=2) likes = api.media_likes(photo.id) photo.l = len(likes) return render_to_response( 'tag.html', {'photos': photos, 'next_url': next_url}, context_instance=RequestContext(request))
def insta(search_term): returnval='' api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET) try: username = search_term #print username if ' ' in username: username = username.replace(' ', '') if not api.user_search(username, 1): return "No user by that name was found." else: userid = api.user_search(username, 1)[0].id recent_media, next_ = api.user_recent_media(user_id=userid,count=5) for media in recent_media: #text = media.caption.text link = media.link returnval += '~'+link+'\n' return returnval except InstagramAPIError as e: if (e.status_code == 400): return "Cannot retrieve data. User is set to private." if (e.status_code == 404): return "Content not found."
def get_ajax(self, request, *args, **kwargs): try: instagram = Instagram.objects.all()[0] api = InstagramAPI(access_token=instagram.access_token) media, discard = api.user_recent_media( user_id=instagram.user_id, count=24) json_dict = { "thumbnails": [{"url": n.images.get("thumbnail").url, "width": n.images.get("thumbnail").width, "height": n.images.get("thumbnail").height, } for n in media], "low_resolution": [{"url": n.images.get("low_resolution").url, "width": n.images.get("low_resolution").width, "height": n.images.get("low_resolution").height, } for n in media], "standard_resolution": [{"url": n.images.get("standard_resolution").url, "width": n.images.get("standard_resolution").width, "height": n.images.get("standard_resolution").height, } for n in media], } except IndexError: json_dict = { "media": [] } return self.render_json_response(json_dict)
def getToken(): if not os.path.exists('accessToken.txt'): print("The first time you run this program, it will need to obtain access to Instagram via") print("a token generated from your account. This token will only require basic (read-only)") print("access to your account in order to download images. Afterwards, the token will be") print("stored in \'accessToken.txt\'. If you ever have problems with this script, delete") print("\'accessToken.txt\' and run this script again to regenerate the token.") client_id = 'd051ace450314ccd8d86fdbff2410a87' client_secret = '91c43e9262494f4c82c887a88b21068c' redirect_uri = 'http://localhost:8515/oauth_callback' scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope = scope) print("Python will now attempt to open the following URL in a web browser:") print(redirect_uri) print("When it loads, it will go to an invalid URL that looks like") print("http://localhost:8515/oauth_callback?code=XXXXXXXXXXXXXXXXXXX") print('Copy and paste the code from the address bar (the XXXs in the above example) below.') webbrowser.open(redirect_uri) print("Paste in code in query string after redirect: "), code = (str(raw_input().strip())) access_token = api.exchange_code_for_access_token(code) print ("access token: " ) print (access_token) pickle.dump( access_token, open( "accessToken.txt", "wb" ) )
def load_photos(request): """ Loads photos from Insagram (not yet other,like G+) and insert in database. """ api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) search_result = api.tag_recent_media(MEDIA_COUNT, LARGE_MEDIA_MAX_ID, MEDIA_TAG) info_photo = "" for m in search_result[0]: photo, is_created = Photo.objects.get_or_create(photo_id=m.id, username=m.user.username) is_like_count_updated = False if not photo.like_count == m.like_count: photo.username = m.user.username photo.user_avatar_url = m.user.profile_picture photo.photo_url = m.images["standard_resolution"].url photo.created_time = m.created_time photo.like_count = m.like_count photo.save() is_like_count_updated = True info_photo += "<li>{} {} {} {} {} {} {} {}</li>".format( m.id, m.user.username, '<img src="{}"/>'.format(m.user.profile_picture), '<img src="{}"/>'.format(m.images["standard_resolution"].url), m.created_time, m.like_count, is_created, is_like_count_updated, ) html = "<html><body><ul>{}</ul></body></html>".format(info_photo) return HttpResponse(html)
def user(username, page=1): u = InstagramAPI(access_token=session['access_token'], client_secret=secret.secrets['client_secret']) id = u.user_search(username)[0].id user_media, next_ = u.user_recent_media(user_id=id,count=20) for i in range(1, page): user_media, next_ = u.user_recent_media(user_id=id, count=20, with_next_url=next_) photos_thumbnail = [] photos_standard = [] title = username + " Recent Media-Page " + str(page) prev_page = False next_page = False if next_: prev_page = True if page != 1: next_page = True for media in user_media: photos_thumbnail.append("%s" % media.images['thumbnail'].url) photos_standard.append("%s" % media.images['standard_resolution'].url) return render_template("recent.html", thumb=photos_thumbnail, photos=photos_standard, prev=prev_page, next=next_page, page=page, title=title)
def get(self): ig_user_id = self.request.get("ig_user_id") if not ig_user_id: self.redirect("/connect") instagram_client = InstagramAPI(**settings.INSTAGRAM_CONFIG) access_token = instagram_client.exchange_user_id_for_access_token(ig_user_id) instagram_client = InstagramAPI(access_token = access_token) user = instagram_client.user("self") profiles = Profile.all() profiles.filter("ig_user_id = ", user.id) profile = (profiles.get() or Profile()) profile.full_name = (user.full_name or user.username) profile.ig_user_id = user.id profile.ig_username = user.username profile.ig_access_token = access_token profile.put() cookieutil = LilCookies(self, settings.COOKIE_SECRET) cookieutil.set_secure_cookie( name = "ig_user_id", value = user.id, expires_days = 365) self.redirect("/")
def write_stream(out_file, production = False, iterations = 61): #Create a file to store output. "a" means append (add on to previous file) fhOut = open(out_file,"a") #authorize access_token = media_mapper.keys.INSTAGRAM_ACCESS_TOKEN client_secret = media_mapper.keys.INSTAGRAM_CLIENT_SECRET api = InstagramAPI(access_token=access_token, client_secret=client_secret) #set time limit for the current time time_marker = calendar.timegm(time.gmtime()) begin_time = time_marker sleep(10) #sleep ten seconds so some instagrams have some time to come in #query for a new batch of 20 photos for i in xrange(iterations): #make sure that it only loops 60 times media_search = api.media_search(lat="37.7833",lng="-122.4167",distance=5000, min_timestamp=time_marker) #get all the metadata in a list instagram_list = instagram_metadata(media_search, time_marker) [json.dump(item, fhOut, indent = 1) for item in instagram_list] time_marker = calendar.timegm(time.gmtime()) #check to make sure that this cycle has taken an hour for request limits end_time = calendar.timegm(time.gmtime()) seconds_left = 3600 -(begin_time-end_time) #find out how much time has passed if seconds_left > 0: #if an hour hasn't passed, sleep so I don't overrequest sleep(seconds_left) fhOut.close()
def index(): # TODO: Move to environment variable access_token = "995294683.26174be.94f2626419534650812cf5ed542d5a9d" api = InstagramAPI(access_token=access_token) # Get 30 pickles starting at a random page num = 30 page = random.randint(0, 10) pickles, next = api.tag_recent_media(num, page, "pickle") choice_pickle = choice(pickles) # Truncate long captions pickle_caption = choice_pickle.caption.text.lower() if choice_pickle.caption else '' pickle_caption = (pickle_caption[:110] + "...") if len(pickle_caption) > 110 else pickle_caption pickle_link = choice_pickle.link pickle_user = choice_pickle.user.username if hasattr(choice_pickle, "images"): pickle_image_link = choice_pickle.images["standard_resolution"].url elif hasattr(choice_pickle, "videos"): # FIXME: Update template pickle_image_link = choice_pickle.videos["standard_resolution"].url # TODO: Download generated image with canvas # TODO: Post the best ones to a an instagram account or tweet them. return render_template('index.html', caption=pickle_caption, username=pickle_user, link=pickle_link, image=pickle_image_link)
def get_redirect_url(self, *args, **kwargs): code = self.request.GET.get("code") settings.use_editable() site = Site.objects.get_current() conf = { "redirect_uri": "http://{0}{1}".format(site.domain, reverse('instagram_oauth')), "client_id": settings.INSTAGRAM_CLIENT_ID, "client_secret": settings.INSTAGRAM_CLIENT_SECRET, } unauthorized_api = InstagramAPI(**conf) logger.debug(unauthorized_api) access_token = unauthorized_api.exchange_code_for_access_token(code) try: instagram = Instagram.objects.all()[0] instagram.access_token = access_token[0] instagram.user_id = int(access_token[1]['id']) instagram.full_name = access_token[1]['full_name'] instagram.username = access_token[1]['username'] instagram.save() except IndexError: Instagram.objects.create(access_token=access_token[0], user_id=int(access_token[1]['id']), full_name=access_token[1]['full_name'], username=access_token[1]['username']) return "/admin/"
def fetch_medias(cls, count): try: last_media = cls.objects.latest() except InstagramMedia.DoesNotExist: last_media = None min_time = '' if last_media: min_time = time.mktime(last_media.created.utctimetuple()) user = InstagramUser.objects.all()[0] api = InstagramAPI(access_token=user.access_token) medias = api.user_recent_media(min_timestamp=min_time, count=count) if not (medias and medias[0]): raise StopIteration for media in medias[0]: if cls.objects.filter(instagram_id=media.id).exists(): # TODO: check and update metadata continue caption = media.caption and media.caption.text or u'' insta_media = cls(instagram_id=media.id, created=media.created_time, caption=caption, comment_count=media.comment_count, like_count=media.like_count, url=media.link or u'', thumbnail_url=media.images['thumbnail'].url, standard_url=media.get_standard_resolution_url()) yield insta_media
def Tag_Search(page=1): if request.method == "POST": query = request.form["query"] if not query: e = "Please Enter something." return render_template("search.html", error=e, title="Tag Search") u = InstagramAPI(access_token=session['access_token'], client_secret=secrets['client_secret']) tag_search, next_tag = u.tag_search(q=query) tag_recent_media, next_ = u.tag_recent_media(tag_name=tag_search[0] .name) for i in range(1, page): tag_recent_media, next_ = u.tag_recent_media(tag_name=tag_search[0] .name, with_next_url=next_) tags = [] imgs = [] title = "Tag Search-Page " + str(page) prev_page = False next_page = False if next_: prev_page = True if page != 1: next_page = True # for media in tag_recent_media: # tags.append("{}".format(media.get_thumbnail_url())) # tags.append("{}".format(media.get_standard_url())) return render_template("search.html", tags=tags, imgs=imgs, prev=prev_page, next=next_page, page=page, title=title) return render_template("search.html")
def _instagram(self, args): api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret) tags = args.keywords.split(' ') try: images = [] for tag in tags: imgs, str_next = api.tag_recent_media(tag_name=str(tag), count=args.max_results) images = list(itertools.chain(images, imgs)) except Exception, error: images = []
def _get_access_token(): api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=REDIRECT_URL) redirect_uri = api.get_authorize_login_url(scope=SCOPE) print("Visit this page in browser and authorize access:\n", redirect_uri) code = input("Paste in code in query string after redirect: ").strip() access_token, user_info = api.exchange_code_for_access_token(code) return access_token
def instagram1(key): api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92') for item in api.user_search(q=key, count=10): username = item.username dp = item.profile_picture did = item.id web = item.website bio = item.bio print dp, username, did,web, bio lol = "text" return lol
def instagram(key): api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92') for item in api.media_search(q=key, count=10, lng=120.98, lat=14.62): key = key photo = item.images['low_resolution'].url username = item.user.username real_name = item.user.full_name dp = item.user.profile_picture date = item.created_time print date, photo , real_name lol = "text" return lol
def handle(token=ACCESS_TOKEN): if token: try: return InstagramAPI(access_token=token) except: pass try: token = access_token() return InstagramAPI(access_token=token) except: print '**** WARNING: NO INSTAGRAM AUTH ****' return no_auth_handle()
def __init__(self): access_token ="182023789.04c8e57.9e150e8ccd49440d96b7e3b0cf53179f" self.api = InstagramAPI(access_token=access_token,client_secret="85ecfb407c34423c8efcf82af4b38695") self.user_ids = {} self.user_imgs = {} # players accounts = ['cristiano', 'leomessi', 'waynerooney', 'zidane', 'iamzlatanibrahimovic', 'toni.kr8s', 'davidluiz_4', 'hazardeden_10', 'davidbeckham', 'andreapirlo21thierryhenry', 'luissuarez9', 'garethbale11', 'andresiniesta8', 'neymarjr', 'kingarturo23oficial', 'manuelneuer', 'didierdrogba', 'mosalah22', 'ronaldolima', 'kaka', 'm10_official', 'jamesrodriguez10', 'ikercasillasoficial', 'mb459', 'marcelotwelve', 'alexis_officia1', 'stevengerrard', 'realmadrid', 'fcbarcelona', 'chelseafc', 'arsenal', 'liverpoolfc', 'manchesterunited', 'mcfcofficial', 'juventus', 'officialasroma', 'inter', 'acmilan', 'acffiorentina', 'psg', 'fcbayern', 'bvb09', 'uefachampionsleague', 'instareplays', 'robgunillustration', 'squawkafootball', 'soccermemes', 'futbolsport', 'nikefootball', 'pumafootball', 'adidasfootball', 'instareplays', '6secfootball101greatgoals', '8fact_football', 'premierleague', 'laliga', 'espnfc', 'beinsports', 'bestoffootball', 'golazoweekly', 'worldgoalz', 'futbol_evolution', 'footballtransfersdailywe_love_football', 'footbalita', '8factfootball', 'football.news', 'footykix', 'yallakoraofficial', 'filgoal1', 'talksport', 'kooora', 'cristiano','leomessi', 'waynerooney','zidane','iamzlatanibrahimovic', 'toni.kr8s','davidluiz_4', 'hazardeden_10','davidbeckham','andreapirlo21', 'thierryhenry','luissuarez9','garethbale11','andresiniesta8','neymarjr','kingarturo23oficial','manuelneuer','didierdrogba','mosalah22', 'ronaldolima','kaka','m10_official','jamesrodriguez10','ikercasillasoficial','mb459','marcelotwelve','alexis_officia1','stevengerrard', # clubs 'realmadrid','fcbarcelona', 'chelseafc','arsenal','liverpoolfc','manchesterunited','mcfcofficial', 'juventus','officialasroma','inter','acmilan','acffiorentina', 'psg', 'fcbayern','bvb09', # other accounts '433','visubal','officialfootballmemes', 'instatroll_football' 'uefachampionsleague','instareplays','robgunillustration','squawkafootball','soccermemes','futbolsport','nikefootball','pumafootball','adidasfootball','instareplays','6secfootball', '101greatgoals','8fact_football','premierleague','laliga','espnfc','beinsports','bestoffootball','golazoweekly','worldgoalz','futbol_evolution','footballtransfersdaily', 'we_love_football','footbalita','8factfootball','football.news','footykix','yallakoraofficial','filgoal1','talksport','kooora'] if not ( os.path.exists('insta_user_ids.pickle') and os.path.exists('insta_user_imgs.pickle')): accounts = list(set(accounts)) for account in accounts: print 'looking for: ', account user_list = self.api.user_search(account) print user_list if user_list: for user in user_list: if user.username == account: self.user_ids[account] = user.id self.user_imgs[account] = user.profile_picture print 'found: ', user with open('insta_user_ids.pickle', 'wb') as f: cPickle.dump(self.user_ids, f) with open('insta_user_imgs.pickle', 'wb') as f: cPickle.dump(self.user_imgs, f) else: with open('insta_user_ids.pickle', 'r') as f: self.user_ids = cPickle.load(f) with open('insta_user_imgs.pickle', 'r') as f: self.user_imgs = cPickle.load(f)
def update_user_likes(download): api = InstagramAPI( access_token=settings.INSTAGRAM_ACCESS_TOKEN, client_secret=settings.INSTAGRAM_CLIENT_SECRET) # Figure out the logged in user user = api.user() username = user.username # Find the media the user has liked liked_media, next = api.user_liked_media() update_likes(user=username, photos=liked_media, download=download)
def pics(limit=4): api = InstagramAPI(access_token=auth.INSTAGRAM_ACCESS_TOKEN, client_secret=auth.INSTAGRAM_CLIENT_SECRET) recent_media, _next = api.user_recent_media(user_id='6204130', count=10) # Only include images, no videos images = [p for p in recent_media if p.type == 'image'] images.sort(key=lambda p: p.created_time, reverse=True) return images[:limit]
def initialize(self): super(InstagramAuth, self).setProvider("instagram") consumer_key = self.application.settings['instagram_oauth']['key'] consumer_secret = \ self.application.settings['instagram_oauth']['secret'] redir_uri = "{0}/auth/instagram".format( self.application.settings['base_url']) self.api = InstagramAPI( client_id=consumer_key, client_secret=consumer_secret, redirect_uri=redir_uri, )
def Popular_Media(): u = InstagramAPI(access_token=session['access_token'], client_secret=secrets['client_secret']) popular_media = u.media_popular() photos_thumbnail = [] photos_standard = [] title = "Popular Media-Page " for media in popular_media: photos_thumbnail.append("%s" % media.images['thumbnail'].url) photos_standard.append("%s" % media.images['standard_resolution'].url) return render_template("recent.html", thumb=photos_thumbnail, photos=photos_standard, title=title)
def home(): insta_api = InstagramAPI(access_token=local_settings.INSTAGRAM_TOKEN) feed = insta_api.user_recent_media(count=15) medias = feed[0] rdd_api = readability.oauth(local_settings.READABILITY_CLIENT_KEY, local_settings.READABILITY_CLIENT_SECRET, token=local_settings.READABILITY_USER_TOKEN) bookmarks = rdd_api.get_bookmarks(limit=10) # ['author', 'content', 'content_size', 'date_published', 'domain', 'excerpt', 'id', 'next_page_href', 'processed', 'short_url', 'title', 'url', 'word_count'] return render_template("index.html", medias=medias, bookmarks=bookmarks)
def get_context_data(self, *args, **kwargs): try: instagram = Instagram.objects.all()[0] api = InstagramAPI(access_token=instagram.access_token) try: media, discard = api.user_recent_media( user_id=instagram.user_id, count=24) except InstagramAPIError as e: logger.error(e) return {"media": []} return {"media": media} except IndexError: return {"media": []}
def transform_uid(self, uid, access_token, cache=None): print >> sys.stderr, "[%s] extracting posts" % uid # Extract the posts for this users api = InstagramAPI(access_token=access_token, client_id=client_id, client_secret=client_secret) media_feed, mf_next_ = api.user_recent_media(user_id=uid, count=feed_limit) while mf_next_: more, mf_next_ = api.user_recent_media(with_next_url=mf_next_) print >> sys.stderr, "[%s] found %d posts" % (uid, len(media_feed)) return (media_feed, self.transform(uid, media_feed, cache))
def auth_request(): api = InstagramAPI(access_token=OTHER['access_token'],client_secret=CONFIG['client_secret']) target_ids = api.user_search(OTHER['target'],1) if len(target_ids) > 1: logging.error('Found mutiple users, please check username') return target_id = target_ids[0].id my_name = api.user().username logging.debug('Starting check recent media') recent_media, url = api.user_recent_media(user_id=target_id, count = 1) liked_media = [] for media in recent_media: logging.debug('Processing media %s' % media.id) users = api.media_likes(media.id) will_like = True for user in users: if user.username == my_name: will_like = False break if will_like: logging.debug('Liking media %s' % media.id) api.like_media(media.id) liked_media.append(media) else: logging.debug('Already liked media %s, aborting like' % media.id) return liked_media
def get_ig_media(tag): client_id = '0db0c30814c14ac48a58c8e27a7b4a5a' client_secret = '8681192578424d78aea183f1bf05f465' from instagram.client import InstagramAPI api = InstagramAPI(client_id=client_id, client_secret=client_secret) media, _next = api.tag_recent_media(33, 0, tag) # let's make it a bit more interesting choice = randint(0, 33) return media[choice].get_standard_resolution_url()
def instagram_activate(): client_id = app.config['INSTAGRAM_CLIENT_ID'] client_secret = app.config['INSTAGRAM_SECRET'] redirect_uri = url_for('instagram_oauthorized', _external=True) # app.logger.info(redirect_uri) scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope=scope) return redirect(redirect_uri)
def post(self): import hashlib import hmac import logging from StringIO import StringIO from time import time from urllib2 import urlopen from django.utils import simplejson from dropbox import helper as dropbox_helper payload = self.request.body # verify payload signature = self.request.headers['X-Hub-Signature'] client_secret = settings.INSTAGRAM_CONFIG['client_secret'] hashing_obj = hmac.new(client_secret.encode("utf-8"), msg=payload.encode("utf-8"), digestmod=hashlib.sha1) digest = hashing_obj.hexdigest() if digest != signature: logging.info("Digest and signature differ. (%s, %s)" % (digest, signature)) return changes = simplejson.loads(payload) for change in changes: profiles = Profile.all() profiles.filter("ig_user_id =", change['object_id']) profile = profiles.get() if not profile: logging.info("Cannot find profile %s", change['object_id']) continue instagram_client = InstagramAPI( access_token=profile.ig_access_token) media, _ = instagram_client.user_recent_media(count=1) media = media[0] media_file = urlopen(media.images['standard_resolution'].url) media_data = media_file.read() dropbox_file = StringIO(media_data) dropbox_file.name = ("%s.jpg" % int(time())) dropbox_client = dropbox_helper.authenticated_client(profile) dropbox_client.put_file(settings.DROPBOX_CONFIG['root'], "/Instagram Photos/", dropbox_file)
def auth_request(): api = InstagramAPI(access_token=OTHER['access_token']) target_ids = api.user_search(OTHER['target']) target_id = None for search_hit in target_ids: if search_hit.username == OTHER['target']: target_id = search_hit.id break if target_id == None: logging.error('Did not find user, please check username') return [] my_name = api.user().username logging.debug('Starting check recent media') recent_media, url = api.user_recent_media(user_id=target_id, count = 20) liked_media = [] for media in recent_media: logging.debug('Processing media %s' % media.id) users = api.media_likes(media.id) will_like = True for user in users: if user.username == my_name: will_like = False break if will_like: logging.debug('Liking media %s' % media.id) api.like_media(media.id) liked_media.append(media) else: logging.debug('Already liked media %s, aborting like' % media.id) return liked_media
def __init__(self, *args, **kwargs): super(InstagramUserPhotoService, self).__init__(*args, **kwargs) # Load the config from the environment config = self.config() # Erorr:author;clarisha octa:main;required:keys;config:edit; access_token = config.get('INSTAGRAM_ACCESS_TOKEN') if not access_token: raise TypeError('INSTAGRAM_ACCESS_TOKEN is required') self.api_client = InstagramAPI(access_token=access_token) self.user_ids, self.usernames = users_from_config( self.api_client, config)
def __init__(self, access_token, client_secret, db_interface): """ Init instagram crawler, and the api object. Args: access_token (str): instagram api access token client_secret (str): instagram api secret client db_interface (MongoInterface) """ self._api = InstagramAPI(access_token=access_token, client_secret=client_secret) self._db_interface = db_interface
def main() : access_token = "YOUR_ACCESS_TOKEN" client_secret = "YOUR_CLIENT_SECRET" api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, next_ = api.user_recent_media(user_id="userid", count=10) for media in recent_media: print media.caption.text # api = InstagramAPI(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET') # popular_media = api.media_popular(count=20) # for media in popular_media: # print media.images['standard_resolution'].url return
def get_medias(user_id, all=False): api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET) medias, next_ = api.user_recent_media(user_id=user_id, count=100) count = 10000 if all else 5 while next_ and count > 0: print('next: %s' % next_) try: more_medias, next_ = api.user_recent_media(with_next_url=next_) if more_medias: medias.extend(more_medias) time.sleep(3) except Exception, e: print("error:%s on get_medias:%s" % (e, next_)) time.sleep(10) count -= 1
def access_token(self,flag): if flag: scope = [] self.api = InstagramAPI(client_id = self.client_id, client_secret = self.client_secret, redirect_uri = self.redirect_uri) redirect_uri = self.api.get_authorize_login_url(scope = scope) print "Visit this page and authorize access in your browser:\n", redirect_uri code = raw_input("Paste in code in query string after redirect: ").strip() self.access_token = self.api.exchange_code_for_access_token(code) print self.access_token else: self.access_token = 'Insert Your actual Client Access token to not repeath this again and again' return self.access_token
def statistics(profile): profile = profile api = InstagramAPI(access_token=profile.access_token, client_secret=CLIENT_SECRET) account = api.user(profile.id) count_media = account.counts['media'] follows = account.counts['follows'] followed_by = account.counts['followed_by'] # Получаем все медиа all_media, next_ = api.user_recent_media(user_id=profile.id) while next_: more_media, next_ = api.user_recent_media(user_id=profile.id, with_next_url=next_) all_media.extend(more_media) likes = 0 comments = 0 count_videos = 0 count_images = 0 for media in all_media: likes += media.like_count comments += media.comment_count if media.type == "video": count_videos += 1 if media.type == "image": count_images += 1 # Среднее вол-во лайков likes_average = likes / len(all_media) # показатель вовлеченности involvement = (likes_average / follows) * 100 statistics = Statistics(profile=profile, likes=likes, likes_average=likes_average, comments=comments, follows=follows, followed_by=followed_by, count_media=count_media, count_images=count_images, count_videos=count_videos, involvement=involvement) statistics.save()
class Aggregator(GenericAggregator): ACCESS_TOKEN = settings.EDSA_INSTAGRAM_ACCESS_TOKEN def init_connector(self): self.connector = InstagramAPI(access_token=self.ACCESS_TOKEN) def search(self, query): if query.startswith('#'): query = query.lstrip('#') res = self.connector.tag_recent_media(tag_name=query)[0] datas = [] for media in res: if media.caption: text = media.caption.text else: text = "" data = { 'social_id': media.id, 'name': 'instagram %s' % media.id, 'slug': 'instagram_%s' % media.id, 'ressource_date': media.created_time, 'description': text, 'media_url': media.get_standard_resolution_url(), 'media_url_type': 'image', 'author': media.user.username, } datas.append(data) return datas
def main(): api = InstagramAPI(client_id='1ed75e7649544ac5b1aacd2a1d6db2b1', client_secret='1b78cda37723445b85f5c6da25469611') global text_file generatePosts(api, 40.730453, -73.994008, 10, 5000)
def user_photos(): #check for IG info in session variables if 'instagram_access_token' in session and 'instagram_user' in session: userAPI = InstagramAPI(access_token=session['instagram_access_token']) recent_media, next = userAPI.user_recent_media( user_id=session['instagram_user'].get('id'), count=20) template_data = { 'size': request.args.get('size', 'thumb'), 'media': recent_media } return render_template('layout.html', **template_data) else: return redirect('/ig_connect')
def _set_up_api_dict(self, api_key_fname): """Ensure the api_key_fname is valid, set up the api_dict :param api_key_fname: file containing api key token info :return: tuple of dictionary of api's and dictionary of api access token and client secret """ cwd = os.path.dirname(__file__) #gets current directory api_tokens_path = os.path.join(cwd, 'api_key_tokens', api_key_fname) #check for validity of path input if not os.path.exists(api_tokens_path): err_msg = '%s does not exist!' % api_key_fname err_msg.format(api_key_fname) # pdb.set_trace() raise IOerror(err_msg) api_dict, api_tokens_dict = dict(), dict() #1 indexing i = 0 with open(api_tokens_path, "r") as f: for line in f: i += 1 [access_token, client_secret] = line.split(',') api_tokens_dict[i] = dict() api_tokens_dict[i]['access_token'] = access_token api_tokens_dict[i]['client_secret'] = client_secret api_dict[i] = InstagramAPI(access_token=access_token, client_secret=client_secret) return api_dict, api_tokens_dict
class Setup: def __init__(self, tag_name): #system vars self.cur = os.getcwd() # import keys config = SafeConfigParser() config.read(self.cur + '/app/settings.ini') client_id = config.get('Instagram', 'client_id') # IG client id (settings.ini) client_secret = config.get('Instagram', 'client_secret') # IG client secret (^) self.api = InstagramAPI(client_id=client_id, client_secret=client_secret) self.images = self.cur + '/app/static/images/' self.housekeeping() self.tag_name=tag_name pprint("looking for \'%s\'..." % self.tag_name) # download 5, but only one image is used at a time self.recent = self.api.tag_recent_media(5, 1000000000, self.tag_name) # recent[0] is list of returned media for media in self.recent[0]: self.keep(media.images['standard_resolution'].url) pprint("Downloaded %s images" % len(self.recent[0])) def housekeeping(self): filelist = [ f for f in os.listdir(self.images + ".") if f.endswith(".jpg") ] pprint("Removing old image files.") for f in filelist: os.remove(self.images + f) def keep(self, img): name = str(img)[-20:] # create new file for img with open(self.images + name, 'w'): urllib.urlretrieve(img, self.images + name)
def Media_Search(): if request.method == "POST": q = request.form['query'] lat = request.form['latitude'] lng = request.form['longitude'] if not q or not lat or not lng: e = "Please Enter latitude and longitude" return render_template("media_search.html", title="Media Search", error=e) u = InstagramAPI(access_token=session['access_token']) media_search = u.media_search(query=q, lat=lat, lng=lng, count=32) media = [] for link in media_search: media.append("{}".format(link.get_thumbnail_url())) return render_template("media_search.html", media=media) return render_template("media_search.html", title="Media Search")