From a818e715efaa2fca792b4a89e9314e9b1695e7bd Mon Sep 17 00:00:00 2001 From: nico <13307130285@fudan.edu.cn> Date: Wed, 4 Apr 2018 01:19:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9E=B6=E6=9E=84=E6=9B=B4=E6=96=B0=20?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API.py | 201 -------------- LotteryResult.py | 66 ++--- OnlineHeart.py | 47 +--- Silver.py | 35 +-- Tasks.py | 59 ++--- bilibili.py | 637 ++++++++++++++++++++++++++++++++++++++++++++- bilibiliCilent.py | 328 +++++++++-------------- conf/bilibili.conf | 18 +- conf/user.conf | 8 +- configloader.py | 128 ++++----- connect.py | 37 ++- login.py | 94 ------- printer.py | 34 +-- run.py | 43 +-- 14 files changed, 940 insertions(+), 795 deletions(-) delete mode 100644 API.py delete mode 100644 login.py diff --git a/API.py b/API.py deleted file mode 100644 index 43697e5..0000000 --- a/API.py +++ /dev/null @@ -1,201 +0,0 @@ -from bilibili import bilibili -import hashlib -import random -import requests -import datetime -import time -import math - - -def CurrentTime(): - currenttime = int(time.mktime(datetime.datetime.now().timetuple())) - return str(currenttime) - -def calculate_sign(str): - hash = hashlib.md5() - hash.update(str.encode('utf-8')) - sign = hash.hexdigest() - return sign - -class API(): - - def __init__(self, bilibili): - self.bilibili = bilibili - - def post_watching_history(self,csrf_token, room_id): - data = { - "room_id": room_id, - "csrf_token": csrf_token - } - url = "https://api.live.bilibili.com/room/v1/Room/room_entry_action" - response = requests.post(url, data=data, headers=self.bilibili.pcheaders) - return 0 - - def check_room_true(self,roomid): - url = "https://api.live.bilibili.com/room/v1/Room/room_init?id="+str(roomid) - response = requests.get(url,headers=self.bilibili.pcheaders) - if response.json()['code'] == 0: - param1 = response.json()['data']['is_hidden'] - param2 = response.json()['data']['is_locked'] - param3 = response.json()['data']['encrypted'] - return param1,param2,param3 - - def silver2coin(self): - url = "https://api.live.bilibili.com/exchange/silver2coin" - response = requests.post(url,headers=self.bilibili.pcheaders) - print("#",response.json()['msg']) - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&ts=' + CurrentTime() - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - app_url = "https://api.live.bilibili.com/AppExchange/silver2coin?"+temp_params+"&sign="+str(hash.hexdigest()) - response1 = requests.post(app_url,headers=self.bilibili.appheaders) - print("#",response1.json()['msg']) - - def get_bag_list(self): - url = "http://api.live.bilibili.com/gift/v2/gift/bag_list" - response = requests.get(url,headers=self.bilibili.pcheaders) - temp = [] - print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '查询可用礼物') - for i in range(len(response.json()['data']['list'])): - bag_id = (response.json()['data']['list'][i]['bag_id']) - gift_id = (response.json()['data']['list'][i]['gift_id']) - gift_num = str((response.json()['data']['list'][i]['gift_num'])).center(4) - gift_name = response.json()['data']['list'][i]['gift_name'] - expireat = (response.json()['data']['list'][i]['expire_at']) - left_time = (expireat-int(CurrentTime())) - left_days = (expireat-int(CurrentTime()))/86400 - print("# " + gift_name + 'X' + gift_num, '(在'+str(math.ceil(left_days))+'天后过期)') - if 0 < int(left_time) < 86400: - temp.append([gift_id,gift_num,bag_id]) - return temp - - def get_uid_in_room(self, roomID): - url = "https://api.live.bilibili.com/room/v1/Room/room_init?id=" + roomID - response = requests.get(url, headers=self.bilibili.pcheaders) - return response.json()['data']['uid'],response.json()['data']['room_id'] - - def send_bag_gift_web(self, roomID, giftID, giftNum, bagID): - url = "http://api.live.bilibili.com/gift/v2/live/bag_send" - temp = self.get_uid_in_room(roomID) - data = { - 'uid': self.bilibili.uid, - 'gift_id': giftID, - 'ruid': temp[0], - 'gift_num': giftNum, - 'bag_id': bagID, - 'platform': 'pc', - 'biz_code': 'live', - 'biz_id': temp[1], - 'rnd': CurrentTime(), - 'storm_beat_id': '0', - 'metadata': '', - 'price': '0', - 'csrf_token': self.bilibili.csrf - } - response = requests.post(url, headers=self.bilibili.pcheaders, data=data) - try: - print(response.json()) - print("# 清理快到期礼物:",response.json()['data']['gift_name']+"x"+str(response.json()['data']['gift_num'])) - except: - print("# 清理快到期礼物成功,但请联系开发者修bug!") - - def user_info(self): - url = "https://api.live.bilibili.com/i/api/liveinfo" - response = requests.get(url, headers=self.bilibili.pcheaders) - print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '查询用户信息') - if(response.json()['code'] == 0): - uname = response.json()['data']['userInfo']['uname'] - achieve = response.json()['data']['achieves'] - user_level = response.json()['data']['userCoinIfo']['user_level'] - silver = response.json()['data']['userCoinIfo']['silver'] - gold = response.json()['data']['userCoinIfo']['gold'] - user_next_level = response.json()['data']['userCoinIfo']['user_next_level'] - user_intimacy = response.json()['data']['userCoinIfo']['user_intimacy'] - user_next_intimacy = response.json()['data']['userCoinIfo']['user_next_intimacy'] - user_level_rank = response.json()['data']['userCoinIfo']['user_level_rank'] - billCoin = response.json()['data']['userCoinIfo']['coins'] - print('# 用户名', uname) - print('# 银瓜子', silver) - print('# 金瓜子', gold) - print('# 硬币数', billCoin) - print('# 成就值', achieve) - print('# 等级值', user_level, '———>', user_next_level) - print('# 经验值', user_intimacy) - print('# 剩余值', user_next_intimacy - user_intimacy) - arrow = int(user_intimacy * 30 / user_next_intimacy) - line = 30 - arrow - percent = user_intimacy / user_next_intimacy * 100.0 - process_bar = '[' + '>' * arrow + '-' * line + ']' + '%.2f' % percent + '%' - print(process_bar) - print('# 等级榜', user_level_rank) - - def send_danmu_msg_andriod(self, msg, roomId): - url = 'https://api.live.bilibili.com/api/sendmsg?' - # page ?? - time = CurrentTime() - list_url = ["access_key=" + self.bilibili.access_key, "appkey=" + self.bilibili.appkey, 'aid=', 'page=1', "build=" + self.bilibili.build] - sign = calculate_sign('&'.join(sorted(list_url))+self.bilibili.app_secret) - - url = url + '&'.join(list_url[:3] + ['sign='+sign] + list_url[3:]) - # print(url) - data = { - 'access_key': self.bilibili.access_key, - 'actionKey': "appkey", - 'appkey': self.bilibili.appkey, - 'build': self.bilibili.build, - # 房间号 - 'cid': roomId, - # 颜色 - 'color': '16777215', - 'device': self.bilibili.device, - # 字体大小 - 'fontsize': '25', - # 实际上并不需要包含 mid 就可以正常发送弹幕, 但是真实的 Android 客户端确实发送了 mid - # 自己的用户 ID!!!! - 'from': '', - # 'mid': '1008****' - 'mobi_app': self.bilibili.mobi_app, - # 弹幕模式 - # 1 普通 4 底端 5 顶端 6 逆向 7 特殊 9 高级 - # 一些模式需要 VIP - 'mode': '1', - # 内容 - "msg": msg, - 'platform': self.bilibili.platform, - # 播放时间 - 'playTime': '0.0', - # 弹幕池 尚且只见过为 0 的情况 - 'pool': '0', - # random 随机数 - # 在 web 端发送弹幕, 该字段是固定的, 为用户进入直播页面的时间的时间戳. 但是在 Android 端, 这是一个随机数 - # 该随机数不包括符号位有 9 位 - # '1367301983632698015' - 'rnd': str((int)(1000000000000000000.0 + 2000000000000000000.0 * random.random())), - "screen_state": '', - # 反正不管用 没实现的 - 'sign': sign, - 'ts': time, - # 必须为 "json" - 'type': "json" - } - # print(data) - response = requests.post(url, headers=self.bilibili.appheaders, data=data) - print(response.json()) - - - def send_danmu_msg_web(self,msg, roomId): - url = 'https://api.live.bilibili.com/msg/send' - data = { - 'color' : '16777215', - 'fontsize' : '25', - 'mode' : '1', - 'msg' : msg, - 'rnd' : '0', - 'roomid' : roomId, - 'csrf_token' :self.bilibili.csrf - } - - - response = requests.post(url, headers=self.bilibili.pcheaders, data=data) - print(response.json()) diff --git a/LotteryResult.py b/LotteryResult.py index 7777d2f..6d8ac5d 100644 --- a/LotteryResult.py +++ b/LotteryResult.py @@ -5,51 +5,29 @@ class LotteryResult(): - - def __init__(self, bilibili): - self.bilibili =bilibili async def query(self): + while 1: - if self.bilibili.activity_raffleid_list: - for i in range(0,len(self.bilibili.activity_roomid_list)): - url = "http://api.live.bilibili.com/activity/v1/Raffle/notice?roomid="+str(self.bilibili.activity_roomid_list[0])+"&raffleId="+str(self.bilibili.activity_raffleid_list[0]) - headers = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'Accept-Language': 'zh-CN,zh;q=0.9', - 'accept-encoding': 'gzip, deflate', - 'Host': 'api.live.bilibili.com', - 'cookie': self.bilibili.cookie, - } - response = requests.get(url, headers=headers) - try: - print("# 房间", str(self.bilibili.activity_roomid_list[0]).center(9), "网页端活动抽奖结果:", response.json()['data']['gift_name']+"x"+str(response.json()['data']['gift_num'])) - del self.bilibili.activity_roomid_list[0] - del self.bilibili.activity_raffleid_list[0] - del self.bilibili.activity_time_list[0] - except: - pass + # print('lotteryresult test') + bilibili().clean_activity() - # print(self.bilibili.TV_raffleid_list) - if self.bilibili.TV_raffleid_list: - for i in range(0, len(self.bilibili.TV_roomid_list)): - url="http://api.live.bilibili.com/gift/v2/smalltv/notice?roomid="+str(self.bilibili.TV_roomid_list[0])+"&raffleId="+str(self.bilibili.TV_raffleid_list[0]) - headers = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'Accept-Language': 'zh-CN,zh;q=0.9', - 'accept-encoding': 'gzip, deflate', - 'Host': 'api.live.bilibili.com', - 'cookie': self.bilibili.cookie, - } - response = requests.get(url, headers=headers) - if response.json()['data']['gift_name'] != "": - try: - print("# 房间", str(self.bilibili.TV_roomid_list[0]).center(9), "小电视道具抽奖结果:", (response.json()['data']['gift_name'])+"x"+str(response.json()['data']['gift_num'])) - del self.bilibili.TV_roomid_list[0] - del self.bilibili.TV_raffleid_list[0] - del self.bilibili.TV_time_list[0] - except: - pass - await asyncio.sleep(60) + + bilibili().clean_TV() + + + # print('自动延迟参数', sleeptime1, sleeptime2) + await asyncio.sleep(30) + ''' + if sleeptime1 != None and sleeptime2 != None: + # print(sleeptime1, sleeptime2) + await asyncio.sleep(min(sleeptime1, sleeptime2)) + elif sleeptime1 == None and sleeptime2 == None: + await asyncio.sleep(60) + elif sleeptime1 != None: + # print(sleeptime1) + await asyncio.sleep(sleeptime1) + else: + # print(sleeptime2) + await asyncio.sleep(sleeptime2) + ''' diff --git a/OnlineHeart.py b/OnlineHeart.py index f9bf798..e07463c 100644 --- a/OnlineHeart.py +++ b/OnlineHeart.py @@ -5,47 +5,29 @@ import datetime import asyncio +def CurrentTime(): + currenttime = int(time.mktime(datetime.datetime.now().timetuple())) + return str(currenttime) + class OnlineHeart(): - def __init__(self, bilibili): - self.bilibili = bilibili - # 发送pc心跳包 //好像有点bug??? - def pcpost_heartbeat(self): - url = 'http://api.live.bilibili.com/User/userOnlineHeart' - response = requests.post(url, headers=self.bilibili.pcheaders) - #print(response.json()) - # 发送app心跳包 def apppost_heartbeat(self): - time = self.CurrentTime() - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&ts=' + time - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - url = 'https://api.live.bilibili.com/mobile/userOnlineHeart?' + temp_params + '&sign=' + str(hash.hexdigest()) - payload = {'roomid': 23058, 'scale': 'xhdpi'} - response = requests.post(url, data=payload, headers=self.bilibili.appheaders) - #print("app端心跳状态:" + response.json()['message']) + bilibili().apppost_heartbeat() + + def pcpost_heartbeat(self): + bilibili().pcpost_heartbeat() - # 心跳礼物 //测试功能 def heart_gift(self): - url = "https://api.live.bilibili.com/gift/v2/live/heart_gift_receive?roomid=3&area_v2_id=34" - response = requests.get(url, headers=self.bilibili.pcheaders) - #print(response.json()) + bilibili().heart_gift() - # 获取当前系统时间的unix时间戳 - def CurrentTime(self): - currenttime = str(int(time.mktime(datetime.datetime.now().timetuple()))) - return currenttime # 因为休眠时间差不多,所以放到这里,此为实验性功能 def draw_lottery(self): for i in range(60,80): - url = "https://api.live.bilibili.com/lottery/v1/box/getStatus?aid="+str(i) - response = requests.get(url,headers=self.bilibili.pcheaders) + response = bilibili().get_lotterylist(i) res = response.json() - #print(res) if res['code'] == 0: temp = response.json()['data']['title'] if "测试" in temp: @@ -56,11 +38,9 @@ def draw_lottery(self): for g in range(0, check): join_end_time = response.json()['data']['typeB'][g]['join_end_time'] join_start_time = response.json()['data']['typeB'][g]['join_start_time'] - ts = self.CurrentTime() + ts = CurrentTime() if int(join_end_time) > int(ts) > int(join_start_time): - url1 = 'https://api.live.bilibili.com/lottery/v1/box/draw?aid=' + str(i) + '&number=' + str( - g + 1) - response1 = requests.get(url1, headers=self.bilibili.pcheaders) + response1 = bilibili().get_gift_of_lottery(i, g) print("当前时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) print("参与抽奖回显:",response1.json()) else: @@ -73,8 +53,9 @@ async def run(self): print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "心跳") self.apppost_heartbeat() self.pcpost_heartbeat() - self.heart_gift() + self.heart_gift() self.draw_lottery() + # print('OnlineHeart is over') await asyncio.sleep(300) diff --git a/Silver.py b/Silver.py index 684968f..88c3d07 100644 --- a/Silver.py +++ b/Silver.py @@ -6,13 +6,6 @@ import asyncio class Silver(): - - def __init__(self, bilibili): - self.bilibili = bilibili - # 获取当前系统时间的unix时间戳 - def CurrentTime(self): - currenttime = str(int(time.mktime(datetime.datetime.now().timetuple()))) - return currenttime # 将time_end时间转换成正常时间 def DataTime(self): @@ -21,14 +14,8 @@ def DataTime(self): # 领瓜子时判断领取周期的参数 def time_start(self): - time = self.CurrentTime() - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&ts=' + time - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - GetTask_url = 'https://api.live.bilibili.com/mobile/freeSilverCurrentTask?' + temp_params + '&sign=' + str( - hash.hexdigest()) - response = requests.get(GetTask_url,headers=self.bilibili.appheaders) + + response = bilibili().get_time_about_silver() temp = response.json() # print (temp['code']) #宝箱领完返回的code为-10017 if temp['code'] == -10017: @@ -40,14 +27,7 @@ def time_start(self): # 领瓜子时判断领取周期的参数 def time_end(self): try: - time = self.CurrentTime() - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&ts=' + time - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - GetTask_url = 'https://api.live.bilibili.com/mobile/freeSilverCurrentTask?' + temp_params + '&sign=' + str( - hash.hexdigest()) - response = requests.get(GetTask_url, headers=self.bilibili.appheaders) + response = bilibili().get_time_about_silver() temp = response.json() time_end = temp['data']['time_end'] return str(time_end) @@ -57,16 +37,9 @@ def time_end(self): # 领取银瓜子 def GetAward(self): try: - time = self.CurrentTime() timeend = self.time_end() timestart = self.time_start() - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&time_end=' + timeend + '&time_start=' + timestart + '&ts=' + time - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - url = 'https://api.live.bilibili.com/mobile/freeSilverAward?' + temp_params + '&sign=' + str( - hash.hexdigest()) - response = requests.get(url, headers=self.bilibili.appheaders) + response = bilibili().get_silver(timestart, timeend) #print(response.json()) return response.json()['code'] except: diff --git a/Tasks.py b/Tasks.py index dd2223c..4626233 100644 --- a/Tasks.py +++ b/Tasks.py @@ -1,23 +1,23 @@ -from API import API from bilibili import bilibili import hashlib import datetime import requests import time import asyncio - +import os +import configloader class Tasks(): - def __init__(self, bilibili, configloader,api): - self.bilibili = bilibili - self.configloader = configloader - self.api = api - + + def __init__(self): + fileDir = os.path.dirname(os.path.realpath('__file__')) + file_user = fileDir + "/conf/user.conf" + self.dic_user = configloader.load_user(file_user) + # 获取每日包裹奖励 def Daily_bag(self): - url = 'http://api.live.bilibili.com/gift/v2/live/receive_daily_bag' - response = requests.get(url, headers=self.bilibili.pcheaders) + response = bilibili().get_dailybag() for i in range(0,len(response.json()['data']['bag_list'])): print("# 获得-" + response.json()['data']['bag_list'][i]['bag_name'] + "-成功") @@ -28,24 +28,19 @@ def CurrentTime(self): # 签到功能 def DoSign(self): - url = 'https://api.live.bilibili.com/sign/doSign' - response = requests.get(url, headers=self.bilibili.pcheaders) + response = bilibili().get_dosign() temp = response.json() print("# 签到状态:",temp['msg']) # 领取每日任务奖励 def Daily_Task(self): - url = 'https://api.live.bilibili.com/activity/v1/task/receive_award' - payload2 = {'task_id': 'double_watch_task'} - response2 = requests.post(url, data=payload2, headers=self.bilibili.appheaders) + response2 = bilibili().get_dailytask() + # print(response2.json()) print("# 双端观看直播:", response2.json()["msg"]) # 应援团签到 def link_sign(self): - url = "https://api.vc.bilibili.com/link_group/v1/member/my_groups" - pcheaders = self.bilibili.pcheaders.copy() - pcheaders['Host'] = "api.vc.bilibili.com" - response = requests.get(url,headers=pcheaders) + response = bilibili().get_grouplist() check = len(response.json()['data']['list']) group_id_list = [] owner_uid_list = [] @@ -55,13 +50,7 @@ def link_sign(self): group_id_list.append(group_id) owner_uid_list.append(owner_uid) for (i1,i2) in zip(group_id_list,owner_uid_list): - temp_params = "_device="+self.bilibili.device+"&_hwid=SX1NL0wuHCsaKRt4BHhIfRguTXxOfj5WN1BkBTdLfhstTn9NfUouFiUV&access_key="+self.bilibili.access_key+"&appkey="+self.bilibili.appkey+"&build="+self.bilibili.build+"&group_id="+str(i1)+"&mobi_app="+self.bilibili.mobi_app+"&owner_id="+str(i2)+"&platform="+self.bilibili.platform+"&src=xiaomi&trace_id=20171224024300024&ts="+self.CurrentTime()+"&version=5.20.1.520001" - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - url = "https://api.vc.bilibili.com/link_setting/v1/link_setting/sign_in?"+temp_params+"&sign="+str(hash.hexdigest()) - self.bilibili.appheaders['Host'] = "api.vc.bilibili.com" - response = requests.get(url,headers=self.bilibili.appheaders) + response = bilibili().assign_group(i1, i2) if response.json()['code'] == 0: if (response.json()['data']['status']) == 1: print("# 应援团 %s 已应援过" %(i1) ) @@ -71,21 +60,20 @@ def link_sign(self): print("# 应援团 %s 应援失败" %(i1)) def send_gift(self): - if self.configloader.dic_user['gift']['on/off'] == "1": + if self.dic_user['gift']['on/off'] == '1': try: - argvs = self.api.get_bag_list() - for i in range(0,len(argvs)): - giftID = argvs[i][0] - giftNum = argvs[i][1] - bagID = argvs[i][2] - roomID = self.configloader.dic_user['gift']['send_to_room'] - self.api.send_bag_gift_web(roomID,giftID,giftNum,bagID) + argvs = bilibili().get_bag_list() + giftID = argvs[0][0] + giftNum = argvs[0][1] + bagID = argvs[0][2] + roomID = self.dic_user['gift']['send_to_room'] + bilibili().send_bag_gift_web(roomID,giftID,giftNum,bagID) except: print("# 没有将要过期的礼物~") def sliver2coin(self): - if self.configloader.dic_user['coin']['on/off'] == "1": - self.api.silver2coin() + if self.dic_user['coin']['on/off'] == '1': + bilibili().silver2coin() async def run(self): while 1: @@ -96,4 +84,5 @@ async def run(self): self.Daily_bag() self.Daily_Task() self.link_sign() + # print('Tasks over.') await asyncio.sleep(21600) diff --git a/bilibili.py b/bilibili.py index 265922a..493770e 100644 --- a/bilibili.py +++ b/bilibili.py @@ -1,11 +1,634 @@ -from configloader import ConfigLoader +import configloader +import os +import hashlib +import random +import requests +import datetime +import time +import math +import requests +import rsa +import base64 +import configparser +from urllib import parse +import codecs +def CurrentTime(): + currenttime = int(time.mktime(datetime.datetime.now().timetuple())) + return str(currenttime) + +def calculate_sign(str): + hash = hashlib.md5() + hash.update(str.encode('utf-8')) + sign = hash.hexdigest() + return sign + class bilibili(): - def __init__(self, configloader): - for i, j in configloader.dic_bilibili.items(): - exec("self." + i + '=j') - # print(self.appkey) + instance = None + def __new__(cls, *args, **kw): + if not cls.instance: + cls.instance = super(bilibili, cls).__new__(cls, *args, **kw) + fileDir = os.path.dirname(os.path.realpath('__file__')) + cls.instance.file_bilibili = fileDir + "/conf/bilibili.conf" + cls.instance.dic_bilibili = configloader.load_bilibili(cls.instance.file_bilibili) + cls.instance.activity_raffleid_list = [] + cls.instance.activity_roomid_list = [] + #cls.instance.activity_time_list = [] + cls.instance.TV_raffleid_list = [] + cls.instance.TV_roomid_list = [] + #cls.instance.TV_time_list = [] + #cls.instance.TVsleeptime = 185 + #cls.instance.activitysleeptime = 125 + + + + + return cls.instance + + + def post_watching_history(self, room_id): + data = { + "room_id": room_id, + "csrf_token": self.dic_bilibili['csrf'] + } + url = "https://api.live.bilibili.com/room/v1/Room/room_entry_action" + response = requests.post(url, data=data, headers=self.dic_bilibili['pcheaders']) + return 0 + + def check_room_true(self,roomid): + url = "https://api.live.bilibili.com/room/v1/Room/room_init?id="+str(roomid) + response = requests.get(url,headers=self.dic_bilibili['pcheaders']) + if response.json()['code'] == 0: + param1 = response.json()['data']['is_hidden'] + param2 = response.json()['data']['is_locked'] + param3 = response.json()['data']['encrypted'] + return param1,param2,param3 + + def silver2coin(self): + url = "https://api.live.bilibili.com/exchange/silver2coin" + response = requests.post(url,headers=self.dic_bilibili['pcheaders']) + print("#",response.json()['msg']) + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&ts=' + CurrentTime() + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + app_url = "https://api.live.bilibili.com/AppExchange/silver2coin?"+temp_params+"&sign="+str(hash.hexdigest()) + response1 = requests.post(app_url,headers=self.dic_bilibili['appheaders']) + print("#",response1.json()['msg']) + + def get_bag_list(self): + url = "http://api.live.bilibili.com/gift/v2/gift/bag_list" + response = requests.get(url,headers=self.dic_bilibili['pcheaders']) + temp = [] + print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '查询可用礼物') + for i in range(len(response.json()['data']['list'])): + bag_id = (response.json()['data']['list'][i]['bag_id']) + gift_id = (response.json()['data']['list'][i]['gift_id']) + gift_num = str((response.json()['data']['list'][i]['gift_num'])).center(4) + gift_name = response.json()['data']['list'][i]['gift_name'] + expireat = (response.json()['data']['list'][i]['expire_at']) + left_time = (expireat-int(CurrentTime())) + left_days = (expireat-int(CurrentTime()))/86400 + print("# " + gift_name + 'X' + gift_num, '(在'+str(math.ceil(left_days))+'天后过期)') + if 0 < int(left_time) < 86400: + temp.append([gift_id,gift_num,bag_id]) + return temp + + def get_uid_in_room(self, roomID): + url = "https://api.live.bilibili.com/room/v1/Room/room_init?id=" + roomID + response = requests.get(url, headers=self.dic_bilibili['pcheaders']) + return response.json()['data']['uid'],response.json()['data']['room_id'] + + def send_bag_gift_web(self, roomID, giftID, giftNum, bagID): + url = "http://api.live.bilibili.com/gift/v2/live/bag_send" + temp = self.get_uid_in_room(roomID) + data = { + 'uid': self.dic_bilibili['uid'], + 'gift_id': giftID, + 'ruid': temp[0], + 'gift_num': giftNum, + 'bag_id': bagID, + 'platform': 'pc', + 'biz_code': 'live', + 'biz_id': temp[1], + 'rnd': CurrentTime(), + 'storm_beat_id': '0', + 'metadata': '', + 'price': '0', + 'csrf_token': self.dic_bilibili['csrf'] + } + response = requests.post(url, headers=self.dic_bilibili['pcheaders'], data=data) + try: + print(response.json()) + print("# 清理快到期礼物:",response.json()['data']['gift_name']+"x"+str(response.json()['data']['gift_num'])) + except: + print("# 清理快到期礼物成功,但请联系开发者修bug!") + + def user_info(self): + url = "https://api.live.bilibili.com/i/api/liveinfo" + response = requests.get(url, headers=self.dic_bilibili['pcheaders']) + print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '查询用户信息') + if(response.json()['code'] == 0): + uname = response.json()['data']['userInfo']['uname'] + achieve = response.json()['data']['achieves'] + user_level = response.json()['data']['userCoinIfo']['user_level'] + silver = response.json()['data']['userCoinIfo']['silver'] + gold = response.json()['data']['userCoinIfo']['gold'] + user_next_level = response.json()['data']['userCoinIfo']['user_next_level'] + user_intimacy = response.json()['data']['userCoinIfo']['user_intimacy'] + user_next_intimacy = response.json()['data']['userCoinIfo']['user_next_intimacy'] + user_level_rank = response.json()['data']['userCoinIfo']['user_level_rank'] + billCoin = response.json()['data']['userCoinIfo']['coins'] + print('# 用户名', uname) + print('# 银瓜子', silver) + print('# 金瓜子', gold) + print('# 硬币数', billCoin) + print('# 成就值', achieve) + print('# 等级值', user_level, '———>', user_next_level) + print('# 经验值', user_intimacy) + print('# 剩余值', user_next_intimacy - user_intimacy) + arrow = int(user_intimacy * 30 / user_next_intimacy) + line = 30 - arrow + percent = user_intimacy / user_next_intimacy * 100.0 + process_bar = '[' + '>' * arrow + '-' * line + ']' + '%.2f' % percent + '%' + print(process_bar) + print('# 等级榜', user_level_rank) + + def send_danmu_msg_andriod(self, msg, roomId): + url = 'https://api.live.bilibili.com/api/sendmsg?' + # page ?? + time = CurrentTime() + list_url = ["access_key=" + self.dic_bilibili['access_key'], "appkey=" + self.dic_bilibili['appkey'], 'aid=', 'page=1', "build=" + self.dic_bilibili['build']] + sign = calculate_sign('&'.join(sorted(list_url))+self.dic_bilibili['app_secret']) + + url = url + '&'.join(list_url[:3] + ['sign='+sign] + list_url[3:]) + + data = { + 'access_key': self.dic_bilibili['access_key'], + 'actionKey': "appkey", + 'appkey': self.dic_bilibili['appkey'], + 'build': self.dic_bilibili['build'], + # 房间号 + 'cid': roomId, + # 颜色 + 'color': '16777215', + 'device': self.dic_bilibili['device'], + # 字体大小 + 'fontsize': '25', + # 实际上并不需要包含 mid 就可以正常发送弹幕, 但是真实的 Android 客户端确实发送了 mid + # 自己的用户 ID!!!! + 'from': '', + # 'mid': '1008****' + 'mobi_app': self.dic_bilibili['mobi_app'], + # 弹幕模式 + # 1 普通 4 底端 5 顶端 6 逆向 7 特殊 9 高级 + # 一些模式需要 VIP + 'mode': '1', + # 内容 + "msg": msg, + 'platform': self.dic_bilibili['platform'], + # 播放时间 + 'playTime': '0.0', + # 弹幕池 尚且只见过为 0 的情况 + 'pool': '0', + # random 随机数 + # 在 web 端发送弹幕, 该字段是固定的, 为用户进入直播页面的时间的时间戳. 但是在 Android 端, 这是一个随机数 + # 该随机数不包括符号位有 9 位 + # '1367301983632698015' + 'rnd': str((int)(1000000000000000000.0 + 2000000000000000000.0 * random.random())), + "screen_state": '', + # 反正不管用 没实现的 + 'sign': sign, + 'ts': time, + # 必须为 "json" + 'type': "json" + } + + response = requests.post(url, headers=self.dic_bilibili['appheaders'], data=data) + print(response.json()) + + def send_danmu_msg_web(self,msg, roomId): + url = 'https://api.live.bilibili.com/msg/send' + data = { + 'color' : '16777215', + 'fontsize' : '25', + 'mode' : '1', + 'msg' : msg, + 'rnd' : '0', + 'roomid' : roomId, + 'csrf_token' :self.dic_bilibili['csrf'] + } + + + response = requests.post(url, headers=self.dic_bilibili['pcheaders'], data=data) + print(response.json()) + + def GetHash(self): + url = 'https://passport.bilibili.com/api/oauth2/getKey' + + temp_params = 'appkey=' + self.dic_bilibili['appkey'] + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(temp_params.encode('utf-8')) + sign = hash.hexdigest() + params = {'appkey': self.dic_bilibili['appkey'], 'sign': sign} + response = requests.post(url, data=params) + value = response.json()['data'] + return value + + def login(self): + + if self.dic_bilibili['account']['username']: + username = str(self.dic_bilibili['account']['username']) + password = str(self.dic_bilibili['account']['password']) + + else: + username = input("# 输入帐号: ") + password = input("# 输入密码: ") + config = configparser.ConfigParser() + config.optionxform = str + config.read_file(codecs.open(self.file_bilibili, "r", "utf8")) + config.set('account','username',username) + config.set('account','password',password) + config.write(codecs.open(self.file_bilibili, "w+","utf8")) + if username != "": + value = self.GetHash() + 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) + # url = 'https://passport.bilibili.com/api/oauth2/login' //旧接口 + url = "https://passport.bilibili.com/api/v2/oauth2/login" + temp_params = 'appkey=' + self.dic_bilibili['appkey'] + '&password=' + password + '&username=' + username + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + sign = hash.hexdigest() + headers = {"Content-type": "application/x-www-form-urlencoded"} + payload = "appkey=" + self.dic_bilibili['appkey'] + "&password=" + password + "&username=" + username + "&sign=" + sign + response = requests.post(url, data=payload, headers=headers) + try: + access_key = response.json()['data']['token_info']['access_token'] + cookie = (response.json()['data']['cookie_info']['cookies']) + cookie_format = "" + for i in range(0, len(cookie)): + cookie_format = cookie_format + cookie[i]['name'] + "=" + cookie[i]['value'] + ";" + self.dic_bilibili['csrf'] = cookie[0]['value'] + self.dic_bilibili['access_key'] = access_key + self.dic_bilibili['cookie'] = cookie_format + self.dic_bilibili['uid'] = cookie[1]['value'] + self.dic_bilibili['pcheaders'] = { + 'Accept': 'application/json, text/plain, */*', + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', + 'Accept-Language': 'zh-CN,zh;q=0.9', + 'accept-encoding': 'gzip, deflate', + 'Host': 'api.live.bilibili.com', + 'cookie': cookie_format + } + self.dic_bilibili['appheaders'] = { + "User-Agent": "bili-universal/6570 CFNetwork/894 Darwin/17.4.0", + "Accept-encoding": "gzip", + "Buvid": "000ce0b9b9b4e342ad4f421bcae5e0ce", + "Display-ID": "146771405-1521008435", + "Accept-Language": "zh-CN", + "Accept": "text/html,application/xhtml+xml,*/*;q=0.8", + "Connection": "keep-alive", + "Host": "api.live.bilibili.com", + 'cookie': cookie_format + } + + print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "登陆成功") + except: + print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "登录失败,错误信息为:",response.json()['message']) + + def get_gift_of_storm(self, dic): + roomid = dic['roomid'] + get_url = "http://api.live.bilibili.com/lottery/v1/Storm/check?roomid=" + str(roomid) + response = requests.get(get_url, headers=self.dic_bilibili['pcheaders']) + temp = response.json() + check = len(temp['data']) + if check != 0 and temp['data']['hasJoin'] != 1: + id = temp['data']['id'] + storm_url = 'http://api.live.bilibili.com/lottery/v1/Storm/join' + payload = { + "id": id, + "color": "16777215", + "captcha_token": "", + "captcha_phrase": "", + "token": "", + "csrf_token": self.dic_bilibili['csrf']} + response1 = requests.post(storm_url, data=payload, headers=self.dic_bilibili['pcheaders'], timeout=2) + return response1 + else: + return None + + def get_gift_of_events(self, text1, text2, raffleid): + headers = { + 'Accept': 'application/json, text/plain, */*', + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', + 'cookie': self.dic_bilibili['cookie'], + 'referer': text2 + } + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + '&event_type=flower_rain-' + str( + raffleid) + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&room_id=' + str( + text1) + '&ts=' + CurrentTime() + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + true_url = 'http://api.live.bilibili.com/YunYing/roomEvent?' + temp_params + '&sign=' + str( + hash.hexdigest()) + pc_url = 'http://api.live.bilibili.com/activity/v1/Raffle/join?roomid=' + str( + text1) + '&raffleId=' + str(raffleid) + response1 = requests.get(true_url, params=params, headers=headers) + pc_response = requests.get(pc_url, headers=headers) + + return response1, pc_response + + + def get_gift_of_TV(self, real_roomid, raffleid): + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + '&id=' + str( + raffleid) + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&roomid=' + str( + real_roomid) + '&ts=' + CurrentTime() + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + true_url = 'http://api.live.bilibili.com/AppSmallTV/join?' + temp_params + '&sign=' + str( + hash.hexdigest()) + response2 = requests.get(true_url, headers=self.dic_bilibili['appheaders']) + return response2 + + def get_gift_of_captain(self,roomid, id): + join_url = "https://api.live.bilibili.com/lottery/v1/lottery/join" + payload = {"roomid": roomid, "id": id, "type": "guard", "csrf_token": self.doc_bilibili['csrf']} + print(payload) + response2 = requests.post(join_url, data=payload, headers=self.dic_bilibili['pcheaders']) + return response2 + + + def get_giftlist_of_events(self, text1): + headers = { + 'Accept': 'application/json, text/plain, */*', + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', + 'Accept-Language': 'zh-CN,zh;q=0.9', + 'accept-encoding': 'gzip, deflate', + 'Host': 'api.live.bilibili.com', + 'cookie': self.dic_bilibili['cookie'], + } + url = 'http://api.live.bilibili.com/activity/v1/Raffle/check?roomid=' + str(text1) + response = requests.get(url, headers=headers) + + return response + + + def get_giftlist_of_TV(self, real_roomid): + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + \ + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&roomid=' + str( + real_roomid) + '&ts=' + CurrentTime() + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + + check_url = 'https://api.live.bilibili.com/AppSmallTV/index?' + temp_params + '&sign=' + str( + hash.hexdigest()) + + headers={ + "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36", + } + response = requests.get(check_url, headers=headers) + + return response + + + def get_giftlist_of_captain(self, roomid): + true_url = 'https://api.live.bilibili.com/lottery/v1/lottery/check?roomid=' + str(roomid) + response1 = requests.get(true_url) + return response1 + + def append_to_activitylist(self, raffleid, text1, time=''): + self.activity_raffleid_list.append(raffleid) + self.activity_roomid_list.append(text1) + # self.activity_time_list.append(int(time)) + #self.activity_time_list.append(int(CurrentTime())) + + + def append_to_TVlist(self, raffleid, real_roomid, time=''): + self.TV_raffleid_list.append(raffleid) + self.TV_roomid_list.append(real_roomid) + # self.TV_time_list.append(int(time)+int(CurrentTime())) + #self.TV_time_list.append(int(CurrentTime())) + + + def check_TVlist(self, raffleid): + if raffleid not in self.TV_raffleid_list: + return True + return False + + def check_activitylist(self, raffleid): + if raffleid not in self.activity_raffleid_list: + return True + return False + + def get_giftids_raffle(self, str): + return self.dic_bilibili['giftids_raffle'][str] + + def get_giftids_raffle_keys(self): + return self.dic_bilibili['giftids_raffle'].keys() + + def get_activity_result(self, activity_roomid, activity_raffleid): + url = "http://api.live.bilibili.com/activity/v1/Raffle/notice?roomid="+str(activity_roomid)+"&raffleId="+str(activity_raffleid) + headers = { + 'Accept': 'application/json, text/plain, */*', + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', + 'Accept-Language': 'zh-CN,zh;q=0.9', + 'accept-encoding': 'gzip, deflate', + 'Host': 'api.live.bilibili.com', + 'cookie': self.dic_bilibili['cookie'], + } + response = requests.get(url, headers=headers) + return response + + def get_TV_result(self, TV_roomid, TV_raffleid): + url="http://api.live.bilibili.com/gift/v2/smalltv/notice?roomid="+str(TV_roomid)+"&raffleId="+str(TV_raffleid) + headers = { + 'Accept': 'application/json, text/plain, */*', + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', + 'Accept-Language': 'zh-CN,zh;q=0.9', + 'accept-encoding': 'gzip, deflate', + 'Host': 'api.live.bilibili.com', + 'cookie': self.dic_bilibili['cookie'], + } + response = requests.get(url, headers=headers) + return response + + def delete_0st_activitylist(self): + del self.activity_roomid_list[0] + del self.activity_raffleid_list[0] + # del self.activity_time_list[0] + + + def delete_0st_TVlist(self): + del self.TV_roomid_list[0] + del self.TV_raffleid_list[0] + # del self.TV_time_list[0] + + def clean_activity(self): + # print(self.activity_raffleid_list) + if self.activity_raffleid_list: + for i in range(0,len(self.activity_roomid_list)): + response = self.get_activity_result(self.activity_roomid_list[0], self.activity_raffleid_list[0]) + json_response = response.json() + # print(json_response) + if json_response['code'] == 0: + data = json_response['data'] + print("# 房间", str(self.activity_roomid_list[0]).center(9), "网页端活动抽奖结果:", data['gift_name']+"x"+str(data['gift_num'])) + + self.delete_0st_activitylist() + + elif json_response['code'] == -400: + # sleepseconds = self.activitysleeptime + self.activity_time_list[0] - int(CurrentTime())+ 2 + # sleepseconds = self.activity_time_list[0] - int(CurrentTime()) + # return sleepsecondsq + return + + else: + print('未知情况') + print(json_response) + + else: + return + + def clean_TV(self): + # print(self.TV_raffleid_list) + if self.TV_raffleid_list: + for i in range(0, len(self.TV_roomid_list)): + + response = self.get_TV_result(self.TV_roomid_list[0], self.TV_raffleid_list[0]) + # if response.json()['data']['gift_name'] != "": + json_response = response.json() + # print(json_response) + if json_response['data']['gift_id'] == '-1': + return + elif json_response['data']['gift_id'] != '-1': + + data = json_response['data'] + print("# 房间", str(self.TV_roomid_list[0]).center(9), "小电视道具抽奖结果:", data['gift_name'] +"x"+str(data['gift_num'])) + + + + self.delete_0st_TVlist() + # else: + # print(int(CurrentTime())) + # sleepseconds = self.TV_time_list[0] - int(CurrentTime()) + 1 + # sleepseconds = self.TV_time_list[0] - int(CurrentTime()) + #return + + # else: + # print('未知') + else: + return + + + # 发送pc心跳包 //好像有点bug??? + def pcpost_heartbeat(self): + url = 'http://api.live.bilibili.com/User/userOnlineHeart' + response = requests.post(url, headers=self.dic_bilibili['pcheaders']) + + + # 发送app心跳包 + + def apppost_heartbeat(self): + time = CurrentTime() + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&ts=' + time + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + url = 'https://api.live.bilibili.com/mobile/userOnlineHeart?' + temp_params + '&sign=' + str(hash.hexdigest()) + payload = {'roomid': 23058, 'scale': 'xhdpi'} + response = requests.post(url, data=payload, headers=self.dic_bilibili['appheaders']) + #print("app端心跳状态:" + response.json()['message']) + + # 心跳礼物 //测试功能 + + def heart_gift(self): + url = "https://api.live.bilibili.com/gift/v2/live/heart_gift_receive?roomid=3&area_v2_id=34" + response = requests.get(url, headers=self.dic_bilibili['pcheaders']) + #print(response.json()) + + + def get_lotterylist(self, i): + url = "https://api.live.bilibili.com/lottery/v1/box/getStatus?aid="+str(i) + response = requests.get(url,headers=self.dic_bilibili['pcheaders']) + return response + + def get_gift_of_lottery(self, i, g): + url1 = 'https://api.live.bilibili.com/lottery/v1/box/draw?aid=' + str(i) + '&number=' + str(g + 1) + response1 = requests.get(url1, headers=self.dic_bilibili['pcheaders']) + return response1 + + def get_time_about_silver(self): + time = CurrentTime() + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&ts=' + time + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + GetTask_url = 'https://api.live.bilibili.com/mobile/freeSilverCurrentTask?' + temp_params + '&sign=' + str( + hash.hexdigest()) + response = requests.get(GetTask_url,headers=self.dic_bilibili['appheaders']) + return response + + def get_silver(self, timestart, timeend): + time = CurrentTime() + temp_params = 'access_key=' + self.dic_bilibili['access_key'] + '&actionKey=' + self.dic_bilibili['actionKey'] + '&appkey=' + self.dic_bilibili['appkey'] + '&build=' + self.dic_bilibili['build'] + '&device=' + self.dic_bilibili['device'] + '&mobi_app=' + self.dic_bilibili['mobi_app'] + '&platform=' + self.dic_bilibili['platform'] + '&time_end=' + timeend + '&time_start=' + timestart + '&ts=' + time + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + url = 'https://api.live.bilibili.com/mobile/freeSilverAward?' + temp_params + '&sign=' + str( + hash.hexdigest()) + response = requests.get(url, headers=self.dic_bilibili['appheaders']) + return response + + def get_dailybag(self): + url = 'http://api.live.bilibili.com/gift/v2/live/receive_daily_bag' + response = requests.get(url, headers=self.dic_bilibili['pcheaders']) + return response + + def get_dosign(self): + url = 'https://api.live.bilibili.com/sign/doSign' + response = requests.get(url, headers=self.dic_bilibili['pcheaders']) + return response + + def get_dailytask(self): + url = 'https://api.live.bilibili.com/activity/v1/task/receive_award' + payload2 = {'task_id': 'double_watch_task'} + response2 = requests.post(url, data=payload2, headers=self.dic_bilibili['appheaders']) + return response2 + + def get_grouplist(self): + url = "https://api.vc.bilibili.com/link_group/v1/member/my_groups" + pcheaders = self.dic_bilibili['pcheaders'].copy() + pcheaders['Host'] = "api.vc.bilibili.com" + response = requests.get(url, headers = pcheaders) + return response + + def assign_group(self, i1, i2): + temp_params = "_device="+self.dic_bilibili['device']+"&_hwid=SX1NL0wuHCsaKRt4BHhIfRguTXxOfj5WN1BkBTdLfhstTn9NfUouFiUV&access_key="+self.dic_bilibili['access_key']+"&appkey="+self.dic_bilibili['appkey']+"&build="+self.dic_bilibili['build']+"&group_id="+str(i1)+"&mobi_app="+self.dic_bilibili['mobi_app']+"&owner_id="+str(i2)+"&platform="+self.dic_bilibili['platform']+"&src=xiaomi&trace_id=20171224024300024&ts="+CurrentTime()+"&version=5.20.1.520001" + params = temp_params + self.dic_bilibili['app_secret'] + hash = hashlib.md5() + hash.update(params.encode('utf-8')) + url = "https://api.vc.bilibili.com/link_setting/v1/link_setting/sign_in?"+temp_params+"&sign="+str(hash.hexdigest()) + appheaders = self.dic_bilibili['appheaders'].copy() + appheaders['Host'] = "api.vc.bilibili.com" + response = requests.get(url,headers= appheaders) + return response + +# a = bilibili() +# b = bilibili() +# print(a is b) +# print(a.dic_bilibili['giftids_raffle']) +# bilibili().test(1) +# bilibili().login() +# print(bilibili().dic_bilibili) + -# configloader = ConfigLoader("color.conf", "user.conf", "bilibili.conf") -# bilibili(configloader) diff --git a/bilibiliCilent.py b/bilibiliCilent.py index 1052d69..206b4b0 100644 --- a/bilibiliCilent.py +++ b/bilibiliCilent.py @@ -1,5 +1,4 @@ -# from bilibili import bilibili -from API import API +from bilibili import bilibili import asyncio import random from struct import * @@ -13,17 +12,19 @@ import sys -def CurrentTime(): - currenttime = str(int(time.mktime(datetime.datetime.now().timetuple()))) - return currenttime - class bilibiliClient(): - def __init__(self, printer, bilibili, api): + def __init__(self, printer): + self.bilibili = bilibili() self.printer = printer - self.bilibili = bilibili - self.api = api + self._reader = None + self._writer = None + self._uid = None + self.connected = False + self._UserCount = 0 + + self.dic_bulletin = { 'cmd': 'str', 'msg': 'str', @@ -33,32 +34,31 @@ def __init__(self, printer, bilibili, api): async def connectServer(self): try: - reader, writer = await asyncio.open_connection(self.bilibili._ChatHost, self.bilibili._ChatPort) + reader, writer = await asyncio.open_connection(self.bilibili.dic_bilibili['_ChatHost'], self.bilibili.dic_bilibili['_ChatPort']) except: print("# 连接无法建立,请检查本地网络状况") return - self.bilibili._reader = reader - self.bilibili._writer = writer - # print("writer and reader are ready") - if (await self.SendJoinChannel(self.bilibili.roomid) == True): - self.bilibili.connected = True + self._reader = reader + self._writer = writer + if (await self.SendJoinChannel(self.bilibili.dic_bilibili['roomid']) == True): + self.connected = True print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '连接弹幕服务器成功') await self.ReceiveMessageLoop() async def HeartbeatLoop(self): - while self.bilibili.connected == False: + while self.connected == False: await asyncio.sleep(0.5) print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '开始心跳') - while self.bilibili.connected == True: - await self.SendSocketData(0, 16, self.bilibili._protocolversion, 2, 1, "") + while self.connected == True: + await self.SendSocketData(0, 16, self.bilibili.dic_bilibili['_protocolversion'], 2, 1, "") await asyncio.sleep(30) async def SendJoinChannel(self, channelId): - self.bilibili._uid = (int)(100000000000000.0 + 200000000000000.0 * random.random()) - body = '{"roomid":%s,"uid":%s}' % (channelId, self.bilibili._uid) - await self.SendSocketData(0, 16, self.bilibili._protocolversion, 7, 1, body) + self._uid = (int)(100000000000000.0 + 200000000000000.0 * random.random()) + body = '{"roomid":%s,"uid":%s}' % (channelId, self._uid) + await self.SendSocketData(0, 16, self.bilibili.dic_bilibili['_protocolversion'], 7, 1, body) return True async def SendSocketData(self, packetlength, magic, ver, action, param, body): @@ -70,52 +70,46 @@ async def SendSocketData(self, packetlength, magic, ver, action, param, body): sendbytes = sendbytes + bytearr # print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), sendbytes) try: - self.bilibili._writer.write(sendbytes) + self._writer.write(sendbytes) except: print(sys.exc_info()[0], sys.exc_info()[1]) - self.bilibili.connected = False + self.connected = False - await self.bilibili._writer.drain() + await self._writer.drain() async def ReceiveMessageLoop(self): - while self.bilibili.connected == True: - tmp = await self.bilibili._reader.read(16) + while self.connected == True: + tmp = await self._reader.read(16) num0 = 16 while num0 != len(tmp) and tmp: - tmp += await self.bilibili._reader.read(num0 - len(tmp)) + tmp += await self._reader.read(num0 - len(tmp)) # print("妈蛋运营商,切劳资包") if not tmp: print("# 网络连接中断或服务器主动断开,请检查本地网络状况,稍后将尝试重连") - self.bilibili.connected = False + self.connected = False break expr, = unpack('!I', tmp[:4]) - # print(expr) - # tmp = await self.bilibili._reader.read(2) - # tmp = await self.bilibili._reader.read(2) - # tmp = await self.bilibili._reader.read(4) + num, = unpack('!I', tmp[8:12]) - # tmp = await self.bilibili._reader.read(4) + num2 = expr - 16 - tmp = await self.bilibili._reader.read(num2) + tmp = await self._reader.read(num2) while num2 != len(tmp) and tmp: - tmp += await self.bilibili._reader.read(num2 - len(tmp)) + tmp += await self._reader.read(num2 - len(tmp)) # print("妈蛋运营商,切劳资包") if not tmp and num2 != 0: print("# 网络连接中断或服务器主动断开,请检查本地网络状况,稍后将尝试重连....") - self.bilibili.connected = False + self.connected = False break if num2 != 0: num -= 1 if num == 0 or num == 1 or num == 2: - # tmp = await self.bilibili._reader.read(4) num3, = unpack('!I', tmp) - self.bilibili._UserCount = num3 + self._UserCount = num3 continue elif num == 3 or num == 4: - # tmp = await self.bilibili._reader.read(num2) - # strbytes, = unpack('!s', tmp) try: messages = tmp.decode('utf-8') except: @@ -123,29 +117,14 @@ async def ReceiveMessageLoop(self): await self.parseDanMu(messages) continue elif num == 5 or num == 6 or num == 7: - # tmp = await self.bilibili._reader.read(num2) continue else: if num != 16: - # tmp = await self.bilibili._reader.read(num2) pass else: continue - def get_gift_of_storm(self, dic): - roomid = dic['roomid'] - get_url = "http://api.live.bilibili.com/lottery/v1/Storm/check?roomid=" + str(roomid) - response = requests.get(get_url, headers=self.bilibili.pcheaders) - temp = response.json() - check = len(temp['data']) - if check != 0 and temp['data']['hasJoin'] != 1: - id = temp['data']['id'] - storm_url = 'http://api.live.bilibili.com/lottery/v1/Storm/join' - payload = {"id": id, "color": "16777215", "captcha_token": "", "captcha_phrase": "", "token": "", - "csrf_token": self.bilibili.csrf} - response1 = requests.post(storm_url, data=payload, headers=self.bilibili.pcheaders, timeout=2) - print(response1.json()) - + async def parseDanMu(self, messages): try: @@ -156,35 +135,29 @@ async def parseDanMu(self, messages): if cmd == 'DANMU_MSG': # print(dic) - # self.printer.printlist_append(['danmu', '弹幕', 'user', dic]) - pass + self.printer.printlist_append(['danmu', '弹幕', 'user', dic]) + return if cmd == 'SYS_GIFT': if 'giftId' in dic.keys(): - if str(dic['giftId']) in self.bilibili.giftids_raffle.keys(): - headers = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'Accept-Language': 'zh-CN,zh;q=0.9', - 'accept-encoding': 'gzip, deflate', - 'Host': 'api.live.bilibili.com', - 'cookie': self.bilibili.cookie, - } + if str(dic['giftId']) in bilibili().get_giftids_raffle_keys(): + await asyncio.sleep(random.uniform(3, 5)) + text1 = dic['real_roomid'] text2 = dic['url'] - await asyncio.sleep(random.uniform(3, 5)) - self.api.post_watching_history(self.bilibili.csrf, text1) - result = self.api.check_room_true(text1) + + bilibili().post_watching_history(text1) + result = bilibili().check_room_true(text1) if True in result: self.printer.printlist_append(['join_lottery', '钓鱼提醒', 'user', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "WARNING:检测到房间", str(text1).center(9), "的钓鱼操作"]) else: - url = 'http://api.live.bilibili.com/activity/v1/Raffle/check?roomid=' + str(text1) + self.printer.printlist_append(['join_lottery', '', 'user', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "检测到房间", str(text1).center(9), - "的" + self.bilibili.giftids_raffle[str(dic['giftId'])] + "活动抽奖"]) - response = requests.get(url, headers=headers) + "的" + bilibili().get_giftids_raffle(str(dic['giftId'])) + "活动抽奖"]) + response = bilibili().get_giftlist_of_events(text1) checklen = response.json()['data'] num = len(checklen) while num != 0: @@ -192,34 +165,21 @@ async def parseDanMu(self, messages): await asyncio.sleep(random.uniform(0.5, 1)) resttime = response.json()['data'][j]['time'] raffleid = response.json()['data'][j]['raffleId'] - if raffleid not in self.bilibili.activity_raffleid_list: + if bilibili().check_activitylist(raffleid): + + + + response1, pc_response = bilibili().get_gift_of_events(text1, text2, raffleid) + + bilibili().append_to_activitylist(raffleid, text1) + self.printer.printlist_append(['join_lottery', '', 'user', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "参与了房间", str(text1).center(9), - "的" + self.bilibili.giftids_raffle[ - str(dic['giftId'])] + "活动抽奖"]) - self.bilibili.activity_raffleid_list.append(raffleid) - self.bilibili.activity_roomid_list.append(text1) - self.bilibili.activity_time_list.append(resttime) - headers = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'cookie': self.bilibili.cookie, - 'referer': text2 - } - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&event_type=flower_rain-' + str( - raffleid) + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&room_id=' + str( - text1) + '&ts=' + CurrentTime() - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - true_url = 'http://api.live.bilibili.com/YunYing/roomEvent?' + temp_params + '&sign=' + str( - hash.hexdigest()) - pc_url = 'http://api.live.bilibili.com/activity/v1/Raffle/join?roomid=' + str( - text1) + '&raffleId=' + str(raffleid) - response1 = requests.get(true_url, params=params, headers=headers) - pc_response = requests.get(pc_url, headers=headers) + "的" + bilibili().get_giftids_raffle( + str(dic['giftId'])) + "活动抽奖"]) + try: self.printer.printlist_append(['join_lottery', '', 'user', "# 移动端活动抽奖结果:", response1.json()['data']['gift_desc']]) @@ -233,121 +193,84 @@ async def parseDanMu(self, messages): break elif dic['giftId'] == 39: self.printer.printlist_append(['join_lottery', '', 'user', "节奏风暴"]) - self.get_gift_of_storm(dic) + + response1 = bilibili().get_gift_of_storm(dic) + if response1 != None: + print(response1.json()) + else: + self.printer.printlist_append(['join_lottery','','debug', [dic, "请联系开发者"]]) else: self.printer.printlist_append(['join_lottery', '', 'debug', [dic, "请联系开发者"]]) try: - headers = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'Accept-Language': 'zh-CN,zh;q=0.9', - 'accept-encoding': 'gzip, deflate', - 'Host': 'api.live.bilibili.com', - 'cookie': self.bilibili.cookie, - } - text1 = dic['real_roomid'] - text2 = dic['url'] - await asyncio.sleep(random.uniform(3, 5)) - self.api.post_watching_history(self.bilibili.csrf, text1) - result = self.api.check_room_true(text1) - if True in result: - self.printer.printlist_append(['join_lottery', '钓鱼提醒', 'user', - time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), - "WARNING:检测到房间", str(text1).center(9), "的钓鱼操作"]) - else: - url = 'http://api.live.bilibili.com/activity/v1/Raffle/check?roomid=' + str(text1) - self.printer.printlist_append(['join_lottery', '', 'user', - time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), - "检测到房间", str(text1).center(9), - "的" + "活动抽奖"]) - response = requests.get(url, headers=headers) - checklen = response.json()['data'] - num = len(checklen) - while num != 0: - for j in range(0, num): - await asyncio.sleep(random.uniform(0.5, 1)) - resttime = response.json()['data'][j]['time'] - raffleid = response.json()['data'][j]['raffleId'] - if raffleid not in self.bilibili.activity_raffleid_list: - self.printer.printlist_append(['join_lottery', '', 'user', - time.strftime('%Y-%m-%d %H:%M:%S', - time.localtime(time.time())), "参与了房间", - str(text1).center(9), - "的" + "活动抽奖"]) - self.bilibili.activity_raffleid_list.append(raffleid) - self.bilibili.activity_roomid_list.append(text1) - self.bilibili.activity_time_list.append(resttime) - headers = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'cookie': self.bilibili.cookie, - 'referer': text2 - } - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&event_type=flower_rain-' + str( - raffleid) + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&room_id=' + str( - text1) + '&ts=' + CurrentTime() - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - true_url = 'http://api.live.bilibili.com/YunYing/roomEvent?' + temp_params + '&sign=' + str( - hash.hexdigest()) - pc_url = 'http://api.live.bilibili.com/activity/v1/Raffle/join?roomid=' + str( - text1) + '&raffleId=' + str(raffleid) - response1 = requests.get(true_url, params=params, headers=headers) - pc_response = requests.get(pc_url, headers=headers) - try: - self.printer.printlist_append(['join_lottery', '', 'user', "# 移动端活动抽奖结果:", - response1.json()['data']['gift_desc']]) - except: - pass - try: - self.printer.printlist_append( - ['join_lottery', '', 'user', "# 网页端活动抽奖状态:", pc_response.json()['message']]) - except: - pass - break + self.printer.printlist_append(['join_lottery', '', 'user', + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), + "检测到房间", str(text1).center(9), + "的" + "活动抽奖"]) + response = bilibili().get_giftlist_of_events(text1) + checklen = response.json()['data'] + num = len(checklen) + while num != 0: + for j in range(0, num): + await asyncio.sleep(random.uniform(0.5, 1)) + resttime = response.json()['data'][j]['time'] + raffleid = response.json()['data'][j]['raffleId'] + if bilibili().check_activitylist(raffleid): + + + + + response1, pc_response = bilibili().get_gift_of_events(text1, text2, raffleid) + bilibili().append_to_activitylist(raffleid, text1) + self.printer.printlist_append(['join_lottery', '', 'user', + time.strftime('%Y-%m-%d %H:%M:%S', + time.localtime(time.time())), "参与了房间", + str(text1).center(9), + "的" + "活动抽奖"]) + + + try: + self.printer.printlist_append(['join_lottery', '', 'user', "# 移动端活动抽奖结果:", + response1.json()['data']['gift_desc']]) + except: + pass + try: + self.printer.printlist_append( + ['join_lottery', '', 'user', "# 网页端活动抽奖状态:", pc_response.json()['message']]) + except: + pass + break except : pass else: - pass - #self.printer.printlist_append(['join_lottery', '普通送礼提示', 'user', ['普通送礼提示', dic['msg_text']]]) + self.printer.printlist_append(['join_lottery', '普通送礼提示', 'user', ['普通送礼提示', dic['msg_text']]]) # self.printer.printlist_append(['join_lottery','','debug', [dic, "请联系开发者"]]) return if cmd == 'SYS_MSG': if set(self.dic_bulletin) == set(dic): - pass - #self.printer.printlist_append(['join_lottery', '', 'user', dic['msg']]) + self.printer.printlist_append(['join_lottery', '系统公告', 'user', dic['msg']]) else: try: TV_url = dic['url'] real_roomid = dic['real_roomid'] # url = "https://api.live.bilibili.com/AppSmallTV/index?access_key=&actionKey=appkey&appkey=1d8b6e7d45233436&build=5230003&device=android&mobi_app=android&platform=android&roomid=939654&ts=1521734039&sign=4f85e1d3ce0e1a3acd46fcf9ca3cbeed" - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + \ - '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&roomid=' + str( - real_roomid) + '&ts=' + CurrentTime() - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) + + await asyncio.sleep(random.uniform(3, 5)) - self.api.post_watching_history(self.bilibili.csrf, real_roomid) - result = self.api.check_room_true(real_roomid) + bilibili().post_watching_history(real_roomid) + result = bilibili().check_room_true(real_roomid) if True in result: self.printer.printlist_append(['join_lottery', '', 'debug', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "WARNING:检测到房间", str(real_roomid).center(9), "的钓鱼操作"]) else: - check_url = 'https://api.live.bilibili.com/AppSmallTV/index?' + temp_params + '&sign=' + str( - hash.hexdigest()) print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "检测到房间", str(real_roomid).center(9), "的小电视抽奖") - headers={ - "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36", - } - response = requests.get(check_url, headers=headers) + + response = bilibili().get_giftlist_of_TV(real_roomid) checklen = response.json()['data']['unjoin'] num = len(checklen) while num != 0: @@ -355,24 +278,18 @@ async def parseDanMu(self, messages): await asyncio.sleep(random.uniform(0.5, 1)) resttime = response.json()['data']['unjoin'][j]['dtime'] raffleid = response.json()['data']['unjoin'][j]['id'] - if raffleid not in self.bilibili.TV_raffleid_list: + if bilibili().check_TVlist(raffleid): + + response2 = bilibili().get_gift_of_TV(real_roomid, raffleid) + + bilibili().append_to_TVlist(raffleid, real_roomid) self.printer.printlist_append(['join_lottery', '小电视', 'user', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "参与了房间", str(real_roomid).center(9), "的小电视抽奖"]) - self.bilibili.TV_raffleid_list.append(raffleid) - self.bilibili.TV_roomid_list.append(real_roomid) - self.bilibili.TV_time_list.append(resttime) + # url = "https://api.live.bilibili.com/AppSmallTV/join?access_key=&actionKey=appkey&appkey=1d8b6e7d45233436&build=5230003&device=android&id=41581&mobi_app=android&platform=android&roomid=3566261&ts=1521731305&sign=ae3d61f496c66069bcfd299fe7ce1792" - temp_params = 'access_key=' + self.bilibili.access_key + '&actionKey=' + self.bilibili.actionKey + '&appkey=' + self.bilibili.appkey + '&build=' + self.bilibili.build + '&device=' + self.bilibili.device + '&id=' + str( - raffleid) + '&mobi_app=' + self.bilibili.mobi_app + '&platform=' + self.bilibili.platform + '&roomid=' + str( - real_roomid) + '&ts=' + CurrentTime() - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - true_url = 'http://api.live.bilibili.com/AppSmallTV/join?' + temp_params + '&sign=' + str( - hash.hexdigest()) - response2 = requests.get(true_url, headers=self.bilibili.appheaders) + self.printer.printlist_append( ['join_lottery', '小电视', 'user', "# 小电视道具抽奖状态:", response2.json()['msg']]) break @@ -387,19 +304,18 @@ async def parseDanMu(self, messages): response = requests.get(search_url) roomid = response.json()['result']['live_user'][0]['roomid'] print(roomid) - true_url = 'https://api.live.bilibili.com/lottery/v1/lottery/check?roomid=' + str(roomid) - response1 = requests.get(true_url) + + response1 = bilibili().get_giftlist_of_captain(roomid) print(response1.json()) num = len(response1.json()['data']['guard']) for i in range(0, num): id = response1.json()['data']['guard'][i]['id'] print(id) - join_url = "https://api.live.bilibili.com/lottery/v1/lottery/join" - payload = {"roomid": roomid, "id": id, "type": "guard", "csrf_token": self.bilibili.csrf} - print(payload) - response2 = requests.post(join_url, data=payload, headers=self.bilibili.pcheaders) + response2 = bilibili().get_gift_of_captain(roomid, id) + print(response2.json()) except: - self.printer.printlist_append(['join_lotter', '', 'user', "# 没领取到奖励,请联系开发者"]) - return \ No newline at end of file + self.printer.printlist_append(['join_lotter', '', 'debug', "# 没领取到奖励,请联系开发者"]) + pass + return diff --git a/conf/bilibili.conf b/conf/bilibili.conf index c1aa294..bd7b08c 100644 --- a/conf/bilibili.conf +++ b/conf/bilibili.conf @@ -8,8 +8,8 @@ platform = android app_secret = 560c52ccd288fed045859ed18bffd973 access_key = cookie = -csrf = -uid = +csrf = +uid = _CIDInfoUrl = http://live.bilibili.com/api/player?id=cid: _ChatPort = 2243 _protocolversion = 1 @@ -18,13 +18,7 @@ _writer = 0 connected = False _UserCount = 0 _ChatHost = livecmt-2.bilibili.com -roomid = 3108569 -activity_raffleid_list = -activity_roomid_list = -activity_time_list = -TV_raffleid_list = -TV_roomid_list = -TV_time_list = +roomid = 48499 [dic-pcheaders] Accept = application/json, text/plain, */* @@ -45,6 +39,10 @@ Connection = keep-alive Host = api.live.bilibili.com cookie = +[account] +username = +password = + [dic-giftids_raffle] 117 = 怦然心动 116 = 漫天花雨 @@ -52,5 +50,5 @@ cookie = [types] int = _ChatPort _protocolversion _reader _writer _UserCount roomid bool = connected -list = activity_raffleid_list activity_roomid_list activity_time_list TV_raffleid_list TV_roomid_list TV_time_list + diff --git a/conf/user.conf b/conf/user.conf index 0572747..5682bb4 100644 --- a/conf/user.conf +++ b/conf/user.conf @@ -1,16 +1,14 @@ [platform] -platform = other +platform = others [gift] on/off = 0 -send_to_room = +send_to_room = [coin] on/off = 0 -[account] -username = -password = + [print_control] join_lottery = user diff --git a/configloader.py b/configloader.py index fcccf14..ac4f5b9 100644 --- a/configloader.py +++ b/configloader.py @@ -5,105 +5,87 @@ # "#969696" def hex_to_rgb_percent(hex_str): color = webcolors.hex_to_rgb_percent(hex_str) - # print([float(i.strip('%'))/100.0 for i in color]) + return [float(i.strip('%'))/100.0 for i in color] # "255 255 255" def rgb_to_percent(rgb_str): color = webcolors.rgb_to_rgb_percent(map(int, rgb_str.split())) - # print([float(i.strip('%'))/100.0 for i in color]) + return [float(i.strip('%'))/100.0 for i in color] -class ConfigLoader(): + - def __init__(self, colorfile, userfile, bilibilifile): - self.dic_color = self.load_color(colorfile) - # print(self.dic_color) - - self.dic_user = self.load_user(userfile) - #print(self.dic_user) - self.dic_bilibili = self.load_bilibili(bilibilifile) - # print(self.dic_bilibili) - print("# 初始化完成") - - def load_bilibili(self, file): - cf_bilibili = configparser.ConfigParser() - cf_bilibili.optionxform = str - # cf_bilibili.read(file) - cf_bilibili.read_file(codecs.open(file, "r", "utf8")) - dic_bilibili = cf_bilibili._sections - # print(dic_bilibili) +def load_bilibili(file): + cf_bilibili = configparser.ConfigParser() + cf_bilibili.optionxform = str + + cf_bilibili.read_file(codecs.open(file, "r", "utf8")) + dic_bilibili = cf_bilibili._sections + - dic_nomalised_bilibili = dic_bilibili['normal'].copy() - # print(dic_nomalised_bilibili) + dic_nomalised_bilibili = dic_bilibili['normal'].copy() + dic_nomalised_bilibili['account'] = dic_bilibili['account'] + + + dic_bilibili_type = dic_bilibili['types'] + # str to int + for i in dic_bilibili_type['int'].split(): - dic_bilibili_type = dic_bilibili['types'] - # str to int - for i in dic_bilibili_type['int'].split(): - # print(dic_bilibili['other'][i]) - dic_nomalised_bilibili[i] = int(dic_bilibili['normal'][i]) + dic_nomalised_bilibili[i] = int(dic_bilibili['normal'][i]) - # str to bool - for i in dic_bilibili_type['bool'].split(): - # print(i) - dic_nomalised_bilibili[i] = True if dic_bilibili['normal'][i] == 'True' else False + # str to bool + for i in dic_bilibili_type['bool'].split(): + + dic_nomalised_bilibili[i] = True if dic_bilibili['normal'][i] == 'True' else False - # str to bool - for i in dic_bilibili_type['list'].split(): - # print(i) - dic_nomalised_bilibili[i] = [] - # print(dic_nomalised_bilibili) + # str to dic - for i in dic_bilibili.keys(): - # print(i) - if i[0:3] == 'dic': - dic_nomalised_bilibili[i[4:]] = dic_bilibili[i] + for i in dic_bilibili.keys(): + # print(i) + if i[0:3] == 'dic': + dic_nomalised_bilibili[i[4:]] = dic_bilibili[i] - # print(dic_nomalised_bilibili['connected']) - # print(dic_nomalised_bilibili['pcheaders']['Host']) - return dic_nomalised_bilibili + + return dic_nomalised_bilibili - def load_color(self, file): - cf_color = configparser.ConfigParser() - # cf_color.read(file) - cf_color.read_file(codecs.open(file, "r", "utf8")) +def load_color(file): + cf_color = configparser.ConfigParser() + + cf_color.read_file(codecs.open(file, "r", "utf8")) - dic_color = cf_color._sections - for i in dic_color.values(): - for j in i.keys(): - # print(i[j]) - if i[j][0] == '#': - i[j] = hex_to_rgb_percent(i[j]) - else: - i[j] = rgb_to_percent(i[j]) + dic_color = cf_color._sections + for i in dic_color.values(): + for j in i.keys(): + if i[j][0] == '#': + i[j] = hex_to_rgb_percent(i[j]) + else: + i[j] = rgb_to_percent(i[j]) - # print(dic_color['user-level']['ul0']) - return dic_color + return dic_color - def load_user(self, file): - cf_user = configparser.ConfigParser() - #cf_user.read(file) - cf_user.read_file(codecs.open(file, "r", "utf8")) - # print(cf_user._sections['platform']['platform']) - dic_user = cf_user._sections - dictionary ={ - 'True':True, - 'False': False, - 'user': 0, - 'debug': 1 - } +def load_user(file): + cf_user = configparser.ConfigParser() + cf_user.read_file(codecs.open(file, "r", "utf8")) + dic_user = cf_user._sections + dictionary ={ + 'True':True, + 'False': False, + 'user': 0, + 'debug': 1 + } - for i in dic_user['print_control'].keys(): - dic_user['print_control'][i] = dictionary[dic_user['print_control'][i]] + for i in dic_user['print_control'].keys(): + dic_user['print_control'][i] = dictionary[dic_user['print_control'][i]] - return dic_user + return dic_user -# configloader = ConfigLoader("color.conf", "user.conf", "bilibili.conf") + diff --git a/connect.py b/connect.py index 23d1948..43ecf4d 100644 --- a/connect.py +++ b/connect.py @@ -1,35 +1,32 @@ import asyncio from bilibiliCilent import bilibiliClient -from bilibili import bilibili from printer import Printer class connect(): tasks = {} - def __init__(self, printer,bilibili, api): + def __init__(self, printer): self.printer = printer - self.bilibili = bilibili - self.api = api + self.task = None async def connect(self): - danmuji = bilibiliClient(self.printer, self.bilibili, self.api) + danmuji = bilibiliClient(self.printer) task1 = asyncio.ensure_future(danmuji.connectServer()) task2 = asyncio.ensure_future(danmuji.HeartbeatLoop()) - self.tasks[self.bilibili.roomid] = [task1, task2] + self.tasks = [task1, task2] while True: await asyncio.sleep(5) - for roomid in self.tasks: - item = self.tasks[roomid] - task1 = item[0] - task2 = item[1] - if task1.done() == True or task2.done() == True: - if task1.done() == False: - task1.cancel() - if task2.done() == False: - task2.cancel() - print('# 重新连接直播间 %s' % roomid) - danmuji = bilibiliClient(self.printer, self.bilibili, self.api) - task11 = asyncio.ensure_future(danmuji.connectServer()) - task22 = asyncio.ensure_future(danmuji.HeartbeatLoop()) - self.tasks[roomid] = [task11, task22] + task1 = self.tasks[0] + task2 = self.tasks[1] + if task1.done() == True or task2.done() == True: + print('Connect Fail') + if task1.done() == False: + task1.cancel() + if task2.done() == False: + task2.cancel() + print('# 重新连接直播间') + danmuji = bilibiliClient(self.printer) + task11 = asyncio.ensure_future(danmuji.connectServer()) + task22 = asyncio.ensure_future(danmuji.HeartbeatLoop()) + self.tasks = [task11, task22] diff --git a/login.py b/login.py deleted file mode 100644 index 373c3b3..0000000 --- a/login.py +++ /dev/null @@ -1,94 +0,0 @@ -import requests -import hashlib -import rsa -import base64 -import configparser -from urllib import parse -import time -import codecs - - -class Login(): - def __init__(self, bilibili, configloader): - self.bilibili = bilibili - self.configloader = configloader - - def GetHash(self): - url = 'https://passport.bilibili.com/api/oauth2/getKey' - temp_params = 'appkey=' + self.bilibili.appkey + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(temp_params.encode('utf-8')) - sign = hash.hexdigest() - params = {'appkey': self.bilibili.appkey, 'sign': sign} - response = requests.post(url, data=params) - value = response.json()['data'] - return value - - def success(self): - - if self.configloader.dic_user['account']['username']: - username = str(self.configloader.dic_user['account']['username']) - password = str(self.configloader.dic_user['account']['password']) - else: - username = input("输入用户名:") - password = input("输入密码:") - config = configparser.ConfigParser() - config.read_file(codecs.open("conf/user.conf", "r", "utf8")) - config.set('account','username',username) - config.set('account','password',password) - config.write(codecs.open("conf/user.conf", "w+","utf8")) - if username != "": - value = self.GetHash() - 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) - # url = 'https://passport.bilibili.com/api/oauth2/login' //旧接口 - url = "https://passport.bilibili.com/api/v2/oauth2/login" - temp_params = 'appkey=' + self.bilibili.appkey + '&password=' + password + '&username=' + username - params = temp_params + self.bilibili.app_secret - hash = hashlib.md5() - hash.update(params.encode('utf-8')) - sign = hash.hexdigest() - headers = {"Content-type": "application/x-www-form-urlencoded"} - payload = "appkey=" + self.bilibili.appkey + "&password=" + password + "&username=" + username + "&sign=" + sign - response = requests.post(url, data=payload, headers=headers) - try: - access_key = response.json()['data']['token_info']['access_token'] - cookie = (response.json()['data']['cookie_info']['cookies']) - cookie_format = "" - for i in range(0, len(cookie)): - cookie_format = cookie_format + cookie[i]['name'] + "=" + cookie[i]['value'] + ";" - self.bilibili.csrf = cookie[0]['value'] - self.bilibili.access_key = access_key - self.bilibili.cookie = cookie_format - self.bilibili.uid = cookie[1]['value'] - self.bilibili.pcheaders = { - 'Accept': 'application/json, text/plain, */*', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', - 'Accept-Language': 'zh-CN,zh;q=0.9', - 'accept-encoding': 'gzip, deflate', - 'Host': 'api.live.bilibili.com', - 'cookie': cookie_format - } - self.bilibili.appheaders = { - "User-Agent": "bili-universal/6570 CFNetwork/894 Darwin/17.4.0", - "Accept-encoding": "gzip", - "Buvid": "000ce0b9b9b4e342ad4f421bcae5e0ce", - "Display-ID": "146771405-1521008435", - "Accept-Language": "zh-CN", - "Accept": "text/html,application/xhtml+xml,*/*;q=0.8", - "Connection": "keep-alive", - "Host": "api.live.bilibili.com", - 'cookie': cookie_format - } - - print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "登陆成功") - except: - print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "登录失败,错误信息为:",response.json()['message']) - - def return_bilibili(self): - return self.bilibili - diff --git a/printer.py b/printer.py index 0835a54..bedf359 100644 --- a/printer.py +++ b/printer.py @@ -4,6 +4,8 @@ pass import webcolors import asyncio +import os +import configloader # "#969696" def hex_to_rgb_percent(hex_str): @@ -20,8 +22,12 @@ def level(str): class Printer(): - def __init__(self, configloader): - self.configloader = configloader + def __init__(self): + fileDir = os.path.dirname(os.path.realpath('__file__')) + file_color = fileDir + "/conf/color.conf" + self.dic_color = configloader.load_color(file_color) + file_user = fileDir + "/conf/user.conf" + self.dic_user = configloader.load_user(file_user) self.printlist=[] def concole_print(self, msg, color=[]): if color: @@ -35,7 +41,7 @@ def concole_print(self, msg, color=[]): def printlist_append(self, dic): tag = False - dic_printcontrol = self.configloader.dic_user['print_control'] + dic_printcontrol = self.dic_user['print_control'] if dic[0] in dic_printcontrol.keys(): if dic_printcontrol[dic[0]] >= level(dic[2]): tag = True @@ -61,7 +67,7 @@ async def clean_printlist(self): while True: for i in self.printlist: if i[0] == 0: - if (self.configloader.dic_user['platform']['platform'] == 'ios_pythonista'): + if (self.dic_user['platform']['platform'] == 'ios_pythonista'): self.concole_print(i[1], i[2]) else: self.concole_print(i[1]) @@ -73,7 +79,7 @@ async def clean_printlist(self): else: print(' '.join(i)) self.printlist=[] - await asyncio.sleep(0.5) + await asyncio.sleep(0.1) @@ -90,25 +96,22 @@ def print_danmu_msg(self, dic): else: if info[2][3] == 1: if info[2][4] == 0: - # self.rgbprint(self.configloader.dic_color['others']['vip'], '爷') list_msg.append('爷 ') - list_color.append(self.configloader.dic_color['others']['vip']) + list_color.append(self.dic_color['others']['vip']) else: - # self.rgbprint(self.configloader.dic_color['others']['svip'], '爷') list_msg.append('爷 ') - list_color.append(self.configloader.dic_color['others']['svip']) + list_color.append(self.dic_color['others']['svip']) if info[2][2] == 1: - # self.rgbprint(self.configloader.dic_color['others']['admin'], '房管') list_msg.append('房管 ') - list_color.append(self.configloader.dic_color['others']['admin']) + list_color.append(self.dic_color['others']['admin']) # 勋章 if info[3]: - list_color.append(self.configloader.dic_color['fans-level']['fl' + str(info[3][0])]) + list_color.append(self.dic_color['fans-level']['fl' + str(info[3][0])]) list_msg.append(info[3][1] + '|' + str(info[3][0]) + ' ') # 等级 if not info[5]: - list_color.append(self.configloader.dic_color['user-level']['ul' + str(info[4][0])]) + list_color.append(self.dic_color['user-level']['ul' + str(info[4][0])]) list_msg.append('UL' + str(info[4][0]) + ' ') try: if info[2][7] != '': @@ -127,10 +130,7 @@ def print_danmu_msg(self, dic): list_color.append([]) return list_msg, list_color - # if (self.configloader.dic_user['platform']['platform'] == 'ios_pythonista'): - # self.concole_print(list_msg, list_color) - # else: - # self.concole_print(list_msg) + diff --git a/run.py b/run.py index a720cee..7f7fde7 100644 --- a/run.py +++ b/run.py @@ -2,28 +2,33 @@ from Silver import Silver from LotteryResult import LotteryResult from Tasks import Tasks -from login import Login from connect import connect import asyncio -from API import API -from configloader import ConfigLoader + from printer import Printer -from bilibili import bilibili - -cf = ConfigLoader("conf/color.conf", "conf/user.conf", "conf/bilibili.conf") -printer = Printer(cf) -bilibili = bilibili(cf) -login = Login(bilibili,cf) -login.success() - -bilibili = login.return_bilibili() -api = API(bilibili) -api.user_info() -task = OnlineHeart(bilibili) -task1 = Silver(bilibili) -task2 = Tasks(bilibili,cf,api) -task3 = LotteryResult(bilibili) -task4 = connect(printer, bilibili, api) +import bilibili +import os + +# fileDir = os.path.dirname(os.path.realpath('__file__')) +# print(fileDir) +# file_color = fileDir + "/conf/color.conf" + + + +printer = Printer() + +bilibili = bilibili.bilibili() + +bilibili.login() + + +bilibili.user_info() +bilibili.get_bag_list() +task = OnlineHeart() +task1 = Silver() +task2 = Tasks() +task3 = LotteryResult() +task4 = connect(printer) tasks = [ task.run(),