forked from tuxity/insta-unfollower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insta-unfollower.py
executable file
·288 lines (212 loc) · 9.54 KB
/
insta-unfollower.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import random
import requests, pickle
import json
import re
cache_dir = 'cache'
session_cache = '%s/session.txt' % (cache_dir)
followers_cache = '%s/followers.json' % (cache_dir)
following_cache = '%s/following.json' % (cache_dir)
instagram_url = 'https://www.instagram.com'
login_route = '%s/accounts/login/ajax/' % (instagram_url)
logout_route = '%s/accounts/logout/' % (instagram_url)
profile_route = '%s/%s/'
query_route = '%s/graphql/query/' % (instagram_url)
unfollow_route = '%s/web/friendships/%s/unfollow/'
session = requests.Session()
def login():
session.headers.update({
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive',
'Content-Length': '0',
'Host': 'www.instagram.com',
'Origin': 'https://www.instagram.com',
'Referer': 'https://www.instagram.com/',
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36'),
'X-Instagram-AJAX': '1',
'X-Requested-With': 'XMLHttpRequest'
})
session.cookies.update({
'ig_pr': '1',
'ig_vw': '1920',
})
reponse = session.get(instagram_url)
if 'csrftoken' in reponse.cookies:
session.headers.update({
'X-CSRFToken': reponse.cookies['csrftoken']
})
else:
print("No csrf token found in cookies, maybe you are temp ban? Wait 1 hour and retry")
return False
time.sleep(random.randint(2, 6))
post_data = {
'username': os.environ.get('INSTA_USERNAME'),
'enc_password': '#PWD_INSTAGRAM_BROWSER:0:1590954226:' + os.environ.get('INSTA_Password')
}
response = session.post(login_route, data=post_data, allow_redirects=True)
response_data = json.loads(response.text)
if 'two_factor_required' in response_data:
print('Please disable 2-factor authentication to login.')
sys.exit(1)
if response_data['authenticated']:
session.headers.update({
'X-CSRFToken': response.cookies['csrftoken']
})
return response_data['authenticated']
# Not so useful, it's just to simulate human actions better
def get_user_profile(username):
response = session.get(profile_route % (instagram_url, username))
extract = re.search(r'window._sharedData = (.+);</script>', str(response.text))
response = json.loads(extract.group(1))
return response['entry_data']['ProfilePage'][0]['graphql']['user']
def get_followers_list():
followers_list = []
query_hash = '56066f031e6239f35a904ac20c9f37d9'
variables = {
"id":session.cookies['ds_user_id'],
"include_reel":False,
"fetch_mutual":False,
"first":50
}
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
while response.status_code != 200:
time.sleep(600) # querying too much, sleeping a bit before querying again
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
print('.', end='', flush=True)
response = json.loads(response.text)
for edge in response['data']['user']['edge_followed_by']['edges']:
followers_list.append(edge['node'])
while response['data']['user']['edge_followed_by']['page_info']['has_next_page']:
variables['after'] = response['data']['user']['edge_followed_by']['page_info']['end_cursor']
time.sleep(2)
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
while response.status_code != 200:
time.sleep(600) # querying too much, sleeping a bit before querying again
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
print('.', end='', flush=True)
response = json.loads(response.text)
for edge in response['data']['user']['edge_followed_by']['edges']:
followers_list.append(edge['node'])
return followers_list
def get_following_list():
follows_list = []
query_hash = 'c56ee0ae1f89cdbd1c89e2bc6b8f3d18'
variables = {
"id":session.cookies['ds_user_id'],
"include_reel":False,
"fetch_mutual":False,
"first":50
}
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
while response.status_code != 200:
time.sleep(600) # querying too much, sleeping a bit before querying again
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
print('.', end='', flush=True)
response = json.loads(response.text)
for edge in response['data']['user']['edge_follow']['edges']:
follows_list.append(edge['node'])
while response['data']['user']['edge_follow']['page_info']['has_next_page']:
variables['after'] = response['data']['user']['edge_follow']['page_info']['end_cursor']
time.sleep(2)
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
while response.status_code != 200:
time.sleep(600) # querying too much, sleeping a bit before querying again
response = session.get(query_route, params={'query_hash': query_hash, 'variables': json.dumps(variables)})
print('.', end='', flush=True)
response = json.loads(response.text)
for edge in response['data']['user']['edge_follow']['edges']:
follows_list.append(edge['node'])
return follows_list
def unfollow(user):
response = session.get(profile_route % (instagram_url, user['username']))
time.sleep(random.randint(2, 4))
# update header again, idk why it changed
session.headers.update({
'X-CSRFToken': response.cookies['csrftoken']
})
response = session.post(unfollow_route % (instagram_url, user['id']))
response = json.loads(response.text)
if response['status'] != 'ok':
print('Error while trying to unfollow {}. Retrying in a bit...'.format(user['username']))
print('ERROR: {}'.format(unfollow.text))
return False
return True
def logout():
post_data = {
'csrfmiddlewaretoken': session.cookies['csrftoken']
}
logout = session.post(logout_route, data=post_data)
if logout.status_code != 200:
return False
return True
def main():
if not os.environ.get('INSTA_USERNAME') or not os.environ.get('INSTA_PASSWORD'):
sys.exit('please provide INSTA_USERNAME and INSTA_PASSWORD environement variables. Abording...')
if not os.path.isdir(cache_dir):
os.makedirs(cache_dir)
if os.path.isfile(session_cache):
with open(session_cache, 'rb') as f:
session.cookies.update(pickle.load(f))
else:
is_logged = login()
if is_logged == False:
sys.exit('login failed, verify user/password combination')
with open(session_cache, 'wb') as f:
pickle.dump(session.cookies, f)
time.sleep(random.randint(2, 4))
connected_user = get_user_profile(os.environ.get('INSTA_USERNAME'))
print('You\'re now logged as {} ({} followers, {} following)'.format(connected_user['username'], connected_user['edge_followed_by']['count'], connected_user['edge_follow']['count']))
time.sleep(random.randint(2, 4))
following_list = []
if os.path.isfile(following_cache):
with open(following_cache, 'r') as f:
following_list = json.load(f)
print('following list loaded from cache file')
if len(following_list) != connected_user['edge_follow']['count']:
if len(following_list) > 0:
print('rebuilding following list...', end='', flush=True)
else:
print('building following list...', end='', flush=True)
following_list = get_following_list()
print(' done')
with open(following_cache, 'w') as f:
json.dump(following_list, f)
followers_list = []
if os.path.isfile(followers_cache):
with open(followers_cache, 'r') as f:
followers_list = json.load(f)
print('followers list loaded from cache file')
if len(followers_list) != connected_user['edge_followed_by']['count']:
if len(following_list) > 0:
print('rebuilding followers list...', end='', flush=True)
else:
print('building followers list...', end='', flush=True)
followers_list = get_followers_list()
print(' done')
with open(followers_cache, 'w') as f:
json.dump(followers_list, f)
followers_usernames = {user['username'] for user in followers_list}
unfollow_users_list = [user for user in following_list if user['username'] not in followers_usernames]
print('you are following {} user(s) who aren\'t following you:'.format(len(unfollow_users_list)))
for user in unfollow_users_list:
print(user['username'])
if len(unfollow_users_list) > 0:
print('Begin to unfollow users...')
for user in unfollow_users_list:
if not os.environ.get('UNFOLLOW_VERIFIED') and user['is_verified'] == True:
continue
time.sleep(random.randint(2, 4))
while unfollow(user) == False:
time.sleep(random.randint(1, 3) * 1000) # High number on purpose
print(' done')
is_logged_out = logout()
if is_logged_out:
sys.exit(0)
if __name__ == "__main__":
main()