Exemplo n.º 1
0
 def __init__(self, instaData):
     self.data = instaData
     self.instaApi = Client("sammy.g.spam", "vq86koli")
     self.counter = 6
     self.comments = {}
     self.contestants = []
     print("InstagramValidityCheck.State : Initialized")
Exemplo n.º 2
0
    def login(self, username: str, password: str):
        """Logs to Instagram

        :param username: Instagram login name
        :param password: Instagram login password
        """
        self.api = Client(username, password)
Exemplo n.º 3
0
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')
Exemplo n.º 4
0
 def __init__(self, username, password):
     print("setting up instagram scraper...")
     self.username = username
     self.password = password
     self.api = Client(username=username, password=password)
     self.user_id = self.api.username_info(self.username)['user']['pk']
     print("instagram scraper successfully initialized!")
Exemplo n.º 5
0
def main(user, password, destinatarios):

    client = Client(user, password)
    for i in destinatarios:
        client.post_comment(i, 'Holis')
    client.logout()
    return
Exemplo n.º 6
0
def login_to_account(username, password):
    try:
        Client(username, password)
        return True
    except Exception as e:
        if (str(e) == "checkpoint_challange_required"):
            return True
        return False
Exemplo n.º 7
0
def login(
    username,
    password,
    user_agent='Instagram 121.0.0.29.119 Android (26/8.0.0; 560dpi; 1440x2792; samsung; SM-G955F; dream2lte; samsungexynos8895; en_US; 185203708)'
):
    device_id = None
    try:
        settings_file = "latest_client.json"
        if not os.path.isfile(settings_file):
            api = Client(
                username,
                password,
                user_agent=user_agent,
                on_login=lambda x: onlogin_callback(x, "latest_client.json"),
            )
        else:
            with open(settings_file) as file_data:
                cached_settings = json.load(file_data, object_hook=from_json)
            device_id = cached_settings.get('device_id')
            api = Client(
                username,
                password,
                user_agent=user_agent,
                settings=cached_settings,
            )

    except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
        api = Client(
            username,
            password,
            device_id=device_id,
            user_agent=user_agent,
            on_login=lambda x: onlogin_callback(x, "latest_client.json"))

    except ClientLoginError as e:
        print('ClientLoginError {0!s}'.format(e))
        exit(9)
    except ClientError as e:
        print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(
            e.msg, e.code, e.error_response))
        exit(9)
    except Exception as e:
        print('Unexpected Exception: {0!s}'.format(e))
        exit(99)

    return api
Exemplo n.º 8
0
def login():
    """ Logs in using details in login_details.txt """
    settings_file_path = SETTINGS_FILE_PATH
    username, password = open_file(LOGIN_FILE_PATH)
    username = username.strip()
    password = password.strip()
    device_id = None
    api = None

    try:
        settings_file = settings_file_path
        if not os.path.isfile(settings_file):
            # settings file does not exist
            print('Unable to find file: {0!s}'.format(settings_file))

            # login new
            api = Client(username, password, on_login=lambda x: on_login_callback(x, settings_file_path))
        else:
            with open(settings_file) as file_data:
                cached_settings = json.load(file_data, object_hook=from_json)
            print('Reusing settings: {0!s}'.format(settings_file))

            device_id = cached_settings.get('device_id')
            # reuse auth settings
            api = Client(username, password, settings=cached_settings)

    except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
        print('ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e))

        # Login expired
        # Do relogin but use default ua, keys and such
        api = Client(username, password, device_id=device_id,
                     on_login=lambda x: on_login_callback(x, settings_file_path))

    except ClientLoginError as e:
        print('ClientLoginError {0!s}'.format(e))
        exit(9)
    except ClientError as e:
        print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response))
        exit(9)
    except Exception as e:
        print('Unexpected Exception: {0!s}'.format(e))
        exit(99)

    return api
