bili-nft-avatar / login.py
rdp-studio's picture
Create login.py
adbd325
import qrcode
import time, requests, urllib, hashlib
def tvsign(params, appkey='4409e2ce8ffd12b8', appsec='59b43e04ad6965f34319062b478f83dd'):
# 为请求参数进行 api 签名
params.update({'appkey': appkey})
params = dict(sorted(params.items())) # 重排序参数 key
query = urllib.parse.urlencode(params) # 序列化参数
sign = hashlib.md5((query + appsec).encode()).hexdigest() # 计算 api 签名
params.update({'sign': sign})
return params
def catch_qr(x):
# 获取二维码
login_info = requests.post('https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code', params=tvsign({
'local_id': '0',
'ts': int(time.time())
})).json()
# 生成二维码
img = qrcode.make(login_info['data']['url']).get_image().convert("RGB")
return img, login_info
def get_uid_key(login_info):
def catch_code():
poll_info = requests.post('https://passport.bilibili.com/x/passport-tv-login/qrcode/poll', params=tvsign({
'auth_code': login_info['data']['auth_code'],
'local_id': '0',
'ts': int(time.time())
})).json()
if poll_info['code'] == 0:
return True, poll_info['data']
elif poll_info['code'] == -3:
raise Exception('API校验密匙错误')
elif poll_info['code'] == -400:
raise Exception('请求错误')
elif poll_info['code'] == 86038:
raise Exception('二维码已失效')
elif poll_info['code'] == 86039:
time.sleep(5)
return False, {}
else:
raise Exception('未知错误')
result = False
code = "连接超时"
attempt = 0
while not result and attempt < 2:
try:
result, login_data = catch_code()
if result:
return result, login_data['cookie_info']['cookies'][2]['value'], login_data['token_info'][
'access_token'], "成功"
else:
time.sleep(1)
attempt += 1
except Exception as e:
return result, "0", "0", e.args[0]
return result, "0", "0", code