-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitfollow.py
More file actions
809 lines (693 loc) · 32.2 KB
/
Copy pathgitfollow.py
File metadata and controls
809 lines (693 loc) · 32.2 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
"""
GitFollow - Automated GitHub follow/unfollow tool.
Strategy:
1. Unfollow anyone followed 24+ hours ago who hasn't followed back.
2. Optionally unfollow existing follows that fail quality criteria (QUALITY_UNFOLLOW=true).
3. Follow new users sourced via GitHub search, filtered by quality criteria.
4. Commit updated state back to the repo (when run via GitHub Actions).
Quality criteria for a follow candidate:
- Username must not match bot/mirror/archive/numeric-only patterns
- Must be a regular User (not an Organization or bot)
- Must have at least MIN_FOLLOWERS followers
- Must have fewer than MAX_REPOS public repos (filters mass-forking bots)
- following/followers ratio must be below MAX_FF_RATIO (filters follow-farmers)
- Account must be at least MIN_ACCOUNT_AGE_DAYS old (filters throwaway accounts)
- Must have at least one of: name, bio, or email set (filters unconfigured bots)
- Must have pushed a commit within the last ACTIVITY_DAYS days
Quality check results are cached in state.json for CACHE_DAYS days to avoid
re-checking the same accounts on every run.
Required env vars:
GH_TOKEN - GitHub personal access token (user:follow scope)
GH_USERNAME - Your GitHub username
Optional env vars:
FOLLOW_LIMIT - Max new follows per run (default: 150)
UNFOLLOW_HOURS - Hours before unfollowing non-followers (default: 24)
WHITELIST - Comma-separated usernames to never unfollow
STATE_FILE - Path to state JSON file (default: data/state.json)
ACTIVITY_DAYS - Days of inactivity before skipping a candidate (default: 30)
MIN_FOLLOWERS - Minimum followers a candidate must have (default: 1)
MAX_REPOS - Skip accounts with more public repos than this (default: 500)
MAX_FF_RATIO - Skip accounts whose following/followers ratio exceeds this (default: 10.0)
MIN_ACCOUNT_AGE_DAYS - Skip accounts newer than this many days (default: 30)
CACHE_DAYS - How long to cache quality check results (default: 7)
QUALITY_UNFOLLOW - Set to "true" to unfollow existing follows that fail quality criteria
SEARCH_MIN_FOLLOWERS - Pre-filter search: min followers in query (default: 10)
SEARCH_MAX_FOLLOWERS - Pre-filter search: max followers in query (default: 1000)
"""
import os
import re
import json
import time
import random
import logging
import threading
import tempfile
import requests
from datetime import datetime, timezone, timedelta
from pathlib import Path
# ── .env loader (headless / CLI support) ──────────────────────────────────────
# Load .env from the script's own directory before reading any env vars.
# gui.py handles this for GUI runs; this block makes "python gitfollow.py" work too.
def _load_dotenv():
env_path = Path(__file__).parent / ".env"
if not env_path.exists():
return
try:
for line in env_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
k = k.strip()
if k and k not in os.environ: # never override already-set vars
os.environ[k] = v.strip()
except Exception:
pass
_load_dotenv()
# ── CA bundle sanity check ────────────────────────────────────────────────────
# Some installers (e.g. PostgreSQL) set CURL_CA_BUNDLE / REQUESTS_CA_BUNDLE /
# SSL_CERT_FILE machine-wide, pointing at their own cert bundle. If that path
# later goes missing, `requests` refuses every call with
# "Could not find a suitable TLS CA certificate bundle". Drop any such
# dangling env var so requests falls back to certifi's bundled certs.
for _ca_var in ("REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE"):
_ca_path = os.environ.get(_ca_var)
if _ca_path and not Path(_ca_path).is_file():
os.environ.pop(_ca_var, None)
# ── Config ────────────────────────────────────────────────────────────────────
TOKEN = os.environ["GH_TOKEN"]
USERNAME = os.environ["GH_USERNAME"]
FOLLOW_LIMIT = int(os.environ.get("FOLLOW_LIMIT", 150))
UNFOLLOW_HRS = int(os.environ.get("UNFOLLOW_HOURS", 24))
WHITELIST = {u.strip().lower() for u in os.environ.get("WHITELIST", "").split(",") if u.strip()}
STATE_FILE = Path(os.environ.get("STATE_FILE", "data/state.json"))
ACTIVITY_DAYS = int(os.environ.get("ACTIVITY_DAYS", 30))
MIN_FOLLOWERS = int(os.environ.get("MIN_FOLLOWERS", 1))
MAX_REPOS = int(os.environ.get("MAX_REPOS", 500))
MAX_FF_RATIO = float(os.environ.get("MAX_FF_RATIO", 10.0))
MIN_ACCOUNT_AGE_DAYS = int(os.environ.get("MIN_ACCOUNT_AGE_DAYS", 30))
CACHE_DAYS = int(os.environ.get("CACHE_DAYS", 7))
QUALITY_UNFOLLOW = os.environ.get("QUALITY_UNFOLLOW", "false").lower() == "true"
SEARCH_MIN_FOLLOWERS = int(os.environ.get("SEARCH_MIN_FOLLOWERS", 10))
SEARCH_MAX_FOLLOWERS = int(os.environ.get("SEARCH_MAX_FOLLOWERS", 1000))
# How long to remember explicitly-unfollowed accounts to prevent re-following them.
UNFOLLOW_MEMORY_DAYS = CACHE_DAYS * 4 # default 28 days
# Bot-like username patterns.
# Requires keyword to appear at a delimiter boundary (-, _) or at string start/end.
# This avoids false-positives like "robotics" or "cloner" while still catching
# "my-bot", "bot_xyz", "data-crawler", "github-mirror" etc.
_BOT_NAME_RE = re.compile(
r'^\d+$'
r'|(^|[-_])(bot|mirror|backup|clone|archive|crawler|scraper)([-_]|$)',
re.I,
)
HEADERS = {
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "GitFollow/2.0 (+https://github.com/Andrew-most-likely/gitfollow)",
}
log = logging.getLogger(__name__)
# Set by the GUI to request a graceful stop between operations.
# Reset to a fresh Event on each run via importlib.reload.
stop_event = threading.Event()
# ── State helpers ─────────────────────────────────────────────────────────────
def load_state() -> dict:
if STATE_FILE.exists():
try:
with open(STATE_FILE, encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, ValueError, OSError) as e:
log.warning("state.json unreadable (%s) — starting fresh", e)
return {
"following": {},
"unfollowed_seen": {},
"quality_cache": {},
"stats": {"followed": 0, "unfollowed": 0, "mutual": 0},
}
def save_state(state: dict):
"""Atomic write: write to a temp file then replace, preventing corruption on crash."""
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = STATE_FILE.with_suffix(".tmp")
try:
with open(tmp, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2)
tmp.replace(STATE_FILE)
except Exception as e:
log.error("Failed to save state: %s", e)
tmp.unlink(missing_ok=True)
raise
log.info("State saved → %s", STATE_FILE)
# ── GitHub API helpers ────────────────────────────────────────────────────────
def _interruptible_sleep(seconds: float):
"""Sleep in 1-second chunks so stop_event can interrupt rate-limit waits."""
end = time.time() + seconds
while time.time() < end:
if stop_event.is_set():
return
time.sleep(min(1.0, end - time.time()))
def api_get(url: str, params: dict = None) -> requests.Response:
"""GET with automatic rate-limit back-off."""
while True:
try:
resp = requests.get(url, headers=HEADERS, params=params, timeout=30)
except requests.exceptions.RequestException as e:
# Covers timeouts, dropped connections, DNS failures, SSL errors, etc.
log.warning("Network error on GET %s (%s) — skipping", url, e)
# Return a fake response object with a non-retryable status so callers
# handle it gracefully rather than crashing the entire run.
return _timeout_response()
if resp.status_code == 401:
log.error("AUTH ERROR 401 on GET %s — token is invalid, expired, or revoked", url)
return resp
if resp.status_code == 429 or (resp.status_code == 403 and "rate limit" in resp.text.lower()):
reset = int(resp.headers.get("X-RateLimit-Reset", time.time() + 60))
wait = max(reset - time.time(), 1)
log.warning("Rate limited — sleeping %.0fs", wait)
_interruptible_sleep(wait)
if stop_event.is_set():
return resp
continue
return resp
def api_write(method: str, url: str) -> int:
"""PUT/DELETE with secondary rate-limit back-off."""
while True:
try:
resp = requests.request(method, url, headers=HEADERS, timeout=30)
except requests.exceptions.RequestException as e:
log.warning("Network error on %s %s (%s) — skipping", method, url, e)
return 0
if resp.status_code == 401:
log.error("AUTH ERROR 401 on %s %s — token is invalid, expired, or revoked", method, url)
return resp.status_code
if resp.status_code == 429 or (
resp.status_code == 403 and (
"rate limit" in resp.text.lower() or
"secondary" in resp.text.lower()
)
):
retry_after = int(resp.headers.get("Retry-After", 60))
log.warning("Secondary rate limit hit — sleeping %ds", retry_after)
_interruptible_sleep(retry_after)
if stop_event.is_set():
return resp.status_code
continue
return resp.status_code
class _timeout_response:
"""Minimal stand-in returned when a request fails outright (timeout, dropped
connection, DNS failure, etc.), so callers don't crash."""
status_code = 0
text = ""
headers = {}
def json(self): return {}
def api_put(url: str) -> int:
return api_write("PUT", url)
def api_delete(url: str) -> int:
return api_write("DELETE", url)
def paginate(url: str, params: dict = None, max_pages: int = 10) -> list:
"""Collect all items from a paginated GitHub list endpoint."""
items, page = [], 1
p = {"per_page": 100, **(params or {})}
while page <= max(1, max_pages):
if stop_event.is_set():
break
p["page"] = page
resp = api_get(url, p)
if resp.status_code == 401:
if page > 1:
log.warning(
"401 on page %d of %s — returning partial results (%d items so far)",
page, url, len(items),
)
else:
log.error("Aborting pagination of %s — 401 Unauthorized (check GH_TOKEN)", url)
break
if resp.status_code != 200:
log.warning("Pagination stopped at page %d for %s — HTTP %s", page, url, resp.status_code)
break
batch = resp.json()
if not batch:
break
items.extend(batch)
page += 1
return items
def get_my_following() -> set:
items = paginate(f"https://api.github.com/users/{USERNAME}/following", max_pages=50)
return {u["login"].lower() for u in items}
def get_my_followers() -> set:
items = paginate(f"https://api.github.com/users/{USERNAME}/followers", max_pages=50)
return {u["login"].lower() for u in items}
def checks_remaining() -> int:
resp = api_get("https://api.github.com/rate_limit")
if resp.status_code == 200:
return resp.json()["resources"]["core"]["remaining"]
return 0
# ── Quality filter ─────────────────────────────────────────────────────────────
def is_quality_candidate(login: str) -> tuple:
"""
Returns (True, "") if the user is worth following, else (False, reason).
Free pre-checks run before any API call; profile checks use the single
/users/{login} response; push-event check is the only extra API call.
"""
# Free pre-check: bot-like username patterns (no API call)
if _BOT_NAME_RE.search(login):
return False, "bot-like username"
resp = api_get(f"https://api.github.com/users/{login}")
if resp.status_code != 200:
return False, "profile fetch failed"
data = resp.json()
if data.get("type", "User") != "User":
return False, "organization/bot"
followers = data.get("followers", 0)
if followers < MIN_FOLLOWERS:
return False, f"fewer than {MIN_FOLLOWERS} followers"
# Mass-forking / mirror bot: too many repos
public_repos = data.get("public_repos", 0)
if public_repos > MAX_REPOS:
return False, f"too many repos ({public_repos})"
# Follow-farmer: following far more people than follow them back
following = data.get("following", 0)
if followers == 0 and following > 50:
return False, f"follow-farmer (following={following}, followers=0)"
if followers > 0 and following / followers > MAX_FF_RATIO:
return False, f"follow-farmer ratio {following}:{followers}"
# Account too new: throwaway/spam accounts
created_at_str = data.get("created_at", "")
if created_at_str:
created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
age_days = (datetime.now(timezone.utc) - created_at).days
if age_days < MIN_ACCOUNT_AGE_DAYS:
return False, f"account too new ({age_days}d old)"
# No profile info: unconfigured / bot account
if not any([data.get("name"), data.get("bio"), data.get("email")]):
return False, "no profile info (name/bio/email all empty)"
cutoff = datetime.now(timezone.utc) - timedelta(days=ACTIVITY_DAYS)
# Fast path: profile updated_at older than cutoff means no activity — skip events fetch
updated_at_str = data.get("updated_at", "")
if updated_at_str:
updated_at = datetime.fromisoformat(updated_at_str.replace("Z", "+00:00"))
if updated_at < cutoff:
return False, f"inactive (no GitHub activity in {ACTIVITY_DAYS}d)"
# Confirm recent activity is a push (not just a profile edit)
events = paginate(f"https://api.github.com/users/{login}/events/public", max_pages=1)
for event in events:
if event.get("type") == "PushEvent":
ts = event.get("created_at", "")
if ts:
created_at = datetime.fromisoformat(ts.replace("Z", "+00:00"))
if created_at >= cutoff:
return True, ""
return False, f"no push commits in last {ACTIVITY_DAYS}d"
def cached_quality_check(login: str, cache: dict) -> tuple:
"""
Returns (ok, reason) from cache if fresh, otherwise calls is_quality_candidate
and stores the result.
"""
cache_cutoff = datetime.now(timezone.utc) - timedelta(days=CACHE_DAYS)
entry = cache.get(login)
if entry:
try:
checked_at = datetime.fromisoformat(entry["checked_at"])
if checked_at >= cache_cutoff:
return entry["ok"], entry["reason"]
except (KeyError, ValueError):
# Corrupt or malformed cache entry — treat as a miss and re-check
pass
ok, reason = is_quality_candidate(login)
cache[login] = {
"checked_at": datetime.now(timezone.utc).isoformat(),
"ok": ok,
"reason": reason,
}
return ok, reason
# ── Core logic ────────────────────────────────────────────────────────────────
def do_unfollows(state: dict, my_followers: set):
"""Unfollow people who haven't followed back after UNFOLLOW_HRS hours."""
cutoff = datetime.now(timezone.utc) - timedelta(hours=UNFOLLOW_HRS)
to_drop = []
for login, info in state["following"].items():
if login.lower() in WHITELIST:
continue
if login.lower() in my_followers:
# They followed back — mark mutual (only increment stat on first detection)
if not info.get("mutual"):
info["mutual"] = True
state["stats"]["mutual"] += 1
log.info("Mutual follow: %s", login)
continue
# Not following us back — reset any stale mutual flag
if info.get("mutual"):
info["mutual"] = False
log.info("No longer following back: %s", login)
followed_at = datetime.fromisoformat(info["followed_at"])
if followed_at <= cutoff:
to_drop.append(login)
for login in to_drop:
if stop_event.is_set():
log.info("Stop requested — halting unfollow pass.")
break
code = api_delete(f"https://api.github.com/user/following/{login}")
if code in (204, 404):
log.info("Unfollowed: %s", login)
del state["following"][login]
state["stats"]["unfollowed"] += 1
# Remember this account so we don't re-follow it immediately
state.setdefault("unfollowed_seen", {})[login] = \
datetime.now(timezone.utc).isoformat()
else:
log.warning("Unfollow failed for %s — HTTP %s", login, code)
time.sleep(0.5)
def candidate_pool(already_in_state: set, my_following: set, unfollowed_seen: set) -> list:
"""
Pull candidates from two high-signal sources:
1. Stargazers of popular repos in curated tech topics (primary).
People who star real projects are almost always real developers.
2. GitHub user search sorted by followers/repos (fallback).
Never sorts by join date — that heavily favours brand-new bot accounts.
"""
skip = already_in_state | my_following | unfollowed_seen | {USERNAME.lower()}
candidates = []
target = FOLLOW_LIMIT * 4 # gather ~4× the limit so quality filter has room to work
# ── Source 1: stargazers of popular repos in curated topics ───────────────
topics = random.sample([
"python", "javascript", "typescript", "rust", "go", "java",
"machine-learning", "web-development", "open-source", "devops",
"cli", "api", "data-science", "game-development", "security",
], k=3)
for topic in topics:
if stop_event.is_set():
break
if len(candidates) >= target:
break
log.info("Finding popular repos in topic: %s ...", topic)
resp = api_get("https://api.github.com/search/repositories", {
"q": f"topic:{topic} stars:>500",
"sort": "stars",
"order": "desc",
"per_page": 5,
"page": random.randint(1, 4),
})
if resp.status_code != 200:
log.warning("Repo search failed for topic %s (%s)", topic, resp.status_code)
time.sleep(1)
continue
repos = resp.json().get("items", [])
time.sleep(1)
for repo in repos:
if stop_event.is_set():
break
if len(candidates) >= target:
break
full_name = repo["full_name"]
log.info("Pulling stargazers from %s ...", full_name)
page = random.randint(1, max(1, repo["stargazers_count"] // 100))
page = min(page, 400)
resp2 = api_get(f"https://api.github.com/repos/{full_name}/stargazers", {
"per_page": 100,
"page": page,
})
if resp2.status_code != 200:
time.sleep(1)
continue
for u in resp2.json():
login = u["login"].lower()
if login not in skip:
candidates.append(login)
skip.add(login)
log.info(" Got %d candidates so far", len(candidates))
time.sleep(1)
# ── Source 2: user search fallback (no join-date sort — attracts new bots) ─
if len(candidates) < target:
sort, order = random.choice([
("repositories", "desc"),
("followers", "desc"),
("followers", "asc"),
])
query = f"type:user followers:{SEARCH_MIN_FOLLOWERS}..{SEARCH_MAX_FOLLOWERS} repos:2..200"
pages_needed = min(((target - len(candidates)) // 100) + 2, 10)
log.info("User search fallback (sort=%s %s) ...", sort, order)
for page in range(1, pages_needed + 1):
if stop_event.is_set():
break
resp = api_get("https://api.github.com/search/users", {
"q": query,
"sort": sort,
"order": order,
"per_page": 100,
"page": page,
})
if resp.status_code != 200:
log.warning("User search returned %s", resp.status_code)
break
items = resp.json().get("items", [])
if not items:
break
for u in items:
login = u["login"].lower()
if login not in skip:
candidates.append(login)
skip.add(login)
log.info("Search page %d: %d total candidates", page, len(candidates))
time.sleep(2)
# ── Last resort: global /users list ───────────────────────────────────────
if not candidates:
since = random.randint(0, 5_000_000)
log.info("Last-resort fallback to global /users since id=%d ...", since)
for _ in range(5):
if stop_event.is_set():
break
resp = api_get("https://api.github.com/users", {"since": since, "per_page": 100})
if resp.status_code != 200:
break
batch = resp.json()
if not batch:
break
for u in batch:
login = u["login"].lower()
if login not in skip:
candidates.append(login)
skip.add(login)
since = batch[-1]["id"]
time.sleep(1)
random.shuffle(candidates)
log.info("Candidate pool ready: %d accounts", len(candidates))
return candidates
def do_follows(state: dict, my_following: set, my_followers: set):
"""Follow up to FOLLOW_LIMIT new users."""
if FOLLOW_LIMIT <= 0:
log.info("Follow pass skipped (FOLLOW_LIMIT=0)")
return
already_tracked = set(state["following"].keys())
unfollowed_seen = set(state.get("unfollowed_seen", {}).keys())
pool = candidate_pool(already_tracked, my_following, unfollowed_seen)
cache = state.setdefault("quality_cache", {})
followed = 0
checked = 0
now_iso = datetime.now(timezone.utc).isoformat()
pool_size = len(pool)
quota = checks_remaining()
log.info("Checking quality of %d candidates (quota=%d) ...", pool_size, quota)
for login in pool:
if stop_event.is_set():
log.info("Stop requested — halting follow pass.")
break
if followed >= FOLLOW_LIMIT:
break
if checked % 100 == 0 and checked > 0:
quota = checks_remaining()
if quota < 50:
log.warning("API quota nearly exhausted — stopping follows early")
break
# Skip if they already follow us (no point in the follow-back game)
if login in my_followers:
continue
# Quality gate (cached)
ok, reason = cached_quality_check(login, cache)
checked += 1
if not ok:
log.info(" [%d/%d] Skipping %s: %s", checked, pool_size, login, reason)
continue
code = api_put(f"https://api.github.com/user/following/{login}")
if code in (204, 200):
log.info("[%d/%d] Followed: %s", followed + 1, FOLLOW_LIMIT, login)
state["following"][login] = {"followed_at": now_iso, "mutual": False}
state["stats"]["followed"] += 1
followed += 1
else:
log.warning("Follow failed for %s — HTTP %s", login, code)
# Polite delay — avoid secondary rate limits
time.sleep(random.uniform(2.0, 4.0))
log.info("Followed %d new users this run", followed)
def do_quality_unfollows(state: dict, my_following: set):
"""
Unfollow accounts we currently follow that fail quality criteria:
orgs/corporations, users with too few followers, or users inactive for
more than ACTIVITY_DAYS days. Mutual follows and whitelisted accounts
are always skipped. Results are cached to avoid redundant API calls.
"""
cache = state.setdefault("quality_cache", {})
to_drop = []
# Only scan accounts still tracked in state (excludes any already unfollowed
# earlier in this same run by do_unfollows).
candidates = [
l for l in my_following
if l in state["following"]
and l not in WHITELIST
and not state["following"].get(l, {}).get("mutual")
]
total = len(candidates)
quota = checks_remaining()
cache_hits = 0
actual_scanned = 0
log.info("Scanning %d followed accounts for quality (quota=%d) ...", total, quota)
# Phase 1: scan the full list, log each result, build to_drop
for i, login in enumerate(candidates, 1):
if stop_event.is_set():
log.info("Stop requested — halting quality unfollow scan.")
break
# Refresh quota every 100 accounts (less frequent to save API calls)
if i % 100 == 1 and i > 1:
quota = checks_remaining()
if quota < 150:
log.warning("API quota low — stopping quality-unfollow checks early")
break
actual_scanned = i
was_cached = login in cache
ok, reason = cached_quality_check(login, cache)
if was_cached:
cache_hits += 1
if ok:
log.info(" [%d/%d] Keeping %s (good quality)", i, total, login)
else:
log.info(" [%d/%d] Queued to unfollow %s: %s", i, total, login, reason)
to_drop.append((login, reason))
time.sleep(0.1)
log.info(
"Scan complete: scanned=%d of %d cache_hits=%d to_unfollow=%d",
actual_scanned, total, cache_hits, len(to_drop),
)
# Phase 2: unfollow the queued accounts
unfollowed = 0
for login, reason in to_drop:
if stop_event.is_set():
log.info("Stop requested — halting quality unfollow pass.")
break
code = api_delete(f"https://api.github.com/user/following/{login}")
if code in (204, 404):
log.info("Quality-unfollowed %s (%s)", login, reason)
state["following"].pop(login, None)
state["stats"]["unfollowed"] += 1
state.setdefault("unfollowed_seen", {})[login] = \
datetime.now(timezone.utc).isoformat()
unfollowed += 1
else:
log.warning("Quality-unfollow failed for %s — HTTP %s", login, code)
time.sleep(0.5)
log.info("Quality unfollow complete: unfollowed=%d", unfollowed)
# ── Entry point ───────────────────────────────────────────────────────────────
def main():
# Configure root logger once — guard prevents duplicate handlers on module reload
if not logging.root.handlers:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log.setLevel(logging.INFO)
log.info("=== GitFollow starting | user=%s ===", USERNAME)
if stop_event.is_set():
log.info("Stop requested before run — aborting.")
return
# Verify the token identity
resp = api_get("https://api.github.com/user")
if resp.status_code == 0:
log.error("Could not reach the GitHub API — check your internet connection")
return
if resp.status_code == 401:
log.error("Token rejected with 401 Unauthorized — verify GH_TOKEN is valid and not expired/revoked")
return
if resp.status_code != 200:
log.error("Token check failed — HTTP %s", resp.status_code)
return
authed_as = resp.json().get("login", "unknown")
log.info("Token authenticated as: %s", authed_as)
if authed_as.lower() != USERNAME.lower():
log.error("Token user (%s) does not match GH_USERNAME (%s) — aborting", authed_as, USERNAME)
return
remaining = checks_remaining()
log.info("API quota remaining: %d", remaining)
if remaining < 100:
log.error("Quota too low to proceed safely — aborting")
return
state = load_state()
# Prune stale quality-cache entries so state.json doesn't grow forever
cache = state.setdefault("quality_cache", {})
cache_cutoff = datetime.now(timezone.utc) - timedelta(days=CACHE_DAYS)
stale_cache = [
k for k, v in cache.items()
if _safe_fromisoformat(v.get("checked_at", "")) < cache_cutoff
]
if stale_cache:
for k in stale_cache:
del cache[k]
log.info("Pruned %d stale cache entries", len(stale_cache))
# Prune old unfollowed_seen entries
unfollowed_seen = state.setdefault("unfollowed_seen", {})
memory_cutoff = datetime.now(timezone.utc) - timedelta(days=UNFOLLOW_MEMORY_DAYS)
stale_seen = [
k for k, v in unfollowed_seen.items()
if _safe_fromisoformat(v) < memory_cutoff
]
if stale_seen:
for k in stale_seen:
del unfollowed_seen[k]
log.info("Pruned %d expired unfollow-memory entries", len(stale_seen))
if stop_event.is_set():
log.info("Stop requested — aborting before API fetch.")
return
my_following = get_my_following()
if stop_event.is_set():
log.info("Stop requested — aborting after following fetch.")
return
my_followers = get_my_followers()
if stop_event.is_set():
log.info("Stop requested — aborting after followers fetch.")
return
log.info("Currently following=%d followers=%d tracked=%d",
len(my_following), len(my_followers), len(state["following"]))
# 1. Sync state: remove entries for accounts we're no longer following
# (manually unfollowed outside this tool)
ghost_entries = [l for l in list(state["following"]) if l not in my_following]
for l in ghost_entries:
del state["following"][l]
# 1b. Backfill anyone followed outside the app (no timestamp yet)
now_iso = datetime.now(timezone.utc).isoformat()
backfilled = 0
for login in my_following:
if login not in state["following"]:
state["following"][login] = {"followed_at": now_iso, "mutual": False}
backfilled += 1
if backfilled:
log.info(
"Backfilled %d externally-followed accounts with current timestamp "
"(they become eligible for unfollow after %dh if no follow-back)",
backfilled, UNFOLLOW_HRS,
)
# 2. Unfollow non-reciprocators (skipped in follow-only mode)
follow_only = os.environ.get("FOLLOW_ONLY", "false").lower() == "true"
if not follow_only:
do_unfollows(state, my_followers)
# 2b. Unfollow existing follows that fail quality criteria (opt-in)
if not follow_only and QUALITY_UNFOLLOW and not stop_event.is_set():
log.info("Quality-unfollow pass enabled (QUALITY_UNFOLLOW=true)")
do_quality_unfollows(state, my_following)
# 3. Follow new candidates
if not stop_event.is_set():
do_follows(state, my_following, my_followers)
# 4. Persist
save_state(state)
stats = state["stats"]
log.info("=== Done | total_followed=%d unfollowed=%d mutual=%d ===",
stats["followed"], stats["unfollowed"], stats["mutual"])
def _safe_fromisoformat(s: str) -> datetime:
"""Parse ISO datetime string, returning epoch on any failure."""
try:
return datetime.fromisoformat(s)
except (ValueError, TypeError):
return datetime.min.replace(tzinfo=timezone.utc)
if __name__ == "__main__":
main()