Exemplo n.º 9
0
def login(username, password):
    # Try load the cookie_jar
    device_id = None
    try:
        settings_file = 'cookie_cache/' + username
        if not os.path.isfile(settings_file):
            # settings file does not exist
            print('Unable to find file: {0!s}'.format(settings_file))

            # login new
            return Client(
                username,
                password,
                on_login=lambda x: onlogin_callback(x, settings_file))
        else:
            with open(settings_file) as file_data:
                cached_settings = json.load(file_data, object_hook=from_json)
            print('Reusing settings: {0!s}'.format(settings_file))

            device_id = cached_settings.get('device_id')
            # reuse auth settings
            return Client(username, password, settings=cached_settings)

    except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
        print(
            'ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(
                e))

        # Login expired
        # Do relogin but use default ua, keys and such
        return Client(username,
                      password,
                      device_id=device_id,
                      on_login=lambda x: onlogin_callback(x, settings_file))

    except ClientLoginError as e:
        print('ClientLoginError {0!s}'.format(e))
        exit(9)
    except ClientError as e:
        print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(
            e.msg, e.code, e.error_response))
        exit(9)
    except Exception as e:
        print('Unexpected Exception: {0!s}'.format(e))
        exit(99)
Exemplo n.º 10
0
async def login(username, password):  # authorize to account
    try:
        api = Client(username, password)
        print('[I] Login to "' + username + '" OK!')
        return api

    except Exception as err:
        print('[E] Login to ' + username + ' FAILED!\n ERROR: {}'.format(err))
        return
Exemplo n.º 11
0
def get_instagram_users(search, max_id=None):
    user_name = 'lam.laca'
    password = '******'
    api = Client(user_name, password)
    if max_id:
        results = api.search_users(search, max_id=max_id)
    else:
        results = api.search_users(search)
    return results
Exemplo n.º 12
0
def StartBruteSpecificInfo(username,password):
    try:
        api = Client(username, password)
        PrintText('HACKED','{0}:{1}'.format(api.authenticated_user_name,password),Fore.GREEN,Fore.WHITE)
        os.system('pause >NUL')
    except instagram_private_api.ClientLoginError as c:
            PrintText('ERROR','{0}:{1} -> {2}'.format(username,password,c),Fore.RED,Fore.WHITE)
    except:
        PrintText('ERROR','{0}:{1} -> ratelimit error waiting {2}s'.format(username,password,retry_time),Fore.RED,Fore.WHITE)
        time.sleep(retry_time)
Exemplo n.º 13
0
    def __init__(self, username, password, API=None, action_interval=8.0, rate=1, interval=86400):
        self.username = username
        self.password = password

        self.action_interval = action_interval
        self.rate = rate
        self.interval = interval
        self.logger = logging.LoggerAdapter(logger, {'user': self.username, 'bot': 'instapost'})

        self.API = Client(self.username, self.password) if API is None else API
Exemplo n.º 14
0
def login():
    #reddit
    reddit = Reddit(client_id=config["client_id"],
                    client_secret=config["client_secret"],
                    password=config["redditpassword"],
                    user_agent=config["user_agent"],
                    username=config["redditusername"])
    # instagram
    instagram = Client(config["instagramusername"],
                       config["instagrampassword"])
    return reddit, instagram
Exemplo n.º 15
0
def isLogin(cookie, setting):
    cookie = decodeCookie(cookie)
    setting = json.loads(setting)
    user = Client("none", "none", cookie=cookie, setting=setting)
    for i in range(3):
        try:
            user.current_user()
            return True
        except ClientConnectionError:
            continue
        except:
            return False
    return False
Exemplo n.º 16
0
    def __init__(self, login=None, password=None, proxy=None):
        self.login = login
        self.password = password
        self.device_id = None

        try:
            settings_file = f'accounts/{self.login}.json'

            if not os.path.isfile(settings_file):

                self.api = Client(self.login,
                                  self.password,
                                  on_login=lambda x: onlogin_callback(
                                      x, f'accounts/{self.login}.json'),
                                  proxy=proxy)
            else:
                with open(settings_file) as file_data:
                    cached_settings = json.load(file_data,
                                                object_hook=from_json)

                self.device_id = cached_settings.get('device_id')

                self.api = Client(self.login,
                                  self.password,
                                  settings=cached_settings,
                                  proxy=proxy)
        except ClientCookieExpiredError as e:
            print('ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.
                  format(e))

            # Login expired
            # Do relogin but use default ua, keys and such
            self.api = Client(
                self.login,
                self.password,
                device_id=self.device_id,
                on_login=lambda x: onlogin_callback(x, settings_file),
                proxy=proxy)
Exemplo n.º 17
0
 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 = []
