def followed_accounts( follower: Account, client: Instagram, config: dict, logger: logging.Logger) -> Generator[Account, None, None]: response = client.get_following( account_id=follower.identifier, count=config['max_followed_scraped'], page_size=config['follows_page_size'], ) accounts = response['accounts'] if 'accounts' in response else [] return (account_from_obj(account) for account in accounts)
from igramscraper.instagram import Instagram # pylint: disable=no-name-in-module from time import sleep instagram = Instagram() instagram.with_credentials('pietro.sonnini00', 'F&#yig4x0j5D') instagram.login(force=False, two_step_verificator=True) sleep(20) # Delay to mimic user username = '******' followings = [] account = instagram.get_account(username) sleep(1) followings = instagram.get_following( account.identifier, 100, 50, delayed=True ) # Get 150 followers of 'username', 100 a time with random delay between requests for following in followings['accounts']: if following.is_private == False: print(following.username)
username = os.environ.get('IG_USERNAME') password = os.environ.get('IG_PASSWORD') instagram.with_credentials(username, password) instagram.login() account = instagram.get_account('aniruddhavpatil') # Available fields # print('Account info:') # print('Id: ', account.identifier) # print('Username: '******'Full name: ', account.full_name) # print('Biography: ', account.biography) # print('External Url: ', account.external_url) # print('Number of published posts: ', account.media_count) # print('Number of followers: ', account.followed_by_count) # print('Number of follows: ', account.follows_count) # print('Is private: ', account.is_private) # print('Is verified: ', account.is_verified) # or simply for printing use # print(account) username = '******' account = instagram.get_account(username) sleep(1) following = instagram.get_following(account.identifier, 356, 100, delayed=True) f = open('iub_following.pkl', 'wb') pickle.dump(following, f) print('Done')
class InstagramAnalyzer: def __init__(self, username, password): self.instagram = Instagram() self._login(username, password) self.likes = {} self.month_posts = {} self.shared_followings = [] self.likes_contributors = {} def _login(self, username, password): self.instagram.with_credentials(username, password) self.instagram.login() def analyze(self, args, **kwargs): for arg in args: if len(args) != 1: self._find_shared_following(arg) medias = self.instagram.get_medias(arg, count=kwargs['count']) self._count_total_likes(arg, medias) self._count_posts_in_month(arg, medias) self._count_likes_contributor(arg, medias) def _count_total_likes(self, username, medias): total_likes = 0 for media in medias: total_likes += media.likes_count self.likes[username] = total_likes def _count_posts_in_month(self, username, medias): start = datetime.now() month_count = {} for media in medias: date = datetime.fromtimestamp(media.created_time) year_month = f'{date.year}-{date.month}' if diff_month(start, date) > 1: start = date month_count[year_month] = 1 elif diff_month(start, date) <= 1: if year_month in month_count.keys(): month_count[year_month] += 1 else: month_count[year_month] = 1 self.month_posts[username] = month_count def _count_likes_contributor(self, arg, medias): contributor_likes = {} for media in medias: accounts = self.instagram.get_media_likes_by_code( media.short_code, 40)['accounts'] for account in accounts: key = account.username if arg not in self.likes_contributors.keys(): self.likes_contributors[arg] = {} if key not in contributor_likes.keys(): contributor_likes[key] = 1 else: contributor_likes[key] += 1 contributor_likes = dict( sorted(contributor_likes.items(), key=operator.itemgetter(1), reverse=True)[:5]) self.likes_contributors[arg] = contributor_likes def _find_shared_following(self, arg): account = self.instagram.get_account(arg) following = self.instagram.get_following( account.identifier, 200, 100, delayed=True)['accounts'] following_username = self._populate_following_username(following) if len(self.shared_followings) == 0: self.shared_followings = following_username else: self.shared_followings = list( set(self.shared_followings).intersection(following_username)) @staticmethod def _populate_following_username(following): following_username = set() for account in following: following_username.add(account.username) return following_username
class InstaAgent(): def __init__(self, username, password): self.username = username self.password = password self.scraper = Instagram() self.target = self.scraper.get_account(username) self.scraper.with_credentials(username, password) self.scraper.login() def get_following_data(self, target_name, tweet_count=None): rows = [[ 'username', 'full name', 'biography', 'prive', 'verfied', 'picture' ]] target = self.scraper.get_account(target_name) if not tweet_count: tweet_count = target.follows_count followers = self.scraper.get_following(target.identifier, tweet_count, 100, delayed=True) for item in followers['accounts']: rows.append([ item.username, item.full_name, item.biography, item.is_private, item.is_verified, item.profile_pic_url ]) return rows def get_followers_data(self, target_name, tweet_count=None): rows = [[ 'username', 'full name', 'biography', 'prive', 'verfied', 'picture' ]] target = self.scraper.get_account(target_name) if not tweet_count: tweet_count = target.follows_count followers = self.scraper.get_followers(target.identifier, tweet_count, 100, delayed=True) for item in followers['accounts']: rows.append([ item.username, item.full_name, item.biography, item.is_private, item.is_verified, item.profile_pic_url ]) return rows def substract_folowing_folowers(self, target): following = self.get_following_data(target, tweet_count=650) followers = self.get_followers_data(target, tweet_count=650) res = [ i for i in following if (i not in followers and not i.is_verified) ] res.index(following[0], 0) with open('./CSVs/' + target + '__following.csv', mode='w') as csvfile: writer = csv.writer(csvfile) writer.writerows(following) with open('./CSVs/' + target + '__followers.csv', mode='w') as csvfile: writer = csv.writer(csvfile) writer.writerows(followers) with open('./CSVs/' + target + '__substract.csv', mode='w') as csvfile: writer = csv.writer(csvfile) writer.writerows(res) def unfollow_list(self, lst): for i in lst: try: target = self.scraper.get_account(i) self.scraper.unfollow(target.identifier) print('unfollowed: ' + i) except Exception as e: print(e)
def start(request): request_json = request.get_json() insta_username = request_json['insta_username'] insta_password = request_json['insta_password'] username = request_json['username'] discord_webhook_url = request_json['discord_webhook_url'] try: instagram = Instagram() instagram.with_credentials(insta_username, insta_password) instagram.login(force=False, two_step_verificator=True) sleep(2) # Delay to mimic user followers = [] account = instagram.get_account(username) sleep(1) curr_time = datetime.datetime.now(timezone('US/Eastern')) curr_time = curr_time.strftime("%b %d, %Y - %H:%M:%S") followers = instagram.get_followers( account.identifier, FOLLOWER_LIMIT, 100, delayed=True ) # Get 150 followers of 'kevin', 100 a time with random delay between requests # print(followers) followings = instagram.get_following(account.identifier, FOLLOWER_LIMIT, 100, delayed=True) current_followers = [] current_followings = [] for following in followings['accounts']: current_followings.append(following.username) for follower in followers['accounts']: current_followers.append(follower.username) del followers del followings not_follow_back = check_not_followback(current_followings, current_followers) if not path.exists(username + "_follower_list.txt"): f = open(username + "_follower_list.txt", "w") f.write(str(current_followers)) f.close() else: f = open(username + "_follower_list.txt", "r+") old_followers = f.read() f.close() old_followers = ast.literal_eval(old_followers) unfollowers = check_unfollowers(current_followers, old_followers) followers = check_followers(current_followers, old_followers) follower_change = len(current_followers) - len(old_followers) follow_count = len(followers) unfollow_count = len(unfollowers) discord_webhook.send_msg(username, follower_change, followers, unfollowers, follow_count, unfollow_count, curr_time, discord_webhook_url, not_follow_back) retMap = { 'username': username, 'follower_change': follower_change, 'followers': followers, 'unfollowers': unfollowers, 'follow_count': follow_count, 'unfollow_count': unfollow_count, 'curr_time': curr_time, 'discord_webhook_url': discord_webhook_url, 'not_follow_back': not_follow_back } f = open(username + "_follower_list.txt", "w") f.write(str(current_followers)) f.close() retJson = json.dumps(retMap) except Exception as e: print(e)
comments2 = instagram.get_media_comments_by_code(media2.short_code, 25) commin2 = [{ 'Comment Owner ID': comment.identifier, 'Comment': comment.text } for comment in comments2['comments']] comments3 = [] comments3 = instagram.get_media_comments_by_code(media3.short_code, 25) commin3 = [{ 'Comment Owner ID': comment.identifier, 'Comment': comment.text } for comment in comments3['comments']] # Ini buat ngambil data Following di Logged Account following = [] following = instagram.get_following(account.identifier, 50, 25, delayed=True) foling_user = [{ 'Account ID': following_user.identifier, 'Account Username': following_user.username, 'Account Full Name': following_user.full_name, 'Account Biography': following_user.biography } for following_user in following['accounts']] # Ini buat ngambil data Followers di Logged Account followers = [] followers = instagram.get_followers(account.identifier, 50, 25, delayed=True) foler_user = [{ 'Account ID': follower.identifier, 'Account Username': follower.username, 'Account Full Name': follower.full_name, 'Account Biography': follower.biography
def create_export(): filename = get_file_name() username = input("Type your username: "******"Type your password: "******"Type the number of people you are following: ")) instagram = Instagram() instagram.with_credentials(username, password, './cache/') try: instagram.login(force=False,two_step_verificator=True) except Exception as e: print(e) print('Incorrect credentials. Relaunch and try again.') return False sleep(2) # Delay to mimic user account = instagram.get_account(username) print(bcolors.OKGREEN + 'Connected to account ' + bcolors.BOLD + account.full_name + ' @' + account.username + bcolors.ENDC) print("Export date: ", today.strftime("%d/%m/%Y")) loading() sleep(1) followers = instagram.get_followers(account.identifier, 400, 100, delayed=True) # Get 400 followers of 'kevin', 100 a time with random delay between requests # Delay to mimic user sleep(1) following = instagram.get_following(account.identifier, nbFollow, 100, delayed=True) if filename != '': with open('./export/' + filename, 'w') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['Followers']) for follower in followers['accounts']: filewriter.writerow([follower.username, follower.full_name]) filewriter.writerow(['Total: ' + str(len(followers['accounts']))]) filewriter.writerow(['']) filewriter.writerow(['Following']) for follow in following['accounts']: filewriter.writerow([follow.username, follow.full_name]) filewriter.writerow(['Total: ' + str(len(following['accounts']))]) filewriter.writerow(['']) filewriter.writerow(['People I follow that do not follow me']) for follow in following['accounts']: if contains(followers['accounts'], lambda x: x.username == follow.username) == False: if follow.is_verified == False: bastards.append(follow) for bastard in bastards: filewriter.writerow([bastard.username, bastard.full_name]) filewriter.writerow(['Total: ' + str(len(bastards))]) filewriter.writerow(['']) filewriter.writerow(['People I do not follow that follow me']) for follower in followers['accounts']: if contains(following['accounts'], lambda x: x.username == follower.username) == False: miskines.append(follower) for miskine in miskines: filewriter.writerow([miskine.username, miskine.full_name]) filewriter.writerow(['Total: ' + str(len(miskines))]) filewriter.writerow(['']) filewriter.writerow(['Verified account I follow']) for follow in following['accounts']: if follow.is_verified == True: verifiedFollow.append(follow) for verified in verifiedFollow: filewriter.writerow([verified.username, verified.full_name]) filewriter.writerow(['Total: ' + str(len(verifiedFollow))]) filewriter.writerow(['']) filewriter.writerow(['Verified account that follow me']) for follower in followers['accounts']: if follower.is_verified == True: verifiedFollowers.append(follower) for verified in verifiedFollowers: filewriter.writerow([verified.username, verified.full_name]) filewriter.writerow(['Total: ' + str(len(verifiedFollowers))]) filewriter.writerow(['']) filewriter.writerow(['Date: ' + today.strftime("%d/%m/%Y")]) print('Export ' + filename + ' finished')