GitHub Python API - PyGithub

PyGithub是GitHub API的Python版,玩了一下,还是蛮有趣的。最初是在chromium-source-tarball项目中一个Python脚本里发现的,竟然能通过Python操作GitHub,再一次证明Python太强大了,TM简直啥都能做。

有个小怪僻,GitHub里Follow我的人,我也Follow回敬一下,礼尚往来嘛,至于后来又取消Follow我的,那我也不再Follow了。当只有几个人时,感觉还能分得清,现在20多个,如果有一个我Follow了他,但后来他取消了对我的Follow,我想找出这个人,然后也取消对他的Follow,貌似不太容易了。正好,用PyGithub来自动化处理吧。

安装PyGithub:

1
pip install pygithub

以下是完整的脚本:

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
#!/usr/bin/env python
# coding: utf-8
# GitHub
# Follow我的, Follow之
# 未Follow我的,从Following中删除之
# 即同步互Follow关系
import getpass
from github import Github
# 始终Follow的大神或朋友
ALWAYS_FOLLOW = [
'torvalds',
'jiangdon2007',
'michaelliao',
'zcbenz',
'ruanyf',
]
def sync():
username = raw_input('Username:')
password = getpass.getpass()
print 'Please wait...'
g = Github(username, password)
me = g.get_user()
followers = me.get_followers()
following = me.get_following()
followers_names = [x.login for x in followers]
following_names = [x.login for x in following]
all_is_ok = True
for user in following_names:
is_my_follower = user in followers_names
in_always_list = user in ALWAYS_FOLLOW
if (not is_my_follower) and (not in_always_list):
me.remove_from_following(g.get_user(user))
print 'User \'%s\' has been removed from following list!' % user
all_is_ok = False
for user in followers_names:
if user not in following_names:
me.add_to_following(g.get_user(user))
print 'New user \'%s\' has been followed!' % user
all_is_ok = False
if all_is_ok:
print 'All is OK!'
if __name__ == "__main__":
sync()

还可以再完善一下,比如还没有加上异常处理。