ohld / igbot

🐙 Free scripts, bots and Python API wrapper. Get free followers with our auto like, auto follow and other scripts!
https://hikerapi.com/p/N2P6iqiM
Apache License 2.0
4.72k stars 1.47k forks source link

Checkpoint Challenge Required error FIXED #630

Closed alberdonpi closed 5 years ago

alberdonpi commented 6 years ago

Please follow the guide below


Before submitting an issue, make sure you have:

Purpose of your issue?

Describe your issue

I've been dealing with the checkpoint_challenge_required annoying error for a while now (the two-step verification from Instagram), and using as reference few other instagram projects (Instagram Private NODE.JS API mainly) I've been finally able to translate into python, bypass that step, receive the code by email or phone and successfully login back to the app.

For now I have the code in a dirty way as I just solved 7 accounts with it, and I have no way to properly test it more and create something nice to integrate with the current code as all my accounts are finally back to work.

My question is, what is the best way for me to share the code so any of you with this problem can test it (as I don't want any accounts credentials) and confirm it works for ALL the cases, help me to clean the code and also to find the best way to integrate it with the bot?

This repository has helped me a lot with my apps, and I would like to give back and finally solve this security step!

basnijholt commented 6 years ago

That sounds great! If you post the code here I could integrate it in a nice way ;)

basnijholt commented 6 years ago

Or you could of course create a pull request and then I could review it for you.

alberdonpi commented 6 years ago

Wow that was fast @basnijholt haha

Ok, I will clean a bit, do my best to create a script and share it here or in a pull request to start with and we will move from there! I'll do it tomorrow or over the weekend when I get some time off! Thanks!

alberdonpi commented 6 years ago

I was trying to add it in a nice way to the current code but didn't have time :( so I will just share the code and you guys can adapt it!