Exemplo n.º 18
0
def unofficial(user_name, password, LIMIT_IMAGE_COUNT, HASHTAG):
    api = Client(user_name, password)

    all_hash_image_posts_urls = []
    next_max_id = None
    while (api.feed_tag(HASHTAG, api.generate_uuid())["more_available"]
           == True) and (len([
               item for sublist in all_hash_image_posts_urls
               for item in sublist
           ]) <= LIMIT_IMAGE_COUNT):
        if next_max_id == None:
            # Gets the first 12 posts
            posts = api.feed_tag(HASHTAG, api.generate_uuid())
            len(posts['items'])
            image_urls = []
            for i in range(len(posts['items'])):
                try:
                    url = posts['items'][i]['image_versions2']['candidates'][0][
                        'url']  # some posts do not have 'image_version2', they are overlooked in that case
                    image_urls.append(url)
                except:
                    pass
                    # Extract the value *next_max_id* from the above response, this is needed to load the next 12 posts
            next_max_id = posts["next_max_id"]
            all_hash_image_posts_urls.append(image_urls)
        else:
            next_page_posts = api.feed_tag(HASHTAG, api.generate_uuid())
            len(next_page_posts['items'])
            # get image urls
            next_image_urls = []
            for i in range(len(next_page_posts['items'])):
                try:
                    url = next_page_posts['items'][i]['image_versions2'][
                        'candidates'][0]['url']
                    next_image_urls.append(url)
                except:
                    pass
            # Extract the value *next_max_id*
            next_max_id = next_page_posts["next_max_id"]
            all_hash_image_posts_urls.append(next_image_urls)

    else:
        flat_hash_image_posts_urls = [
            item for sublist in all_hash_image_posts_urls for item in sublist
        ]
        print(
            f"A total of {len(flat_hash_image_posts_urls)} image post urls were retrieved from the Instagram page."
        )

    return flat_hash_image_posts_urls
Exemplo n.º 19
0
def login(username, password):
    try:
        api = Client(username, password)
        results = api.feed_timeline()
        items = results.get('items', [])
        for item in items:
            print(item)
            media = ClientCompatPatch.media(item)
            print(media['code'])
    except:
        messagebox.showinfo(
            "Hata",
            "Instagram girişi hatalı lütfen kullanıcı adı şifrenizi kontrol ediniz"
        )
Exemplo n.º 20
0
def official(user_name, password, LIMIT_IMAGE_COUNT, USERNAME):
    api = Client(user_name, password)

    all_image_posts_urls = []
    next_max_id = None
    while (api.username_feed(USERNAME, max_id=next_max_id)["more_available"]
           == True) and (len(
               [item for sublist in all_image_posts_urls
                for item in sublist]) <= LIMIT_IMAGE_COUNT):
        if next_max_id == None:
            # Gets the first 12 posts
            posts = api.username_feed(USERNAME)
            len(posts['items'])
            image_urls = []
            for i in range(len(posts['items'])):
                try:
                    url = posts['items'][i]['image_versions2']['candidates'][
                        0]['url']
                    image_urls.append(url)
                except:
                    pass
            # Extract the value *next_max_id* from the above response, this is needed to load the next 12 posts
            next_max_id = posts["next_max_id"]
            all_image_posts_urls.append(image_urls)
        else:
            next_page_posts = api.username_feed(USERNAME, max_id=next_max_id)
            len(next_page_posts['items'])
            # get image urls
            next_image_urls = []
            for i in range(len(next_page_posts['items'])):
                try:
                    url = next_page_posts['items'][i]['image_versions2'][
                        'candidates'][0]['url']
                    next_image_urls.append(url)
                except:
                    pass
            # Extract the value *next_max_id*
            next_max_id = next_page_posts["next_max_id"]
            all_image_posts_urls.append(next_image_urls)

    else:
        flat_image_posts_urls = [
            item for sublist in all_image_posts_urls for item in sublist
        ]
        print(
            f"A total of {len(flat_image_posts_urls)} image post urls were retrieved from the Instagram page."
        )

    return flat_image_posts_urls
