Repository: Dawnnnnnn/bilibili-tools Branch: master Commit: 87ac9e9c8ba9 Files: 4 Total size: 14.6 KB Directory structure: gitextract_rky7b4ou/ ├── .gitignore ├── README.md ├── login.py └── main.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store *.iml *.xml ================================================ FILE: README.md ================================================ # bilibili-tools 挖坑开始 此项目为 bilibili 主站各项功能实现 另一已完成项目为 bilibili 直播站各功能实现 https://github.com/Dawnnnnnn/bilibili-live-tools 目前已实现: 每日投币 每日登录 每日分享 每日观看 Q:观看,分享,投币的视频如何选取? A:拉取关注列表,并在关注列表里 up 主投稿中随机选几个视频 Q:如何关闭自己不想要的功能? A: > tasks2 = [ # judge().coin_run(), # 投币任务 judge().share_run(), # 分享任务 judge().watch_run(), # 观看任务 judge().judge_run() # 仲裁案件] 将你不想开启的功能删掉或者注释掉即可 默认不打开投币功能,如想快速提高主站等级,把那一行注释去掉就可以了 挖坑结束,后期完善一下 issue 里提到的案件仲裁问题就没事了。 懒的加那个投票阙值了。。。。案件仲裁直接删了....还想用的话就用上一个版本。。 ================================================ FILE: login.py ================================================ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019/9/16 22:19 # @Author : Dawnnnnnn # @Contact: 1050596704@qq.com import base64 import random import requests import rsa import string from urllib import parse import hashlib # temporary app parameter appkey = '4409e2ce8ffd12b8' build = '101800' # device = 'android_tv_yst' mobi_app = 'android_tv_yst' app_secret = '59b43e04ad6965f34319062b478f83dd' class BiliLogin: ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36" def __init__(self): self.cookie = "" self.access_token = "" def post(self, url, data=None, headers=None, json=None, decode=True, timeout=10): try: response = requests.post(url, data=data, headers=headers, json=json, timeout=timeout) return response.json() if decode else response.content except: return None def get(self, url, headers=None, decode=True, timeout=10): try: response = requests.get(url, headers=headers, timeout=timeout) return response.json() if decode else response.content except: return None def getSign(self, param): salt = "59b43e04ad6965f34319062b478f83dd" signHash = hashlib.md5() signHash.update(f"{param}{salt}".encode()) return signHash.hexdigest() def access_token_2_cookies(self, access_token): params = f"access_key={access_token}&appkey={appkey}&gourl=https%3A%2F%2Faccount.bilibili.com%2Faccount%2Fhome" url = f"https://passport.bilibili.com/api/login/sso?{params}&sign={self.getSign(params)}" response = requests.get(url, allow_redirects=False) return response.cookies.get_dict(domain=".bilibili.com") # 登录 def login(self, username, password): self.username, self.password = username, password appKey = "4409e2ce8ffd12b8" url = "https://passport.snm0516.aisee.tv/api/oauth2/getKey" data = {'appkey': appKey, 'sign': self.getSign(f"appkey={appKey}")} response = self.post(url, data=data) if response and response.get('code') == 0: keyHash = response['data']['hash'] pubKey = rsa.PublicKey.load_pkcs1_openssl_pem( response['data']['key'].encode()) else: print(f"Key获取失败 {response}") return False url = "https://passport.snm0516.aisee.tv/api/tv/login" param = f"appkey={appkey}&build={build}&captcha=&channel=master&guid=XYEBAA3E54D502E37BD606F0589A356902FCF&mobi_app={mobi_app}&password={parse.quote_plus(base64.b64encode(rsa.encrypt(f'{keyHash}{self.password}'.encode(), pubKey)))}&platform=android&token=5598158bcd8511e2&ts=0&username={parse.quote_plus(self.username)}" data = f"{param}&sign={self.getSign(param)}" headers = {'Content-type': "application/x-www-form-urlencoded"} response = self.post(url, data=data, headers=headers) while response and response.get('code') == -105: self.cookie = f"sid={''.join(random.choices(string.ascii_lowercase + string.digits, k=8))}" url = "https://passport.snm0516.aisee.tv/api/captcha?token=5598158bcd8511e2" headers = {'Cookie': self.cookie, 'Host': "snm0516.aisee.tv", 'User-Agent': BiliLogin.ua} response = self.get(url, headers=headers, decode=False) if response is None: continue url = "http://106.75.36.27:19951/captcha/v1" img = base64.b64encode(response) img = str(img, encoding="utf-8") json = {'image': img} response = self.post(url, json=json, decode=True) print(f"验证码识别结果为: {response['message']}") url = "https://passport.snm0516.aisee.tv/api/tv/login" param = f"appkey={appKey}&captcha={response['message']}&channel=master&guid=XYEBAA3E54D502E37BD606F0589A356902FCF&mobi_app={mobi_app}&password={parse.quote_plus(base64.b64encode(rsa.encrypt(f'{keyHash}{self.password}'.encode(), pubKey)))}&platform=android&token=5598158bcd8511e2&ts=0&username={parse.quote_plus(self.username)}" data = f"{param}&sign={self.getSign(param)}" headers = {'Content-type': "application/x-www-form-urlencoded", 'Cookie': self.cookie} response = self.post(url, data=data, headers=headers) if response and response.get('code') == 0: cookie_info = self.access_token_2_cookies(response['data']['token_info']['access_token']) for key, value in cookie_info.items(): self.cookie = self.cookie + key + "=" + value + ";" self.access_token = response['data']['token_info']['access_token'] print(f"{self.username}登录成功 {self.cookie} {self.access_token}") with open("cookies.txt", "a+", encoding="utf-8")as f: f.write(f"{self.username}----{self.cookie}----{self.access_token}\n") return self.username, self.cookie, self.access_token else: print(f"{self.username}登录失败 {response}") ================================================ FILE: main.py ================================================ import random import asyncio import requests import time import json import hashlib import rsa import base64 import re import datetime from urllib import parse from login import BiliLogin def CurrentTime(): currenttime = str(int(time.mktime(datetime.datetime.now().timetuple()))) return currenttime class login(): cookies = "" username = input("输入用户名:") password = input("输入密码:") headers = { "Host": "api.bilibili.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Cookie": cookies } csrf = "" uid = "" access_key = "" async def calc_sign(self, str): str = str + "560c52ccd288fed045859ed18bffd973" hash = hashlib.md5() hash.update(str.encode('utf-8')) sign = hash.hexdigest() return sign async def get_pwd(self, username, password): url = 'https://passport.bilibili.com/api/oauth2/getKey' temp_params = 'appkey=1d8b6e7d45233436' sign = await self.calc_sign(temp_params) params = {'appkey': '1d8b6e7d45233436', 'sign': sign} response = requests.post(url, data=params) value = response.json()['data'] key = value['key'] Hash = str(value['hash']) pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(key.encode()) password = base64.b64encode(rsa.encrypt( (Hash + password).encode('utf-8'), pubkey)) password = parse.quote_plus(password) username = parse.quote_plus(username) return username, password def login(self): name, login.cookies, login.access_key = BiliLogin().login(login.username, login.password) s1 = re.findall(r'bili_jct=(\S+)', login.cookies, re.M) s2 = re.findall(r'DedeUserID=(\S+)', login.cookies, re.M) login.headers = { "Host": "api.bilibili.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Cookie": login.cookies } login.csrf = (s1[0]).split(";")[0] login.uid = (s2[0].split(";")[0]) class judge(login): def randomint(self): return ''.join(str(random.choice(range(10))) for _ in range(17)) def CurrentTime(self): millis = int((time.time() * 1000)) return str(millis) async def query_reward(self): url = "https://account.bilibili.com/home/reward" headers = { "Referer": "https://account.bilibili.com/account/home", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36", "Cookie": login.cookies } response = requests.get(url, headers=headers) iflogin = response.json()['data']['login'] ifwatch_av = response.json()['data']['watch_av'] ifshare_av = response.json()['data']['share_av'] ifgive_coin = response.json()['data']['coins_av'] return [iflogin, ifwatch_av, ifshare_av, int(ifgive_coin)] async def get_attention(self): top50_attention_list = [] url = "https://api.bilibili.com/x/relation/followings?vmid=" + \ str(login.uid) + "&ps=50&order=desc" headers = { "Host": "api.bilibili.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Cookie": login.cookies } response = requests.get(url, headers=headers) checklen = len(response.json()['data']['list']) for i in range(0, checklen): uids = (response.json()['data']['list'][i]['mid']) top50_attention_list.append(uids) return top50_attention_list async def getsubmit_video(self): top50_attention_list = await self.get_attention() video_list = [] for mid in top50_attention_list: url = "https://space.bilibili.com/ajax/member/getSubmitVideos?mid=" + \ str(mid) + "&pagesize=100&tid=0" response = requests.get(url) datalen = len(response.json()['data']['vlist']) for i in range(0, datalen): aid = response.json()['data']['vlist'][i]['aid'] video_list.append(aid) return video_list async def givecoin(self): video_list = await self.getsubmit_video() url = "https://api.bilibili.com/x/web-interface/coin/add" aid = video_list[random.randint(0, len(video_list))] data = { "aid": aid, "multiply": "1", "cross_domain": "true", "csrf": login.csrf } headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36", "Referer": "https://www.bilibili.com/video/av" + str(aid), "Origin": "https://www.bilibili.com", "Host": "api.bilibili.com", "Cookie": login.cookies } response = requests.post(url, data=data, headers=headers) print("coin_task:", response.text) if response.json()['code'] != 0: await self.givecoin() await asyncio.sleep(10) async def get_cid(self, aid): url = "https://www.bilibili.com/widget/getPageList?aid=" + str(aid) response = requests.get(url) cid = response.json()[0]['cid'] return cid async def share(self): video_list = await self.getsubmit_video() aid = video_list[random.randint(0, len(video_list))] url1 = "https://app.bilibili.com/x/v2/view/share/add" headers = { "User-Agent": "Mozilla/5.0 BiliDroid/5.26.3 (bbcallen@gmail.com)", "Host": "app.bilibili.com", "Cookie": "sid=8wfvu7i7" } ts = CurrentTime() temp_params = "access_key=" + login.access_key + "&aid=" + \ str( aid) + "&appkey=1d8b6e7d45233436&build=5260003&from=7&mobi_app=android&platform=android&ts=" + str( ts) sign = await self.calc_sign(temp_params) data = { "access_key": login.access_key, "aid": aid, "appkey": "1d8b6e7d45233436", "build": "5260003", "from": "7", "mobi_app": "android", "platform": "android", "ts": ts, "sign": sign } response = requests.post(url1, headers=headers, data=data) print("分享视频:", response.json()) async def watch_av(self, aid, cid): url = "https://api.bilibili.com/x/report/web/heartbeat" headers = { "Host": "api.bilibili.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36", "Referer": "https://www.bilibili.com/video/av" + str(aid), "Cookie": login.cookies } data = { "aid": aid, "cid": cid, "mid": login.uid, "csrf": login.csrf, "played_time": "0", "realtime": "0", "start_ts": self.CurrentTime(), "type": "3", "dt": "2", "play_type": "1" } response = requests.post(url, headers=headers, data=data) print("watch_Av_state:", response.text) async def coin_run(self): while 1: try: i = await self.query_reward() coin_exp = i[3] while coin_exp < 50: await self.givecoin() coin_exp = coin_exp + 10 if coin_exp == 50: print("投币任务完成") await asyncio.sleep(86400) await self.coin_run() except: print("coin_run出错") async def share_run(self): while 1: try: await self.share() print("分享任务完成") await asyncio.sleep(21600) except: print("share_run出错") async def watch_run(self): while 1: try: video_list = await self.getsubmit_video() aid = video_list[random.randint(0, len(video_list))] cid = await self.get_cid(aid) await self.watch_av(aid, cid) await asyncio.sleep(21600) except: print("watch_run出错") judge().login() loop = asyncio.get_event_loop() tasks2 = [ judge().coin_run(), judge().share_run(), judge().watch_run(), ] loop.run_until_complete(asyncio.wait(tasks2))