-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfollow_github.py
More file actions
305 lines (254 loc) · 11 KB
/
follow_github.py
File metadata and controls
305 lines (254 loc) · 11 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import requests
from requests.auth import HTTPBasicAuth
from time import sleep, time
import json
import os
from dotenv import load_dotenv
from random import randint
import sys
load_dotenv()
USERNAME = os.getenv('GITHUB_USERNAME')
TOKEN = os.getenv('GITHUB_TOKEN')
def load_users(filename):
with open(filename, 'r') as file:
data = json.load(file)
return data.get('usuarios', [])
def is_user_followed(username):
url = f'https://api.github.com/user/following/{username}'
try:
response = requests.get(url, auth=HTTPBasicAuth(USERNAME, TOKEN))
if response.status_code == 204:
return True
elif response.status_code == 404:
return False
else:
print(f'Error checking if you follow {username}. Status code: {response.status_code}')
return False
except requests.RequestException as e:
print(f'Error checking {username}: {e}')
return False
def follow_user(username, failed_users):
if is_user_followed(username):
print(f'Already following: {username}. Skipping...')
return
url = f'https://api.github.com/user/following/{username}'
try:
response = requests.put(url, auth=HTTPBasicAuth(USERNAME, TOKEN))
if response.status_code == 204:
print(f'Followed: {username}')
elif response.status_code == 404:
print(f'Not found: {username}')
elif response.status_code == 403:
rate_limit_reset = int(response.headers.get('X-RateLimit-Reset', 0))
wait_time = max(0, rate_limit_reset - time())
print(f'Rate limit exceeded. Waiting {wait_time / 60:.2f} minutes.')
sleep(wait_time)
failed_users.append(username)
elif response.status_code == 429:
rate_limit_reset = int(response.headers.get('X-RateLimit-Reset', 0))
wait_time = max(0, rate_limit_reset - time())
print(f'Error 429: too many requests. Waiting {wait_time / 60:.2f} minutes before retrying.')
sleep(wait_time)
failed_users.append(username)
else:
print(f'Error following {username}. Status code: {response.status_code}')
failed_users.append(username)
except requests.RequestException as e:
print(f'Error following {username}: {e}')
failed_users.append(username)
def save_failed_users(failed_users):
if failed_users:
output_dir = 'static'
os.makedirs(output_dir, exist_ok=True)
output_file = os.path.join(output_dir, 'failed_users.json')
with open(output_file, 'w', encoding='utf-8') as f:
json.dump({"usuarios": failed_users}, f, indent=2, ensure_ascii=False)
print(f'Failed users saved to: {output_file}')
def get_following_users():
if not USERNAME or not TOKEN:
print('Error: GitHub credentials are not configured.')
print('Make sure you have GITHUB_USERNAME and GITHUB_TOKEN in your .env file')
return []
following_users = []
url = 'https://api.github.com/user/following'
page = 1
per_page = 100
print(f'Connecting to GitHub API as: {USERNAME}')
while True:
try:
params = {'page': page, 'per_page': per_page}
response = requests.get(url, auth=HTTPBasicAuth(USERNAME, TOKEN), params=params)
if response.status_code == 200:
users = response.json()
if not users:
if page == 1:
print('No followed users found.')
break
following_users.extend([user['login'] for user in users])
print(f'Page {page}: {len(users)} users found (Total: {len(following_users)})')
page += 1
if len(users) < per_page:
break
elif response.status_code == 401:
print('Authentication error. Verify that your GitHub token is valid.')
print('API response:', response.text[:200])
break
elif response.status_code == 403 or response.status_code == 429:
rate_limit_reset = int(response.headers.get('X-RateLimit-Reset', 0))
wait_time = max(0, rate_limit_reset - time())
print(f'Rate limit exceeded. Waiting {wait_time / 60:.2f} minutes.')
sleep(wait_time)
continue
else:
print(f'Error getting followed users. Status code: {response.status_code}')
print(f'Response: {response.text[:200]}')
break
except requests.RequestException as e:
print(f'Error getting followed users: {e}')
break
return following_users
def check_rate_limit(response=None):
if response is None:
url = 'https://api.github.com/rate_limit'
try:
response = requests.get(url, auth=HTTPBasicAuth(USERNAME, TOKEN))
if response.status_code != 200:
return True
except:
return True
try:
remaining = int(response.headers.get('X-RateLimit-Remaining', 5000))
reset_time = int(response.headers.get('X-RateLimit-Reset', 0))
if remaining < 100 and reset_time > 0:
wait_time = max(0, reset_time - time())
if wait_time > 0:
print(f'\n⚠️ Low rate limit ({remaining} remaining). Waiting {wait_time / 60:.1f} minutes...')
sleep(wait_time)
return False
except (ValueError, KeyError):
pass
return True
def does_user_follow_me(username, check_rate=True):
url = f'https://api.github.com/users/{username}/following/{USERNAME}'
try:
response = requests.get(url, auth=HTTPBasicAuth(USERNAME, TOKEN))
if check_rate:
check_rate_limit(response)
if response.status_code == 204:
return True
elif response.status_code == 404:
return False
else:
return False
except requests.RequestException:
return False
def unfollow_user(username, failed_users):
if not is_user_followed(username):
return
url = f'https://api.github.com/user/following/{username}'
try:
response = requests.delete(url, auth=HTTPBasicAuth(USERNAME, TOKEN))
check_rate_limit(response)
if response.status_code == 204:
pass
elif response.status_code == 404:
pass
elif response.status_code == 403:
rate_limit_reset = int(response.headers.get('X-RateLimit-Reset', 0))
wait_time = max(0, rate_limit_reset - time())
print(f'\n⚠️ Rate limit exceeded. Waiting {wait_time / 60:.2f} minutes.')
sleep(wait_time)
failed_users.append(username)
elif response.status_code == 429:
rate_limit_reset = int(response.headers.get('X-RateLimit-Reset', 0))
wait_time = max(0, rate_limit_reset - time())
print(f'\n⚠️ Error 429: too many requests. Waiting {wait_time / 60:.2f} minutes.')
sleep(wait_time)
failed_users.append(username)
else:
failed_users.append(username)
except requests.RequestException:
failed_users.append(username)
def unfollow_non_followers():
if not USERNAME or not TOKEN:
print('Error: GitHub credentials are not configured.')
print('Make sure you have GITHUB_USERNAME and GITHUB_TOKEN in your .env file')
return
print('Getting list of users you are following...')
following_users = get_following_users()
if not following_users:
print('\nNo users you are following were found.')
print('This may be due to:')
print(' 1. You are really not following any users')
print(' 2. Authentication error (verify your token)')
print(' 3. The token does not have the necessary permissions')
return
print(f'Found {len(following_users)} users you are following.')
print("Checking which ones don't follow you back...")
print('(Reduced pauses, automatically checking rate limits)\n')
non_followers = []
failed_users = []
last_print_time = time()
print_interval = 5
for i, username in enumerate(following_users, 1):
current_time = time()
if current_time - last_print_time >= print_interval or i == 1 or i == len(following_users):
print(f'[{i}/{len(following_users)}] Checking... ({len(non_followers)} don\'t follow you so far)')
last_print_time = current_time
if not does_user_follow_me(username):
non_followers.append(username)
sleep(randint(300, 700) / 1000)
if i % 50 == 0:
print(f' → Processed {i} users. Safety pause...')
sleep(randint(1, 2))
if not non_followers:
print('\nExcellent! All users you follow also follow you back.')
return
print(f'\nFound {len(non_followers)} users who don\'t follow you back.')
respuesta = input('Do you want to unfollow these users? (y/n): ').lower().strip()
if respuesta != 'y':
print('Operation cancelled.')
return
print(f'\nUnfollowing {len(non_followers)} users...')
last_print_time = time()
for i, username in enumerate(non_followers, 1):
current_time = time()
if current_time - last_print_time >= print_interval or i == 1 or i == len(non_followers):
print(f'[{i}/{len(non_followers)}] Processing...')
last_print_time = current_time
unfollow_user(username, failed_users)
sleep(randint(500, 1000) / 1000)
if i % 30 == 0:
print(f' → Processed {i} users. Safety pause...')
sleep(randint(1, 2))
if failed_users:
save_failed_users(failed_users)
print(f'\n{len(failed_users)} users could not be processed. Check the failed users file.')
else:
print(f'\n✓ Process completed. Unfollowed {len(non_followers)} users.')
def main():
if len(sys.argv) > 1 and sys.argv[1] == '--unfollow':
unfollow_non_followers()
return
users_to_follow = load_users('static/usuarios.json')
failed_users = []
if not users_to_follow:
print('No users found to follow.')
return
for user in users_to_follow:
follow_user(user, failed_users)
sleep(randint(1, 5))
save_failed_users(failed_users)
if __name__ == "__main__":
print("=" * 60)
print("GitHub Mass Following Script")
print("=" * 60)
print("\nAvailable modes:")
print(" 1. Follow users (default mode): python follow_github.py")
print(" 2. Unfollow those who don't follow you: python follow_github.py --unfollow")
print("=" * 60)
if len(sys.argv) > 1 and sys.argv[1] == '--unfollow':
print("\nMode: Unfollow users who don't follow you\n")
else:
print("\nMode: Follow users from the list\n")
main()