subzeroid / instagrapi

🔥 The fastest and powerful Python library for Instagram Private API 2024
https://hikerapi.com/p/bkXQlaVe
MIT License
4.33k stars 684 forks source link

New password challenge fails every time. #851

Open nizarlj opened 2 years ago

nizarlj commented 2 years ago

Describe the bug New password challenge fails every time.

To Reproduce

from instagrapi.mixins.challenge import ChallengeChoice
from instagrapi import Client

from email.header import decode_header
from datetime import datetime
import imaplib
import random
import email
import pytz
utc=pytz.UTC

CHALLENGE_EMAIL = "CHALLENGE_EMAIL"
CHALLENGE_PASSWORD = "CHALLENGE_PASSWORD"
start_time = datetime.now()
now = start_time.astimezone(utc)

def get_challenge_code(username):
    imap=imaplib.IMAP4_SSL("imap.gmail.com")
    imap.login(CHALLENGE_EMAIL, CHALLENGE_PASSWORD)
    imap.select("inbox")
    type, data = imap.search(None, "ALL", "SINCE", now.strftime("%d-%b-%Y"), "SUBJECT", '"Verify your account"')
    mail_ids=data[0]
    id_list=mail_ids.split()

    mails = {}
    for i in range(int(id_list[-1]),int(id_list[0])-1,-1):
        type, data=imap.fetch(str(i ), "(RFC822)")
        for response_part in data :
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1].decode('utf-8'))

                date = decode_header(msg["Date"])[0][0]
                date = datetime.strptime(date, "%a, %d %b %Y %H:%M:%S %z")
                date = date.astimezone(utc)

                if date < now: continue

                subject = msg['subject']
                from_mail =  msg['from']

                body = ""
                for part in msg.walk():
                    body += part.get_payload(decode=True).decode('utf-8')
                    # if part.get_content_type() == 'text/plain':
                    #     body += part.get_payload()

                if username not in body: continue

                first_part = '</p><p style="margin:10px 0 10px 0;color:#565a5c;font-size:18px;"><font size="6">'
                first_part_index = body.find(first_part)
                if first_part_index == -1: continue

                code = body[first_part_index+len(first_part):first_part_index+len(first_part) + 6]

                mails[i] = { "subject": subject, "from": from_mail, "body": body, "date": date, "msg": msg, "code": code }

    imap.logout()

    if len(mails) == 0:
        return None

    latest_mail_id = max(mails, key=lambda x: mails[x]["date"])
    latest_mail = mails[latest_mail_id]

    return latest_mail["code"]

def challenge_code_handler(username, choice):
    if choice == ChallengeChoice.SMS:
        return False
    elif choice == ChallengeChoice.EMAIL:
        return get_challenge_code(username)
    return False

def change_password_handler(username):
    # Simple way to generate a random string
    chars = list("abcdefghijklmnopqrstuvwxyz1234567890!&£@#")
    password = "".join(random.sample(chars, 8))
    return password

IG_USERNAME = "IG_USERNAME"
IG_PASSWORD = "IG_PASSWORD"

cl = Client()
cl.challenge_code_handler = challenge_code_handler
cl.change_password_handler = change_password_handler
cl.login(IG_USERNAME, IG_PASSWORD)

Traceback Code entered "991136" for IG_USERNAME (2 attempts by 5 seconds) Password entered "w!174g£j" for IG_USERNAME (0 attempts by 5 seconds) Traceback (most recent call last): File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 298, in _send_private_request response.raise_for_status() File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://i.instagram.com/api/v1/feed/reels_tray/

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 434, in private_request self._send_private_request(endpoint, kwargs) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 330, in _send_private_request raise ChallengeRequired(last_json) instagrapi.exceptions.ChallengeRequired: challenge_required

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 298, in _send_private_request response.raise_for_status() File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: https://i.instagram.com/api/v1/bloks/apps/com.instagram.challenge.navigation.take_challenge/

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "A:\Programming\python\bots\instabot rewritten\test.py", line 86, in cl.login(IG_USERNAME, IG_PASSWORD) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\auth.py", line 418, in login self.login_flow() File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\auth.py", line 167, in login_flow check_flow.append(self.get_reels_tray_feed("cold_start")) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\auth.py", line 244, in get_reels_tray_feed return self.private_request("feed/reels_tray/", data) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 445, in private_request self.challenge_resolve(self.last_json) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\challenge.py", line 78, in challenge_resolve return self.challenge_resolve_simple(challenge_url) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\challenge.py", line 421, in challenge_resolve_simple
return self.bloks_change_password(pwd, self.last_json['challenge_context']) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\bloks.py", line 46, in bloks_change_password return self.bloks_action("com.instagram.challenge.navigation.take_challenge", data) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\bloks.py", line 21, in bloks_action result = self.private_request(f"bloks/apps/{action}/", self.with_default_data(data)) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 447, in private_request raise e File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 434, in private_request self._send_private_request(endpoint, kwargs) File "C:\Users\nizar\AppData\Local\Programs\Python\Python310\lib\site-packages\instagrapi\mixins\private.py", line 374, in _send_private_request raise ClientError(e, response=e.response, last_json) instagrapi.exceptions.ClientError: 500 Server Error: Internal Server Error for url: https://i.instagram.com/api/v1/bloks/apps/com.instagram.challenge.navigation.take_challenge/

Expected behavior Successful login.

Desktop

marcouderzo commented 2 years ago

Same problem here:

(instagrapi.exceptions.ClientError: 500 Server Error: Internal Server Error for url: https://i.instagram.com/api/v1/bloks/apps/com.instagram.challenge.navigation.take_challenge/)

with a different code. At login it always asks a challenge code from email, then asks for the password. Finally, it fails with this error. Seems like Instagram keeps blocking the login as it thinks it is an unrecognized login.

@adw0rd Any solution? This seems a big problem

rubenelportero commented 2 years ago

Here the same but without a password...

Enter code (6 digits) for XXXX (ChallengeChoice.EMAIL): 655045 Code entered "655045" for XXXX (0 attempts by 5 seconds) Traceback (most recent call last): File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\private.py", line 298, in _send_private_request response.raise_for_status() File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://i.instagram.com/api/v1/accounts/login/

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\private.py", line 434, in private_request self._send_private_request(endpoint, kwargs) File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\private.py", line 330, in _send_private_request raise ChallengeRequired(last_json) instagrapi.exceptions.ChallengeRequired: challenge_required

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\private.py", line 298, in _send_private_request response.raise_for_status() File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://i.instagram.com/api/v1/accounts/login/

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\rubenelportero\Desktop\Insta-py\test.py", line 4, in cl.login("--", "--") File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\auth.py", line 391, in login logged = self.private_request("accounts/login/", data, login=True) File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\private.py", line 451, in private_request return self._send_private_request(endpoint, kwargs) File "C:\Users\rubenelportero\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\private.py", line 330, in _send_private_request raise ChallengeRequired(last_json) instagrapi.exceptions.ChallengeRequired: challenge_required

davebaird commented 1 year ago

Exact same issue as OP. Any solutions?