Exemple #1
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)
Exemple #2
0
def main():
    global api
    try:
        api = Client(None, None, settings=file_get_contents("data.bin", "rb"))
    except:
        if os.path.exists("data.bin"):
            os.remove("data.bin")
        username = input('Your username:'******'Your password:'******'fetch':
        fetch()
    elif command == 'hide':
        hide_all()
    elif command == 'unhide':
        unhide_all()
    elif command == 'reset':
        reset()
    else:
        show_help()

    if os.path.exists("data.bin") == False:
        file_put_contents("data.bin", "wb", api.settings)
Exemple #3
0
    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()
class StorySaver:
    def __init__(self, user_name: str, password: str, result_file_path: str):
        self.user_name = user_name
        self.api = Client(user_name, password)
        self.api.login()
        self.rank_token = Client.generate_uuid()
        # self.result_json = open(result_file_path, "w", encoding='utf-8')

    def getMyFollowingList(self) -> list:
        user_pk = self.api.user_detail_info(
            self.user_name)["user_detail"]["user"]["pk"]
        return self.api.user_following(user_pk, self.rank_token)["users"]

    def _saveStory(self, user_pk):
        stories = self.api.user_story_feed(user_pk).get("reel", "")
        if stories is not None:
            # self.result_json.write(json.dumps(stories))
            # self.result_json.write("\n")

            for item in stories.get("items", []):
                username = item["user"]["username"]

                img_url = item.get("image_versions2",
                                   []).get("candidates", [])[0]["url"]
                img_folder = "photos/" + username + "/"
                img_filename = img_folder + urlparse(img_url).path.split(
                    "/")[-1]
                self.save_To_S3(img_filename, img_url)

                if item.get("video_versions", []):
                    video_url = item.get("video_versions", [])[0]["url"]
                    video_folder = "video/" + username + "/"
                    video_filename = video_folder + urlparse(
                        video_url).path.split("/")[-1]
                    self.save_To_S3(video_filename, video_url)
                logging.debug(img_url)

    def startSave(self):
        users = self.getMyFollowingList()
        for user in users:
            time.sleep(1)
            self._saveStory(str(user["pk"]))

    @staticmethod
    def saveFileSystem(url, path_and_filename):
        if not os.path.exists(path_and_filename):
            os.makedirs(path_and_filename)
        urlretrieve(url, path_and_filename)

    @staticmethod
    def save_To_S3(s3_folder, url):
        service_url = "https://url-2-s3.herokuapp.com/upload"

        payload = json.dumps({"url": url, "fileNameAndPath": s3_folder})
        headers = {'Content-Type': 'application/json'}
        response = requests.request("POST",
                                    service_url,
                                    headers=headers,
                                    data=payload)
        print(response.text.encode('utf8'))
Exemple #5
0
    def __init__(self):
        settings_file = "settings.json"

        if len(sys.argv) < 3:
            print(
                'Usage: python unliker.py username password max_remove(optional)'
            )
            os._exit(1)
        else:
            self.user = sys.argv[1]
            self.pwd = sys.argv[2]

        if not os.path.isfile(settings_file):
            print("Settings file not found...")
            self.api = Client(
                self.user,
                self.pwd,
                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...")
            self.api = Client(self.user, self.pwd, settings=cached_settings)

        self.following = set([
            u['username']
            for u in self.api.user_following(self.api.authenticated_user_id,
                                             self.api.generate_uuid())['users']
        ])  # used for filtering
Exemple #6
0
def login(api: Client):
    username = pil.ig_user
    try:
        api.login()
    except (ClientCheckpointRequiredError, ClientChallengeRequiredError) as e:
        challenge_url = e.challenge_url

        challenge_pattern = r'.*challenge/(?P<account_id>\d.*)/(?P<identifier>\w.*)/'
        match = re.search(challenge_pattern, challenge_url)
        if not match:
            raise ClientError('Unable to parse challenge')

        match_dict = match.groupdict()
        account_id = match_dict['account_id']
        identifier = match_dict['identifier']

        res = api.choose_confirm_method(
            account_id,
            '1')  # confirm_method param has default value 1, you can pass 0
        magic_code = get_code_from_email(username)
        if magic_code:
            code = magic_code
        else:
            code = input('Enter code from email: ')
        api.send_challenge(account_id, identifier, code)
Exemple #7
0
def insta_api(message, photo_list, user_name, password, hashtag):
    api = Client(user_name, password)
    caption = str(message) + " " + hashtag

    # Generate new credintails or load existing
    basepath = path.dirname(__file__)
    filepath = path.abspath(path.join(basepath, "..", "credentials.json"))

    with open(filepath, "r") as read_file:
        data = json.load(read_file)
        print(data)

    # Force api credits (saved)

    api.uuid = data['uuid']
    api.device_id = data['device_id']
    api.ad_id = data['ad_id']
    api.session_id = data['session_id']

    # if len(photo_list) == 1:  # Если пришла 1 фотка в списке

    one_image = photo_list[0]
    print(one_image)

    buf = io.BytesIO()
    one_image.save(buf, format='JPEG')
    byte_im = buf.getvalue()
    print(byte_im)

    size = (one_image.width, one_image.height)
    print(size)

    api.login()
    api.post_photo(byte_im, size, caption)
    def __init__(self, username, password):
        self.__username = username
        self.__password = password
        self.__api = None

        try:
            self.__api = Client(auto_patch=True,
                                authenticate=True,
                                username=self.__username,
                                password=self.__password)
            print("login effettuato con successo!\n")
        except ClientLoginError:
            print("La password che hai inserito non è corretta\n")
            return
        except ClientError:
            print(
                "Se hai l'autenticazione a due fattori attiva, il bot non può funzionare\n"
            )
            print(
                "Puoi disattivarla per usare il bot, e al termine riattivarla\n"
            )
            return

        user_feed_info = self.__api.user_feed('329452045', count=10)
        for post in user_feed_info:
            print('%s from %s' % (post['link'], post['user']['username']))
def already_liked(api: Client,
                  target_id: str,
                  type_like: str = 'post',
                  own_feed: bool = False) -> bool:
    """
    Check if the post / comment is already liked by the current user
    
    Arguments:
        api (Client) : Object instagram Client
        target_id (str) : Id of comment or post
        type_like (str) : String that can be post or comment
        own_feed (bool) : If it's the current user's feed
        
    Returns:
        bool - if the post or comment is already liked
    
    """
    is_liked = False
    if type_like == 'post':
        likes = api.media_likers(target_id)['users']
    else:
        likes = api.comment_likers(target_id)

    bot_id = int(api.authenticated_user_id)

    if likes:
        collection_likes = likes['users'] if own_feed else likes

        for likers in collection_likes:
            if bot_id == likers['pk']:
                is_liked = True

    return is_liked
 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!")
def delete(api: Client,
           target_id: str,
           target_type: str,
           parent_id: str = '') -> None:
    """
    Delete a post or comment chosen by the current user
    
    Arguments:
        api (Client) : Object instagram Client
        target_id (str) : Id of the post or comment to delete
        target_type (str) : String that can be post or comment
        parent_id (str) : In the event that a comment is deleted,
                          it stores the id of the post that contains said comment,
                          
    """
    if target_type == 'post':
        result = api.delete_media(media_id=target_id)
    else:
        result = api.delete_comment(media_id=parent_id, comment_id=target_id)

    if result['status'] == 'ok':
        print_write_chatbot(
            f"The {target_type} has been successfully removed!\n",
            color='green',
            attrs_color=['bold'])

    else:
        print_write_chatbot(
            f"The {target_type} could not be removed. Please try again later\n",
            color='red',
            attrs_color=['bold'])
Exemple #12
0
 def setup_api(self):
     '''
     isitialise self.api for the given user
     reusing or creating new settings
     '''
     try:
         with open(self.settings_path) as settings_file:
             cached_settings = json.load(settings_file, object_hook=from_json)
             self.device_id = cached_settings.get('device_id')
             print('Reusing settings: {0}'.format(self.settings_path))
             self.api = Client(self.user.username,
                               self.user.password,
                               settings=cached_settings)
     except (ClientCookieExpiredError, ClientLoginRequiredError, FileNotFoundError) as ex:
         print(str(ex))
         # Login expired, renew cookie upon login
         self.api = Client(self.user.username,
                           self.user.password,
                           on_login=lambda x: on_login(x, self.settings_path))
     except ClientLoginError as ex:
         print('ClientLoginError {0!s}'.format(ex))
         sys.exit(9)
     except ClientError as ex:
         print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(ex.msg,
                                                                         ex.code,
                                                                         ex.error_response))
         sys.exit(9)
     except Exception as ex:
         print('Unexpected Exception: {0!s}'.format(ex))
         sys.exit(99)
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
Exemple #14
0
    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
Exemple #15
0
 def __init__(self,
              username,
              password,
              API=None,
              action_interval=8.0,
              rate=120,
              interval=5400,
              unfollow_all=True):
     self.username = username
     self.password = password
     self.action_interval = action_interval
     self.rate = rate
     self.interval = interval
     self.unfollow_all = unfollow_all
     try:
         from app import logger
         logger = get_logger()
     except ImportError:
         pass
     self.logger = logging.LoggerAdapter(logger, {
         'user': self.username,
         'bot': 'instaunfollow'
     })
     self.API = Client(self.username, self.password) if API is None else API
     self.webAPI = WebClient()
def InstagramPoster(photo, description, credit):
    import requests
    import json
    import time
    from random import randint
    from instagram_private_api import Client, MediaRatios
    from instagram_private_api_extensions import media
    from PIL import Image

    global instagram_username, instagram_password, insta_hashtags

    InstagramAPI = Client(instagram_username, instagram_password)

    try:
        mycaption = '"' + description + '"' + " (Via: u/" + credit + ")\n\n.\n.\n.\n.\n.\n.\n" + insta_hashtags
        try:
            post_before = NumberOfPosts(instagram_username)
            photo_data, photo_size = media.prepare_image(
                'picture_to_post.jpg', aspect_ratios=MediaRatios.standard)
            InstagramAPI.post_photo(photo_data, photo_size, caption=mycaption)

            if NumberOfPosts(instagram_username) == post_before:
                print("ERROR: It did not post, please try again!")
            else:
                print("Photo posted!")

        except Exception as e:
            print("Error...")
            exit(0)

    except Exception as e:
        print(e)
def edit_profile(api: Client) -> None:
    """
    Available personal data is edited.
    What are full name, private account, biography, url, email, phone number and gender
    
    Arguments:
        api (Client) - object Client instagram
    """

    # I call _call_api because the original function "current_user" was passing wrong parameters
    # and the request was not made correctly
    user_profile = api._call_api('accounts/current_user/',
                                 query={'edit': 'true'})['user']
    text_to_print = "Your actual profile is: \n"
    genders = ['male', 'female', 'unspecified']
    print_write_chatbot(text_to_print)
    attributes = {
        'Full name': 'full_name',
        'Private account': 'is_private',
        'Biography': 'biography',
        'External url': 'external_url',
        'Email': 'email',
        'Phone number': 'phone_number',
        'Gender': 'gender',
    }

    new_profile_data = {}

    all_data = show_profile_data(user_profile, attributes, genders)

    text_to_print += all_data
    get_new_profile_data(user_profile, attributes, new_profile_data, genders)

    try:
        status_account = api.set_account_private(
        ) if new_profile_data['is_private'] else api.set_account_public()
        result = api.edit_profile(
            first_name=new_profile_data['full_name'],
            biography=new_profile_data['biography'],
            external_url=new_profile_data['external_url'],
            email=new_profile_data['email'],
            gender=int(new_profile_data['gender']),
            phone_number=new_profile_data['phone_number'])
        if result and status_account['status'] == 'ok':
            text = "Profile has been modified successfully!"
            print_write_chatbot(message=text,
                                color='green',
                                attrs_color=['bold'])
        else:
            text = "There was a problem updating the profile, please try again\n"
            print_write_chatbot(message=text,
                                color='red',
                                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'])
Exemple #18
0
 def __init__(self, instaData):
     self.data = instaData
     self.instaApi = Client("sammy.g.spam", "vq86koli")
     self.counter = 6
     self.comments = {}
     self.maybe = {}
     self.contestants = []
     print("InstagramValidityCheck.State : Initialized")
def do_authenticate(args, app_logger):
    '''
    Authenticate using user and password
    '''
    app_logger.debug('Authenticating against Instagram')
    try:
        cache_file = args.cache_file_path
        if not os.path.isfile(cache_file):
            app_logger.debug('Unable to find file: {0!s}'.format(cache_file))
            app_logger.debug('Continuing with new login...')
            api = Client(args.username,
                         args.password,
                         on_login=lambda x: onlogin_callback(
                             x, args.cache_file_path, app_logger))
        else:
            app_logger.debug(
                'Loading cache from file: {0!s}'.format(cache_file))
            cached_settings = read_json_file(cache_file, app_logger)
            #with open(cache_file) as file_data:
            #    cached_settings = json.load(file_data, object_hook=from_json)
            device_id = cached_settings.get('device_id')
            app_logger.debug('Reusing auth settings...')
            api = Client(args.username,
                         args.password,
                         settings=cached_settings)
    except (ClientCookieExpiredError, ClientLoginRequiredError) as auth_err:
        app_logger.debug(
            'ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(
                auth_err))
        app_logger.debug('Login expired...')
        app_logger.debug('Doing relogin with same UA and settings...')
        api = Client(args.username,
                     args.password,
                     device_id=device_id,
                     on_login=lambda x: onlogin_callback(
                         x, args.cache_file_path, app_logger))
    except ClientLoginError as auth_err:
        app_logger.critical('ClientLoginError {0!s}'.format(auth_err))
        sys.exit(9)
    except (ClientCheckpointRequiredError,
            ClientChallengeRequiredError) as auth_err:
        app_logger.critical(
            'ClientChallengeRequired {0!s} (Code: {1:d}, Response: {2!s})'.
            format(auth_err.msg, auth_err.code, auth_err.error_response))
        sys.exit(9)
    except ClientError as auth_err:
        app_logger.critical(
            'ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(
                auth_err.msg, auth_err.code, auth_err.error_response))
        sys.exit(9)
    except Exception as auth_err:
        app_logger.critical('Unexpected Exception: {0!s}'.format(auth_err))
        sys.exit(99)
    cookie_expiry = api.cookie_jar.auth_expires
    app_logger.debug('Cookie Expiry: {0!s}'.format(
        datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%dT%H:%M:%SZ')))
    return api
Exemple #20
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
Exemple #21
0
    def init_grammer(self, iduser):
        self.id_user = iduser

        self.datauser = self.get_auth_data()

        instalogin = self.datauser['login']
        instapwd = self.datauser['passwd']
        instacookie = self.datauser['cookie']

        device_id = None

        settings_file = instacookie
        try:
            if not os.path.isfile(settings_file):
                # settings file does not exist
                #если файл куки не найден то он создается
                #print('Невозможно найти файл: {0!s}'.format(settings_file))
                # login new
                api = Client(
                    instalogin, instapwd,
                    on_login=lambda x: self.onlogin_callback(x, instacookie))
                return api
            else:
                #если куки найдены то они используются
                with open(settings_file) as file_data:
                    cached_settings = json.load(file_data, object_hook = self.from_json)
                #print('Повторное использование настроек: {0!s}'.format(settings_file))
                device_id = cached_settings.get('device_id')
                # reuse auth settings
                api = Client(
                    instalogin, instapwd,
                    settings=cached_settings)
                return api
        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(
                instalogin, instapwd,
                device_id=device_id,
                on_login=lambda x: self.onlogin_callback(x, instacookie))

            return api

        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)
Exemple #22
0
def get_stories(twitter_api):
    last = src.last.get_last(src.last.PostType.STORY)
    highest = last

    try:
        if not os.path.isfile(SETTINGS_FILE_PATH):
            insta_api = Client(
                USERNAME,
                PASSWORD,
                on_login=lambda x: login_callback(x, SETTINGS_FILE_PATH))
        else:
            with open(SETTINGS_FILE_PATH) as settings_file:
                cached_settings = json.load(settings_file,
                                            object_hook=from_json)
            print('Reusing settings: {0!s}'.format(SETTINGS_FILE_PATH))

            insta_api = Client(USERNAME, PASSWORD, settings=cached_settings)

    #except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
    except Exception as e:
        print('Exception: {0!s}'.format(e))
        exit(-1)

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

    data = insta_api.user_story_feed(os.getenv('INSTAGRAM_USERID'))

    if data['reel'] != None:
        for item in data['reel']['items']:
            story_id = item['pk']
            if (story_id > last):
                print(story_id)
                print(item['taken_at'])
                timestamp = datetime.datetime.fromtimestamp(
                    item['taken_at'], pytz.timezone('Asia/Tokyo'))
                tweet_data = [
                    '【Story】 #鈴木このみ ',
                    timestamp.strftime('%Y-%m-%d %H:%M')
                ]
                if os.getenv('ENV', 'dev') == 'production':
                    twitter_api.PostUpdate(''.join(tweet_data),
                                           item['video_versions'][0]['url'])
                else:
                    twitter_api.write(''.join(tweet_data) + '\n\n')
                    twitter_api.write(item['video_versions'][0]['url'] +
                                      '\n\n')

                if story_id > highest:
                    highest = story_id

        if highest > last:
            src.last.set_last(str(highest), src.last.PostType.STORY)
Exemple #23
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
def get_client(username, password) -> Client:
    if os.path.isfile(settings_file_path):
        print(f'Reusing settings: {settings_file_path}')
        device_id = get_settings().get('device_id')

        return Client(username, password, settings=get_settings())

    return Client(username,
                  password,
                  on_login=lambda x: onlogin_callback(x, settings_file_path))
Exemple #25
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')
Exemple #26
0
    def Login(self, username, password):
        device_id = None
        api = None

        try:
            settings_file = 'info.json'
            if not os.path.isfile(settings_file):
                # settings file does not exist
                self.PrintText('UNABLE TO FIND FILE',
                               '{0!s}'.format(settings_file), Fore.MAGENTA,
                               Fore.MAGENTA)

                # login new
                api = Client(
                    username,
                    password,
                    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)

                self.PrintText('REUSING SETTINGS',
                               '{0!s}'.format(settings_file), Fore.MAGENTA,
                               Fore.MAGENTA)

                device_id = cached_settings.get('device_id')
                # reuse auth settings
                api = Client(username, password, settings=cached_settings)
        except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
            self.PrintText('ClientCookieExpiredError/ClientLoginRequiredError',
                           '{0!s}'.format(e), Fore.RED, Fore.RED)

            # Login expired
            # Do relogin but use default ua, keys and such
            api = Client(
                username,
                password,
                device_id=device_id,
                on_login=lambda x: self.onlogin_callback(x, settings_file))
        except ClientLoginError as e:
            self.PrintText('ClientLoginError', '{0!s}'.format(e), Fore.RED,
                           Fore.RED)
        except ClientError as e:
            self.PrintText(
                'ClientError {0!s}', '(Code: {1:d}, Response: {2!s})'.format(
                    e.msg, e.code, e.error_response), Fore.RED, Fore.RED)
        except Exception as e:
            self.PrintText('Unexpected Exception', '{0!s}'.format(e), Fore.RED,
                           Fore.RED)

        # Show when login expires
        #cookie_expiry = api.cookie_jar.auth_expires
        #print('Cookie Expiry: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%dT%H:%M:%SZ')))
        return api
Exemple #27
0
def login(args):
    settings_file_path = args.settings_file_path
    username = args.username
    password = args.password
    print('Client version: {0!s}'.format(client_version))
    device_id = 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))
            print('New login...')

            # login new
            api = Client(
                username, password,
                on_login=lambda x: onlogin_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))
        print('New login using default ua, keys etc...')

        # Login expired
        # Do relogin but use default ua, keys and such
        api = Client(
            username, password,
            device_id=device_id,
            on_login=lambda x: onlogin_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)

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

    return api
