forked from subzeroid/instagrapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge_resolvers.py
69 lines (58 loc) · 1.98 KB
/
challenge_resolvers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
Example to handle Email/SMS challenges
"""
import email
import imaplib
import re
from instagrapi import Client
CHALLENGE_EMAIL = ''
CHALLENGE_PASSWORD = ''
IG_USERNAME = ''
IG_PASSWORD = ''
def get_code_from_email(username):
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(CHALLENGE_EMAIL, CHALLENGE_PASSWORD)
mail.select("inbox")
result, data = mail.search(None, "(UNSEEN)")
assert result == "OK", "Error1 during get_code_from_email: %s" % result
ids = data.pop().split()
for num in reversed(ids):
mail.store(num, "+FLAGS", "\\Seen") # mark as read
result, data = mail.fetch(num, "(RFC822)")
assert result == "OK", "Error2 during get_code_from_email: %s" % result
msg = email.message_from_string(data[0][1].decode())
payloads = msg.get_payload()
if not isinstance(payloads, list):
payloads = [msg]
code = None
for payload in payloads:
body = payload.get_payload(decode=True).decode()
if "<div" not in body:
continue
match = re.search(">([^>]*?({u})[^<]*?)<".format(u=username), body)
if not match:
continue
print("Match from email:", match.group(1))
match = re.search(r">(\d{6})<", body)
if not match:
print('Skip this email, "code" not found')
continue
code = match.group(1)
return code
return False
def get_code_from_sms(username):
while True:
code = input(f"Enter code (6 digits) for {username}: ").strip()
if code and code.isdigit():
return code
return None
def challenge_code_handler(username, choice):
if choice == 0:
return get_code_from_sms(username)
elif choice == 1:
return get_code_from_email(username)
return False
if __name__ == '__main__':
cl = Client()
cl.challenge_code_handler = challenge_code_handler
cl.login(IG_USERNAME, IG_PASSWORD)