I simplified it and adapted it (I'm using a custom version of your repository) and it worked for me. Please note I couldn't test it with too many accounts so it still has work to do. This part solves the checkpoint_challenge_required error, where you select a method to get a code, put it back and reactivate your account. Also, note there are a lot of prints in the middle of the steps, that is just for debugging purposes, you can remove them once ready to go to prod.

I also fixed couple of other challenges (suspicious login attempt, phone and email verification), but as I couldn't try more than once, I don't have the code ready.

Feel free to send me the errors/challenges you get and I will try to fix them and update the code.

import os
import sys
import time
import json
import pprint

from instabot import Bot

sys.path.append(os.path.join(sys.path[0], '../'))

COOKIE_FNAME = 'cookie.txt'

def _print_bot_last_state(bot):
    """Just pretty print the bot last state."""
    pprint.pprint(bot.last_response, indent=4)
    pprint.pprint(bot.last_response.headers, indent=4)
    pprint.pprint(bot.last_json, indent=4)

def _get_challenge_choices(last_json):
    """Analise the Json response and get possible choices."""
    choices = []

    # Checkpoint challenge
    if last_json.get('step_name', '') == 'select_verify_method':
        choices.append("Checkpoint challenge received")
        if 'phone_number' in last_json['step_data']:
            choices.append('0 - Phone')
        if 'email' in last_json['step_data']:
            choices.append('1 - Email')

    # Login alert challenge.
    # TODO: TESTS NEEDED
    if last_json.get('step_name', '') == 'delta_login_review':
        choices.append("Login attempt challenge received")
        choices.append('0 - It was me')
        choices.append('0 - It wasn\'t me')

    # If no choices found, use 1 as default.
    # TODO: TESTS NEEDED
    if not choices:
        choices.append(
            '"{}" challenge received'.format(
                last_json.get('step_name', 'Unknown')))
        choices.append('0 - Default')

    return choices

def _reset_challenge(_bot):
    """Is recommended to reset the challenge at the beginning."""
    challenge_url = _bot.last_json['challenge']['api_path'][1:]
    reset_url = challenge_url.replace('/challenge/', '/challenge/reset/')
    try:
        _bot.send_request(reset_url, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False
    return True

def _solve_checkpoint_challenge(_bot):
    """Solve the annoying checkpoint_challenge"""
    # --- Start challenge
    time.sleep(3)
    challenge_url = _bot.last_json['challenge']['api_path'][1:]
    try:
        _bot.send_request(
            challenge_url, None, login=True, with_signature=False)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # --- Choose and send back the choice
    # TODO: Sometimes ask to confirm phone or email. 
    # TODO: TESTS NEEDED
    time.sleep(3)
    choices = _get_challenge_choices(_bot.last_json)
    for choice in choices:
        print(choice)
    code = input('Insert choice:\n')
    data = json.dumps({'choice': code})
    try:
        _bot.send_request(challenge_url, data, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # Print output for testing
    _print_bot_last_state(_bot)

    # --- Wait for the code, insert the code
    time.sleep(3)
    print("A code has been sent to the method selected, please check.")
    code = input('Insert code:\n')
    data = json.dumps({'security_code': code})
    try:
        _bot.send_request(challenge_url, data, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # Print output for testing
    _print_bot_last_state(_bot)

    # --- If user logged in, save cookie, otherwise PASS
    worked = (
        ('logged_in_user' in _bot.last_json)
        and (_bot.last_json.get('action', '') == 'close')
        and (_bot.last_json.get('status', '') == 'ok'))
    if worked:
        # IMPORTANT, save the cookie at this step!
        _bot.save_cookie(COOKIE_FNAME)
        return True
    else:
        _bot.logger.error('Not possible to log in. Reset and try again')
        return False

bot = Bot()

try:
    bot.login(use_cookie=False)
    bot.logger.info('User logged successfully, no Challenge required')
    exit()
except Exception as e:
    bot.logger.error(e)
    if bot.last_json.get('error_type', '') == 'checkpoint_challenge_required':
        print("Checkpoint_challenge found, attempting to solve...")
        success = _solve_checkpoint_challenge(bot)
        if success:
            bot.login(cookie_fname=COOKIE_FNAME)
    else:
        print("Unknown challenge found, share the next output to get support")
        _print_bot_last_state(bot)
lukasz00500 commented 6 years ago

where i should add this code ?

stale[bot] commented 5 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

steffanjensen commented 5 years ago

How can i add this to my code?

ryanbrewster124 commented 5 years ago

please specify where to implement this code

ryanbrewster124 commented 5 years ago

I was trying to add it in a nice way to the current code but didn't have time :( so I will just share the code and you guys can adapt it!

I simplified it and adapted it (I'm using a custom version of your repository) and it worked for me. Please note I couldn't test it with too many accounts so it still has work to do. This part solves the checkpoint_challenge_required error, where you select a method to get a code, put it back and reactivate your account. Also, note there are a lot of prints in the middle of the steps, that is just for debugging purposes, you can remove them once ready to go to prod.

I also fixed couple of other challenges (suspicious login attempt, phone and email verification), but as I couldn't try more than once, I don't have the code ready.

Feel free to send me the errors/challenges you get and I will try to fix them and update the code.

import os
import sys
import time
import json
import pprint

from instabot import Bot

sys.path.append(os.path.join(sys.path[0], '../'))

COOKIE_FNAME = 'cookie.txt'

def _print_bot_last_state(bot):
    """Just pretty print the bot last state."""
    pprint.pprint(bot.last_response, indent=4)
    pprint.pprint(bot.last_response.headers, indent=4)
    pprint.pprint(bot.last_json, indent=4)

def _get_challenge_choices(last_json):
    """Analise the Json response and get possible choices."""
    choices = []

    # Checkpoint challenge
    if last_json.get('step_name', '') == 'select_verify_method':
        choices.append("Checkpoint challenge received")
        if 'phone_number' in last_json['step_data']:
            choices.append('0 - Phone')
        if 'email' in last_json['step_data']:
            choices.append('1 - Email')

    # Login alert challenge.
    # TODO: TESTS NEEDED
    if last_json.get('step_name', '') == 'delta_login_review':
        choices.append("Login attempt challenge received")
        choices.append('0 - It was me')
        choices.append('0 - It wasn\'t me')

    # If no choices found, use 1 as default.
    # TODO: TESTS NEEDED
    if not choices:
        choices.append(
            '"{}" challenge received'.format(
                last_json.get('step_name', 'Unknown')))
        choices.append('0 - Default')

    return choices

def _reset_challenge(_bot):
    """Is recommended to reset the challenge at the beginning."""
    challenge_url = _bot.last_json['challenge']['api_path'][1:]
    reset_url = challenge_url.replace('/challenge/', '/challenge/reset/')
    try:
        _bot.send_request(reset_url, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False
    return True

def _solve_checkpoint_challenge(_bot):
    """Solve the annoying checkpoint_challenge"""
    # --- Start challenge
    time.sleep(3)
    challenge_url = _bot.last_json['challenge']['api_path'][1:]
    try:
        _bot.send_request(
            challenge_url, None, login=True, with_signature=False)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # --- Choose and send back the choice
    # TODO: Sometimes ask to confirm phone or email. 
    # TODO: TESTS NEEDED
    time.sleep(3)
    choices = _get_challenge_choices(_bot.last_json)
    for choice in choices:
        print(choice)
    code = input('Insert choice:\n')
    data = json.dumps({'choice': code})
    try:
        _bot.send_request(challenge_url, data, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # Print output for testing
    _print_bot_last_state(_bot)

    # --- Wait for the code, insert the code
    time.sleep(3)
    print("A code has been sent to the method selected, please check.")
    code = input('Insert code:\n')
    data = json.dumps({'security_code': code})
    try:
        _bot.send_request(challenge_url, data, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # Print output for testing
    _print_bot_last_state(_bot)

    # --- If user logged in, save cookie, otherwise PASS
    worked = (
        ('logged_in_user' in _bot.last_json)
        and (_bot.last_json.get('action', '') == 'close')
        and (_bot.last_json.get('status', '') == 'ok'))
    if worked:
        # IMPORTANT, save the cookie at this step!
        _bot.save_cookie(COOKIE_FNAME)
        return True
    else:
        _bot.logger.error('Not possible to log in. Reset and try again')
        return False

bot = Bot()

try:
    bot.login(use_cookie=False)
    bot.logger.info('User logged successfully, no Challenge required')
    exit()
except Exception as e:
    bot.logger.error(e)
    if bot.last_json.get('error_type', '') == 'checkpoint_challenge_required':
        print("Checkpoint_challenge found, attempting to solve...")
        success = _solve_checkpoint_challenge(bot)
        if success:
            bot.login(cookie_fname=COOKIE_FNAME)
    else:
        print("Unknown challenge found, share the next output to get support")
        _print_bot_last_state(bot)

where do we put this code please help

ryanbrewster124 commented 5 years ago

That sounds great! If you post the code here I could integrate it in a nice way ;)

hi there, so is there a fix for this?? please help me

TheGlobalist commented 5 years ago

I was trying to add it in a nice way to the current code but didn't have time :( so I will just share the code and you guys can adapt it!

I simplified it and adapted it (I'm using a custom version of your repository) and it worked for me. Please note I couldn't test it with too many accounts so it still has work to do. This part solves the checkpoint_challenge_required error, where you select a method to get a code, put it back and reactivate your account. Also, note there are a lot of prints in the middle of the steps, that is just for debugging purposes, you can remove them once ready to go to prod.

I also fixed couple of other challenges (suspicious login attempt, phone and email verification), but as I couldn't try more than once, I don't have the code ready.

Feel free to send me the errors/challenges you get and I will try to fix them and update the code.

import os
import sys
import time
import json
import pprint

from instabot import Bot

sys.path.append(os.path.join(sys.path[0], '../'))

COOKIE_FNAME = 'cookie.txt'

def _print_bot_last_state(bot):
    """Just pretty print the bot last state."""
    pprint.pprint(bot.last_response, indent=4)
    pprint.pprint(bot.last_response.headers, indent=4)
    pprint.pprint(bot.last_json, indent=4)

def _get_challenge_choices(last_json):
    """Analise the Json response and get possible choices."""
    choices = []

    # Checkpoint challenge
    if last_json.get('step_name', '') == 'select_verify_method':
        choices.append("Checkpoint challenge received")
        if 'phone_number' in last_json['step_data']:
            choices.append('0 - Phone')
        if 'email' in last_json['step_data']:
            choices.append('1 - Email')

    # Login alert challenge.
    # TODO: TESTS NEEDED
    if last_json.get('step_name', '') == 'delta_login_review':
        choices.append("Login attempt challenge received")
        choices.append('0 - It was me')
        choices.append('0 - It wasn\'t me')

    # If no choices found, use 1 as default.
    # TODO: TESTS NEEDED
    if not choices:
        choices.append(
            '"{}" challenge received'.format(
                last_json.get('step_name', 'Unknown')))
        choices.append('0 - Default')

    return choices

def _reset_challenge(_bot):
    """Is recommended to reset the challenge at the beginning."""
    challenge_url = _bot.last_json['challenge']['api_path'][1:]
    reset_url = challenge_url.replace('/challenge/', '/challenge/reset/')
    try:
        _bot.send_request(reset_url, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False
    return True

def _solve_checkpoint_challenge(_bot):
    """Solve the annoying checkpoint_challenge"""
    # --- Start challenge
    time.sleep(3)
    challenge_url = _bot.last_json['challenge']['api_path'][1:]
    try:
        _bot.send_request(
            challenge_url, None, login=True, with_signature=False)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # --- Choose and send back the choice
    # TODO: Sometimes ask to confirm phone or email. 
    # TODO: TESTS NEEDED
    time.sleep(3)
    choices = _get_challenge_choices(_bot.last_json)
    for choice in choices:
        print(choice)
    code = input('Insert choice:\n')
    data = json.dumps({'choice': code})
    try:
        _bot.send_request(challenge_url, data, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # Print output for testing
    _print_bot_last_state(_bot)

    # --- Wait for the code, insert the code
    time.sleep(3)
    print("A code has been sent to the method selected, please check.")
    code = input('Insert code:\n')
    data = json.dumps({'security_code': code})
    try:
        _bot.send_request(challenge_url, data, login=True)
    except Exception as e:
        _bot.logger.error(e)
        return False

    # Print output for testing
    _print_bot_last_state(_bot)

    # --- If user logged in, save cookie, otherwise PASS
    worked = (
        ('logged_in_user' in _bot.last_json)
        and (_bot.last_json.get('action', '') == 'close')
        and (_bot.last_json.get('status', '') == 'ok'))
    if worked:
        # IMPORTANT, save the cookie at this step!
        _bot.save_cookie(COOKIE_FNAME)
        return True
    else:
        _bot.logger.error('Not possible to log in. Reset and try again')
        return False

bot = Bot()

try:
    bot.login(use_cookie=False)
    bot.logger.info('User logged successfully, no Challenge required')
    exit()
except Exception as e:
    bot.logger.error(e)
    if bot.last_json.get('error_type', '') == 'checkpoint_challenge_required':
        print("Checkpoint_challenge found, attempting to solve...")
        success = _solve_checkpoint_challenge(bot)
        if success:
            bot.login(cookie_fname=COOKIE_FNAME)
    else:
        print("Unknown challenge found, share the next output to get support")
        _print_bot_last_state(bot)

I've tried to implement your code but, even though if it passes the challenge, and retries with success after, then the logger tells me that I'm not logged in

qwertyNodes commented 5 years ago

why this thread marked as FIXED ? cant find here working fixing

hustlefilled commented 5 years ago

where do you paste that code??

TheGlobalist commented 5 years ago

where do you paste that code??

Right after the bot's instantiation, but it doesn't work

hustlefilled commented 5 years ago

oh ok thanks

alex-grover commented 5 years ago

I integrated the code in my fork, I only did some basic manual tests but it's working for me now. Give the PR a look if you need!