-
Notifications
You must be signed in to change notification settings - Fork 1
/
bilibili.py
415 lines (350 loc) · 14.5 KB
/
bilibili.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
# python lib
import asyncio
import aiohttp
from typing import Optional
# custom lib
from account import Account
from printer import cprint
from ratelimiter import RateLimiter
from exceptions import HttpError
class Bilibili:
instance = None
client: Optional[aiohttp.ClientSession] = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Bilibili, cls).__new__(cls, *args, **kwargs)
inst = cls.instance
inst.banned = False
inst._session = cls.client
inst._session_l = RateLimiter(cls.client) \
if cls.client is not None \
else None
inst.web_headers = {
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/77.0.3865.90 Safari/537.36'),
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
}
return cls.instance
@property
def session(self):
return self._session
@property
def rl_session(self):
return self._session_l
async def get(self, url, params=None, headers=None, cookies=None, rate_limited: bool = True):
if rate_limited == True:
session = self.rl_session
else:
session = self.session
err = None
for _ in range(3):
try:
response = await session.get(
url, params=params,
headers=headers, cookies=cookies, ssl=False)
response.raise_for_status()
r_json = await response.json(content_type=None)
if 0 == r_json['code']:
return r_json
else:
cprint(f'{r_json}', error=True)
return None
except aiohttp.ClientError as exc:
err = exc
cprint(f'aiohttp ClientError: {exc}', color='red')
if err:
raise HttpError(f'Request failed: {err} @url {url!r}')
async def post(self, url, params=None, headers=None, cookies=None, data=None, rate_limited: bool = True):
if rate_limited == True:
session = self.rl_session
else:
session = self.session
err = None
for _ in range(3):
# fire request
try:
response = await session.post(
url, params=params, headers=headers,
cookies=cookies, data=data, ssl=False)
response.raise_for_status()
r_json = await response.json(content_type=None)
return r_json
except aiohttp.ClientError as exc:
err = exc
cprint(f'aiohttp ClientError: {exc}', color='red')
if err:
raise HttpError(f'Request failed: {err} @url {url!r}')
async def request_area_list(self):
url = 'https://api.live.bilibili.com/room/v1/Area/getList'
headers = self.web_headers.copy()
response = await self.get(url, headers=headers)
return response
async def request_gift_config(self):
url = 'https://api.live.bilibili.com/gift/v4/Live/giftConfig'
headers = self.web_headers.copy()
response = await self.get(url, headers=headers)
return response
async def request_check_live_status(self, roomid:int):
response = await self.request_check_live_info(roomid)
if response is None:
return
if response['code'] == 0:
return response['data']['live_status']
async def request_check_live_info(self, roomid:int):
url = 'https://api.live.bilibili.com/room/v1/Room/get_info'
headers = self.web_headers.copy()
params = {
'room_id': roomid,
}
response = await self.get(url, headers=headers, params=params)
return response
async def request_check_area(self,
areaid:int,
page:int = 1,
page_size:int = 99):
'''
Get a list of rooms in area ``areaid``
'''
url = 'https://api.live.bilibili.com/room/v3/area/getRoomList'
params = {
'parent_area_id': areaid,
'page': page,
'page_size': page_size,
}
headers = self.web_headers.copy()
response = await self.get(url, headers=headers, params=params)
return response
async def request_check_room(self,
roomid:int,
rate_limited: bool = False,
account: Optional[Account] = None):
'''
Check for lottery in room ``roomid``
'''
url = 'https://api.live.bilibili.com/xlive/lottery-interface/v1/lottery/Check'
params = { 'roomid': roomid }
headers = self.web_headers.copy()
cookies = account.web_cookies.copy() if account is not None else None
response = await self.get(url,
headers=headers,
params=params,
rate_limited=rate_limited,
cookies=cookies)
return response
async def request_live_count(self):
url = 'https://api.live.bilibili.com/room/v1/Area/getLiveRoomCountByAreaID'
params = { 'areaId': 0 }
headers = self.web_headers.copy()
response = await self.get(url, params=params, headers=headers)
return response
async def request_live_recommendation(self, page:int, page_size:int=30):
url = 'https://api.live.bilibili.com/room/v1/room/get_user_recommend'
page_size = 100 if page_size > 100 else page_size
params = { 'page': page , 'page_size': page_size }
headers = self.web_headers.copy()
response = await self.get(url, params=params, headers=headers)
return response
async def post_join_raffle(self,
post_data: dict,
account: Optional[Account] = None):
if account is None or account.banned:
return
url = 'https://api.live.bilibili.com/xlive/lottery-interface/v5/smalltv/join'
headers = self.web_headers.copy()
cookies = account.web_cookies.copy()
for _ in range(3):
response = await self.rl_session.post(
url, headers=headers,
cookies=cookies, data=post_data)
try:
response.raise_for_status()
js = await response.json()
if 0 == js['code']:
return js
elif '访问被拒绝' in js.get('message'):
account.banned = True
account.cprint(f'访问被拒绝', color='purple')
return None
else:
cprint(f'{js}', color='red')
return js
except (aiohttp.ClientPayloadError,
aiohttp.ClientResponseError) as exc:
cprint(f'aiohttp ClientError: {exc}', color='red')
async def post_join_guard(self,
post_data: dict,
account: Optional[Account] = None):
if account is None or account.banned:
return
url = 'https://api.live.bilibili.com/xlive/lottery-interface/v3/guard/join'
headers = self.web_headers.copy()
cookies = account.web_cookies.copy()
for _ in range(3):
response = await self.rl_session.post(
url, headers=headers,
cookies=cookies, data=post_data)
try:
response.raise_for_status()
js = await response.json()
if 0 == js['code']:
return js
elif '访问被拒绝' == js.get('message'):
account.banned = True
account.cprint(f'访问被拒绝', color='purple')
return None
else:
return None
except (aiohttp.ClientPayloadError,
aiohttp.ClientResponseError) as exc:
cprint(f'aiohttp ClientError: {exc}', color='red')
async def post_join_pk(self,
post_data: dict,
account: Optional[Account] = None):
if account is None or account.banned:
return
url = 'https://api.live.bilibili.com/xlive/lottery-interface/v2/pk/join'
headers = self.web_headers.copy()
cookies = account.web_cookies.copy()
for _ in range(3):
response = await self.rl_session.post(
url, headers=headers,
cookies=cookies, data=post_data)
try:
response.raise_for_status()
js = await response.json()
if 0 == js['code']:
return js
elif '访问被拒绝' == js.get('message'):
account.banned = True
account.cprint(f'访问被拒绝', color='purple')
return None
elif '领取过' in js.get('message'):
account.cprint(f'已领取', color='purple')
return None
else:
return None
except (aiohttp.ClientPayloadError,
aiohttp.ClientResponseError) as exc:
cprint(f'aiohttp ClientError: {exc}', color='red')
# {"code":0,"msg":"ok","message":"ok","data":[]}
async def post_room_entry(self,
roomid: int,
account: Optional[Account] = None):
if account is None:
return
url = 'https://api.live.bilibili.com/room/v1/Room/room_entry_action'
headers = self.web_headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
cookies = account.web_cookies.copy()
data = {
'room_id': roomid,
'platform': 'pc',
'csrf_token': cookies['bili_jct'],
'csrf': cookies['bili_jct'],
'visit_id': '',
}
response = await self.post(
url, data=data, headers=headers, cookies=cookies)
return response
async def post_open_club_award(self,
item_id: str,
account: Account):
if account is None or item_id not in [ str(i) for i in range(1, 1+6) ]:
return
url = 'https://api.live.bilibili.com/activity/v1/UnionFans/openPrivilege'
headers = self.web_headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
cookies = account.web_cookies.copy()
data = {
'id': item_id,
'csrf_token': cookies['bili_jct'],
'csrf': cookies['bili_jct'],
}
response = await self.post(
url, data=data, headers=headers, cookies=cookies)
return response
async def request_club_award(self, account: Account):
'''
"code": 0,
"data": {
"money_num": "60672765",
"list": {
"1": 1, // 1 (未) 2 (已)
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1
}
}
'''
if account is None:
return
url = 'https://api.live.bilibili.com/activity/v1/UnionFans/getPrivilege'
headers = self.web_headers.copy()
cookies = account.web_cookies.copy()
response = await self.get(
url, headers=headers, cookies=cookies)
return response
async def request_task_info(self, account: Account):
if account is None:
return
url = 'https://api.live.bilibili.com/i/api/taskInfo'
headers = self.web_headers.copy()
cookies = account.web_cookies.copy()
response = await self.get(
url, headers=headers, cookies=cookies)
return response
async def post_checkin(self, account: Account):
if account is None:
return
url = 'https://api.live.bilibili.com/sign/doSign'
headers = self.web_headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
cookies = account.web_cookies.copy()
response = await self.get(
url, headers=headers, cookies=cookies)
return response
async def post_obtain_double_award(self, account: Account):
if account is None:
return
url = 'https://api.live.bilibili.com/activity/v1/task/receive_award'
headers = self.web_headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
cookies = account.web_cookies.copy()
data = {
'task_id': 'double_watch_task',
'csrf_token': cookies['bili_jct'],
'csrf': cookies['bili_jct'],
}
response = await self.post(
url, data=data, headers=headers, cookies=cookies)
return response
async def post_user_online_heart(self, account: Account):
if account is None:
return
url = 'https://api.live.bilibili.com/User/userOnlineHeart'
headers = self.web_headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
cookies = account.web_cookies.copy()
data = {
'csrf_token': cookies['bili_jct'],
'csrf': cookies['bili_jct'],
'visit_id': '',
}
response = await self.post(
url, data=data, headers=headers, cookies=cookies)
# {"code":0,"msg":"OK","message":"OK","data":{"giftlist":[]}}
return response
async def post_bag_gift(self, account: Account, data: dict):
if account is None:
return
url = 'https://api.live.bilibili.com/gift/v2/live/bag_send'
headers = self.web_headers.copy()
headers['Content-Type'] = 'application/x-www-form-urlencoded'
cookies = account.web_cookies.copy()
response = await self.post(
url, data=data, headers=headers, cookies=cookies)
return response