Exemplo n.º 21
0
Arquivo: ibot.py Projeto: rhawiz/ibot
def main():
    if len(sys.argv) >= 3:
        user_name = sys.argv[1]
        password = sys.argv[2]
        wait_before_start = 0
        interval = None
        action_interval = None
        unfollow_first = False
        rate = None
        if len(sys.argv) == 4:
            wait_before_start = int(sys.argv[3])
        if len(sys.argv) == 5:
            unfollow_first = True if sys.argv[4] else False
        if len(sys.argv) == 6:
            interval = int(sys.argv[5])
        if len(sys.argv) == 7:
            action_interval = int(sys.argv[6])
        if len(sys.argv) == 8:
            rate = int(sys.argv[7])

    else:
        user_name = input("Username:"******"Password:"******"Time to wait before starting bot in seconds:") or 0)
        unfollow_first = True if input("Unfollow all first:") else False
        interval = int(
            input("Interval in seconds (wait time between 40 requests):"))
        action_interval = int(
            input("Action Interval (wait time between each request):"))
        rate = int(input("Rate (amount of requests between each interval):"))

    print(">> Bot started. Waiting {} seconds before starting.".format(
        wait_before_start))
    print(">> Unfollow First: {}".format(unfollow_first))
    print(">> Interval: {}".format(interval))
    print(">> Action Interval: {}".format(action_interval))
    print(">> Rate: {}".format(rate))
    sleep(wait_before_start)

    api = Client(user_name, password)

    print(">> Logged in with user '{}'".format(user_name))

    f1 = unfollow if unfollow_first else follow
    f2 = follow if unfollow_first else unfollow
    while True:
        f1(api, interval=interval, action_interval=action_interval, rate=rate)
        f2(api, interval=interval, action_interval=action_interval, rate=rate)
