def channelback(request): if request.method == 'POST': metadata = request.POST.get('metadata', '') newState = request.POST.get('state', '') message = request.POST.get('message', '') parentId = request.POST.get('parent_id', '') recipientId = request.POST.get('recipient_id', '') metaJson = json.loads(metadata) client_id = metaJson['client_id'] client_secret = metaJson['client_secret'] access_token = metaJson['token'] name = metaJson['name'] mediaIdSplit = parentId.split('-') media_id = mediaIdSplit[2] api = InstagramAPI(access_token=access_token, client_secret=client_secret) comment = api.create_media_comment(media_id, message) mediaComments = api.media_comments(media_id) commentId = '' for mediaComment in mediaComments: if mediaComment.text == message: commentId = mediaComment.id newCommentId = "cmnt-" + commentId + '-' + media_id print(newCommentId) response_data = {} response_data['external_id'] = newCommentId response_data['allow_channelback'] = True return HttpResponse(json.dumps(response_data, ensure_ascii=False), content_type="application/json;charset=UTF-8")
def get_all_comments_from_media(user, access_token, filename, min_timestamp, max_timestamp): comments_table = {'Data' : []} api = InstagramAPI(access_token=access_token) # Remember to specify a friggin timestamp to prevent going over # the limit of api calls recent_media, next = api.user_recent_media(user_id=user, min_timestamp=min_timestamp, max_timestamp=max_timestamp) while next: more_media, next = api.user_recent_media(with_next_url=next) recent_media.extend(more_media) for media in recent_media: comments = api.media_comments(media.id) for comment in comments: comments_table['Data'].append({'User' : comment.user.username, 'Comment' : comment.text.encode('utf-8'), 'Media_ID' : media.id, 'Image' : media.link, 'Created_at' : comment.created_at}) followers_data = comments_table['Data'] csv_file = open(filename, 'wb') csv_writer = csv.writer(csv_file) count = 0 for data in followers_data: if count == 0: header = data.keys() csv_writer.writerow(header) count += 1 csv_writer.writerow(data.values()) csv_file.close() print "%s created successfully" % filename return comments_table
access_token = '' api = InstagramAPI(client_id=client_id, client_secret=client_secret, access_token=access_token) def username_to_id(username): """Accepts a username and returns its ID.""" user = api.user_search(q=username, count=1) if username != user[0].username: logger.error('Username to ID failed') return user[0].id username_selfies = ['arikunc0r0'] for i in username_selfies: userid = username_to_id(i) print '=============================' print 'mulai dari user id =', userid print 'username =', i all_media_ids = [] #all_media_caps = [] #all_media_img = [] media_ids, next = api.user_recent_media(user_id=str(userid), count=3) print(media_ids) for media_id in media_ids: print(media_id.id) print(api.media_comments(media_id.id))
def fun2(): api = InstagramAPI(access_token='YOUR_ACCESS_TOKEN', client_secret='YOUR_CLIENT_SECRET') recent_media, next_ = api.user_recent_media(user_id='concept_club') media_id = recent_media[0].id # XXX return api.media_comments(media_id)
class provider(basicProvider): ''' This class is used to: 1. Make the connection to the Instagram API 2. Get user's Photos 3. Get OPENi album Photos 4. Post Photos to OPENi album ''' def __init__(self, access_token): ''' Initiate the connector ''' self.connector = InstagramAPI(access_token=access_token) # region Media API # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Media_API # region Photo Object # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Photo_Mapping def get_a_photo(self, data): ''' GET API_PATH/[PHOTO_ID] ''' # /media/media-id (ie media/628147512937366504_917877895) print data['media_id'] raw_data = self.connector.media(data['media_id']) print raw_data response = { 'meta': { 'total_count': 1, 'next': None }, 'data': [ self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes) ] } return response def get_all_photos_for_account(self, data): ''' GET API_PATH/[ACCOUNT_ID]/photos ''' # /users/user-id (ie users/917877895) raw_datas, next = self.connector.user_recent_media(data['account_id']) print raw_datas response = { 'meta': { 'total_count': len(raw_datas), 'next': next }, 'data': [] } for raw_data in raw_datas: response['data'].append( self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes)) return response # region Connections def get_photo_comments(self, data): ''' GET API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) raw_datas = self.connector.media_comments(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data': [] } for raw_data in raw_datas['data']: response['data'].append( self.format_comment_response( raw_data['id'], 'Photo Comment', 'openi', defJsonRes, raw_data['from']['id'], raw_data['from']['username'], defJsonRes, raw_data['created_time'], defJsonRes, defJsonRes, raw_data['text'], defJsonRes)) return response def post_comment(self, data): ''' POST API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) # 'error_message': 'Please visit http://bit.ly/instacomments for commenting access' Please email apidevelopers[at]instagram.com for access. return defaultMethodResponse def delete_comment(self, data): ''' DELETE API_PATH/[COMMENT_ID] ''' # /media/media-id/comments/comment-id (ie media/628147512937366504_917877895/comments/628902539272471262) response = self.connector.delete_comment(data['media_id'], data['comment_id']) return response def like_a_photo(self, data): ''' POST API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.like_media(data['media_id']) return response def get_photo_likes(self, data): ''' GET API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) raw_datas = self.connector.media_likes(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data': [] } for raw_data in raw_datas['data']: response['data'].append( self.format_comment_response( defJsonRes, #id 'Photo Like', #obj_type 'openi', #service defJsonRes, #url raw_data['id'], #from:id raw_data['username'], #from:username defJsonRes, #from:url defJsonRes, #time:created_time defJsonRes, #time:edited_time defJsonRes #target_id )) return 'Not supported by this service' def unlike_photo(self, data): ''' DELETE API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.unlike_media(data['media_id']) return response
from instagram.client import InstagramAPI access_token = "access token goes here" client_secret = "client secret goes here" api = InstagramAPI(access_token=access_token, client_secret=client_secret) print(api.media_comments(media_id))
class Instagram: def __init__(self): self.api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI) def set_access_token(self, access_token): self.api = InstagramAPI(access_token=access_token) def media_popular(self, **params): popular = memcache.get("popular_feed") if not popular: popular = self.api.media_popular(count=params["count"], max_id=params["max_id"]) memcache.add("popular_feed", popular, 300) return popular def user_media_feed(self, **params): user_id = params["user_id"] max_id = params["max_id"] count = params["count"] feed = memcache.get("user_media_feed_%s_%s" % (user_id, max_id)) if not feed: feed = self.api.user_media_feed(count=count, max_id=max_id) memcache.add("user_media_feed_%s_%s" % (user_id, max_id), feed, 300) return feed def user_liked_feed(self, **params): user_id = params["user_id"] max_id = params["max_id"] count = params["count"] feed = memcache.get("user_liked_feed_%s_%s" % (user_id, max_id)) if not feed: feed = self.api.user_liked_feed(count=count, max_like_id=max_id) memcache.add("user_liked_feed_%s_%s" % (user_id, max_id), feed, 300) return feed def user(self, user_id): user = memcache.get("user_%s" % (user_id)) if not user: user = self.api.user(user_id) user["full_name"] = escape(user["full_name"].encode("utf-8")) user["full_name"] = self._convert_emoji(user["full_name"]) memcache.add("user_%s" % (user_id), user, 300) return user def media(self, media_id): media = memcache.get("media_%s" % media_id) if not media: media = self.api.media(media_id) media.user["full_name"] = escape(media.user["full_name"].encode("utf-8")) media.user["full_name"] = self._convert_emoji(media.user["full_name"]) if media.caption: media.caption["text_original"] = media.caption["text"] media.caption["text"] = escape(media.caption["text"].encode("utf-8")) media.caption["text"] = self._convert_emoji(media.caption["text"]) media.caption["text"] = self._convert_tag_to_link(media.caption["text"]) memcache.add("media_%s" % media_id, media, 300) return media def media_comments(self, media_id): comments = memcache.get("media_comments_%s" % (media_id)) if not comments: converter = emoji.factory("softbank", "utf-8") converter.prefix = '<span class="emoji emoji_' converter.suffix = '"></span>' comments = self.api.media_comments(media_id) for comment in comments: comment["text"] = escape(comment["text"].encode("utf-8")) comment["text"] = self._convert_emoji(comment["text"]) comment["text"] = self._convert_tag_to_link(comment["text"]) memcache.add("media_comments_%s" % (media_id), comments, 300) return comments def media_likes(self, media_id): likes = memcache.get("media_likes_%s" % (media_id)) if not likes: likes = self.api.media_likes(media_id) memcache.add("media_likes_%s" % (media_id), likes, 300) return likes def user_recent_media(self, **params): user_id = params["user_id"] max_id = params["max_id"] feed = memcache.get("user_recent_media_%s_%s" % (user_id, max_id)) if not feed: feed = self.api.user_recent_media(user_id=user_id, max_id=max_id) memcache.add("user_recent_media_%s_%s" % (user_id, max_id), feed, 300) return feed def user_follows(self, **params): user_id = params["user_id"] count = params["count"] cursor = params["cursor"] follows = memcache.get("user_follows_%s_%s_%s" % (user_id, count, cursor)) if not follows: follows = self.api.user_follows(user_id=user_id, count=count, cursor=cursor) for user in follows[0]: user["full_name"] = escape(user["full_name"].encode("utf-8")) user["full_name"] = self._convert_emoji(user["full_name"]) memcache.add("user_follows_%s_%s_%s" % (user_id, count, cursor), follows, 300) return follows def user_followed_by(self, **params): user_id = params["user_id"] count = params["count"] cursor = params["cursor"] follows = memcache.get("user_followed_by_%s_%s_%s" % (user_id, count, cursor)) if not follows: follows = self.api.user_followed_by(user_id=user_id, count=count, cursor=cursor) for user in follows[0]: user["full_name"] = escape(user["full_name"].encode("utf-8")) user["full_name"] = self._convert_emoji(user["full_name"]) memcache.add("user_followed_by_%s_%s_%s" % (user_id, count, cursor), follows, 300) return follows def like_media(self, **params): user_id = params["user_id"] media_id = params["media_id"] max_id = params["max_id"] self.api.like_media(media_id) memcache.add("user_has_liked_%s_%s" % (user_id, media_id), True, 300) memcache.delete("media_likes_%s" % (media_id)) def unlike_media(self, **params): user_id = params["user_id"] media_id = params["media_id"] max_id = params["max_id"] self.api.unlike_media(media_id) memcache.delete("user_has_liked_%s_%s" % (user_id, media_id)) memcache.delete("media_likes_%s" % (media_id)) def create_media_comment(self, **params): media_id = params["media_id"] text = params["text"] self.api.create_media_comment(media_id=media_id, text=text) memcache.delete("media_%s" % media_id) memcache.delete("media_comments_%s" % media_id) def user_find_by_username(self, username): user = memcache.get("user_find_by_username_%s" % (username)) if not user: users = self.api.user_search(q=username, count=None) for u in users: if username == u["username"]: user = u memcache.add("user_find_by_username_%s" % (username), user) return user def tag_recent_media(self, **params): tag_name = params["tag_name"] count = params["count"] max_id = params["max_id"] feed = memcache.get("tag_recent_media_%s_%s" % (tag_name, max_id)) if not feed: feed = self.api.tag_recent_media(tag_name=tag_name, count=count, max_id=max_id) memcache.add("tag_recent_media_%s_%s" % (tag_name, max_id), feed, 300) return feed def get_authorize_login_url(self, **params): uri = memcache.get("authorize_login_uri") if not uri: uri = self.api.get_authorize_login_url(scope=params["scope"]) memcache.add("authorize_login_uri", uri, 300) return uri def _convert_emoji(self, text): converter = emoji.factory("softbank", "utf-8") converter.prefix = '<span class="emoji emoji_' converter.suffix = '"></span>' text = converter.convert(text) return text def _convert_tag_to_link(self, text): text = re.sub(r"#([a-zA-Z0-9\-]+)", '<a href="/tag/\g<1>">#\g<1></a>', text) return text def relationship(self, **params): owner_id = params["owner_id"] my_id = params["my_id"] relationship = memcache.get("relationship_%s_%s" % (my_id, owner_id)) if not relationship: relationship = self.api.relationship(owner_id) memcache.add("relationship_%s_%s" % (my_id, owner_id), relationship, 300) return relationship def follow_user(self, **params): owner_id = params["owner_id"] my_id = params["my_id"] relationship = self.api.follow_user(user_id=owner_id) memcache.delete("relationship_%s_%s" % (my_id, owner_id)) return relationship def unfollow_user(self, **params): owner_id = params["owner_id"] my_id = params["my_id"] relationship = self.api.unfollow_user(user_id=owner_id) memcache.delete("relationship_%s_%s" % (my_id, owner_id)) return relationship
class provider(basicProvider): ''' This class is used to: 1. Make the connection to the Instagram API 2. Get user's Photos 3. Get OPENi album Photos 4. Post Photos to OPENi album ''' def __init__(self, access_token): ''' Initiate the connector ''' self.connector = InstagramAPI(access_token=access_token) # region Media API # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Media_API # region Photo Object # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Photo_Mapping def get_a_photo(self, data): ''' GET API_PATH/[PHOTO_ID] ''' # /media/media-id (ie media/628147512937366504_917877895) print data['media_id'] raw_data = self.connector.media(data['media_id']) print raw_data response = { 'meta': { 'total_count': 1, 'next': None }, 'data': [self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes )] } return response def get_all_photos_for_account(self, data): ''' GET API_PATH/[ACCOUNT_ID]/photos ''' # /users/user-id (ie users/917877895) raw_datas, next = self.connector.user_recent_media(data['account_id']) print raw_datas response = { 'meta': { 'total_count': len(raw_datas), 'next': next }, 'data' : [] } for raw_data in raw_datas: response['data'].append(self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes )) return response # region Connections def get_photo_comments(self, data): ''' GET API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) raw_datas = self.connector.media_comments(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data' : [] } for raw_data in raw_datas['data']: response['data'].append(self.format_comment_response( raw_data['id'], 'Photo Comment', 'openi', defJsonRes, raw_data['from']['id'], raw_data['from']['username'], defJsonRes, raw_data['created_time'], defJsonRes, defJsonRes, raw_data['text'], defJsonRes )) return response def post_comment(self, data): ''' POST API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) # 'error_message': 'Please visit http://bit.ly/instacomments for commenting access' Please email apidevelopers[at]instagram.com for access. return defaultMethodResponse def delete_comment(self, data): ''' DELETE API_PATH/[COMMENT_ID] ''' # /media/media-id/comments/comment-id (ie media/628147512937366504_917877895/comments/628902539272471262) response = self.connector.delete_comment(data['media_id'], data['comment_id']) return response def like_a_photo(self, data): ''' POST API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.like_media(data['media_id']) return response def get_photo_likes(self, data): ''' GET API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) raw_datas = self.connector.media_likes(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data' : [] } for raw_data in raw_datas['data']: response['data'].append(self.format_comment_response( defJsonRes,#id 'Photo Like',#obj_type 'openi',#service defJsonRes,#url raw_data['id'],#from:id raw_data['username'],#from:username defJsonRes,#from:url defJsonRes,#time:created_time defJsonRes,#time:edited_time defJsonRes#target_id )) return 'Not supported by this service' def unlike_photo(self, data): ''' DELETE API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.unlike_media(data['media_id']) return response # endregion Connections # endregion Photo Object # endregion Media API
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 commentsBaseDir = "../../data/comments" commentsDataDir = os.path.join(commentsBaseDir, str(resourceID % 1000)) try: os.makedirs(commentsDataDir) except OSError: pass # Load user feed file feedsBaseDir = "../../data/feeds" feedsFilePath = os.path.join(feedsBaseDir, str(resourceID % 1000), "%s.feed" % resourceID) with open(feedsFilePath, "r") as feedFile: feed = json.load(feedFile) # Initialize return variables responseCode = 3 extraInfo = {"InstagramAppFilter": {}} # Execute collection comments = [] for media in feed: self.echo.out(u"Media: %s." % media["id"]) while (True): try: mediaComments = api.media_comments(media_id=media["id"], return_json=True) except (InstagramAPIError, InstagramClientError) as error: if (error.status_code == 400): self.echo.out(error, "ERROR") responseCode = -4 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: retrys = 0 sleepSecondsMultiply = 3 comments.extend(mediaComments) break # Save JSON file containing comments data for the user feed output = open(os.path.join(commentsDataDir, "%s.comments" % media["id"]), "w") json.dump(feed, output) output.close() # Get rate remaining to send back to InstagramAppFilter extraInfo["InstagramAppFilter"]["appname"] = application["name"] extraInfo["InstagramAppFilter"]["apprate"] = int(api.x_ratelimit_remaining) if api.x_ratelimit_remaining else None return ({#"crawler_name": socket.gethostname(), "response_code": responseCode}, extraInfo, None)
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')
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')
def acme_test(): # 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']) # recent_media, next = api.user_recent_media(user_id=922345846,count=30) # check = recent_media[0].location.point.latitude 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) contest_followers = [] for uid in uids: followers, next = api.user_followed_by(user_id= uid) for follower in followers: contest_followers.append(follower.username) while next: followers, next = api.user_follows(with_next_url=next) for follower in followers: contest_followers.append(follower.username) contest_followers = list(set(contest_followers)) ## old hack way # acme_id = '922345846' # acme_followers, next = api.user_followed_by(user_id= acme_id) # acme_users = [] # for user in acme_followers: # acme_users.append(user.username) # i = 0 # while len(acme_users) < acme_basics.counts['followed_by']-50: # i += 1 # response = urllib.urlopen(next) # data = json.loads(response.read()) # for user in data['data']: # acme_users.append(user['username']) # next = data['pagination']['next_url'] def is_follower(username): return (username in contest_followers) 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 = [] for img_id in contest_imgs: contest_comments = api.media_comments(media_id = img_id ) for comment in contest_comments: if comment.user.username not in valid_participants and comment.user.username not in user_list: if len(tagged_users(comment.text)) >= 3 and is_follower(comment.user.username): valid_participants.append(comment.user.username) templateData = { 'comments' : contest_comments, 'participants' : valid_participants, } return render_template('test.html', **templateData) else: return redirect('/connect')
from hashlib import sha256 def generate_sig(endpoint, params, secret): sig = endpoint for key in sorted(params.keys()): sig += '|%s=%s' % (key, params[key]) return hmac.new(secret, sig, sha256).hexdigest() def save_picture(url, i): import urllib urllib.urlretrieve(url, "pictures/picture_{0}.jpg".format(str(i))) from instagram.client import InstagramAPI api = InstagramAPI(client_id='cab252bf28404d94b9b224ce34bfe0dc', client_secret='768d8cbfd06e4bc3abe1e4836a2222a4') popular_media = api.media_search(lat=55.615966, lng=12.076837, distance=8000, max_timestamp=1433894400) #popular_media = api.tag_search('rf15') for i, media in enumerate(popular_media): url = media.images['standard_resolution'].url print url media_id = media.get_id() comments = api.media_comments(media_id) print comments likes = api.media_likes(media_id) print likes save_picture(url, i) #lat 55.615966, #long 12.076837