def generate_client_from_cache(username: str, password: str, settingsFilePath: str = None) -> object:
	"""
	Summary:
		Generates an instance of instagram_private_api.Client that reuses saved settings,
		like cookies, to minimize login attempts. If no file exists, then a settings file
		will be generated.
		CREDIT: https://github.com/ping/instagram_private_api

	Args:
		username: a valid instagram username
		password: a valid instagram password
		settingsFilePath: (optional) the path to the file that holds settings

	Returns:
		An instance of instagram_private_api.Client
	"""
	try:
		if settingsFilePath == None:
			settingsFile = "instagram_client_cache.json"
		else:
			settingsFile = settingsFilePath
		if not os.path.isfile(settingsFile):
			# settings file does not exist
			print('Unable to find file: {0!s}'.format(settingsFile))
			# login new
			api = Client(
				username, password,
				on_login=lambda x: onlogin_callback(x, settingsFile))
		else:
			with open(settingsFile) as fileData:
				cachedSettings = json.load(fileData, object_hook=from_json)
			print('Reusing settings: {0!s}'.format(settingsFile))
			#deviceId = cachedSettings.get('device_id')
			# reuse auth settings
			api = Client(
				username, password,
				settings=cachedSettings)
		return api
	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,
			on_login=lambda x: onlogin_callback(x, settingsFilePath))
	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)