Exemplo n.º 22
0
def login(username, password, path_cookie):
    print('Client version: {0!s}'.format(client_version))
    device_id = None

    try:
        if not os.path.isfile(path_cookie):
            api = Client(username, password, on_login=lambda x: onlogin_callback(x, "insta_cookie"))

        else:
            with open(path_cookie) as file_data:
                cached_settings = json.load(file_data, object_hook=from_json)
            print('Reusing settings: {0!s}'.format(path_cookie))
            device_id = cached_settings.get('device_id')
            # reuse auth settings
            api = Client(username, password, settings=cached_settings)

    except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
        print('ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e))
        api = Client(username, password, device_id=device_id, on_login=lambda x: onlogin_callback(x, "insta_cookie"))

    except ClientLoginError as e:
        print('ClientLoginError {0!s}'.format(e))
        sys.exit()
    except ClientError as e:
        print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response))
        sys.exit()
    except Exception as e:
        print('Unexpected Exception: {0!s}'.format(e))
        sys.exit()

    # Show when login expires
    cookie_expiry = api.cookie_jar.auth_expires
    print('Cookie Expiry: {0!s}'.format(datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%dT%H:%M:%SZ')))
    print("\n")

    return api
Exemplo n.º 23
0
def searchLocation(cookie, setting, location):
    try:
        cookie = decodeCookie(cookie)
        # setting = json.loads(setting)
        user = Client("none", "none", cookie=cookie, setting=setting)
        for i in range(3):
            try:
                out = user.location_fb_search(location, rank_token=user.generate_uuid())
                out = list(map(lambda x: {"locationId":x["location"]["pk"],"name":x["location"]["name"]},out["items"]))
                return out
            except ClientCookieExpiredError:
                return {"error": "نیاز به لاگین مجدد"}
    except ClientCookieExpiredError:
        return {"error": "نیاز به لاگین مجدد"}
    return []
Exemplo n.º 24
0
def send_to_instagram(instance):
    photo_data, photo_size = media.prepare_image(
        instance.image.path, aspect_ratios=MediaRatios.standard)
    caption = instance.title.title() + "\n" + f"#{instance.category}"
    for tag in instance.tags.all():
        caption += f" #{tag}"

    for user, passwd in accounts.items():
        try:
            api = Client(user, passwd)
            api.post_photo(photo_data, photo_size, caption=caption)

        except Exception as error:
            with open("logs/insta_log.txt", 'a') as f:
                text = str(error) + "\n"
                f.write(text)
Exemplo n.º 25
0
def getUserByUID(uid):
  global user_cache
  
  try:
    if not (uid in user_cache.keys()):
      
      with open('cookies/cookie2', "rb") as f:
        user_cook = pickle.load(f)
      
      user_cache[uid] = Client('user','pass',cookie=user_cook[uid])
      return user_cache[uid]
    
    else:
      return user_cache[uid]
  except Exception as e:
    return str(e)
Exemplo n.º 26
0
def login():
    api = None
    while api is None:
        usr, pwd = None, None
        usr = input("User name: ")
        pwd = getpass.getpass("Password")

        try:
            api = Client(usr, pwd, auto_patch=True)
        except KeyboardInterrupt:
            raise ()
        except:
            print("Fail to login")
            api = None

    return api
Exemplo n.º 27
0
    def get_friends(self, nickname):
        user_name = ''
        password = ''

        api = Client(user_name, password)
        results = api.username_info(nickname)
        id = results['user']['pk']
        followings = self.get_followings(id, api)
        followers = self.get_followers(id, api)
        if (len(followings) == 0 and len(followers) == 0
                and results['user']['is_private'] == True):
            print('Account is private. Follow to account')
            #         api.friendships_create(id)
            return None, id
        friend_list = list(set(followings) & set(followers))
        return friend_list, id
Exemplo n.º 28
0
    def activate(self, config=None):
        from app.core.instafollow import InstaFollow
        from app.core.instapost import InstaPost
        from app.core.instaunfollow import InstaUnfollow

        # from app.core.instagramapi import InstagramAPI
        from instagram_private_api import Client
        # API = InstagramAPI(self.username, self.password)
        API = Client(self.username, self.password)
        # API.login()

        base_config = {
            'username': self.username,
            'password': self.password,
            'API': API
        }

        config = default_config if config is None else config
        follow_config = config.get('follow')
        follow_config.update(base_config)
        follow_config['similar_users'] = self.similar_users

        unfollow_config = config.get('unfollow')
        unfollow_config.update(base_config)

        post_config = config.get('post')
        post_config.update(base_config)

        follow_bot = InstaFollow(**follow_config)
        unfollow_bot = InstaUnfollow(**unfollow_config)
        post_bot = InstaPost(**post_config)

        p = multiprocessing.Process(target=bot_worker,
                                    args=(
                                        follow_bot,
                                        unfollow_bot,
                                        post_bot,
                                    ))

        self.active = True

        p.start()

        self.pid = p.pid
        logger.info("created process {}".format(p.pid))

        db.session.commit()
Exemplo n.º 29
0
    def __init__(self, username: str, password: str, verbose=False):

        if verbose:
            log.basicConfig(
                format="[%(asctime)s] (%(levelname)s) %(message)s", level=log.DEBUG
            )

        else:
            log.basicConfig(format="[%(asctime)s] (%(levelname)s) %(message)s")

        try:
            self.client = Client(username=username, password=password)
            log.info("Login success")

        except errors.ClientLoginError as error:
            log.error("An error occurred while trying to log in")
            raise error
Exemplo n.º 30
0
def get_instagram(input_instagram, input_path_to_known_picture,
                  input_firstname, input_lastname, input_email):
    user_name = 'florianrusch9297'
    password = '******'
    api = Client(user_name, password)

    items = api.username_feed(input_instagram)['items']

    imagesURL = []
    for count, item in enumerate(items):
        if (item['media_type'] is 1 or item['media_type'] is 2):
            image_versions2 = item['image_versions2']['candidates']
            image_url = image_versions2[0]['url']
            imagesURL.append(image_url)

    known_image = face_recognition.load_image_file("./uploads/" +
                                                   input_path_to_known_picture)
    known_faces = face_recognition.face_encodings(known_image)
    root_download_path = "./instagram-downloads/"

    counter = 0
    for url_to_image in imagesURL[:]:
        path_to_download = root_download_path + input_firstname + "-" + \
            input_lastname + "-" + input_email + str(counter) + ".jpg"
        urllib.request.urlretrieve(url_to_image, path_to_download)
        counter += 1
        for known_face in known_faces:
            try:
                unknown_image = face_recognition.load_image_file(
                    path_to_download)
            except IOError:
                break
            unknown_faces = face_recognition.face_encodings(unknown_image)
            wasnt_found = True
            for unknown_face in unknown_faces:
                result = face_recognition.compare_faces([known_face],
                                                        unknown_face)
                if True in result:
                    wasnt_found = False
            if wasnt_found:
                imagesURL.remove(url_to_image)
                os.remove(path_to_download)

    output_data = {}
    output_data["pictures"] = imagesURL
    return output_data