-
Notifications
You must be signed in to change notification settings - Fork 2
/
syclover_auto_weibo.py
193 lines (166 loc) · 6.11 KB
/
syclover_auto_weibo.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
# !/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
import os
import time
import requests
import logging
import threading
from collections import OrderedDict
BASE_DIR = os.path.realpath(os.path.dirname(__file__))
SESSION = requests.session()
SESSION.mount('https://', requests.adapters.HTTPAdapter(max_retries=3))
LOG_FORMAT = '<%(levelname)s> %(asctime)s: %(message)s'
logging.basicConfig(filename=os.path.join(BASE_DIR, '.syclover-auto-weibo.log'),
level=logging.INFO,
format=LOG_FORMAT)
APP_KEY = os.getenv('APP_KEY')
APP_SECRET = os.getenv('APP_SECRET')
REDIRECT_URI = os.getenv('REDIRECT_URI')
ACCOUNT = os.getenv('ACCOUNT')
PASSWORD = os.getenv('PASSWORD')
REPOST_URL = 'https://api.weibo.com/2/statuses/repost.json'
REPOST_PHRASE = '转一个'
with open(os.path.join(BASE_DIR, 'syclovers')) as f:
SYCLOVERS = [uid.strip() for uid in f]
def is_syclover(uid):
return str(uid) in SYCLOVERS
def load_reposted_id(id_type):
if id_type == 'atme_since_id':
with open(os.path.join(BASE_DIR, '.atme_since_id')) as f:
return int(f.read().decode('utf-8') or 0)
elif id_type == 'comment_since_id':
with open(os.path.join(BASE_DIR, '.comment_since_id')) as f:
return int(f.read().decode('utf-8') or 0)
def save_reposted_id(id_type, since_id):
if id_type == 'atme_since_id':
with open(os.path.join(BASE_DIR, '.atme_since_id'), 'w') as f:
f.write(str(since_id).encode('utf-8'))
elif id_type == 'comment_since_id':
with open(os.path.join(BASE_DIR, '.comment_since_id'), 'w') as f:
f.write(str(since_id).encode('utf-8'))
def auth():
url = "https://api.weibo.com/oauth2/authorize"
auth_url = "%s?client_id=%s&redirect_uri=%s" % (url, APP_KEY, REDIRECT_URI)
post_data = {
'client_id': APP_KEY,
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
'action': 'submit',
'userId': ACCOUNT,
'passwd': PASSWORD,
'isLoginSina': 0,
'from': '',
'regCallback': '',
'state': '',
'ticket': '',
'withOfficalFlag': 0
}
headers = {
'Referer': auth_url,
'Content-Type': 'application/x-www-form-urlencoded'
}
r = SESSION.post(url, data=post_data, headers=headers)
code = r.url.split('=')[1]
return code
def get_token():
code = auth()
url = "https://api.weibo.com/oauth2/access_token"
post_data = {
'client_id': APP_KEY,
'client_secret': APP_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
}
r = SESSION.post(url, data=post_data)
data = r.json()
return data
def repost(params):
resp = SESSION.post(REPOST_URL, data=params)
try:
resp.raise_for_status()
except Exception as e:
logging.debug(str(e))
def check_atme(delay=3):
statuses_mentions_url = 'https://api.weibo.com/2/statuses/mentions.json'
data = get_token()
access_token = data['access_token']
since_id = load_reposted_id('atme_since_id')
logging.info('[@ in status] since_id: %s' % since_id)
params = {
'source': APP_KEY,
'access_token': access_token,
'since_id': since_id
}
r = SESSION.get(statuses_mentions_url, params=params)
statuses = r.json()['statuses']
if statuses:
for status in statuses:
if not is_syclover(status['user']['id']):
continue
if REPOST_PHRASE not in status['text']:
continue
repost_text = status['text'].split('//@', 1)
if len(repost_text) == 2 and REPOST_PHRASE in repost_text[1]:
continue
params = {
'source': APP_KEY,
'access_token': access_token,
'is_comment': 3,
'id': status['id'],
'status': REPOST_PHRASE
}
logging.info('[REPOST] @ in status, status_id: %s, uid: %s' %
(status['id'], status['user']['id']))
time.sleep(delay)
threading.Thread(target=repost, args=(params,)).start()
save_reposted_id('atme_since_id', statuses[0]['id'])
logging.info('[@ in status] new_since_id: %s' % statuses[0]['id'])
def check_comment(delay=3):
comments_to_me_url = 'https://api.weibo.com/2/comments/to_me.json'
since_id = load_reposted_id('comment_since_id')
logging.info('[@ in comment] since_id:%s' % since_id)
data = get_token()
params = {
'source': APP_KEY,
'access_token': data['access_token'],
'since_id': since_id
}
r = SESSION.get(comments_to_me_url, params=params)
comments = r.json()['comments']
if not comments:
comments_mentions_url = 'https://api.weibo.com/2/comments/mentions.json'
r = SESSION.get(comments_mentions_url, params=params)
comments = r.json()['comments']
results = OrderedDict()
for a_comment in comments:
results[a_comment['id']] = {
'text': a_comment['text'],
'wid': a_comment['status']['id'],
'weibo': a_comment['status']['text'],
'uid': a_comment['user']['id'],
}
if results:
for _, value_dict in results.iteritems():
if not is_syclover(value_dict['uid']):
continue
if REPOST_PHRASE not in value_dict['text']:
continue
params = {
'source': APP_KEY,
'access_token': data['access_token'],
'id': value_dict['wid'],
'is_comment': 3,
'status': REPOST_PHRASE
}
time.sleep(delay)
threading.Thread(target=repost, args=(params,)).start()
logging.info('[REPOST] @ in comment, status_id: %s, uid: %s' %
(value_dict['wid'], value_dict['uid']))
save_reposted_id('comment_since_id', results.keys()[0])
logging.info('[@ in comment] new_since_id: %s' % results.keys()[0])
if __name__ == '__main__':
check_atme()
check_comment()
logging.info('=' * 48)