def follow(api: Client) -> None: """ A specific user was searched and that user will be followed by the current user Arguments: api (Client) : Object instagram Client """ search_users(api) username = input_user_chat(f"Who do you want to follow? ") user = api.username_info(username)['user'] user_id = user['pk'] try: api.friendships_create(user_id=user_id) text = f"{username} has a private account, we have sent him a request with success!" if user[ 'is_private'] else f"{username} has been followed with success!" print_write_chatbot(message=text, color='green', attrs_color=['bold']) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"There was an error:{error}", color="red", attrs_color=['bold'])
print('Жди ' + str(t) + ' сек') print() time.sleep(t) except ClientError as e: print('Лимит подписок исчерпан') #Я не подписан, а на меня подписаны elif data_follow['following'] == False and data_follow[ 'followed_by'] == True: print('Пользователь: ' + following['username']) print( 'Подписка невзаимная с моей строны - подписка на пользователя(' + str(s_podpiska) + ')') try: api.friendships_create(pk) s_podpiska += 1 t = randint(config.START_SLEEP_TIME_TO_FOLLOW, config.FINISH_SLEEP_TIME_TO_FOLLOW) print('Жди ' + str(t) + ' сек') print() time.sleep(t) except ClientError as e: print('Лимит отписок исчерпан') else: print('Пользователь: ' + following['username']) print('Пользователь взаимен, пропускаем его') t = randint(1, 2) print('Жди ' + str(t) + ' сек')
class InstaFollow: def __init__(self, username, password, similar_users, API=None, action_interval=8.0, rate=75, interval=5400): self.username = username self.password = password if isinstance(similar_users, str): self.similar_users = [x.strip() for x in similar_users.split(",")] else: self.similar_users = similar_users self.action_interval = action_interval self.rate = rate self.interval = interval self.logger = logging.LoggerAdapter(logger, { 'user': self.username, 'bot': 'instafollow' }) self.API = Client(self.username, self.password) if API is None else API self.webAPI = WebClient() def _get_user_ids(self, save_to=None): self.logger.info('Collecting users to follow...') # Randomly select root account to search for users account = self.similar_users[randint(0, len(self.similar_users) - 1)] username_info = self.API.username_info(account) # Get root account id root_account_id = username_info.get('user').get('pk') # Get root account posts max_id = '' pages = 1 media_ids = [] for i in range(0, pages): user_feed = self.API.user_feed(root_account_id, max_id=max_id) media_items = user_feed.get('items') for media in media_items: media_ids.append(media.get('id')) max_id = user_feed.get('next_max_id') user_ids = [] for media_id in media_ids: media_likers = self.API.media_likers(media_id) try: users = media_likers.get('users') except ChunkedEncodingError as e: self.logger.error("Failed to retrieve user list", e) users = [] for user in users: id = user.get('pk') user_ids.append(id) user_ids = list(set(user_ids)) self.logger.info("Found {} new users...".format(len(user_ids))) return user_ids def _login(self): attempts = 0 while attempts <= 10: try: if self.API.login(): return True except Exception as e: self.logger.exception("Failed to login...") sleep(6) attempts += 1 return False def start(self): self.logger.info("Follow bot started...") users = [] while len(users) < 7000: users += self._get_user_ids() progress = 0 bad_requests = 0 successful_requests = 0 while users: progress += 1 # if not self.API.is_logged_in: # self.API.login() id = users.pop(0) res = self.API.friendships_create(id) if res.get("status", False) != "ok": users.append(id) bad_requests += 1 elif res.get("status", False) == "ok": successful_requests += 1 if bad_requests == 10: self.logger.info( "10 bad requests...sleeping for 3 mins 20 secs.") sleep(200) bad_requests = 0 if not (progress % self.rate): progress = 0 followings = self.webAPI.user_info2(self.username).get( "follows", {}).get("count", 0) if followings > 7000: break wait = uniform(self.interval * 0.9, self.interval * 1.1) self.logger.info( "Cycle ended for user {} with {} successful requests and {} followers...sleeping for {}mins" .format(self.username, successful_requests, followings, wait / 60)) successful_requests = 0 sleep(wait) # Sleep n seconds +/ 10% to induce randomness between each action sleep( uniform(self.action_interval * 0.9, self.action_interval * 1.1))
class InstagramManager(object): def __init__(self): self.username = config_reader.ConfigHelper.read_config( 'account', 'username') self.password = config_reader.ConfigHelper.read_config( 'account', 'password') self.api = Client(self.username, self.password) self.follower_list = [] self.story_user_list = [] self.daily_follow_num = int( config_reader.ConfigHelper.read_config('setting', 'daily_follow_num')) self.comment_list = config_reader.ConfigHelper.get_comments() self.tag_feeds = [] self.tag_hot_feeds = [] def re_login(self): self.api = Client(self.username, self.password) def start_work(self): self.deal_account() #self.api.current_user(); #self.deal_unfollow() #self.deal_tag() #self.deal_story() #self.deal_comment_and_like() def deal_account(self): username = config_reader.ConfigHelper.read_config( 'setting', 'focus_account') user_id = self.get_user_id(username) if user_id is None: print('no this user') else: page_num = config_reader.ConfigHelper.read_config( 'page', 'page_num') self.get_follower(user_id, page_num) for follower in self.follower_list: pk = follower.get('pk') name = follower.get('username') self.api.friendships_create(pk) database_helper.DatabaseHelper.insert_follower(pk, name) config_reader.ConfigHelper.write_config('follower', str(pk), name, 'daily_result.ini') def deal_unfollow(self): followers = database_helper.DatabaseHelper.select_follower() for follower in followers: follow_timestamp = follower.timestamp timestamp = time.time() # 根据配置天数自动取关 day = int( config_reader.ConfigHelper.read_config('setting', 'unfollow_days')) time_diff = day * 24 * 60 * 60 if timestamp - follow_timestamp >= time_diff: if self.has_real_followed(follower.user_id, follower.username): print('start_friendships_destroy:' + follower.username) self.api.friendships_destroy(follower.user_id) database_unfollower_helper.DatabaseUnFollowHelper.insert_data( follower.user_id, follower.username) print('friendships_destroy:' + follower.username) def deal_comment_and_like(self): for follower in self.follower_list: pk = follower.get('pk') name = follower.get('username') print('comment:' + name) is_private = follower.get('is_private') if not is_private: feeds = self.get_user_feed(pk) for feed in feeds: media_id = feed.get('pk') self.comment_feed(media_id) self.like_feed(media_id) print(name + ' comment and like success') else: print(name + 'is a private account') def deal_tag(self, max_id=None): tag = config_reader.ConfigHelper.read_config('setting', 'focus_tag') if max_id is None: feed_tag = self.api.feed_tag(tag) else: feed_tag = self.api.feed_tag(tag, max_id=max_id) next_max_id = feed_tag.get('next_max_id') if next_max_id: self.deal_tag(next_max_id) return self.set_feeds(feed_tag) self.set_hot_feeds(feed_tag) for feed in self.tag_feeds: media_id = feed.get('pk') self.comment_feed(media_id) for hot_feed in self.tag_hot_feeds: media_id = hot_feed.get('pk') self.comment_feed(media_id) def get_user_id(self, username): results = self.api.search_users(username) users = [] users.extend(results.get('users', [])) for user in users: if user.get('username') == username: pk = user.get('pk') return pk return None def get_follower(self, user_id, max_id=None): if max_id is None: user_followers = self.api.user_followers(user_id) else: user_followers = self.api.user_followers(user_id, max_id=max_id) users = [] users.extend(user_followers.get('users', [])) for user in users: pk = user.get('pk') username = user.get('username') is_meet = (not self.has_followed(pk) ) and self.is_meet_requirements(pk, username) if is_meet: self.follower_list.append(user) # 取到了每天需要follow数量即可停止 if len(self.follower_list) >= self.daily_follow_num: return next_max_id = user_followers.get('next_max_id') config_reader.ConfigHelper.write_config('page', 'page_num', next_max_id) if next_max_id: self.get_follower(user_id, next_max_id) # 是否满足我们follow的要求 def is_meet_requirements(self, user_id, username): if database_meet_helper.DatabaseMeetHelper.is_un_meet(user_id): print('DatabaseMeetHelper un_meet') return False post_meet_num = int( config_reader.ConfigHelper.read_config('follower_request', 'post')) follower_meet_num = int( config_reader.ConfigHelper.read_config('follower_request', 'followers')) following_meet_num = int( config_reader.ConfigHelper.read_config('follower_request', 'following')) user_info = self.api.user_info(user_id).get('user') post_num = user_info.get('media_count') follower_count = user_info.get('follower_count') following_count = user_info.get('following_count') is_meet = (post_num >= post_meet_num and follower_count >= follower_meet_num and following_count >= following_meet_num) print(str(user_id) + ":" + str(is_meet)) if not is_meet: database_meet_helper.DatabaseMeetHelper.insert_data( user_id, username) return is_meet # 判断是否关注过,包括已经关注、发送过关注请求(私人账户)、已经关注过(可能现在已经取关) def has_followed(self, user_id): friendships_show = self.api.friendships_show(user_id) is_following = friendships_show.get('following') outgoing_request = friendships_show.get('outgoing_request') database_is_followed = database_helper.DatabaseHelper.is_followed( user_id) return is_following or outgoing_request or database_is_followed # 判断是正在关注的,用于取关的时候用到,只有在ins中关注的才需要取关 def has_real_followed(self, user_id, user_name): # 如果在去粉的数据库中,则说明已经被去粉,就不再去调用ins接口,否则很容易被限制 if database_unfollower_helper.DatabaseUnFollowHelper.is_in_data( user_id): return False try: friendships_show = self.api.friendships_show(user_id) is_following = friendships_show.get('following') outgoing_request = friendships_show.get('outgoing_request') return is_following or outgoing_request except ClientError as e: print('has_real_followed ClientError') return False def set_feeds(self, feed_tag): feeds = feed_tag.get('items') daily_recent_posts = config_reader.ConfigHelper.read_config( 'setting', 'daily_recent_posts') tag_feed_request_like = config_reader.ConfigHelper.read_config( 'setting', 'tag_feed_request_like') for feed in feeds: media_id = feed.get('pk') media_info = self.api.media_info(media_id) item = media_info.get('items')[0] like_count = item.get('like_count') if like_count > int(tag_feed_request_like): self.tag_feeds.append(feed) if len(self.tag_feeds) >= int(daily_recent_posts): break def set_hot_feeds(self, feed_tag): hot_feeds = feed_tag.get('ranked_items') daily_top_posts = config_reader.ConfigHelper.read_config( 'setting', 'daily_top_posts') for hot_feed in hot_feeds: self.tag_hot_feeds.append(hot_feed) if len(self.tag_hot_feeds) >= int(daily_top_posts): break # 获取某个用户的post(数量根据配置) def get_user_feed(self, user_id): user_feed = self.api.user_feed(user_id) feeds = user_feed.get('items') num = int( config_reader.ConfigHelper.read_config('follower_request', 'post_num_for_comment')) return feeds[:int(num)] # 对post进行评论 def comment_feed(self, media_id): length = len(self.comment_list) x = random.randint(0, length - 1) comment = self.comment_list[x] print('start comment,media_id:' + str(media_id) + "——" + comment) try: self.api.post_comment(media_id, str(comment)) print('comment:' + comment + ' success') except Exception as e: print('comment:' + comment + ' error:' + str(e)) # 对post进行like def like_feed(self, media_id): self.api.post_like(media_id) def deal_story(self): self.get_user_story() def get_user_story(self): reels_tray = self.api.reels_tray() broadcasts = reels_tray.get('broadcasts') tray = reels_tray.get('tray') for item in tray: user = item.get('user') name = user.get('username') user_detail_info = self.api.user_detail_info( user.get('pk')).get('user_detail').get('user') post_num = user_detail_info.get('media_count') follower_count = user_detail_info.get('follower_count') following_count = user_detail_info.get('following_count') post_meet_num = int( config_reader.ConfigHelper.read_config('story_request', 'post')) follower_meet_num = int( config_reader.ConfigHelper.read_config('story_request', 'followers')) following_meet_num = int( config_reader.ConfigHelper.read_config('story_request', 'following')) daily_story_comment_num = int( config_reader.ConfigHelper.read_config('setting', 'daily_story_comment')) is_meet = (post_num >= post_meet_num and follower_count >= follower_meet_num and following_count <= following_meet_num) if is_meet: stories = item.get('items') if stories is None: continue for story in stories: length = len(self.comment_list) x = random.randint(0, length) comment = self.comment_list[x] self.api.broadcast_comment(story.get('pk'), comment) print(name + 'story comment:' + comment + "success") self.story_user_list.append(item) if len(self.story_user_list) >= daily_story_comment_num: break
def main(): logo = f""" {Style.BRIGHT + Fore.RED} ▄▄ ▄███▄{Style.RESET_ALL} {Style.BRIGHT + Fore.RED}▄▀▀▀▀ ▄▄▄ ▀▀▀▀▄ {Style.BRIGHT + Fore.MAGENTA}Instagram Kitleye Göre Takipçi Bulucu{Style.RESET_ALL} {Style.BRIGHT + Fore.RED}█ █ █ █ {Style.BRIGHT + Fore.RED}+-----------------------------------+{Style.RESET_ALL} {Style.BRIGHT + Fore.RED}█ ▀▄▄▄▀ █ {Style.BRIGHT + Fore.YELLOW}HACKED BY GODEST{Style.RESET_ALL} {Style.BRIGHT + Fore.RED}▀▄▄▄▄▄▄▄▄▄▄▄▄▄▀{Style.RESET_ALL} """ print(logo) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Hangi takip etme yöntemini kullanmak istersiniz:{Style.RESET_ALL}") tmp = (11 * " ") print(f"{Style.RESET_ALL}{tmp}{Style.BRIGHT + Fore.MAGENTA}1 > {Style.RESET_ALL + Fore.WHITE}Hastag kullanarak takipçi bulma.{Style.RESET_ALL}") print(f"{Style.RESET_ALL}{tmp}{Style.BRIGHT + Fore.MAGENTA}2 > {Style.RESET_ALL + Fore.WHITE}Kullanıcıdan takipçi bulma.{Style.RESET_ALL}") print(f"{Style.RESET_ALL}") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[>] {Style.BRIGHT + Fore.WHITE}Seçiminiz:{Style.RESET_ALL} ", end="") method = input() if (method != "1" and method != "2"): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Seçiminiz 1 veya 2 olmalıdır!{Style.RESET_ALL}") exit(0) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Ardaşık takipler sırasında kaç saniye beklensin: {Style.RESET_ALL}", end="") sleep_sec = input() try: int(sleep_sec) except: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Bekleme süresi bir sayı olmalıdır!{Style.RESET_ALL}") exit(0) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Kullanıcı adınız: {Style.RESET_ALL}", end="") username = input() if (" " in username or username.strip() == ""): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Kullanıcı adınız boş veya boşluk içeriyor!{Style.RESET_ALL}") exit(0) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Şifreniz: {Style.RESET_ALL}", end="") password = input() if (password.strip() == ""): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Şifreniz boş olamaz!{Style.RESET_ALL}") exit(0) try: api = Client(username, password) except errors.ClientLoginError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Kullanıcı adınız veya şifreniz hatalı! ({e}){Style.RESET_ALL}") exit(0) except errors.ClientChallengeRequiredError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Giriş için doğrulama gerekli! ({e}){Style.RESET_ALL}") exit(0) except errors.ClientCheckpointRequiredError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Giriş için doğrulama gerekli! ({e}){Style.RESET_ALL}") exit(0) except errors.ClientSentryBlockError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Giriş yapılamadı! Hesap spam olarak işaretlenmiş! ({e}){Style.RESET_ALL}") exit(0) except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Bağlantı hatası! ({e}){Style.RESET_ALL}") exit(0) except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Giriş yapılamadı! ({e}){Style.RESET_ALL}") exit(0) print("") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}Giriş yapıldı!{Style.RESET_ALL}") if ("R35" not in logo): print("Bu Programı Godest'ten Çaldım O Kadar Malım'ki Bunu Kaldırmayı Unuttum.") exit(0) if (method == "1"): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Aramak istediğiniz hastagleri giriniz ('#' siz ve hastagler arası virgül koyunuz):{Style.RESET_ALL} ", end="") hashtags = input() hashtag_list = hashtags.strip().split(",") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{len(hashtag_list)} adet hastag aranacak!{Style.RESET_ALL}") for hashtag in hashtag_list: if (hashtag.strip() == ""): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Boş hashtag bulundu! Geçiliyor.{Style.RESET_ALL}") continue try: data = api.top_search(hashtag) if (len(data["users"]) == 0): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{hashtag} hashtagini kimse kullanmamış! Geçiliyor!{Style.RESET_ALL}") continue tmp = len(data["users"]) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} adet kullanıcıya takip atılacak!{Style.RESET_ALL}") for users in data["users"]: if ("user" not in users): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Kullanıcı bulunamadı! Geçiliyor.{Style.RESET_ALL}") continue user_data = users["user"] tmp = user_data["username"] try: if(api.friendships_show(user_data["pk"])["following"] == True): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına zaten takip atıldı! Geçildi!{Style.RESET_ALL}") continue api.friendships_create(user_data["pk"]) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atıldı!{Style.RESET_ALL}") except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atılamadı! ({e}){Style.RESET_ALL}") except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atılamadı! Bağlantı hatası!({e}){Style.RESET_ALL}") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.CYAN}[*] {Style.BRIGHT + Fore.WHITE}{sleep_sec} saniye bekleniyor!{Style.RESET_ALL}") sleep(int(sleep_sec)) continue except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Hashtag bilgileri alınamadı! ({e}){Style.RESET_ALL}") except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Bağlantı hatası! ({e}){Style.RESET_ALL}") elif (method == "2"): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Hedefin kullanıcı adını girin:{Style.RESET_ALL} ", end="") target_username = input() if (" " in target_username or target_username.strip() == ""): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Hedefin kullanıcı adı boş veya boşluk içeriyor!{Style.RESET_ALL}") exit(0) try: data = api.username_info(target_username) data = api.user_followers(data["user"]["pk"], api.generate_uuid()) tmp = data["users"] print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{len(tmp)} adet kullanıcıya takip atılacak!{Style.RESET_ALL}") for user in data["users"]: try: tmp = user["username"] if(api.friendships_show(str(user["pk"]))["following"] == True): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına zaten takip atıldı! Geçildi!{Style.RESET_ALL}") continue api.friendships_create(str(user["pk"])) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atıldı!{Style.RESET_ALL}") except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atılamadı! ({e}){Style.RESET_ALL}") except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atılamadı! Bağlantı hatası!({e}){Style.RESET_ALL}") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.CYAN}[*] {Style.BRIGHT + Fore.WHITE}{sleep_sec} saniye bekleniyor!{Style.RESET_ALL}") sleep(int(sleep_sec)) continue except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Hashtag bilgileri alınamadı! ({e}){Style.RESET_ALL}") except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Bağlantı hatası! ({e}){Style.RESET_ALL}") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.CYAN}[*] {Style.BRIGHT + Fore.WHITE}Takip işlemleri bitti!{Style.RESET_ALL}")
print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} adet kullanıcıya takip atılacak!{Style.RESET_ALL}") for users in data["users"]: if ("user" not in users): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Kullanıcı bulunamadı! Geçiliyor.{Style.RESET_ALL}") continue user_data = users["user"] tmp = user_data["username"] try: if(api.friendships_show(user_data["pk"])["following"] == True): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına zaten takip atıldı! Geçildi!{Style.RESET_ALL}") continue api.friendships_create(user_data["pk"]) print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.GREEN}[+] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atıldı!{Style.RESET_ALL}") except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atılamadı! ({e}){Style.RESET_ALL}") except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}{tmp} kullanıcısına takip atılamadı! Bağlantı hatası!({e}){Style.RESET_ALL}") print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.CYAN}[*] {Style.BRIGHT + Fore.WHITE}{sleep_sec} saniye bekleniyor!{Style.RESET_ALL}") sleep(int(sleep_sec)) continue except errors.ClientError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Hashtag bilgileri alınamadı! ({e}){Style.RESET_ALL}") except errors.ClientConnectionError as e: print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.RED}[-] {Style.BRIGHT + Fore.WHITE}Bağlantı hatası! ({e}){Style.RESET_ALL}") elif (method == "2"): print(f"{Style.RESET_ALL}{get_time()} {Style.BRIGHT + Fore.MAGENTA}[?] {Style.BRIGHT + Fore.WHITE}Hedefin kullanıcı adını girin:{Style.RESET_ALL} ", end="")
class Osintgram: api = None api2 = None geolocator = Nominatim(user_agent="http") user_id = None target_id = None is_private = True following = False target = "" writeFile = False jsonDump = False def __init__(self, target, is_file, is_json): u = self.__getUsername__() p = self.__getPassword__() print("\nAttempt to login...") self.login(u, p) self.setTarget(target) self.writeFile = is_file self.jsonDump = is_json def setTarget(self, target): self.target = target user = self.get_user(target) self.target_id = user['id'] self.is_private = user['is_private'] self.following = self.check_following() self.__printTargetBanner__() def __getUsername__(self): try: u = open("config/username.conf", "r").read() u = u.replace("\n", "") return u except FileNotFoundError: pc.printout("Error: file \"config/username.conf\" not found!", pc.RED) pc.printout("\n") sys.exit(0) def __getPassword__(self): try: p = open("config/pw.conf", "r").read() p = p.replace("\n", "") return p except FileNotFoundError: pc.printout("Error: file \"config/pw.conf\" not found!", pc.RED) pc.printout("\n") sys.exit(0) def __get_feed__(self): data = [] result = self.api.user_feed(str(self.target_id)) data.extend(result.get('items', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) data.extend(results.get('items', [])) next_max_id = results.get('next_max_id') return data def __get_comments__(self, media_id): comments = [] result = self.api.media_comments(str(media_id)) comments.extend(result.get('comments', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.media_comments(str(media_id), max_id=next_max_id) comments.extend(results.get('comments', [])) next_max_id = results.get('next_max_id') return comments def __printTargetBanner__(self): pc.printout("\nLogged as ", pc.GREEN) pc.printout(self.api.username, pc.CYAN) pc.printout(". Target: ", pc.GREEN) pc.printout(str(self.target), pc.CYAN) pc.printout(" [" + str(self.target_id) + "]") if self.is_private: pc.printout(" [PRIVATE PROFILE]", pc.BLUE) if self.following: pc.printout(" [FOLLOWING]", pc.GREEN) else: pc.printout(" [NOT FOLLOWING]", pc.RED) print('\n') def change_target(self): pc.printout("Insert new target username: "******"Searching for target localizations...\n") data = self.__get_feed__() locations = {} for post in data: if 'location' in post and post['location'] is not None: lat = post['location']['lat'] lng = post['location']['lng'] locations[str(lat) + ', ' + str(lng)] = post.get('taken_at') address = {} for k, v in locations.items(): details = self.geolocator.reverse(k) unix_timestamp = datetime.datetime.fromtimestamp(v) address[details.address] = unix_timestamp.strftime( '%Y-%m-%d %H:%M:%S') sort_addresses = sorted(address.items(), key=lambda p: p[1], reverse=True) if len(sort_addresses) > 0: t = PrettyTable() t.field_names = ['Post', 'Address', 'time'] t.align["Post"] = "l" t.align["Address"] = "l" t.align["Time"] = "l" pc.printout( "\nWoohoo! We found " + str(len(sort_addresses)) + " addresses\n", pc.GREEN) i = 1 json_data = {} addrs_list = [] for address, time in sort_addresses: t.add_row([str(i), address, time]) if self.jsonDump: addr = {'address': address, 'time': time} addrs_list.append(addr) i = i + 1 if self.writeFile: file_name = "output/" + self.target + "_addrs.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['address'] = addrs_list json_file_name = "output/" + self.target + "_addrs.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_captions(self): if self.check_private_profile(): return pc.printout("Searching for target captions...\n") captions = [] data = self.__get_feed__() counter = 0 try: for item in data: if "caption" in item: if item["caption"] is not None: text = item["caption"]["text"] captions.append(text) counter = counter + 1 sys.stdout.write("\rFound %i" % counter) sys.stdout.flush() except AttributeError: pass except KeyError: pass json_data = {} if counter > 0: pc.printout("\nWoohoo! We found " + str(counter) + " captions\n", pc.GREEN) file = None if self.writeFile: file_name = "output/" + self.target + "_captions.txt" file = open(file_name, "w") for s in captions: print(s + "\n") if self.writeFile: file.write(s + "\n") if self.jsonDump: json_data['captions'] = captions json_file_name = "output/" + self.target + "_followings.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) if file is not None: file.close() else: pc.printout("Sorry! No results found :-(\n", pc.RED) return def get_total_comments(self): if self.check_private_profile(): return pc.printout("Searching for target total comments...\n") comments_counter = 0 posts = 0 data = self.__get_feed__() for post in data: comments_counter += post['comment_count'] posts += 1 if self.writeFile: file_name = "output/" + self.target + "_comments.txt" file = open(file_name, "w") file.write( str(comments_counter) + " comments in " + str(posts) + " posts\n") file.close() if self.jsonDump: json_data = {'comment_counter': comments_counter, 'posts': posts} json_file_name = "output/" + self.target + "_comments.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) pc.printout(str(comments_counter), pc.MAGENTA) pc.printout(" comments in " + str(posts) + " posts\n") def get_followers(self): if self.check_private_profile(): return pc.printout("Searching for target followers...\n") followers = [] rank_token = AppClient.generate_uuid() data = self.api.user_followers(str(self.target_id), rank_token=rank_token) for user in data['users']: u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followers.append(u) t = PrettyTable(['ID', 'Username', 'Full Name']) t.align["ID"] = "l" t.align["Username"] = "******" t.align["Full Name"] = "l" json_data = {} followings_list = [] for node in followers: t.add_row([str(node['id']), node['username'], node['full_name']]) if self.jsonDump: follow = { 'id': node['id'], 'username': node['username'], 'full_name': node['full_name'] } followings_list.append(follow) if self.writeFile: file_name = "output/" + self.target + "_followers.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followers'] = followers json_file_name = "output/" + self.target + "_followers.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) def get_followings(self): if self.check_private_profile(): return pc.printout("Searching for target followings...\n") followings = [] rank_token = AppClient.generate_uuid() data = self.api.user_following(str(self.target_id), rank_token=rank_token) for user in data['users']: u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) t = PrettyTable(['ID', 'Username', 'Full Name']) t.align["ID"] = "l" t.align["Username"] = "******" t.align["Full Name"] = "l" json_data = {} followings_list = [] for node in followings: t.add_row([str(node['id']), node['username'], node['full_name']]) if self.jsonDump: follow = { 'id': node['id'], 'username': node['username'], 'full_name': node['full_name'] } followings_list.append(follow) if self.writeFile: file_name = "output/" + self.target + "_followings.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followings'] = followings_list json_file_name = "output/" + self.target + "_followings.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) def get_hashtags(self): if self.check_private_profile(): return pc.printout("Searching for target hashtags...\n") hashtags = [] counter = 1 texts = [] data = self.api.user_feed(str(self.target_id)) texts.extend(data.get('items', [])) next_max_id = data.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) texts.extend(results.get('items', [])) next_max_id = results.get('next_max_id') for post in texts: if post['caption'] is not None: caption = post['caption']['text'] for s in caption.split(): if s.startswith('#'): hashtags.append(s.encode('UTF-8')) counter += 1 if len(hashtags) > 0: hashtag_counter = {} for i in hashtags: if i in hashtag_counter: hashtag_counter[i] += 1 else: hashtag_counter[i] = 1 ssort = sorted(hashtag_counter.items(), key=lambda value: value[1], reverse=True) file = None json_data = {} hashtags_list = [] if self.writeFile: file_name = "output/" + self.target + "_hashtags.txt" file = open(file_name, "w") for k, v in ssort: hashtag = str(k.decode('utf-8')) print(str(v) + ". " + hashtag) if self.writeFile: file.write(str(v) + ". " + hashtag + "\n") if self.jsonDump: hashtags_list.append(hashtag) if file is not None: file.close() if self.jsonDump: json_data['hashtags'] = hashtags_list json_file_name = "output/" + self.target + "_hashtags.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_info(self): content = requests.get("https://www.instagram.com/" + str(self.target) + "/?__a=1") if content.status_code == 404: print("Oops... " + str(self.target) + " non exist, please enter a valid username.") sys.exit(2) data = content.json() data = data['graphql']['user'] pc.printout("[ID] ", pc.GREEN) pc.printout(str(data['id']) + '\n') pc.printout("[FULL NAME] ", pc.RED) pc.printout(str(data['full_name']) + '\n') pc.printout("[BIOGRAPHY] ", pc.CYAN) pc.printout(str(data['biography']) + '\n') pc.printout("[FOLLOWED] ", pc.BLUE) pc.printout(str(data['edge_followed_by']['count']) + '\n') pc.printout("[FOLLOW] ", pc.GREEN) pc.printout(str(data['edge_follow']['count']) + '\n') pc.printout("[BUSINESS ACCOUNT] ", pc.RED) pc.printout(str(data['is_business_account']) + '\n') if data['is_business_account']: pc.printout("[BUSINESS CATEGORY] ") pc.printout(str(data['business_category_name']) + '\n') pc.printout("[VERIFIED ACCOUNT] ", pc.CYAN) pc.printout(str(data['is_verified']) + '\n') if data['business_email']: pc.printout("[BUSINESS EMAIL] ", pc.BLUE) pc.printout(str(data['business_email']) + '\n') pc.printout("[HD PROFILE PIC] ", pc.GREEN) pc.printout(str(data['profile_pic_url_hd']) + '\n') if data['connected_fb_page']: pc.printout("[FB PAGE] ", pc.RED) pc.printout(str(data['business_email']) + '\n') if self.jsonDump: user = { 'id': data['id'], 'full_name': data['full_name'], 'biography': data['biography'], 'edge_followed_by': data['edge_followed_by']['count'], 'edge_follow': data['edge_follow']['count'], 'is_business_account': data['is_business_account'], 'is_verified': data['is_verified'], 'profile_pic_url_hd': data['profile_pic_url_hd'] } if data['business_email']: user['business_email'] = data['business_email'] if data['connected_fb_page']: user['connected_fb_page'] = data['connected_fb_page'] json_file_name = "output/" + self.target + "_info.json" with open(json_file_name, 'w') as f: json.dump(user, f) def get_total_likes(self): if self.check_private_profile(): return pc.printout("Searching for target total likes...\n") like_counter = 0 posts = 0 data = self.__get_feed__() for post in data: like_counter += post['like_count'] posts += 1 if self.writeFile: file_name = "output/" + self.target + "_likes.txt" file = open(file_name, "w") file.write( str(like_counter) + " likes in " + str(like_counter) + " posts\n") file.close() if self.jsonDump: json_data = {'like_counter': like_counter, 'posts': like_counter} json_file_name = "output/" + self.target + "_likes.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) pc.printout(str(like_counter), pc.MAGENTA) pc.printout(" likes in " + str(posts) + " posts\n") def get_media_type(self): if self.check_private_profile(): return pc.printout("Searching for target captions...\n") counter = 0 photo_counter = 0 video_counter = 0 data = self.__get_feed__() for post in data: if "media_type" in post: if post["media_type"] == 1: photo_counter = photo_counter + 1 elif post["media_type"] == 2: video_counter = video_counter + 1 counter = counter + 1 sys.stdout.write("\rChecked %i" % counter) sys.stdout.flush() sys.stdout.write(" posts") sys.stdout.flush() if counter > 0: if self.writeFile: file_name = "output/" + self.target + "_mediatype.txt" file = open(file_name, "w") file.write( str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n") file.close() pc.printout( "\nWoohoo! We found " + str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n", pc.GREEN) if self.jsonDump: json_data = {"photos": photo_counter, "videos": video_counter} json_file_name = "output/" + self.target + "_mediatype.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_who_commented(self): if self.check_private_profile(): return pc.printout("Searching for users who commented...\n") data = self.__get_feed__() users = [] for post in data: comments = self.__get_comments__(post['id']) for comment in comments: if not any(u['id'] == comment['user']['pk'] for u in users): user = { 'id': comment['user']['pk'], 'username': comment['user']['username'], 'full_name': comment['user']['full_name'], 'counter': 1 } users.append(user) else: for user in users: if user['id'] == comment['user']['pk']: user['counter'] += 1 break if len(users) > 0: ssort = sorted(users, key=lambda value: value['counter'], reverse=True) json_data = {} t = PrettyTable() t.field_names = ['Comments', 'ID', 'Username', 'Full Name'] t.align["Comments"] = "l" t.align["ID"] = "l" t.align["Username"] = "******" t.align["Full Name"] = "l" for u in ssort: t.add_row([ str(u['counter']), u['id'], u['username'], u['full_name'] ]) print(t) if self.writeFile: file_name = "output/" + self.target + "_users_who_commented.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['users_who_commented'] = ssort json_file_name = "output/" + self.target + "_users_who_commented.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_who_tagged(self): if self.check_private_profile(): return pc.printout("Searching for users who tagged target...\n") posts = [] result = self.api.usertag_feed(self.target_id) posts.extend(result.get('items', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) posts.extend(results.get('items', [])) next_max_id = results.get('next_max_id') if len(posts) > 0: pc.printout("\nWoohoo! We found " + str(len(posts)) + " photos\n", pc.GREEN) users = [] for post in posts: if not any(u['id'] == post['user']['pk'] for u in users): user = { 'id': post['user']['pk'], 'username': post['user']['username'], 'full_name': post['user']['full_name'], 'counter': 1 } users.append(user) else: for user in users: if user['id'] == post['user']['pk']: user['counter'] += 1 break ssort = sorted(users, key=lambda value: value['counter'], reverse=True) json_data = {} t = PrettyTable() t.field_names = ['Photos', 'ID', 'Username', 'Full Name'] t.align["Photos"] = "l" t.align["ID"] = "l" t.align["Username"] = "******" t.align["Full Name"] = "l" for u in ssort: t.add_row([ str(u['counter']), u['id'], u['username'], u['full_name'] ]) print(t) if self.writeFile: file_name = "output/" + self.target + "_users_who_tagged.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['users_who_tagged'] = ssort json_file_name = "output/" + self.target + "_users_who_tagged.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_photo_description(self): if self.check_private_profile(): return content = requests.get("https://www.instagram.com/" + str(self.target) + "/?__a=1") data = content.json() dd = data['graphql']['user']['edge_owner_to_timeline_media']['edges'] if len(dd) > 0: pc.printout( "\nWoohoo! We found " + str(len(dd)) + " descriptions\n", pc.GREEN) count = 1 t = PrettyTable(['Photo', 'Description']) t.align["Photo"] = "l" t.align["Description"] = "l" json_data = {} descriptions_list = [] for i in dd: node = i.get('node') descr = node.get('accessibility_caption') t.add_row([str(count), descr]) if self.jsonDump: description = {'description': descr} descriptions_list.append(description) count += 1 if self.writeFile: file_name = "output/" + self.target + "_photodes.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['descriptions'] = descriptions_list json_file_name = "output/" + self.target + "_descriptions.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_photo(self): if self.check_private_profile(): return limit = -1 pc.printout("How many photos you want to download (default all): ", pc.YELLOW) user_input = input() try: if user_input == "": pc.printout("Downloading all photos avaible...\n") else: limit = int(user_input) pc.printout("Downloading " + user_input + " photos...\n") except ValueError: pc.printout("Wrong value entered\n", pc.RED) return data = [] counter = 0 result = self.api.user_feed(str(self.target_id)) data.extend(result.get('items', [])) next_max_id = result.get('next_max_id') while next_max_id: results = self.api.user_feed(str(self.target_id), max_id=next_max_id) data.extend(results.get('items', [])) next_max_id = results.get('next_max_id') try: for item in data: if counter == limit: break if "image_versions2" in item: counter = counter + 1 url = item["image_versions2"]["candidates"][0]["url"] photo_id = item["id"] end = "output/" + self.target + "_" + photo_id + ".jpg" urllib.request.urlretrieve(url, end) sys.stdout.write("\rDownloaded %i" % counter) sys.stdout.flush() else: carousel = item["carousel_media"] for i in carousel: if counter == limit: break counter = counter + 1 url = i["image_versions2"]["candidates"][0]["url"] photo_id = i["id"] end = "output/" + self.target + "_" + photo_id + ".jpg" urllib.request.urlretrieve(url, end) sys.stdout.write("\rDownloaded %i" % counter) sys.stdout.flush() except AttributeError: pass except KeyError: pass sys.stdout.write(" photos") sys.stdout.flush() pc.printout( "\nWoohoo! We downloaded " + str(counter) + " photos (saved in output/ folder) \n", pc.GREEN) def get_user_propic(self): content = requests.get("https://www.instagram.com/" + str(self.target) + "/?__a=1") if content.status_code == 404: print("Oops... " + str(self.target) + " non exist, please enter a valid username.") sys.exit(2) data = content.json() uurl = data["graphql"]["user"] if "profile_pic_url_hd" in uurl: URL = data["graphql"]["user"]["profile_pic_url_hd"] else: URL = data["graphql"]["user"]["profile_pic_url"] if URL != "": end = "output/" + self.target + "_propic.jpg" urllib.request.urlretrieve(URL, end) pc.printout("Target propic saved in output folder\n", pc.GREEN) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user_stories(self): if self.check_private_profile(): return pc.printout("Searching for target stories...\n") data = self.api.user_reel_media(str(self.target_id)) counter = 0 if data['items'] is not None: # no stories avaibile counter = data['media_count'] for i in data['items']: story_id = i["id"] if i["media_type"] == 1: # it's a photo url = i['image_versions2']['candidates'][0]['url'] end = "output/" + self.target + "_" + story_id + ".jpg" urllib.request.urlretrieve(url, end) elif i["media_type"] == 2: # it's a gif or video url = i['video_versions'][0]['url'] end = "output/" + self.target + "_" + story_id + ".mp4" urllib.request.urlretrieve(url, end) if counter > 0: pc.printout( str(counter) + " target stories saved in output folder\n", pc.GREEN) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_people_tagged_by_user(self): pc.printout("Searching for users tagged by target...\n") ids = [] username = [] full_name = [] post = [] counter = 1 data = self.__get_feed__() try: for i in data: if "usertags" in i: c = i.get('usertags').get('in') for cc in c: if cc.get('user').get('pk') not in ids: ids.append(cc.get('user').get('pk')) username.append(cc.get('user').get('username')) full_name.append(cc.get('user').get('full_name')) post.append(1) else: index = ids.index(cc.get('user').get('pk')) post[index] += 1 counter = counter + 1 except AttributeError as ae: pc.printout("\nERROR: an error occurred: ", pc.RED) print(ae) print("") pass if len(ids) > 0: t = PrettyTable() t.field_names = ['Posts', 'Full Name', 'Username', 'ID'] t.align["Posts"] = "l" t.align["Full Name"] = "l" t.align["Username"] = "******" t.align["ID"] = "l" pc.printout( "\nWoohoo! We found " + str(len(ids)) + " (" + str(counter) + ") users\n", pc.GREEN) json_data = {} tagged_list = [] for i in range(len(ids)): t.add_row([post[i], full_name[i], username[i], str(ids[i])]) if self.jsonDump: tag = { 'post': post[i], 'full_name': full_name[i], 'username': username[i], 'id': ids[i] } tagged_list.append(tag) if self.writeFile: file_name = "output/" + self.target + "_tagged.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['tagged'] = tagged_list json_file_name = "output/" + self.target + "_tagged.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_user(self, username): content = requests.get("https://www.instagram.com/" + username + "/?__a=1") if content.status_code == 404: print("Oops... " + str(self.target) + " non exist, please enter a valid username.") sys.exit(2) data = content.json() if self.writeFile: file_name = "output/" + self.target + "_user_id.txt" file = open(file_name, "w") file.write(str(data['graphql']['user']['id'])) file.close() user = dict() user['id'] = data['graphql']['user']['id'] user['is_private'] = data['graphql']['user']['is_private'] return user def set_write_file(self, flag): if flag: pc.printout("Write to file: ") pc.printout("enabled", pc.GREEN) pc.printout("\n") else: pc.printout("Write to file: ") pc.printout("disabled", pc.RED) pc.printout("\n") self.writeFile = flag def set_json_dump(self, flag): if flag: pc.printout("Export to JSON: ") pc.printout("enabled", pc.GREEN) pc.printout("\n") else: pc.printout("Export to JSON: ") pc.printout("disabled", pc.RED) pc.printout("\n") self.jsonDump = flag def login(self, u, p): try: settings_file = "config/settings.json" if not os.path.isfile(settings_file): # settings file does not exist print('Unable to find file: {0!s}'.format(settings_file)) # login new self.api = AppClient( auto_patch=True, authenticate=True, username=u, password=p, on_login=lambda x: self.onlogin_callback(x, settings_file)) else: with open(settings_file) as file_data: cached_settings = json.load(file_data, object_hook=self.from_json) # print('Reusing settings: {0!s}'.format(settings_file)) # reuse auth settings self.api = AppClient( username=u, password=p, settings=cached_settings, on_login=lambda x: self.onlogin_callback(x, settings_file)) except (ClientCookieExpiredError, ClientLoginRequiredError) as e: print('ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'. format(e)) # Login expired # Do relogin but use default ua, keys and such self.api = AppClient( auto_patch=True, authenticate=True, username=u, password=p, on_login=lambda x: self.onlogin_callback(x, settings_file)) except ClientError as e: #pc.printout('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response), pc.RED) error = json.loads(e.error_response) pc.printout(error['message'], pc.RED) pc.printout("\n") if 'challenge' in error: print("Please follow this link to complete the challenge: " + error['challenge']['url']) exit(9) def to_json(self, python_object): if isinstance(python_object, bytes): return { '__class__': 'bytes', '__value__': codecs.encode(python_object, 'base64').decode() } raise TypeError(repr(python_object) + ' is not JSON serializable') def from_json(self, json_object): if '__class__' in json_object and json_object['__class__'] == 'bytes': return codecs.decode(json_object['__value__'].encode(), 'base64') return json_object def onlogin_callback(self, api, new_settings_file): cache_settings = api.settings with open(new_settings_file, 'w') as outfile: json.dump(cache_settings, outfile, default=self.to_json) # print('SAVED: {0!s}'.format(new_settings_file)) def check_following(self): endpoint = 'users/{user_id!s}/full_detail_info/'.format( **{'user_id': self.target_id}) return self.api._call_api( endpoint)['user_detail']['user']['friendship_status']['following'] def check_private_profile(self): if self.is_private and not self.following: pc.printout( "Impossible to execute command: user has private profile\n", pc.RED) send = input("Do you want send a follow request? [Y/N]: ") if send.lower() == "y": self.api.friendships_create(self.target_id) print( "Sent a follow request to target. Use this command after target accepting the request." ) return True return False def get_fwersemail(self): if self.check_private_profile(): return pc.printout( "Searching for emails of target followers... this can take a few minutes\n" ) followers = [] rank_token = AppClient.generate_uuid() data = self.api.user_followers(str(self.target_id), rank_token=rank_token) for user in data['users']: u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followers.append(u) results = [] for follow in followers: content = requests.get("https://www.instagram.com/" + str(follow['username']) + "/?__a=1") data = content.json() data = data['graphql']['user'] if data['business_email']: follow['email'] = data['business_email'] results.append(follow) if len(results) > 0: t = PrettyTable(['ID', 'Username', 'Full Name', 'Email']) t.align["ID"] = "l" t.align["Username"] = "******" t.align["Full Name"] = "l" t.align["Email"] = "l" json_data = {} for node in results: t.add_row([ str(node['id']), node['username'], node['full_name'], node['email'] ]) if self.writeFile: file_name = "output/" + self.target + "_fwersemail.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followers_email'] = results json_file_name = "output/" + self.target + "_fwersemail.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED) def get_fwingsemail(self): if self.check_private_profile(): return pc.printout( "Searching for emails of users followed by target... this can take a few minutes\n" ) followings = [] rank_token = AppClient.generate_uuid() data = self.api.user_following(str(self.target_id), rank_token=rank_token) for user in data['users']: u = { 'id': user['pk'], 'username': user['username'], 'full_name': user['full_name'] } followings.append(u) results = [] for follow in followings: content = requests.get("https://www.instagram.com/" + str(follow['username']) + "/?__a=1") data = content.json() data = data['graphql']['user'] if data['business_email']: follow['email'] = data['business_email'] results.append(follow) if len(results) > 0: t = PrettyTable(['ID', 'Username', 'Full Name', 'Email']) t.align["ID"] = "l" t.align["Username"] = "******" t.align["Full Name"] = "l" t.align["Email"] = "l" json_data = {} for node in results: t.add_row([ str(node['id']), node['username'], node['full_name'], node['email'] ]) if self.writeFile: file_name = "output/" + self.target + "_fwingsemail.txt" file = open(file_name, "w") file.write(str(t)) file.close() if self.jsonDump: json_data['followings_email'] = results json_file_name = "output/" + self.target + "_fwingsemail.json" with open(json_file_name, 'w') as f: json.dump(json_data, f) print(t) else: pc.printout("Sorry! No results found :-(\n", pc.RED)
target_followers = api.user_followers(pk, rank_tok) i=1 like_posts = [] #идем по каждому фолловеру for tg_follower in target_followers['users']: print('\tБерем его друга: ' + tg_follower['username']) if tg_follower['is_private'] == False: #print(tg_follower) data_follow = api.friendships_show(tg_follower['pk']) #print(data_follow) #Я на него не подписан if data_follow['following'] == False: print('\t\tОн не в друзьях, подписка') #подписываемся friend = api.friendships_create(tg_follower['pk']) cnt_feed=randint(2, 3) #print('Пролайкаем ' + str(cnt_feed) + 'поста') feed_user = api.user_feed(tg_follower['pk']) f=1 sum_time = 0 #идем по каждому посту в ленте пользователя for feed in feed_user['items']: id_media = feed['id'] #проверим, ставили ли мы лайк на этот пост conn = psycopg2.connect(dbname='grammer', user='******', password='******', host='localhost') cursor = conn.cursor() cursor.execute("""SELECT id FROM likes WHERE account = %s AND id_account = %s AND id_post = %s """, (id, str(tg_follower['pk']), str(id_media))) res = cursor.fetchone()
print('[i] Operation aborted!') exit() maxx = int(input('[%] Maximum users to follow: ')) initial_user = input('[%] What user do you want the suggested people to come from?: ') exclusions_x = exclusions.split(';') user_info = api.username_info(initial_user) uid = user_info['user']['pk'] suggested = api.discover_chaining(uid)['users'] i = 0 while(True): for u_info in suggested: if(i == maxx): print('[i] Max users reached!') print('[+] Followed ' + str(i) + ' users!') exit() if(i % entries_ == 0 and i != 0): print('[i] Waiting ' + str(SECURE_DELAY) + ' seconds before continuing for security reasons...') time.sleep(SECURE_DELAY) if(u_info['username'] in exclusions_x): print('[i] User ' + u_info['username'] + ' is present in exclusion list. skipping...') continue api.friendships_create(u_info['pk']) print('[+] Followed: uid = ' + str(u_info['pk']) + ' ; username = '******'username'] + ' ; name = ' + u_info['full_name']) i += 1 print('[+] Followed ' + str(i) + ' users!')
'fcbarcelona': '260375673', 'realmadrid': '290023231', 'theellenshow': '18918467', 'justintimberlake': '303054725', 'zendaya': '9777455' } for i in range(1000): for key, value in celebrities.items(): while is_connected() == False: print("no internet connecton ") print("rechecking ...") sleep(1) api.friendships_create(value) print("{0} : Followed successfully".format(key)) sleep(5) print('') print('relaxing ..') print('') for key, value in celebrities.items(): while is_connected() == False: print("no internet connecton ") print("rechecking ...") sleep(1) api.friendships_destroy(value) print("{0} : Unfollowed successfully".format(key))