-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
1661 lines (1488 loc) · 44.9 KB
/
main.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
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import hashlib
import json
import logging
import os
import random
import re
import sys
import time
from multiprocessing.dummy import Pool
from threading import Lock, Thread
import requests
from bs4 import BeautifulSoup
from config import Config
lock = Lock()
pool = Pool(100)
is_frequent = False
is_too_many_weibo = False
writable = True
is_finish = False
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'}
cf = Config('config.ini', '配置')
def create_weibo(text, cid):
"""
创建微博
:param text: 内容
:param cid: 超话id
:return:
"""
def retry():
for info in get_weibo_info(gsid):
t = info['t']
mid = info['mid']
title = info['title']
if title == weibo_title and t > time.time() - get_time_after_zero() or abs(
t - get_close_zero_time()) < 600:
add_config(mid)
return mid
else:
print('创建微博失败,正在重试')
time.sleep(1)
mid = create_weibo(text, cid)
return mid
h = {'Referer': 'https://weibo.com'}
h.update(headers)
cookies = {'SUB': gsid}
data = {
'text': text, 'sync_wb': '1',
'api': f'http://i.huati.weibo.com/pcpage/operation/publisher/sendcontent?sign=super&page_id={cid}',
'topic_id': f'1022:{cid}'}
url = 'https://weibo.com/p/aj/proxy?ajwvr=6'
r = requests.post(url, data=data, cookies=cookies, headers=h)
try:
logging.info(str(r.status_code) + ':' + str(r.json()))
except:
logging.warning(str(r.status_code) + ':' + r.text)
return retry()
code = r.json()['code']
if code == 100000:
mid = r.json()['data']['mid']
add_config(mid)
return mid
elif code == 100001:
return False
elif code == 20019:
return retry()
# Redis连接异常
elif code == 200124:
return retry()
else:
print(r.json()['msg'])
return retry()
def retry(n, t):
"""
重试装饰器
:param n: 重试次数
:param t: 重试时间
:return:
"""
def wrapper(f):
def retry_thread(*args, **kwargs):
for i in range(n):
if run(*args, **kwargs):
break
time.sleep(t)
def run(*args, **kwargs):
try:
with unwritable():
r = f(*args, **kwargs)
except:
r = False
logging.warning(str(sys.exc_info()))
if r != False:
return True
def wrapped(*args, **kwargs):
if not run(*args, **kwargs):
Thread(target=lambda: retry_thread(*args, **kwargs)).start()
return wrapped
return wrapper
def add_config(mid):
cf.Add('配置', 'mid', mid)
cf.Add('配置', 'time', str(time.time()))
def comment(args):
"""
评论微博
:param args:
:return:
"""
global com_suc_num
global com_err_num
global is_frequent
global is_too_many_weibo
mid, content = args
detail_url = 'https://m.weibo.cn/detail/' + mid
if get_mid_num() >= comment_max:
with lock:
print(f'你已经评论{comment_max}条了')
exit()
if mid_in_file(mid):
with lock:
print('你已经评论:' + detail_url)
return
cookies = {'SUB': gsid}
wait_time = 0.5
while True:
try:
if wait_time >= 8:
is_frequent = True
com_err_num += 1
return False
r = requests.get(detail_url, cookies=cookies, headers=headers)
logging.info(str(r.status_code))
if r.status_code == 200:
break
elif r.status_code == 418:
time.sleep(wait_time)
elif r.status_code == 403:
with lock:
print('评论失败:' + detail_url)
return False
wait_time *= 2
except:
pass
st = r.cookies.get_dict()['XSRF-TOKEN']
cookies.update(r.cookies.get_dict())
url = 'https://m.weibo.cn/api/comments/create'
data = {'content': content, 'mid': mid, 'st': st}
while True:
try:
r = requests.post(url, data=data, cookies=cookies, headers=headers, timeout=1)
try:
logging.info(str(r.status_code) + ':' + mid + ':' + str(r.json()))
except:
logging.warning(str(r.status_code) + ':' + mid)
break
except:
pass
try:
if r.json()['ok'] == 1:
with lock:
print('评论成功:' + detail_url)
if mid != my_mid:
mid_write_file(mid)
com_suc_num += 1
return True
else:
with lock:
print('评论失败:' + detail_url)
com_err_num += 1
if r.json()['ok'] == 0:
print(r.json()['msg'])
errno = r.json()['errno']
# 频繁
if errno == '100005':
is_frequent = True
# 已经评论
elif errno == '20019':
mid_write_file(mid)
# 只允许粉丝评论
elif errno == '20210':
mid_error_write_file(mid)
# 只允许关注用户评论
elif errno == '20206':
mid_error_write_file(mid)
# 发微博太多
elif errno == '20016':
is_too_many_weibo = True
# 异常
elif errno == '200002':
exit()
# 服务器走丢了
elif errno == '100001':
mid_error_write_file(mid)
# 在黑名单中,无法进行评论
elif errno == '20205':
mid_error_write_file(mid)
# 微博不存在或暂无查看权限
elif errno == '20101':
mid_error_write_file(mid)
# 由于作者隐私设置,你没有权限评论此微博
elif errno == '20130':
mid_error_write_file(mid)
return False
except SystemExit:
# 退出进程
push_wechat('weibo_comments', f'''{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}
{errno}:{r.json()['msg']}''')
os._exit(int(errno))
except:
with lock:
print('评论失败:' + detail_url)
if r.json()['errno'] == '100005':
is_frequent = True
com_err_num += 1
return False
def edit_weibo(mid, content):
"""
修改微博
:param mid:
:param content:
:return:
"""
global at_file
print('正在修改微博')
cookies = {'SUB': gsid}
url = f'https://m.weibo.cn/detail/{mid}'
r = requests.get(url, cookies=cookies, headers=headers)
logging.info(str(r.status_code))
st = r.cookies.get_dict()['XSRF-TOKEN']
cookies.update(r.cookies.get_dict())
url = f'https://m.weibo.cn/api/statuses/update'
data = {'content': content, 'editId': mid, 'st': st}
h = {'Referer': 'https://m.weibo.cn'}
h.update(headers)
r = requests.post(url, data=data, cookies=cookies, headers=h)
logging.info(str(r.status_code))
if r.json()['ok'] == 1:
print('修改微博成功')
else:
print(r.json()['msg'])
at_file = False
def random_repost_weibo(n=2):
"""
随机转发微博
:param n: 转发数量
:return:
"""
while n > 0:
mid_list = get_mid_list()
if len(mid_list) >= n:
for mid in random.sample(mid_list, n):
new_mid = repost_weibo(mid, '转发微博')
if not new_mid:
continue
else:
n -= 1
if repost_and_del:
del_weibo(new_mid)
time.sleep(0.5)
@retry(3, 10)
def repost_specified_weibo(mid):
"""
转发指定微博
:return:
"""
new_mid = repost_weibo(mid, repost_weibo_dict[mid])
if not new_mid:
return False
if repost_and_del:
del_weibo(new_mid)
def repost_weibo(mid, content):
"""
转发微博
:param mid:
:param content:
:return:
"""
url = 'https://m.weibo.cn/compose/repost'
cookies = {'SUB': gsid}
r = requests.get(url, cookies=cookies, headers=headers)
logging.info(str(r.status_code))
st = r.cookies.get_dict()['XSRF-TOKEN']
cookies.update(r.cookies.get_dict())
data = {'content': content, 'mid': mid, 'st': st}
h = {'Referer': 'https://m.weibo.cn'}
h.update(headers)
url = 'https://m.weibo.cn/api/statuses/repost'
r = requests.post(url, headers=h, data=data, cookies=cookies)
logging.info(str(r.status_code))
if r.json()['ok'] == 1:
new_mid = r.json()['data']['mid']
with unwritable():
print(f'转发成功:https://m.weibo.cn/detail/{mid}')
print(f'新微博:https://m.weibo.cn/detail/{new_mid}')
return new_mid
else:
with unwritable():
print(r.json()['msg'])
return False
def del_weibo(mid):
"""
删除微博
:param mid:
:return:
"""
url = 'https://m.weibo.cn'
cookies = {'SUB': gsid}
r = requests.get(url, cookies=cookies, headers=headers)
st = r.cookies.get_dict()['XSRF-TOKEN']
cookies.update(r.cookies.get_dict())
data = {'mid': mid, 'st': st}
h = {'Referer': 'https://m.weibo.cn'}
h.update(headers)
url = 'https://m.weibo.cn/profile/delMyblog'
r = requests.post(url, headers=h, data=data, cookies=cookies)
with unwritable():
print(r.json()['msg'])
if r.json()['ok'] == 1:
return True
else:
return False
def after_zero(t):
"""
判断是否是当天零点后发布的
:param t:
:return:
"""
if type(t) is str:
if t == '刚刚':
return True
elif re.match('^(\d{1,2})分钟前$', t):
if int(t[:-3]) * 60 < int(time.time() - time.timezone) % 86400:
return True
elif re.match('^(\d{1,2})小时前$', t):
if int(t[:-3]) * 3600 < int(time.time() - time.timezone) % 86400:
return True
return False
else:
if t >= int(time.time()) - int(time.time() - time.timezone) % 86400:
return True
return False
def write_file(file_name, text):
"""
写入文件
:param file_name:
:param text:
:return:
"""
open(file_name, 'a').close()
with open(file_name, 'r') as f:
if text not in f.read():
with open(file_name, 'a') as f1:
f1.write(text + '\n')
def mid_write_file(mid):
"""
记录已经评论的mid
:param mid:
:return:
"""
write_file('mid.txt', mid)
def mid_error_write_file(mid):
"""
记录评论失败的mid
:param mid:
:return:
"""
write_file('mid_error.txt', mid)
def at_write_file(name):
"""
记录已经at的name
:param name:
:return:
"""
write_file('at.txt', name)
def in_file(file_name, text):
"""
判断文本是否在文件里
:param file_name:
:param text:
:return:
"""
open(file_name, 'a').close()
with open(file_name, 'r') as f:
return text in f.read()
def mid_in_file(mid):
"""
判断mid是否已经评论
:param mid:
:return:
"""
return in_file('mid.txt', mid)
def mid_error_in_file(mid):
"""
是否是评论失败的mid
:param mid:
:return:
"""
return in_file('mid_error.txt', mid)
def following_in_file(uid):
"""
用户是否在关注列表里
:param uid:
:return:
"""
return in_file('following.txt', uid)
def fans_in_file(uid):
"""
用户是否在粉丝列表里
:param uid:
:return:
"""
return in_file('fans.txt', uid)
def at_in_file(at):
"""
用户是否在粉丝列表里
:param uid:
:return:
"""
return in_file('at.txt', at)
def clear_mid_file():
"""
清除mid文件
:return:
"""
open('mid.txt', 'w').close()
def clear_mid_error_file():
"""
清除mid_error文件
:return:
"""
open('mid_error.txt', 'w').close()
def clear_at_file():
"""
清除at文件
:return:
"""
open('at.txt', 'w').close()
def clear_log():
"""
清除log文件
:return:
"""
open('weibo.log', 'w').close()
def clear_mid_json():
"""
清除mid.json文件
:return:
"""
open('mid.json', 'w').close()
def get_file_num(file_name):
"""
获取文件中字符串的数量
:return:
"""
count = 0
open(file_name, 'a').close()
with open(file_name, 'r') as f:
for i in f.read().split('\n'):
if i != '':
count += 1
return count
def get_mid_num():
"""
获取已经评论的mid的数量
:return:
"""
return get_file_num('mid.txt')
def get_mid_error_num():
"""
获取无法评论数的mid的数量
:return:
"""
return get_file_num('mid_error.txt')
def get_at_list():
"""
获取at列表
:return:
"""
open('at.txt', 'a').close()
with open('at.txt', 'r') as f:
text = f.read()
return ['@' + i for i in text.split('\n') if i != '']
def get_weibo_info(gsid):
"""
获取已发微博的信息
:param gsid:
:return:
"""
cookies = {'SUB': gsid}
uid = get_uid(gsid)
url = f'https://m.weibo.cn/profile/info?uid={uid}'
r = requests.get(url, cookies=cookies, headers=headers)
try:
logging.info(str(r.status_code) + ':' + str(r.json()))
except:
logging.warning(str(r.status_code) + ':' + r.text)
info = []
for i, j in enumerate(r.json()['data']['statuses']):
try:
t = j['created_at']
t = time.mktime(time.strptime(' '.join(t.split()[:4] + t.split()[-1:]), '%c'))
mid = r.json()['data']['statuses'][i]['mid']
except:
continue
try:
title = r.json()['data']['statuses'][i]['raw_text'][:-2]
except:
title = r.json()['data']['statuses'][i]['text']
info.append({'t': t, 'mid': mid, 'title': title})
info.sort(key=lambda keys: keys['t'], reverse=True)
return info
def get_my_name():
"""
获取自己的名字
:return:
"""
name = cf.GetStr('配置', 'name')
if name != '':
return name
url = f'https://m.weibo.cn/profile/info?uid={uid}'
r = requests.get(url, headers=headers)
try:
logging.info(str(r.status_code) + ':' + str(r.json()))
except:
logging.warning(str(r.status_code))
name = r.json()['data']['user']['screen_name']
cf.Add('配置', 'name', name)
return name
def wait_time(n, text='等待时间'):
"""
等待n秒
:param n:
:return:
"""
while n + 1:
time.sleep(1)
with lock:
w_gen.send({text: n})
n -= 1
with lock:
w_gen.send({text: None})
def get_follow():
"""
获取粉丝和关注列表
:return:
"""
def get_following_list():
"""
获取关注列表
:return:
"""
following_list = []
page = 1
cookies = {'SUB': gsid}
while True:
url = f'https://m.weibo.cn/api/container/getIndex?containerid=231093_-_selffollowed&page={page}'
while True:
try:
r = requests.get(url, cookies=cookies, headers=headers)
if r.status_code == 418:
raise
r.json()
break
except:
wait_time(120)
if r.json()['ok'] == 0:
break
card_page = 0
if len(r.json()['data']['cards']) == 2:
card_page = 1
for i in r.json()['data']['cards'][card_page]['card_group']:
screen_name = i['user']['screen_name']
uid = i['user']['id']
print(screen_name, uid)
following_list.append(str(uid))
print(len(following_list))
page += 1
return following_list
def get_fans_list():
"""
获取粉丝列表
:return:
"""
fans_list = []
cookies = {'SUB': gsid}
since_id = ''
while True:
url = f'https://m.weibo.cn/api/container/getIndex?containerid=231016_-_selffans&since_id={since_id}'
r = requests.get(url, cookies=cookies, headers=headers)
if r.status_code == 418:
wait_time(60)
if r.json()['ok'] == 0:
break
card_page = 0
if len(r.json()['data']['cards']) == 2:
card_page = 1
for i in r.json()['data']['cards'][card_page]['card_group']:
screen_name = i['user']['screen_name']
uid = i['user']['id']
print(screen_name, uid)
fans_list.append(str(uid))
print(len(fans_list))
if 'since_id' not in r.json()['data']['cardlistInfo']:
break
since_id = r.json()['data']['cardlistInfo']['since_id']
return fans_list
if comment_following:
try:
open('following.txt', 'r').close()
except:
print('正在爬取关注列表')
with open('fans.txt', 'w') as f:
f.write('\n'.join(get_following_list()))
if comment_follow_me:
try:
open('fans.txt', 'r').close()
except:
print('正在爬取粉丝列表')
with open('fans.txt', 'w') as f:
f.write('\n'.join(get_fans_list()))
def at_weibo_gen():
"""
at生成器
:return:
"""
while True:
name = yield
if not at_in_file(name):
at_write_file(name)
at_list = get_at_list()
if len(at_list) and len(at_list) % 50 == 0:
content = weibo_title + ' ' + ' '.join(at_list)
if at_edit_weibo:
edit_weibo(my_mid, content)
at_gen = at_weibo_gen()
next(at_gen)
def write_gen():
"""
生成器并行输出
:return:
"""
l = {}
while True:
d = yield
if type(d) is dict:
l[list(d)[0]] = d[list(d)[0]]
s = '\r' + ','.join([str(i) + ':' + str(l[i]) for i in l if l[i] != None])
if writable:
sys.stdout.write(s + ' ' * 32)
sys.stdout.flush()
w_gen = write_gen()
next(w_gen)
def get_mid(cid):
"""
获取微博
:param cid: 超话id
:param page: 页数
:return: 微博列表
"""
global is_frequent
def mid_in_file(mid):
return len([i for i in read_mid() if 'mid' in i.keys() and mid == i['mid']]) == 1
def analysis_and_join_list(mblog):
global is_finish
time_state = mblog['created_at']
try:
t = mblog['latest_update']
t = time.mktime(time.strptime(' '.join(t.split()[:4] + t.split()[-1:]), '%c'))
except:
t = time_state
mid = mblog['mid']
text = mblog['text']
user_id = str(mblog['user']['id'])
screen_name = mblog['user']['screen_name']
if not after_zero(t):
is_finish = True
return
if is_finish and mid_in_file(mid):
return
write_mid({'mid': mid, 'user_id': user_id, 'text': text, 'screen_name': screen_name})
return True
since_id = ''
i = 1
while True:
with lock:
w_gen.send({'正在爬取页数': i})
url = f'https://m.weibo.cn/api/container/getIndex?containerid={cid}_-_sort_time' + since_id
wait_time = 0.5
while True:
try:
if wait_time >= 8:
is_frequent = True
r = requests.get(url, headers=headers)
logging.info(str(r.status_code))
if r.status_code == 200 and r.json()['ok'] == 1:
break
# 反爬
elif r.status_code == 418:
time.sleep(wait_time)
elif r.status_code == 502:
time.sleep(0.5)
wait_time *= 2
except:
pass
card_page = 0
try:
for cards in r.json()['data']['cards']:
if 'card_group' in cards:
for card in cards['card_group']:
if card['card_type'] == '9':
mblog = card['mblog']
if analysis_and_join_list(mblog) is None:
with lock:
w_gen.send({'正在爬取页数': None})
return
since_id = '&since_id=' + str(r.json()['data']['pageInfo']['since_id'])
except:
pass
with lock:
w_gen.send({'等待评论数': len(get_mid_list())})
i += 1
def loop_get_mid(cid):
"""
循环爬取mid
:param cid:
:return:
"""
while True:
with lock:
w_gen.send({'等待评论数': len(get_mid_list())})
t = gen.send(get_weibo_time)
wait_time(t, '获取微博等待时间')
get_mid(cid)
def write_mid(mid_dict: dict):
"""
把mid写入文件
:param mid_dict:
:return:
"""
open('mid.json', 'a').close()
with open('mid.json', 'r') as f1:
try:
l = [dict(t) for t in set([tuple(d.items()) for d in json.loads(f1.read())])]
except:
l = []
with open('mid.json', 'w+') as f:
if mid_dict not in l:
l.append(mid_dict)
f.write(json.dumps(l, indent=2))
def read_mid():
"""
读取mid列表文件
:return:
"""
open('mid.json', 'a').close()
with open('mid.json', 'r') as f1:
try:
l = json.loads(f1.read())
except:
l = []
return l
def get_mid_list():
"""
获取未评论的mid列表
:return:
"""
mid_list = []
for mid_dict in read_mid():
comments = True
screen_name = mid_dict['screen_name']
text = mid_dict['text']
user_id = mid_dict['user_id']
mid = mid_dict['mid']
if at_file:
at_gen.send(screen_name)
if at_comment and '@' + my_name in text:
pass
else:
if comment_following and not following_in_file(user_id):
comments = False
if comment_follow_me and not fans_in_file(user_id):
comments = False
if comments and mid != my_mid and not mid_in_file(mid) and not mid_error_in_file(mid) and user_id != uid:
mid_list.append((mid, user_id, text, screen_name))
return mid_list
def get_my_mid():
"""
获取配置中自己的微博
:return:
"""
mid = cf.GetStr('配置', 'mid')
if mid == '':
info_list = get_weibo_info(gsid)
if not info_list:
return False
for info in info_list:
mid = info['mid']
title = info['title']
if title == weibo_title:
cf.Add('配置', 'mid', mid)
return mid
return False
return mid
def get_gsid():
"""
获取gsid
:return:
"""
gsid = cf.GetStr('配置', 'gsid')
if gsid == '':
print('请前往"https://m.weibo.cn"获取gsid')
gsid = input('请输入你的gsid:')
cf.Add('配置', 'gsid', gsid)
return gsid
def is_today(t=None):
"""
获取配置中的信息的时间
:return: bool
"""
if t is None:
t = cf.GetFloat('配置', 'time')
zero_time = int(time.time()) - int(time.time() - time.timezone) % 86400
if t != None and t >= zero_time:
return True
else:
return False
def get_time_after_zero():
"""
获取零点后的秒数
:return:
"""
return int(time.time() - time.timezone) % 86400
def wait_zero():
"""
等待零点
:return:
"""
while True:
t = get_time_after_zero()
if t == 0:
with lock:
w_gen.send({'距离零点': None})
break
with lock:
w_gen.send({'距离零点': f'{86400 - t}s'})
time.sleep(0.1)
def get_uid(gsid, config=False):
"""
获取用户的id
:param gsid:
:return:
"""
global is_frequent
if config:
uid = cf.GetStr('配置', 'uid')
if uid != '':
return uid
cookies = {'SUB': gsid}
url = 'https://m.weibo.cn/api/config'
while True:
try:
r = requests.get(url, cookies=cookies, headers=headers)
except requests.exceptions.SSLError:
time.sleep(1)
continue
try:
logging.info(str(r.status_code) + ':' + str(r.json()))
except:
logging.warning(str(r.status_code))
if r.status_code == 200:
break
elif r.status_code == 502:
time.sleep(0.5)
elif r.status_code == 418:
is_frequent = True
return
elif r.status_code == 403:
is_frequent = True
return
try:
uid = r.json()['data']['uid']
if not cf.GetStr('配置', uid):
cf.Add('配置', 'uid', uid)
return uid
except:
if not r.json()['data']['login']:
print('请重新登录')