def connection_instagram(user_credentials: dict = {}) -> object:
    """
    The connection with the instagram api is generated (instagram_private_api module)
    Arguments:
        user_credentials (dict) = Dictionary in which the credentials of the user's instagram
                                  account are stored (default {})
    Returns:
            object - The Client object
    """

    api = ''
    if not user_credentials:
        credentials = get_credentials()
        username = credentials['instagram']['username']
        password = credentials['instagram']['password']
    else:
        username = user_credentials['username']
        password = user_credentials['password']

    settings_file = os.path.abspath('credentials/instagram_api.json')

    if os.path.isfile(settings_file):
        delete_expired_cookie(settings_file)

    if not os.path.isfile(settings_file):
        # If the credentials do not exist, do a new login
        try:
            api = Client(
                username,
                password,
                on_login=lambda x: on_login_callback(x, settings_file))
        except Exception as err:
            write_log(STATUS_FILE, str(err), "Exception")

    else:
        # If the credentials do not exist, do a new login
        cached_settings = get_cached_settings(settings_file)
        device_id = cached_settings.get('device_id')
        try:
            api = Client(username,
                         password,
                         device_id=device_id,
                         settings=cached_settings)

        except Exception as e:
            write_log(STATUS_FILE, str(e), "Exception")

    print_write_chatbot(
        "You have successfully connected with the instagram! \n",
        color='green',
        attrs_color=['bold'])

    return api
Exemple #30
0
    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(": ", pc.RED)
            pc.printout(e.msg, pc.RED)
            pc.printout("\n")
            if 'challenge' in error:
                print("Please follow this link to complete the challenge: " +
                      error['challenge']['url'])
            exit(9)