def makeRss(hash_id): if 'api' in session: api = session['api'] else: access_token = redis_server.get(hash_id) api = InstagramAPI(access_token=access_token) liked = api.user_liked_media(count=-1) username = api.user().username user_id = api.user().id items = [] for i in liked[0]: if i.caption: title = i.caption.text else: title='' link = i.images['standard_resolution'].url description = "<img src='%s' title='%s'/>" % (link, title) item = PyRSS2Gen.RSSItem(title,link,description) items.append(item) title = "%s's Instamator RSS Feed" % username link = "http://instamator.ep.io/%s/rss" % hash_id rss = PyRSS2Gen.RSS2( title= title, description ='', link=link, items=items, ) rss_response = rss.to_xml() response = make_response(rss_response) response.headers['Content-Type'] = 'application/rss+xml' return response
def makeJson(hash_id): if 'api' in session: api = session['api'] else: access_token = redis_server.get(hash_id) api = InstagramAPI(access_token=access_token) liked = api.user_liked_media(count=-1) user_id = api.user().id #print liked dumpcontent = [] for i in liked[0]: tmpdict = {} if i.caption: tmpdict["description"] = "<img src='%s' title='%s'/>" % (i.images['standard_resolution'].url, i.caption.text) tmpdict["title"] = i.caption.text else: tmpdict["description"] = "<img src='%s' title=''/>" % (i.images['standard_resolution'].url) tmpdict["title"] = '' tmpdict["link"] = i.images['standard_resolution'].url dumpcontent.append(tmpdict) opendump = json.dumps(dumpcontent) response = make_response(str(opendump)) response.headers['Content-Type'] = 'application/json' return response
def crawl_all_feeders(): api = InstagramAPI(access_token=access_token) try: #recent_media, next_ = api.user_recent_media(user_id="mmoorr", count=10) media_feed, next_ = api.user_media_feed(count=20) except InstagramAPIError as ie: print("Instagram API error" + str(ie)) return except Exception as e: print("General exception" + str(e)) return crawled={} for media in media_feed: if media.user.id in crawled: continue crawled[media.user.id] = True try: recent_media, next_ = api.user_recent_media(user_id=media.user.id, count=10) user_info = api.user(user_id=media.user.id) except InstagramAPIError as ie: print("Instagram API error" + str(ie)) return except Exception as e: print("General exception" + str(e)) return print ("Got %d items for user %s"%(len(recent_media), media.user)) print ("This is %s, ID %s, bio %s, followed by %s"%(user_info.full_name, user_info.id, user_info.bio, user_info.counts['followed_by'])) print ("++")
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(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 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 find_self(access_token): client_secret = "22a6a272eeaa4b18aba7b242ade48cd3" api = InstagramAPI(access_token=access_token, client_secret=client_secret) self_info = api.user() return self_info
def timepost_on_id(request): print 'timepost_on_id' if request.method == 'POST': form = InstagramUserIDForm(request.POST) if form.is_valid(): user_id = request.POST['pk'] account = SocialAccount.objects.get(user__username=request.user.username) social_app = SocialApp.objects.get(name='Instagram') token = SocialToken.objects.get(account=account, app=social_app) api = InstagramAPI(access_token=token) id_user = api.user(user_id) # url = 'https://api.instagram.com/v1/users/{id}?access_token={token}'.format(id=user_id, token=token.token) # response = requests.get(url) try: user = User.objects.get(username=id_user.username) user.uid = user_id user.save() except User.DoesNotExist: user = User() user.uid = user_id user.username = id_user.username user.save() get_paginated_followers.delay(user, api) return HttpResponseRedirect('/users/graph/{0}'.format(user.username))
def get_user_details(user, access_token, filename): user_table = {'Data' : []} api = InstagramAPI(access_token=access_token) user_details = api.user(user_id=user) for details in user_details: user_table['Data'].append({'Username' : details.username, 'Bio' : details.bio, 'Website' : details.website, 'Profile_pic' : details.profile_picture, 'Full_name' : details.full_name, 'Posts' : details.counts.media, 'Followed_by' : details.counts.followed_by, 'Follows' : details.counts.follows, 'ID' : details.id}) user_data = user_table['Data'] csv_file = open(filename, 'wb') csv_writer = csv.writer(csv_file) count = 0 for data in user_data: if count == 0: header = data.keys() csv_writer.writerow(header) count += 1 csv_writer.writerow(data.values()) csv_file.close() return user_table
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 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 user_self(): if 'instagram_access_token' in session and 'instagram_user' in session: userAPI = InstagramAPI(access_token=session['instagram_access_token']) userSelf = userAPI.user(user_id=session['instagram_user'].get('id')) return '''Welcome ''' + userSelf.full_name else: return redirect('/connect')
def get_instagram_follower_count(user): api = InstagramAPI(client_id='13245ce01c854900a3a964b9bdd964c5', client_secret='ed11480527dc4f6d959bc2fde47d25da') instagram_uid_list = SocialAccount.objects.filter(user_id=user.id, provider='instagram') if (len(instagram_uid_list) > 0): user.instagram_followers = api.user( instagram_uid_list[0].uid).counts['followed_by'] user.save()
def get_instagram_followers(self, user_id): print "get_instagram_followers", user_id try: api = InstagramAPI( client_id=self.INSTAGRAM_SETTINGS["CLIENT_ID"], client_secret=self.INSTAGRAM_SETTINGS["CLIENT_SECRET"] ) user = api.user(user_id) return user.counts["followed_by"] except Exception as e: raise InstagramError
def update_user_likes(download): api = InstagramAPI(access_token=settings.INSTAGRAM_ACCESS_TOKEN.decode(), client_secret=settings.INSTAGRAM_CLIENT_SECRET.decode()) # 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 crawl(self, resourceID, filters): # Extract filters application = filters[0]["data"]["application"] self.echo.out(u"ID: %s (App: %s)." % (resourceID, application["name"])) # Get authenticated API object clientID = str(application["clientid"]) clientSecret = str(application["clientsecret"]) api = InstagramAPI(client_id = clientID, client_secret = clientSecret) # Configure data storage directory usersBaseDir = "../../data-update/users" usersDataDir = os.path.join(usersBaseDir, str(int(resourceID) % 1000)) try: os.makedirs(usersDataDir) except OSError: pass # Initialize return variables resourceInfo = {"current_state": "valid"} extraInfo = {"InstagramAppFilter": {}, "MySQLBatchInsertFilter": []} # Execute collection while True: try: userInfo = api.user(user_id=resourceID, return_json=True) request = urllib2.Request("http://instagram.com/%s" % userInfo["username"]) userPage = urllib2.urlopen(request).read() except (InstagramAPIError, InstagramClientError) as error: if (error.status_code == 400): if (error.error_type == "APINotAllowedError"): resourceInfo["current_state"] = "not_allowed" break elif (error.error_type == "APINotFoundError"): resourceInfo["current_state"] = "not_found" break else: raise else: userInfoFilePath = os.path.join(usersDataDir, "%s.user" % resourceID) userPageFilePath = os.path.join(usersDataDir, "%s.html" % resourceID) with open(userInfoFilePath, "w") as output: json.dump(userInfo, output) with open(userPageFilePath, "w") as output: output.write(userPage) os.chmod(userInfoFilePath, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH) os.chmod(userPageFilePath, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH) # Send user information back to batch insert filter userInfo["counts_media"] = userInfo["counts"]["media"] userInfo["counts_follows"] = userInfo["counts"]["follows"] userInfo["counts_followed_by"] = userInfo["counts"]["followed_by"] del userInfo["counts"] extraInfo["MySQLBatchInsertFilter"].append(userInfo) resourceInfo["is_verified"] = (re.search("\"is_verified\":true", userPage) is not None) break return (resourceInfo, extraInfo, None)
def insta(account): """ @account: str """ log(account, "@") api = InstagramAPI( client_id=cfg.get('instagram', 'client_id'), client_secret=cfg.get('instagram', 'client_secret') ) user = api.user_search(account)[0] found_user = api.user(user.id) return found_user.counts['followed_by']
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 main(): client = client_packet(client_id='923490f7659a44fb8a83db1a4134992f', client_secret='58999a8bbb0c42e78213585de310cafe', redirect_uri='https://192.168.0.82', begin_user_id='190353205') # access_token = client.Access_token(True) # api = InstagramAPI(client_id=client.client_id, client_secret=client.client_secret, access_token=access_token[0]) api = InstagramAPI(client_id=client.client_id, client_secret=client.client_secret) print('start searching') popular_media = api.media_popular(count=20) print('finish searching') for media in popular_media: print(media.images['standard_resolution'].url) user = api.user('190353205')
def user(user_id): num_followed_by = 0 num_follows = 0 num_media = 0 try: api = InstagramAPI(access_token=access_token, client_secret=client_secret) user = api.user(user_id) num_media = user.counts['media'] num_followed_by = user.counts['followed_by'] num_follows = user.counts['follows'] except Exception as e: print(e) return num_followed_by,num_follows,num_media
def main(app, data): api = InstagramAPI(client_id=environ.get('INSTAGRAM_CLIENT_ID'), client_secret=environ.get('INSTAGRAM_CLIENT_SECRET'), access_token=environ.get('INSTAGRAM_ACCESS_TOKEN')) user = api.user().__dict__ recent_media, next_ = api.user_recent_media() user['media'] = [] for media in recent_media: user['media'] += [media, ] return user
def access(request): instance = UserSocialAuth.objects.get(user=request.user, provider='instagram') access_token = instance.tokens['access_token'] esistenza_track = Utente.objects.filter(utente = instance).exists() if esistenza_track: user_obj = Utente.objects.get(utente = instance) user_obj.token_block = False user_obj.save() return HttpResponseRedirect('/') else: api = InstagramAPI( access_token = access_token, client_ips = MIOIP, client_secret = CLIENT_SECRET ) try: informazioni = api.user() except InstagramAPIError as errore: errore_mortale(errore, instance) followed_by = informazioni.counts['followed_by'] #linguaggio = request.META['LANGUAGE'] linguaggio = translation.get_language_from_request(request) if linguaggio == 'it': lingua = 'it' elif linguaggio == 'ro': lingua = 'ro' elif linguaggio == "fr": lingua = "fr" else: lingua = 'en' nuove_stats = Utente(utente = instance, follower_iniziali = followed_by, lingua = lingua) nuove_stats.save() nuovo_pacchetto(instance, 2) nuovi_tag(instance) return HttpResponseRedirect('/')
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()
def authenticate(): code = request.args['code'] try: access_token = unauthenticated_api.exchange_code_for_access_token(code) if not access_token: return 'Could not get access token' api = InstagramAPI(access_token=access_token) session['access_token'] = access_token session['api'] = api session['user_id'] = api.user().id return redirect(url_for('index')) except Exception, e: print e
def report_task(instance): access_token = instance.tokens['access_token'] api = InstagramAPI( access_token = access_token, client_ips = MIOIP, client_secret = CLIENT_SECRET ) stats_obj = Utente.objects.get(utente = instance) follower_iniziali = stats_obj.follower_iniziali follower_iniziali = float(follower_iniziali) informazioni = api.user() follower_attuali = informazioni.counts['followed_by'] follower_attuali = float(follower_attuali) #Variazione percentuali numero di follower percentuale = ( (follower_attuali - follower_iniziali) / follower_attuali ) * 100 percentuale = round(percentuale, 2) #I tag che ho usano maggiormente lista_ordinata, lista_tag = statistiche_tag(api) primo = lista_ordinata[0] tag_primo = lista_tag[primo] secondo = lista_ordinata[1] tag_secondo = lista_tag[secondo] terzo = lista_ordinata[2] tag_terzo = lista_tag[terzo] #Miei follower con piu' follower lista_ordinata = follower_per_num_follower(api) primo_follower = lista_ordinata[0].username primo_follower_num_follower = lista_ordinata[0].num_follower secondo_follower = lista_ordinata[1].username secondo_follower_num_follower = lista_ordinata[1].num_follower terzo_follower = lista_ordinata[2].username terzo_follower_num_follower = lista_ordinata[2].num_follower return primo_follower + " - " + str(primo_follower_num_follower)
def main(): if "access_token" in session: u = InstagramAPI(access_token=session['access_token'], client_secret=secrets['client_secret']) user = u.user() c, conn = connection() x = c.execute("SELECT * FROM user WHERE access_token = '{0}'".format(str(session['access_token']))) session['id'] = user.id session['username'] = user.username if int(x) == 0: c.execute("INSERT INTO user VALUES('{0}','{1}','{2}')".format(session['access_token'],user.username,user.full_name)) conn.commit() c.close() conn.close() return render_template("call.html", title=user.username, full_name=user.full_name, profile_picture=user.profile_picture, counts=user.counts) else: return render_template("index.html")
def makeText(hash_id): '''Makes Text file about Instagram likes hash_id: unique id for user ''' if 'api' in session: api = session['api'] else: access_token = redis_server.get(hash_id) api = InstagramAPI(access_token=access_token) liked = api.user_liked_media(count = -1) user_id = api.user().id textcontent = [] for i in liked[0]: textcontent.append(i.images['standard_resolution'].url) text_response = "\n".join(textcontent) response = make_response(text_response) response.headers['Content-Type'] = 'text/plain' return response
def get(self): code = self.request.get('code') token = _api.exchange_code_for_access_token(code) if not token: self.redirect('/error') client = Client(access_token=token) user = client.user('self') profile = Profile.all().filter('ig_user_id = ', user.id) profile = (profile.get() or Profile()) profile.full_name = (user.fullname or user.username) profile.ig_user_id = user.id profile.ig_username = user.username profile.ig_access_token = access_token profile.put() cookie = Cookies(self, settings.COOKIE_SECRET) cookie.set_secure_cookie(name = 'ig_user_id', value = user.id, expires_days = 365) self.redirect('/connect')
def crawl(self, resourceID, filters): self.echo.out(u"User ID received: %s." % resourceID) # Extract filters application = filters[0]["data"]["application"] # Get authenticated API object clientID = application["clientid"] clientSecret = application["clientsecret"] api = InstagramAPI(client_id = clientID, client_secret = clientSecret) self.echo.out(u"App: %s." % str(application["name"])) # Configure exception handling maxNumberOfRetrys = 8 retrys = 0 sleepSecondsMultiply = 3 # Configure data storage directory usersBaseDir = "../../data/users" usersDataDir = os.path.join(usersBaseDir, str(resourceID % 1000)) try: os.makedirs(usersDataDir) except OSError: pass # Initialize return variables responseCode = 3 #extraInfo = {"InstagramAppFilter": {}, "SaveResourcesFilter": []} extraInfo = {"InstagramAppFilter": {}} # Execute collection while (True): try: userInfo = api.user(user_id=resourceID, return_json=True) except (InstagramAPIError, InstagramClientError) as error: if (error.status_code == 400): if (error.error_type == "APINotAllowedError"): responseCode = -4 break elif (error.error_type == "APINotFoundError"): responseCode = -5 break else: if (retrys < maxNumberOfRetrys): sleepSeconds = 2 ** sleepSecondsMultiply self.echo.out(u"API call error. Trying again in %02d second(s)." % sleepSeconds, "EXCEPTION") time.sleep(sleepSeconds) sleepSecondsMultiply += 1 retrys += 1 else: raise SystemExit("Maximum number of retrys exceeded.") else: output = open(os.path.join(usersDataDir, "%s.user" % resourceID), "w") json.dump(userInfo, output) output.close() # Extract user counts to send back to SaveResourcesFilter # userCounts = {"counts_media": userInfo["counts"]["media"], # "counts_follows": userInfo["counts"]["follows"], # "counts_followedby": userInfo["counts"]["followed_by"]} # extraInfo["SaveResourcesFilter"].append((resourceID, userCounts)) break # Get rate remaining to send back to InstagramAppFilter extraInfo["InstagramAppFilter"]["appname"] = application["name"] extraInfo["InstagramAppFilter"]["apprate"] = int(api.x_ratelimit_remaining) return ({#"crawler_name": socket.gethostname(), "response_code": responseCode}, extraInfo, None)
class Instagram: def __init__(self, api_index): self.api = InstagramAPI( client_id=credentials.instagram_credentials[api_index] ["client_id"], client_secret=credentials.instagram_credentials[api_index] ["client_secret"]) self.access_token = credentials.instagram_credentials[api_index][ "access_token"][0] return None def get_user(self, username): users = self.api.user_search(username) user_list = [ u for u in users if u.username.lower() == username.lower() ] if not user_list: print("Couldn't find Instagram information for " + username) return None else: return user_list[0] def check_rate_limit(self): while True: rl = self.api.x_ratelimit_remaining rl = int(rl) if rl else None if rl and rl < configs.min_instagram_rate_limit_remaining: print("RATE LIMIT: " + str(rl)) time.sleep(configs.instagram_seconds_sleep_after_rate_limit) break else: print("rate limit: " + str(rl)) break return True def get_user_by_id(self, user_id): self.check_rate_limit() try: return self.api.user(user_id) except: return None def get_user_data_dict(self, user): try: user_id = user.id response = urllib2.urlopen("https://api.instagram.com/v1/users/" + str(user_id) + "/?access_token=" + self.access_token) except: return dict() data = json.load(response) info = { self.tkey(k): data["data"][k].encode("utf8") for k in ["username", "bio", "website", "full_name", "id"] } info["link"] = "https://instagram.com/" + info["username"] + "/" counts = { self.tkey(k): data["data"]["counts"][k] for k in ["media", "follows", "followed_by"] } info.update(counts) return info def get_follows(self, user_id): # rate limit issue happens here self.check_rate_limit() follows, next_ = self.api.user_follows(user_id) while next_: self.check_rate_limit() more_follows, next_ = self.api.user_follows(user_id, with_next_url=next_) follows.extend(more_follows) ret = [int(f.id) for f in follows if f.id] return ret @staticmethod def tkey(key): tk = { "full_name": "name", "media": "num_posts", "follows": "num_follows", "followed_by": "num_followers", "bio": "description", "id": "user_id" } ret = tk[key] if key in tk else key ret = ret.encode("utf8") return ret
from instagram.client import InstagramAPI CLIENT_ID = "" client_secret = "" api = InstagramAPI(CLIENT_ID, client_secret) user_id = "jerrinjoe" api.user(user_id) print(api.user_media_feed())
def get_report(request): # Аутентификация profile = Profile.from_request(request) if profile is None: raise Exception("Залогиньтесь, сударь!") 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_video = 0 count_photo = 0 prepare_hours = [[0, 0] for i in range(24)] filters_dict = {} filters_list = [] tags_dict = {} tags_list = [] last_media = [] # обработка всех медиа for media in all_media: likes += media.like_count comments += media.comment_count if media.type == "video": count_video += 1 if media.type == "image": count_photo += 1 # распределение по времени prepare_hours[media.created_time.hour][0] += 1 prepare_hours[media.created_time.hour][1] += media.like_count # фильтры if filters_dict.get(media.filter): filters_dict[media.filter][0] += 1 filters_dict[media.filter][1] += media.like_count else: filters_dict[media.filter] = [1, media.like_count] # хэштеги for tag in media.tags: if tag.name == 'дазаебисьвобщемта': continue if tags_dict.get(tag.name): tags_dict[tag.name][0] += 1 tags_dict[tag.name][1] += media.like_count else: tags_dict[tag.name] = [1, media.like_count] # формирование списка фильтров for key, value in filters_dict.items(): filters_list.append((key, value[1]/value[0])) filters_list.sort(key=lambda x: x[1], reverse=True) if len(filters_list) > 3: filters = [a for a, b in filters_list[:3]] else: filters = [a for a, b in filters_list] # формирование списка тегов for key, value in tags_dict.items(): tags_list.append((key, value[1] / value[0])) tags_list.sort(key=lambda x: x[1], reverse=True) if len(tags_list) > 5: tags = [a for a, b in tags_list[:5]] else: tags = [a for a, b in tags_list] # распределение по времени в преглядном виде hours = [b/a if a is not 0 else 0 for a, b in prepare_hours] # получаем вчерашний день yesterday = datetime.datetime.now() - datetime.timedelta(days=7) # последние медиа (за последний день) for media in all_media: if media.created_time < yesterday: break target = { 'image': media.images['thumbnail'].url, 'like_count': media.like_count, 'comment_count': media.comment_count } last_media.append(target) # самые обсуждаемые медиа all_media.sort(key=lambda x: x.comment_count, reverse=True) max_comments = all_media[:8] max_comments_images = [] for media in max_comments: max_comments_images.append({ 'image': media.images['thumbnail'].url, 'like_count': media.like_count, 'comment_count': media.comment_count }) # самые популярные медиа all_media.sort(key=lambda x: x.like_count, reverse=True) max_like = all_media[:8] max_like_images = [] for media in max_like: max_like_images.append({ 'image': media.images['thumbnail'].url, 'like_count': media.like_count, 'comment_count': media.comment_count }) # Среднее кол-во комментариев comments_average = comments/len(all_media) # Среднее вол-во лайков likes_average = likes/len(all_media) # показатель вовлеченности involvement = (likes_average/follows)*100 # формирование отета response = { 'follows': follows, 'followed_by': followed_by, 'count_media': count_media, 'count_video': count_video, 'count_photo': count_photo, 'likes': likes, 'comments': comments, 'tags': tags, 'max_like': max_like_images, 'max_comments': max_comments_images, 'filters': filters, 'comments_average': comments_average, 'likes_average': likes_average, 'involvement': round(involvement, 1), 'hours': hours, 'last_media': last_media } return JsonResponse(response)
#begin_user_id = '19185689' # - Kayley Cuoco #begin_user_id = '1513623915' # - Ragav - Zero followers, zero following #begin_user_id = '18428658' # - Kim Kardashian #begin_user_id = '1867327' # - Bill Gates # initiliaze the client client = ist.client_packet(client_id = client_id, client_secret = client_secret, redirect_uri = redirect_uri, begin_user_id = begin_user_id) access_token = client.access_token( True ) # once you run the code first time. Reset this inside the instagram.py file and start using false flag api = InstagramAPI(client_id = client.client_id, client_secret = client.client_secret, access_token=access_token[0]) # begin api first use print "\n\n\n\n\n\n\n#########+++++++++=========+++++++++#########" print "Crawler Details :" tryflag = True while tryflag: try: user = api.user('1513623915') tryflag = False except: print "sleeping .. " print "Remaining API requests " + str(api.x_ratelimit_remaining) + " of " + str(api.x_ratelimit) time.sleep(60) print "awake .. " print "Initialized user :"******"User Id :" + user.id print "User Full Name: " + user.full_name print "Number of Images Posted : " + str(user.counts['media']) print "Number of Followers : " + str(user.counts['followed_by']) print "Number Follows: " +str(user.counts['follows']) print "#########+++++++++=========+++++++++#########\n\n\n\n\n\n\n"
def success_metrics(): # if instagram info is in session variables, then display user photos if 'instagram_access_token' in session and 'instagram_user' in session: api = InstagramAPI(access_token=session['instagram_access_token']) users_to_follow = 'knowlita, acme_nyc' user_list = users_to_follow.split(',') user_list = [x.strip(' ') for x in user_list] def find_insta_handles(text): p = re.compile('(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([_A-Za-z]+[_A-Za-z0-9]+)') return p.findall(text) def tagged_users(comment): handles = find_insta_handles(comment) handles = [str(i) for i in handles] handles = [y for y in handles if y not in user_list] return handles knowlita_contest_img_id = '937178239574293509_922345846' acme_contest_img_id = '937173533246931090_28306327' contest_imgs = [knowlita_contest_img_id, acme_contest_img_id] valid_participants = [] tagged = [] ntp = [] tp = [] for img_id in contest_imgs: contest_comments = api.media_comments(media_id = img_id) for comment in contest_comments: for user in tagged_users(comment.text): tagged.append(user) if len(tagged_users(comment.text)) >= 3: valid_participants.append(comment.user.username) if comment.user.username in tagged: tp.append(comment.user.username) else: ntp.append(comment.user.username) user_search = api.user_search(q='knowlita') knowlita = api.user(user_search[0].id) num_tagged_participants = len(tp) num_untagged_participants = len(ntp) num_tagged_users = len(tagged) num_valid_participants = len(valid_participants) num_followers = knowlita.counts['followed_by'] virality_coef = float(num_tagged_participants)/num_tagged_users contest_engagement = float(num_untagged_participants)/num_followers templateData = { 'valid_participants' : valid_participants, 'tp' : tp, 'ntp' : ntp, 'num_untagged_participants' : str(num_untagged_participants), 'num_tagged_participants' : str(num_tagged_participants), 'num_valid_participants' : str(num_valid_participants), 'num_tagged_users' : str(num_tagged_users), 'num_followers' : str(num_followers), 'virality_coef' : str(round(virality_coef,4)), 'contest_engagement' : str(round(contest_engagement,4)), } return render_template('success_metrics.html', **templateData) else: return redirect('/connect')
from instagram.client import InstagramAPI access_token = "593674689.02ce2b1.cb812cd9bef24efda4ed366e7e9ff252" api = InstagramAPI(access_token=access_token) user_info = api.user('society6') print user_info
def loop_printer(ine): for i in ine: if type(i) == list: loop_printer(i) elif type(i) == dict: print(i) loop_printer(i) else: print('OLOLOLO', i) loop_printer(line['data']) #line = ' '.join(line['data']) #line = simplejson.loads(line) #print(len(line['data']), type(line['data']), line['data']) #print(api.user_follows(user_id2)) #print(api.user_followed_by(user_id2)) print(api.user(user_id)) #print(api.user_media_feed()) #print(api.user_liked_media()) print(api.user_search('jogryn')) #works print(api.user_relationship(user_id2)) #works print(line['data'][0]['images']) recent_media, next_ = api.user_recent_media() photos = [] for media in recent_media: photos.append('<img src="%s"/>' % media.images['thumbnail'].url)
def single_artist(request, *args, **kwargs): """View single artist""" if "slug" in kwargs: try: username = kwargs["slug"] user = User.objects.get(username=username) display = "artist" except: return HttpResponse("Error") else: if not request.user.is_authenticated: return HttpResponse("Error") user = request.user display = "profile" string = get_profile_string(kwargs, user) audios = Audio.objects.filter(user=user, is_complete=True).order_by('-added') playlists = AudioPlaylist.objects.filter(user=user).order_by('-added') videos = Video.objects.filter(user=user, is_complete=True).order_by('-added') social = UserSocial.objects.filter(user=UserProfile.objects.get(user=user)) if len(social): social = {i.account: i.link for i in social} user_status = "" genres = None if audios: genres = Set([i.genre for i in audios]) user_status_list = UserStatus.objects.filter(user=UserProfile.objects.get( user=user)).order_by('-created') if len(user_status_list): user_status = user_status_list[0].status try: a = UserSocialAuth.objects.get(user_id=user.id, provider='instagram') access_token = a.access_token api = InstagramAPI(access_token=access_token, client_secret=settings.SOCIAL_AUTH_INSTAGRAM_SECRET) recent_media, next_ = api.user_recent_media(user_id=int(a.uid), count=23) imgs = [] for media in recent_media: imgs.append(media.images['standard_resolution'].url) instagram = imgs nickname = str(api.user()).split(':')[1].replace(' ', '') except UserSocialAuth.DoesNotExist: instagram = '' nickname = '' template_name = 'single-artist.html' template_data = { "string": string, 'audios': audios, 'instagram': instagram, 'nickname': nickname, 'playlists': playlists, 'videos': videos, 'user': user, 'display': display, 'social': social, 'user_status': user_status, 'genres': genres } return render_to_response(template_name, template_data, context_instance=RequestContext(request))
def myRecentLikes(): #written by Tim content = "<h2>User's Recent Likes</h2>" access_token = request.session['access_token'] if not access_token: print "Missing Access Token" return 'Missing Access Token' try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) _user_id =(api.user()).id liked_media, next = api.user_liked_media(count=9) print "Webpage is loading...." counter = 0; photos = [] filters = [] usersThatLiked = [] content += "<div id='liked_media'>" content +="<style>figure{ width:33.3%; float:left; margin:0px; text-align:center; padding:0px;} </style>" for media in liked_media: content += "<figure>" filters.append(media.filter) usersThatLiked.extend(api.media_likes(media_id = media.id)) counter = counter +1 #photos.append('<div style="float:left;">') if(media.type == 'video'): content += ('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url())) #photos.append('<video controls width height="150"><source type="video/mp4" src="%s"/></video>' % (media.get_standard_resolution_url())) else: content+= ("<img src=%s/>" % (media.get_low_resolution_url())) content+= ("<figcaption>@%s" % (media.user.username)) content+= "</figcaption>" #photos.append('<div class="floated_img"><img src="%s"/></div>' % (media.get_thumbnail_url())) content+="</figure>" content+= "</div><br>" filterCounter = Counter(filters) #makes a counter object based on the list of filters usersThatLikedCounter = Counter(usersThatLiked) #counts instances of any person liking the same pictures that the user did #outputs a ranked list of the filters used in the liked posts above content += "<h2> Filters used (count): </h2><ol>" for filterWithCount in filterCounter.most_common(): content += "<li>" + filterWithCount[0] +" ("+str(filterWithCount[1])+")</li>" content += "</ol>" #gets a list of people that our user follows (used to make accurate suggestions of people to follow) following_list, next_ = api.user_follows() #make a set of user id numbers following_ids = set() for user in following_list: following_ids.add(user.id) #outputs the most common users that liked the same media content += "<h2> Top users that also liked these posts: </h2><p>Below is a list of users who also liked the posts above, if you are not already following them, there will be a link.<ol>" for userWithCount in usersThatLikedCounter.most_common(11): if (userWithCount[0].id != _user_id): #makes sure that the current user is not displayed content += "<li>" + userWithCount[0].username +" ("+str(userWithCount[1])+" similar likes)" if(userWithCount[0].id not in following_ids): content += (" <a href='/user_follow/%s'>Follow</a>" % (userWithCount[0].id)) content += (" <p>Here's a link to their Instagram Profile:" ) content += (" <a href='https://www.instagram.com/%s'>instagram.com/%s</a></p></li>" % (userWithCount[0].username, userWithCount[0].username)) content += "</ol>" except Exception as e: print "in exception ..." print(e) return "%s %s <br/>Remaining API Calls = %s/%s" % (get_nav(),content,api.x_ratelimit_remaining,api.x_ratelimit)
if code: access_token, user_info = api.exchange_code_for_access_token( code) if not access_token: return 'Could not get access token' # Sessions are used to keep this data OAUTH_TOKEN = access_token api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) userid = user_info['id'] username = user_info['username'] post_ct = api.user().counts['media'] else: return "Uhoh no code provided" except Exception, e: return "Error in acquire step 1: " + str(e) try: if username == alleged_user: unique_id = np.random.randint(1e10) conn = util.connect_db() if medium == "twitter": register_user(medium, userid, username, unique_id, post_ct, conn, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) elif medium == "instagram":
#!/usr/bin/env python from instagram.client import InstagramAPI import sys import time # You need to fill out these 3 lines. # Need to create and instagram dev account to get an access token and client secret # Input instagram userID of the person you wish the box to monitor. access_token = "" client_secret = "" user_id = "" previous_followers = 0 api = InstagramAPI(access_token=access_token, client_secret=client_secret) while True: try: user_info = api.user(user_id=user_id) number_of_followers = user_info.counts["followed_by"] if number_of_followers != previous_followers: print "Followers: %s - %s" % (number_of_followers, time.asctime(time.localtime(time.time()))) previous_followers = number_of_followers time.sleep(1) except KeyboardInterrupt: sys.exit(0)
from instagram.client import InstagramAPI # https://www.instagram.com/oauth/authorize/?client_id=0279ab24db9344f69052c0881b4bf4f4&redirect_uri=https://github.com/kenhua-l/small-projects&response_type=code # code=41cbfe90b5774c3fa54fe1a05f7d4481 # curl -F 'client_id=0279ab24db9344f69052c0881b4bf4f4' -F 'client_secret=9c5ee7cebda144da87b9fb6138aab832' -F 'grant_type=authorization_code' -F 'redirect_uri=https://github.com/kenhua-l/small-projects' -F 'code=41cbfe90b5774c3fa54fe1a05f7d4481' https://api.instagram.com/oauth/access_token # {"access_token": "180513666.0279ab2.3a368108977c4986808e391c4502fef8", "user": {"id": "180513666", "username": "******", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/18580026_424685234572292_4995985617465638912_a.jpg", "full_name": "Liew Ken Hua", "bio": "\ud83d\ude0e\ud83d\ude1c\ud83d\ude18 | \ud83c\udfa8", "website": "", "is_business": false}} access_token = "180513666.0279ab2.3a368108977c4986808e391c4502fef8" client_secret = "9c5ee7cebda144da87b9fb6138aab832" api = InstagramAPI(access_token=access_token, client_secret=client_secret) # user_id="180513666" use = api.user("180513666") print use
class RecolectorUsuario(Recolector): """ Recolecta la información del usuario dado un nombre de usuario, Es muy importante porque todas las queries en Instagram usan id y no nombre. Por lo que es necesario hacer un patrón proxy """ def __init__(self, escritor): super(RecolectorUsuario, self).__init__(escritor) self.authorizator = GetAuthorizations(4999) self.apoyo = ApoyoInstagram() self.api = None self.inicializa() def inicializa(self): self.authorizator.load_token() client_id, client_secret = self.authorizator.get_secret() self.api = InstagramAPI(client_id=client_id, client_secret=client_secret) def recolecta(self, query, forceDownload = False): """ Implementado proxy por ahora solo admite un usuario por nombre de usuario """ id = self.apoyo.isUserInDBByUsername(query) if id == False: usuariosArray = self.privateRealizaConsulta(query) self.guarda(usuariosArray) else: if self.apoyo.isUserCompleteInDBByUsername(query) == True: if forceDownload == True: usuariosArray = self.privateRealizaConsulta_id(id) self.guarda(usuariosArray) else: usuariosArray = self.privateRealizaConsulta_id(id) self.guarda(usuariosArray) def guarda(self, arrayDatos): #if len(self.escritores) == 0: # print arrayDatos for escritor in self.escritores: escritor.escribe(arrayDatos) def privateRealizaConsulta(self, query): if self.authorizator.is_limit_api(): raise Exception('LIMITE') try: users = self.api.user_search(q=query, count="1") if len(users) <= 0: return [] user = users[0] identificador = user.id self.authorizator.add_query_to_key() usuarioFinal = self.api.user(identificador) self.authorizator.add_query_to_key() return [usuarioFinal] except Exception, e: self.authorizator.add_query_to_key() print e if "429" in str(e): raise Exception('LIMITE') return []
def search(username, access_token): #user_q = User.query.filter_by(nickname = username).first() #if user_q: # api = InstagramAPI(access_token=user_q.access_token) #else: # file_with_token = open('app/access_token', "r") # access_token = file_with_token.readline().split()[0] api = InstagramAPI(access_token=access_token) user_id = [] for user in api.user_search(q=username): if user.username == username: user_id = [user] #print user_id #print type(user_id) #print 'OK_TEST_1' if user_id: recent_media, next_ = api.user_recent_media(user_id=str(user_id[0].id), count=11) liked = api.user_liked_media(user_id=str(user_id[0].id)) liked = liked[:-1] user_liked = {} for media in liked[0]: if 'user' in dir(media): if media.user.username in user_liked: user_liked[media.user.username] += 1 else: user_liked[media.user.username] = 1 user_liked_sorted = [] for pair in reversed(sorted(user_liked.items(), key=lambda item: item[1])): user_liked_sorted.append([pair[0], pair[1]]) locations = {} for feed in recent_media: if 'location' in dir(feed): loc = feed.location.name.lower() if loc: if loc in locations: locations[loc] += 1 else: locations[loc] = 1 locations_sorted = [] for pair in reversed(sorted(locations.items(), key=lambda item: item[1])): locations_sorted.append([pair[0], pair[1]]) tags = {} for feed in recent_media: if 'tags' in dir(feed): for tag in feed.tags: key = tag.name.lower() if key in tags: tags[key] +=1 else: tags[key] = 1 tags_sorted = [] for pair in reversed(sorted(tags.items(), key=lambda item: item[1])): tags_sorted.append([pair[0], pair[1]]) captions = {} for feed in recent_media: if 'caption' in dir(feed): if 'text' in dir(feed.caption): caption = feed.caption.text.lower() + ' ' word = "" for symb in caption: if (ord(symb) == ord('#')) or (ord(u'a') <= ord(symb) <= ord(u'z')) or (ord(u'а') <= ord(symb) <= ord(u'я')): word+=symb else: if word: if not (word[0] == '#'): if (ord(u'а') <= ord(word[0]) <= ord(u'я')): word = morph.parse(word)[0].normal_form type = morph.parse(word)[0].tag.POS if type == 'PREP' or type == 'CONJ' or type == 'PRCL' or type == 'INTJ' or type == 'NUMR' or type == 'COMP': continue elif (ord(u'a') <= ord(word[0]) <= ord(u'z')): word = stemmer.stem(word) type = nltk.pos_tag(nltk.tokenize.word_tokenize(word))[0][1] if type == 'IN' or type == 'CC' or type == 'RB' or type == 'JJR': continue if word not in stopwords: if word in captions: captions[word]+=1 else: captions[word]=1 word = "" comments = [] comment_rating = {} for media in recent_media: for obj in media.comments: user_commented = unicode(obj.user.username) if user_commented in comment_rating: comment_rating[user_commented] += 1 else: comment_rating[user_commented] = 1 comment = obj.text.lower() + ' ' comments.append(obj.text) word = "" for symb in comment: if (ord(symb) == ord('@')) or (ord(symb) == ord('#')) or (ord(u'a') <= ord(symb) <= ord(u'z')) or (ord(u'а') <= ord(symb) <= ord(u'я')): word+=symb else: if word: if not ((word[0] == '#') or (word[0] == '@')): if (ord(u'а') <= ord(word[0]) <= ord(u'я')): word = morph.parse(word)[0].normal_form type = morph.parse(word)[0].tag.POS if type == 'PREP' or type == 'CONJ' or type == 'PRCL' or type == 'INTJ' or type == 'NUMR' or type == 'COMP': continue elif (ord(u'a') <= ord(word[0]) <= ord(u'z')): word = stemmer.stem(word) type = nltk.pos_tag(nltk.tokenize.word_tokenize(word))[0][1] if type == 'IN' or type == 'CC' or type == 'RB' or type == 'JJR': continue if word not in stopwords: if word in captions: captions[word]+=1 else: captions[word]=1 word = "" captions_sorted = [] for pair in reversed(sorted(captions.items(), key=lambda item: item[1])): captions_sorted.append([pair[0], pair[1]]) comment_rating_sorted = [] for pair in reversed(sorted(comment_rating.items(), key=lambda item: item[1])): comment_rating_sorted.append([pair[0], pair[1]]) images = {} videos = [] filters = {} likes_of_users = {} count_of_all_likes = 0 for media in recent_media: if 'videos' not in dir(media) and 'images' in dir(media): if (media.images['standard_resolution'].url) in images: images[media.images['standard_resolution'].url] += media.like_count else: images[media.images['standard_resolution'].url] = media.like_count filter = unicode(media.filter) if filter in filters: filters[filter] += 1 else: filters[filter] = 1 if 'videos' in dir(media): videos.append(media.videos['standard_resolution'].url) for usr in media.likes: if usr.username in likes_of_users: likes_of_users[usr.username] += 1 else: likes_of_users[usr.username] = 1 count_of_all_likes+=media.like_count likes_of_users_sorted = [] for pair in reversed(sorted(likes_of_users.items(), key=lambda item: item[1])): likes_of_users_sorted.append([pair[0], pair[1]]) images_sorted = [] for pair in reversed(sorted(images.items(), key=lambda item: item[1])): images_sorted.append([pair[0], pair[1]]) filters_sorted = [] for pair in reversed(sorted(filters.items(), key=lambda item: item[1])): filters_sorted.append([pair[0], pair[1]]) user_bsc = api.user(user_id[0].id) basic_information = [user_bsc.id, user_bsc.full_name, user_bsc.website, user_bsc.counts["media"], count_of_all_likes, user_bsc.counts["follows"], user_bsc.counts["followed_by"], user_bsc.profile_picture, user_bsc.bio] #print "OK_TEST_2" return [basic_information, images_sorted, videos, captions_sorted, tags_sorted, locations_sorted, comments, user_liked_sorted, likes_of_users_sorted, comment_rating_sorted, filters_sorted] else: return [] # print "IMAGES" # for obj in images: # print obj # # print "VIDEOS" # for obj in videos: # print obj # # print "CAPTIONS:" # for obj in captions_sorted: # print obj[0], obj[1] # # print "HASHTAGS:" # for obj in tags_sorted: # print obj[0], obj[1] # # print "PLACES:" # for obj in locations_sorted: # print obj[0], obj[1] # # print "MOST POPULAR PLACES:" # mstpopular = locations_sorted[:3] # for obj in mstpopular: # print obj[0], obj[1]
def run_contest(): # if instagram info is in session variables, then display user photos if 'instagram_access_token' in session and 'instagram_user' in session: api = InstagramAPI(access_token=session['instagram_access_token']) identifier = re.compile("We've teamed up with our friends") users_to_follow = 'knowlita, acme_nyc' user_list = users_to_follow.split(',') user_list = [x.strip(' ') for x in user_list] uids = [] for key_user in user_list: user_search = api.user_search(q=key_user) uids.append(user_search[0].id) media_ids = [] for uid in uids: recent_media, next = api.user_recent_media( user_id=uid , count=30) for media in recent_media: if media.caption != None: if identifier.search(media.caption.text): media_ids.append(media.id) else: recent_media, next = api.user_recent_media( with_next_url = next) for media in recent_media: if media.caption != None: if identifier.search(media.caption.text): media_ids.append(media.id) media_ids = [media_ids[0],media_ids[2]] def find_insta_handles(text): p = re.compile('(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([_A-Za-z]+[_A-Za-z0-9]+)') return p.findall(text) def tagged_users(comment): handles = find_insta_handles(comment) handles = [str(i) for i in handles] handles = [y for y in handles if y not in user_list] return handles valid_participants = [] tagged = [] ntp = [] tp = [] for img_id in media_ids: contest_comments = api.media_comments(media_id = img_id) for comment in contest_comments: if comment.user.username not in user_list: for user in tagged_users(comment.text): tagged.append(user) if len(tagged_users(comment.text)) >= 3 and comment.user.username not in user_list and comment.user.username not in valid_participants: valid_participants.append(comment.user.username) if comment.user.username in tagged: tp.append(comment.user.username) else: ntp.append(comment.user.username) ## note that this measure is technically wrong, as the users could have overlapping followers tot_num_followers = 0 for key in user_list: key_search = api.user_search(q=key) key_basics = api.user(key_search[0].id) tot_num_followers += key_basics.counts['followed_by'] num_tagged_participants = len(tp) num_untagged_participants = len(ntp) num_tagged_users = len(tagged) num_valid_participants = len(valid_participants) virality_coef = float(num_tagged_participants)/num_tagged_users contest_engagement = float(num_untagged_participants)/tot_num_followers templateData = { 'media_ids' : media_ids, #'comments' : contest_comments, 'valid_participants' : valid_participants, 'tp' : tp, 'ntp' : ntp, 'tagged' : tagged, 'num_untagged_participants' : str(num_untagged_participants), 'num_tagged_participants' : str(num_tagged_participants), 'num_valid_participants' : str(num_valid_participants), 'num_tagged_users' : str(num_tagged_users), 'num_followers' : str(tot_num_followers), 'virality_coef' : str(round(virality_coef,4)), 'contest_engagement' : str(round(contest_engagement,4)), } return render_template('run_contest.html', **templateData) else: return redirect('/connect')
count = 1 for media in tagged_media: print '\n',RED+'Post'+ENDCOLOR, count count +=1 ''' Trying to do sentiment analysis of the image, but as the Instagram database is secure, we do not get access to the private https: URLs img_url = media.images['standard_resolution'].url img_response = alchemyapi.imageExtraction('url', img_url) if img_response['status'] == 'OK': print(json.dumps(img_response, indent=4)) else: print('Error in image extraction call: ', img_response['statusInfo']) ''' # Printing the caption of the image and doing sentiment analysis of the # caption targeted towards CapitalOne name = api.user(media.user.id) print name if hasattr(media, 'caption'): print YELLOW+"Caption :"+ENDCOLOR, media.caption.text response = alchemyapi.sentiment_targeted('text', media.caption.text, 'capital') if response['status'] == 'OK': print GREEN+'Sentiment type: '+ENDCOLOR, response['docSentiment']['type'] if 'score' in response['docSentiment']: print GREEN + 'Sensitivity Score: '+ENDCOLOR, response['docSentiment']['score'] else: print('Error in targeted sentiment analysis call: ', response['statusInfo'])
from instagram.client import InstagramAPI from urlparse import urlparse, parse_qs from progressbar import ProgressBar, SimpleProgress, Bar import sys, string max_photos_per_request = 100 total_likes = num_returned = 0 access_token = string.strip(open("token.txt").read()) api = InstagramAPI(access_token=access_token) if len(sys.argv) == 2: user = api.user_search(sys.argv[1], 1)[0] # optional argument: user id (default: self) else: user = api.user("self") media_count = api.user(user.id).counts["media"] pbar = ProgressBar(widgets=[SimpleProgress(), " photos ", Bar()], maxval=media_count).start() next_max_id = "" while True: recent_media, next = api.user_recent_media(user_id=user.id, count=max_photos_per_request, max_id=next_max_id) num_returned += len(recent_media) if num_returned > pbar.maxval: # Instagram media count isn't always accurate :( pbar.maxval = num_returned pbar.update(num_returned) for media in recent_media: