ping / instagram_private_api

A Python library to access Instagram's private API.
MIT License
2.99k stars 618 forks source link

What to do after a suspicious flag? ClientError Bad Request: challenge_required #44

Closed ahmednooor closed 6 years ago

ahmednooor commented 6 years ago

Before submitting an issue, make sure you have:

Which client are you using?

Purpose of your issue?


For a bug report, you must include the Python version used, code that will reproduce the error, and the error log/traceback.

Paste the output of python -V here: Python 3.6.1

Code:

def ig_login(username, password, _ID):
    registered_users_file = THIS_FOLDER_G + "/db/__rgstd__.json"
    with open(registered_users_file, 'r') as infile:
        registered_users = json.load(infile)
    if username not in registered_users:
        registered_users[username] = False
        with open(registered_users_file, 'w') as outfile:
            json.dump(registered_users, outfile, indent=2)
        return {"status": "error", "msg": "New User."}

    device_id = None
    settings_file = THIS_FOLDER_G + "/db/data/cookies/" + username + "_" + _ID + ""

    try:
        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,
                device_id=device_id,
                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
            api = Client(
                username, password,
                settings=cached_settings)

        current_user = api.current_user()

    except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
        print('ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e))
        # if os.path.isfile(settings_file):
        #     os.remove(settings_file)
        return {"status": "error", "msg": "Invalid Username or Password."}
        # Login expired
        # Do relogin but use default ua, keys and such
        # settings_file = THIS_FOLDER_G + "/db/data/cookies/" + username + "_" + _ID + ""
        # api = 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))
        # if os.path.isfile(settings_file):
        #     os.remove(settings_file)
        return {"status": "error", "msg": "Invalid Username or Password."}

    except ClientError as e:
        print('ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response))
        # if os.path.isfile(settings_file):
        #     os.remove(settings_file)
        return {"status": "error", "msg": "Invalid Username or Password."}

    except Exception as e:
        print('Unexpected Exception: {0!s}'.format(e))
        return {"status": "error", "msg": "Something went wrong."}

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

    print('All ok')

    if registered_users[username] == False:
        registered_users[username] = True
        with open(registered_users_file, 'w') as outfile:
            json.dump(registered_users, outfile, indent=2)

    return api

@app.route('/login', methods=["POST"])
def login():
    _ID = request.form.get('_ID')
    username = request.form.get('username')
    password = request.form.get('password')

    try:
        SEC_KEY = get_SEC_KEY(_ID)
        if SEC_KEY == "Not Found":
            return jsonify({"status": "error", "msg": "Secret Key Not Found"})

        password = decrypt_data(password, SEC_KEY)
    except:
        return jsonify({"status": "error", "msg": "Encryption Error."})

    api = ig_login(username, password, _ID)

    if isinstance(api, dict) and "status" in api and api["status"] == "error":
        return jsonify(api)
    else:
        user_id = api.authenticated_user_id
        current_user = api.current_user()

        followers = api.user_followers(user_id)
        initial_followers_file = THIS_FOLDER_G + "/db/data/initial_followers/" + username + ".json"
        if not os.path.isfile(initial_followers_file):
            with open(initial_followers_file, 'w') as outfile:
                json.dump(followers, outfile, indent=None)
                print('SAVED: {0!s}'.format(initial_followers_file))
        else:
            pass

        IDS_PATH = THIS_FOLDER_G + "/db/__ids__.json"
        with open(IDS_PATH, 'r') as infile:
            ID_ENTRIES = json.load(infile)

        if username in ID_ENTRIES:
            if _ID not in ID_ENTRIES[username]:
                ID_ENTRIES[username].append(_ID)
        else:
            ID_ENTRIES[username] = []
            ID_ENTRIES[username].append(_ID)

        with open(IDS_PATH, 'w') as outfile:
            json.dump(ID_ENTRIES, outfile, indent=2)

        return jsonify(current_user)

Complete File Link: https://github.com/ahmednooor/instagram_unfollow_check/blob/master/app.py

Error/Debug Log: On first login request:

ClientError URLError <urlopen error timed out> (Code: 0, Response: )

And on later login requests:

ClientError Bad Request: challenge_required (Code: 400, Response: {"message": "challenge_required", "challenge": {"url": "https://i.instagram.com/challenge/<mock_value>/<mock_value>/", "api_path": "/challenge/<mock_value>/<mock_value>/", "hide_webview_header": true, "lock": true, "logout": false, "native_flow": true}, "status": "fail", "error_type": "checkpoint_challenge_required"})

Describe your issue

Background: I am creating a REST api with Flask for an app and using this api to check followers, unfollowers etc. It was working fine for past couple days but suddenly raising challange_required error. Question: What to do after a suspicious flag? I have marked (this was me) and confirmed with secret code but the error is still there. Any advice/solution on the matter would be extremely appreciated. Thanks.

ping commented 6 years ago

IG flags your account as suspicious usually for one or more of the reasons below:

  1. You're using the api from a different location
  2. Your IP has been flagged as spammy
  3. Your api usage behavior caused your account to be flagged as spammy

Don't do any of the above.