def get_non_followers(username, password, my_max_following=1000): api = Client(username, password, timeout=30) print('Successfully Logged In.') my_account = api.username_info(username)['user'] # Getting my following list my_following = api.user_following(my_account['pk'], api.generate_uuid()) all_following = [*my_following['users']] print('Getting your followers...') sleep(2) # mimicking the real user while len(my_following) < my_max_following and my_following['next_max_id']: next_list = api.user_following(my_account['pk'], api.generate_uuid(), max_id=my_following['next_max_id']) print(next_list['next_max_id']) all_following += next_list['users'] sleep(2) # mimicking the real user if not next_list['next_max_id']: break # Checking print('Checking...') not_following = 0 for user in all_following: try: resp = api.user_following(user['pk'], api.generate_uuid(), query=username) if not resp['users']: print(f"@{user['username']} is not following you back") not_following += 1 except: pass print(f'Total of {not_following} accounts do not follow you back')
def setupClients(self): self.log_info("Setting up clients with given credentials") for account in self.account_creds: u = account["u"] p = account["p"] self.log_debug( "Creating Instagram client object with username: %s " % u) try: c = Client(account["u"], account["p"]) self.client_objs.append({ "client": c, "feed": None, "u": u, "uuid": c.generate_uuid() }) self.log_info( "Successfully created Instagram client object with username: %s " % u) except Exception as e: self.log_warning( "Error encountered when authenticating to Instagram with username: %s - SKIPPING" % u) self.log_error("%s\n%s" % (e, traceback.format_exc())) continue
def get_new_posts(api, from_date, to_date, tag, username, media_type): # Call the api new_posts = [] uuid = Client.generate_uuid() results = api.feed_tag(tag, uuid) loop = True date_flags = 0 date_flags_thresold = 4 assert len(results.get('items', [])) > 0 while loop: posts = results.get('items', []) # iterate throught the results for post in posts: # retrieve post data mt, dt, usr, iurl, vurl, id = extract_post_data(post) # if the post is within the date range if (dt > from_date and dt < to_date and usr != username): if mt == media_type or media_type == 0: new_posts.append(post) # count the wrong dates if dt < from_date: date_flags += 1 if date_flags > date_flags_thresold: loop = False next_max_id = results.get('next_max_id') results = api.feed_tag(tag, uuid, max_id = next_max_id) assert len(results.get('items', [])) > 0 return new_posts
def main(): success = False username, password = get_user_passwd() user_settings = get_user_settings() while not success: # try: if user_settings is False: print('Logging user to create cookie...') api = Client(username, password) user_settings = api.settings save_settings(user_settings) else: print('Getting saved cookie...') cookie = user_settings['cookie'] api = Client('', '', cookie=cookie) user_id = api.authenticated_user_id rank_token = api.generate_uuid() following = api.user_following(user_id=user_id, rank_token=rank_token)['users'] followers = api.user_followers(user_id=user_id, rank_token=rank_token) with open('followers.json', 'w') as f: json.dump(followers, f) success = True
def get_follows(api: Client, show: bool = True, follow_type: str = 'following') -> dict: """ Depending on the follow_type, a dictionary will be obtained that contains the users who follow the current user or those that the current user is following Arguments: api (Client) : Object instagram Client show (bool) : Indicates whether the filtered user names should be printed or not follow_type (str) : Can be following or followed """ rank = api.generate_uuid() user_id = api.authenticated_user_id if follow_type == 'following': results = api.user_following(user_id, rank) prefix = "You are" else: results = api.user_followers(user_id, rank) prefix = "Your" text = f"{prefix} {follow_type}: \n" if show: print_write_chatbot(text, color='blue', attrs_color=['bold', 'underline']) for user in results['users']: print_write_chatbot(f"{user['username']}") return results
class Endpoint: def __init__(self, username, password): self.username = username self.password = password self.api = Client(username, password) def getUserID(self): return self.api.authenticated_user_id def getFollowers(self, userid): return self.api.user_followers(userid, self.api.generate_uuid()) def getFollowing(self, userid): return self.api.user_following(userid, self.api.generate_uuid()) def getFeedLiked(self): return self.api.feed_liked()
def get_token_uuid(app_logger): ''' Function to generate rank token UUID ''' app_logger.debug('Generating rank token...') rank_token = Client.generate_uuid() app_logger.debug('Generated rank token is {0!s}'.format(rank_token)) return rank_token
def getHashtagGen(generate_rank=Client.generate_uuid(), hashtag = 'cats', limit = 60): rank_token = generate_rank has_more = True id_tag_results = [] while has_more and rank_token and len(id_tag_results) < limit: results = api.tag_search(hashtag, rank_token, exclude_list=id_tag_results) id_tag_results.extend(i['id'] for i in results.get('results', [])) has_more = results.get('has_more') rank_token = results.get('rank_token') yield results.get('results', [])
def getHashtag(generate_rank=Client.generate_uuid(), hashtag = 'cats', limit = 60): rank_token = generate_rank has_more = True tag_results = [] while has_more and rank_token and len(tag_results) < limit: results = api.tag_search( hashtag, rank_token, exclude_list=[t['id'] for t in tag_results]) tag_results.extend(results.get('results', [])) has_more = results.get('has_more') rank_token = results.get('rank_token') return tag_results
def get_followers(userid): followers = [] rank_token = Client.generate_uuid() res = api.user_following(userid, rank_token) followers.extend(res.get("users", [])) next_max_id = res.get("next_max_id") while next_max_id: res = api.user_following(userid, rank_token, max_id=next_max_id) followers.extend(res.get("users", [])) next_max_id = res.get("next_max_id") return followers
def getAllUsersGen(user_id = '2958144170', rank_token = Client.generate_uuid()): followers = [] results = api.user_followers(user_id, rank_token) followers = results.get('users', []) yield [id['pk'] for id in followers] next_max_id = results.get('next_max_id') while next_max_id: results = api.user_followers(user_id, rank_token, max_id=next_max_id) followers = results.get('users', []) yield [id['pk'] for id in followers] next_max_id = results.get('next_max_id')
def getHashtagFeedGen(gen_token = Client.generate_uuid(), hashtag = 'cats', limit = 60): results = api.feed_tag(hashtag, gen_token) tgs_number = len(results.get('ranked_items', [])) tgs_number += len(results.get('items', [])) yield results.get('ranked_items', []) + results.get('items', []) more_available = results['more_available'] while more_available: results = api.feed_tag(hashtag, gen_token) yield results.get('ranked_items', []) + results.get('items', []) tgs_number += len(results.get('ranked_items', []) + results.get('items', [])) if tgs_number >= limit: break more_available = results['more_available']
def getAllUsers(user_id = '2958144170', rank_token = Client.generate_uuid()): followers = [] results = api.user_followers(user_id, rank_token) followers.extend(results.get('users', [])) next_max_id = results.get('next_max_id') while next_max_id: results = api.user_followers(user_id, rank_token, max_id=next_max_id) followers.extend(results.get('users', [])) next_max_id = results.get('next_max_id') followers.sort(key=lambda x: x['pk']) return [id['pk'] for id in followers]
def getHashtagFeed(gen_token = Client.generate_uuid(), hashtag = 'cats', limit = 60): results = api.feed_tag(hashtag, gen_token) tgs = [] tgs.extend(results.get('ranked_items', [])) tgs.extend(results.get('items', [])) more_available = results['more_available'] while more_available: results = api.feed_tag(hashtag, gen_token) tgs.extend(results.get('ranked_items', [])) tgs.extend(results.get('items', [])) if len(tgs) >= limit: break more_available = results['more_available'] return tgs
def first_run(api: instagram_private_api.Client) -> Dict[str, int]: """ Finds all users that you are following, and puts them into a dictionary. :param api: Instagram API that is logged into :return: dictionary. key: instagram username. value: instagram user_id """ # Initialize result dictionary dict_of_users_following = {} # Iterate through client's user_following. uses user_id and uuid, returns a dictionary we go through for user in api.user_following(api.authenticated_user_id, api.generate_uuid())['users']: # every use is a dictionary. 'pk' is user_id. username is username. dict_of_users_following[user['username']] = user['pk'] # Return result return dict_of_users_following
def searchUser(cookie, setting, userName): cookie = decodeCookie(cookie) # setting = json.loads(setting) try: user = Client("none", "none", cookie=cookie, setting=setting) for i in range(3): try: out = user.search_users(userName, rank_token=user.generate_uuid()) out = list(map(lambda x: {"userId": x["pk"], "username": x["username"],"pic_url": x["profile_pic_url"], 'followers': x["follower_count"]}, out["users"])) return out except ClientCookieExpiredError: return {"error": "نیاز به لاگین مجدد"} except ClientCookieExpiredError: return {"error": "نیاز به لاگین مجدد"} return []
def main(): os.system('cls') user = input(Fore.YELLOW + "[Paso 1/4] " + Fore.CYAN + "Correo de la cuenta" + Fore.YELLOW + "\n-> ") password = getpass(Fore.YELLOW + "[Paso 2/4] " + Fore.CYAN + "Contraseña de la cuenta" + Fore.YELLOW + "\n-> ") msj = input(Fore.YELLOW + "[Paso 3/4] " + Fore.CYAN + "Mensaje a enviar" + Fore.YELLOW + "\n-> ") max_comments = input(Fore.YELLOW + "[Paso 4/4] " + Fore.CYAN + "Número máximo de comentarios" + Fore.YELLOW + "\n-> ") client = Client(user, password) userid = client.authenticated_user_id rank_token = client.generate_uuid() destinatarios = [] publicaciones = [] publicaciones_aux = [] users = client.user_following(userid, rank_token)['users'] for i in users: contact = i['pk'] destinatarios.append(contact) print(destinatarios) client.logout() bot = Bot() bot.login(username=user, password=password, use_cookie=False) for i in destinatarios: publicaciones_aux = bot.get_user_medias(user_id=i, is_comment=True) publicaciones.append(publicaciones_aux[0]) bot.logout() print(publicaciones) comment(user, password, publicaciones, msj, max_comments) print(Fore.WHITE) os.system('pause')
def find_split(self, instagram_account): # Выполянет поиск пересечений result_followers = [] for account in instagram_account: logging.info("Check %s " % account) rank_token = Client.generate_uuid() user_id = self.api.username_info(account)["user"]["pk"] followers = [] results = self.api.user_followers(user_id, rank_token) followers.extend(results.get('users', [])) next_max_id = results.get('next_max_id') while next_max_id: results = self.api.user_followers(user_id, rank_token=rank_token, max_id=next_max_id) followers.extend(results.get('users', [])) if len(followers) >= 20000: # get only first 600 or so break next_max_id = results.get('next_max_id') followers.sort(key=lambda x: x['pk']) result_followers.append(followers) logging.info("Finding split") split = [] for f_list in result_followers: for item in f_list: if item in split: continue find = 0 for f in result_followers: if item in f: find += 1 if find == len(result_followers): split.append(item) logging.info("Find account: %i" % len(split)) return split
def like_user_recent_photo(instagram_api, name): """Like most recent post by user""" rank_token = Client.generate_uuid() result = instagram_api.search_users(name, rank_token) if result['num_results'] <= 0: print(f'ERROR: User {name} not found') else: user = result['users'][0] if user['friendship_status']['is_private'] is True: print(f'User {name} is private') else: feed = instagram_api.user_feed(user['pk']) first_item = feed["items"][0] if "comment_likes_enabled" in first_item and \ first_item["comment_likes_enabled"] is False: print( f'User {name} most recent post has disabled for likes and comments' ) elif first_item["has_liked"]: print(f'User {name} most recent post has already been liked') else: instagram_api.post_like(first_item["id"]) print(f'You just liked the most recent post of user {name}')