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 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 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_likes_from_media(user, access_token, filename, min_timestamp, max_timestamp): media_likes = {'Data' : []} api = InstagramAPI(access_token=access_token) recent_media, next = api.user_recent_media(user_id=user, min_timestamp=min_timestamp, max_timestamp=max_timestamp) for media in recent_media: media_like = api.media_likes(media.id) for like in media_like: media_likes['Data'].append({'Username' : like.username.encode('utf-8'), 'Profile_pic' : like.profile_picture, 'User_id' : str(like.id), 'Full_name' : like.full_name.encode('utf-8'), 'Media_ID' : media.id, 'Image' : media.link}) likes_data = media_likes['Data'] csv_file = open(filename, 'wb') csv_writer = csv.writer(csv_file) count = 0 for data in likes_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 media_likes
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)
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
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
from instagram.client import InstagramAPI access_token = "25290587.1677ed0.7131ff8507da447bb7fe54dab79fd273" client_secret = "a8545940747f4536873f06e4a60c23a4" api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, next_ = api.user_recent_media(user_id="259220806", count=1) for media in recent_media: print (media.caption.text) curMedia = str(media) curMedia = curMedia[7:] likesArr = api.media_likes(curMedia) print (likesArr) followersList = open('followersList.txt', 'w+') followers, next = api.user_followed_by(user_id="259220806") count = 0 while len(followers)<100: more_follows, next = api.user_followed_by(with_next_url=next) followers.extend(more_follows) count += 50 #strFollowers = [] #for name in followers: # strFollowers.append(str(name)[6:]) for name in followers: curMedia = api.user_liked_media() #user = api.user()
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
def find_friends(access_token): client_secret = "22a6a272eeaa4b18aba7b242ade48cd3" api = InstagramAPI(access_token=access_token, client_secret=client_secret) #sets recent_feed media recent_feed, next_ = api.user_recent_media(100) """ Finding users tagged in your photos, this should be the most important factor """ users = [] num_photos_in_feed = 0 num_photos_tagged = 0 for media in recent_feed: num_photos_in_feed += 1 if media.users_in_photo: for tagged_person in media.users_in_photo: num_photos_tagged += 1 users.append(tagged_person.user) tagged_user = {} for user in users: if user.id in tagged_user.keys(): tagged_user[user.id] += 1 else: tagged_user[user.id] = 1 #Done #likes - list of users that has liked each photo likes = [] for media in recent_feed: a = api.media_likes(media.id) for i in a: likes.append(i) # d_ids - dict key = user id and value is number of times they have liked a photo likes_ids = [user.id for user in likes] d_ids = {} for userid in likes_ids: d_ids[userid] = likes_ids.count(userid) #users is list of all users that you have liked a photo of theirs feed, next_ = api.user_liked_media(access_token=access_token, count = 100) users = [] for media in feed: users.append(media.user) #d - pairs users and number of times you have liked their photo other_ids = [user.id for user in users] d = {} for user in other_ids: d[user] = other_ids.count(user) #all relevant users like_users = {} for user in likes: like_users[user.id] = user liked_users = {} for user in users: liked_users[user.id] = user like_users.update(liked_users) all_users = list(like_users.values()) #give scores to each user scores = {} for user in all_users: score = 0 if user.id in d_ids: # d_ids - dict key = user id and value is number of times they have liked a photo score += 5 *d_ids[user.id] if user.id in d: score += 2 * d[user.id] #d - pairs users and number of times you have liked their photo if user.id in tagged_user: if (num_photos_tagged < 2) or ((num_photos_tagged/num_photos_in_feed) < .2): score += 14 * tagged_user[user.id] else: score += 13 * tagged_user[user.id] scores[user] = score #print(d) #print(d_ids) #gives scores for like_me index scores_likeme = {} for user in all_users: score = 0 if user.id in d_ids: score += d_ids[user.id] scores_likeme[user] = score final_likeme = [] for _ in range(5): v=list(scores_likeme.values()) k=list(scores_likeme.keys()) score = k[v.index(max(v))] final_likeme.append(score.full_name) scores_likeme.pop(score) final_likeme_str = str(final_likeme) #print(final_likeme, "diff") #gives scores for like_them index scores_likethem = {} for user in all_users: score = 0 if user.id in d: score += d[user.id] scores_likethem[user] = score final_likethem = [] for _ in range(5): v=list(scores_likethem.values()) k=list(scores_likethem.keys()) score = k[v.index(max(v))] final_likethem.append(score.full_name) scores_likethem.pop(score) final_likethem_str = str(final_likethem) #print(final_likethem, 'more diff') #compute final list of 5 best users with highest scores final = [] finalname = [] finalscore = [] for _ in range(5): v=list(scores.values()) k=list(scores.keys()) score = k[v.index(max(v))] final.append(score) finalname.append(score.full_name) finalscore.append(scores[score]) scores.pop(score) final_str = str(final) finalname_str = str(finalname) finalscore_str = str(finalscore) return final
#get recent media ids with the tag "CapitalOne", only get the most recent 80 #tag_recent_media returns 2 variables, the media ID in an array and the next #url for the next page media_ids,next = api.tag_recent_media(tag_name='CapitalOne', count=20) #obtain the max_tag_id to use to get the next page of results temp,max_tag=next.split('max_tag_id=') max_tag=str(max_tag) for media_id in media_ids: users.append(media_id.user.id) media_all_ids.append(media_id.id) captions.append(media_id.caption.text) post_likes = api.media_likes(media_id.id) likes.append(len(post_likes)) for user_id in users: users_info = api.user(user_id=user_id) print users_info.username + ' currently has ' + str(users_info.counts['media']) + ' posts.' print users_info.username + ' currently has ' + str(users_info.counts['followed_by']) + ' followers.' print users_info.username + ' is currently following ' + str(users_info.counts['follows']) + ' people.' # list of positive key-words and emojis, including smiley faces, hearts, celebrations, money bags, etc. positive_word_list = ['thanks', 'great', 'appreciate', 'awesome', 'good', u'\U0001F60D', u'\U0001F60A', u'\U0001F44D', u'\U0001F44C', u'\U0001F498', u'\u2764', u'\U0001F493', u"\U0001F614", u"\U0001F495", u"\U0001F496", u"\U0001F497", u"\U0001F499", u"\U0001F49A", u"\U0001F49B", u"\U0001F49C", u"\U0001F49D", u"\U0001F49E", u"\U0001F389", u"\U0001F38A", u"\U0001F4B0", u"\U0001F4B8", u"\U0001F4B3", u"\U0001F603", u"\U0001F64C"]