各种适配新Android Api,修复各种Bug

This commit is contained in:
Jerry Yan 2019-01-31 23:05:48 +08:00
parent a1cfc9b914
commit 81f730ea68
6 changed files with 83 additions and 69 deletions

14
Gift.py
View File

@ -16,7 +16,11 @@ class Gift:
def parse(self, json): def parse(self, json):
self.user = User(json) self.user = User(json)
if "extra" in json: if "common" in json and json["common"] is not None:
if Gift.roomID != int(json["common"]["room_id"]):
Gift.roomID = int(json["common"]["room_id"])
self.update()
if "extra" in json and json["extra"] is not None:
if "present_info" in json["extra"] and json["extra"]['present_info'] is not None: if "present_info" in json["extra"] and json["extra"]['present_info'] is not None:
self.ID = int(json["extra"]['present_info']['id']) self.ID = int(json["extra"]['present_info']['id'])
self.count = json["extra"]['present_info']['repeat_count'] self.count = json["extra"]['present_info']['repeat_count']
@ -25,11 +29,11 @@ class Gift:
self.count = json["extra"]['present_end_info']['count'] self.count = json["extra"]['present_end_info']['count']
if self.ID in self.giftList: if self.ID in self.giftList:
self.amount = self.giftList[self.ID]["Price"] * self.count self.amount = self.giftList[self.ID]["Price"] * self.count
else:
self.update()
@staticmethod def update(self):
def update(roomID): p = requests.get("https://i.snssdk.com/videolive/gift/get_gift_list?room_id={roomID}".format(roomID = self.roomID))
Gift.roomID = roomID
p = requests.get("https://i.snssdk.com/videolive/gift/get_gift_list?room_id={roomID}".format(roomID= roomID))
d = p.json() d = p.json()
if "gift_info" not in d: if "gift_info" not in d:
print("错误:礼物更新失败") print("错误:礼物更新失败")

View File

@ -48,10 +48,11 @@ class Lottery:
if self.isFinished: if self.isFinished:
ret = "恭喜以下中奖用户:\n" ret = "恭喜以下中奖用户:\n"
for i in self.luckyUsers: for i in self.luckyUsers:
ret += "\t{} {}\n".format(i,self.prizeName) ret += "> {} {}\n".format(i,self.prizeName)
ret += "\t参与人数:{}".format(self.joinedUserCount) ret += "> 参与人数:{}".format(self.joinedUserCount)
return ret return ret
elif self.isActive: elif self.isActive:
return "正在抽奖中。。。参与人数:{}".format(self.joinedUserCount) return "正在抽奖中。。。\n" \
"> 参与人数:{}".format(self.joinedUserCount)
else: else:
return "抽奖已失效" return "抽奖已失效"

View File

@ -23,10 +23,14 @@ class User:
self.type = json["extra"]["user_room_auth_status"]["user_type"] self.type = json["extra"]["user_room_auth_status"]["user_type"]
self.block = json["extra"]["user_room_auth_status"]["is_block"] self.block = json["extra"]["user_room_auth_status"]["is_block"]
self.mute = json["extra"]["user_room_auth_status"]["is_silence"] self.mute = json["extra"]["user_room_auth_status"]["is_silence"]
elif "room" in json: elif "room" in json and json["room"] is not None:
if "user_info" in json["room"]: if "user_info" in json["room"] and json["room"]["user_info"] is not None:
self.ID = json["room"]['user_info']['user_id'] self.ID = json["room"]['user_info']['user_id']
self.name = json["room"]['user_info']['name'] self.name = json["room"]['user_info']['name']
elif "anchor" in json and json["anchor"] is not None:
if "user_info" in json["anchor"] and json["anchor"]['user_info'] is not None:
self.ID = json["anchor"]['user_info']['user_id']
self.name = json["anchor"]['user_info']['name']
if self.type is None: if self.type is None:
self.type = 0 self.type = 0
if isinstance(self.level, str): if isinstance(self.level, str):

View File

@ -31,7 +31,9 @@ def readInput(caption, default, timeout: int = 5):
msvcrt.putch(b"\b") msvcrt.putch(b"\b")
if len(input) == 0: if len(input) == 0:
start_time = time.time() start_time = time.time()
elif 32 <= ord(chr) <= 126: # space_char elif 32 > ord(chr) or 255 > ord(chr) > 126: # space_char
continue
else:
input += chr.decode("utf8") input += chr.decode("utf8")
if len(input) == 0 and (time.time() - start_time) > timeout: if len(input) == 0 and (time.time() - start_time) > timeout:
break break
@ -119,7 +121,7 @@ class WinMain(Api):
def onJoin(self, user: User): def onJoin(self, user: User):
set_cmd_text_color(BACKGROUND_WHITE | FOREGROUND_BLACK) set_cmd_text_color(BACKGROUND_WHITE | FOREGROUND_BLACK)
print("感谢", user, "加入了粉丝团") print("欢迎", user, "加入了粉丝团")
resetColor() resetColor()
def onSubscribe(self, user: User): def onSubscribe(self, user: User):
@ -171,24 +173,14 @@ def warning(*args):
if __name__ == "__main__": if __name__ == "__main__":
room = 97621754276 # 永恒 name = "永恒de草薙"
# room = 75366565294
# room = 83940182312 #Dae
resetColor() resetColor()
print("西瓜直播弹幕助手 by JerryYan") print("西瓜直播弹幕助手 by JerryYan")
if len(sys.argv) > 1: if len(sys.argv) > 1:
if sys.argv[-1] == "a": name = sys.argv[1]
SHOW_ALL = True
try:
room = int(sys.argv[1])
except:
pass
else: else:
try: name = readInput("请输入主播用户名(请用拼音字母),默认为", name, 3)
room = int(readInput("请输入房间号,默认为永恒的房间号", room, 3)) api = WinMain(name)
except ValueError:
pass
api = WinMain.findRoomByUserId(room)
print("进入", api.roomLiver, "的直播间") print("进入", api.roomLiver, "的直播间")
if not api.isValidRoom: if not api.isValidRoom:
input("房间不存在") input("房间不存在")
@ -198,7 +190,10 @@ if __name__ == "__main__":
while True: while True:
if api.isLive: if api.isLive:
os.system("title {}".format(api.getTitle())) os.system("title {}".format(api.getTitle()))
try:
api.getDanmaku() api.getDanmaku()
except Exception as e:
print(e.__str__())
time.sleep(1) time.sleep(1)
else: else:
set_cmd_text_color(FOREGROUND_RED) set_cmd_text_color(FOREGROUND_RED)

43
api.py
View File

@ -17,6 +17,7 @@ class XiGuaLiveApi:
isLive: bool = False isLive: bool = False
isValidRoom: bool = False isValidRoom: bool = False
_rawRoomInfo = {} _rawRoomInfo = {}
name: str = ""
roomID: int = 0 roomID: int = 0
roomTitle: str = "" roomTitle: str = ""
roomLiver: User = None roomLiver: User = None
@ -25,10 +26,9 @@ class XiGuaLiveApi:
_updRoomCount:int = 0 _updRoomCount:int = 0
lottery:Lottery = None lottery:Lottery = None
def __init__(self, roomId: int = 6651493149011086094): def __init__(self, name: str = "永恒de草薙"):
self.roomID = roomId self.name = name
self.updRoomInfo() self.updRoomInfo()
Gift.update(self.roomID)
def _updateRoomInfo(self, json): def _updateRoomInfo(self, json):
if "extra" in json: if "extra" in json:
@ -63,7 +63,7 @@ class XiGuaLiveApi:
print("消息 :", user, "关注了主播") print("消息 :", user, "关注了主播")
def onJoin(self, user: User): def onJoin(self, user: User):
print("感谢", user, "加入了粉丝团") print("欢迎", user, "加入了粉丝团")
def onMessage(self, msg: str): def onMessage(self, msg: str):
print("消息 :", msg) print("消息 :", msg)
@ -78,6 +78,7 @@ class XiGuaLiveApi:
print("中奖消息 :", i) print("中奖消息 :", i)
def updRoomInfo(self): def updRoomInfo(self):
if self.isLive:
p = s.post("https://i.snssdk.com/videolive/room/enter?version_code=730" p = s.post("https://i.snssdk.com/videolive/room/enter?version_code=730"
"&device_platform=android", "&device_platform=android",
data="room_id={roomID}&version_code=730" data="room_id={roomID}&version_code=730"
@ -99,6 +100,23 @@ class XiGuaLiveApi:
if l.isActive: if l.isActive:
self.lottery = l self.lottery = l
return True return True
else:
p = s.get("https://security.snssdk.com/video/app/search/live/?version_code=730&device_platform=android"
"&format=json&keyword={}".format(self.name))
d = p.json()
if "data" in d:
for i in d["data"]:
if i["block_type"] != 0:
continue
if len(i["cells"]) == 0:
return
self.isLive = i["cells"][0]["anchor"]["user_info"]["is_living"]
self.roomID = int(i["cells"][0]["anchor"]["room_id"])
self.roomLiver = User(i["cells"][0])
if self.isLive:
return self.updRoomInfo()
else:
return False
@staticmethod @staticmethod
def findRoomByUserId(userId:int): def findRoomByUserId(userId:int):
@ -119,7 +137,7 @@ class XiGuaLiveApi:
d = p.json() d = p.json()
if "data" in d: if "data" in d:
for i in d["data"]: for i in d["data"]:
if i["block_type"] != 2: if i["block_type"] != 0:
continue continue
for _i in i["cells"]: for _i in i["cells"]:
ret.append(_i["room"]) ret.append(_i["room"])
@ -170,7 +188,7 @@ class XiGuaLiveApi:
else: else:
pass pass
self._updRoomCount += 1 self._updRoomCount += 1
if self._updRoomCount > 30 or len(d['data']) == 0: if self._updRoomCount > 120 or len(d['data']) == 0:
if self.lottery is not None: if self.lottery is not None:
self.lottery.checkFinished() self.lottery.checkFinished()
if self.lottery.isFinished: if self.lottery.isFinished:
@ -182,18 +200,13 @@ class XiGuaLiveApi:
if __name__ == "__main__": if __name__ == "__main__":
room = 97621754276 # 永恒 name = "永恒de草薙"
# room = 75366565294 if len(sys.argv) > 2:
# room = 83940182312 #Dae
if len(sys.argv) > 1:
if sys.argv[-1] == "d": if sys.argv[-1] == "d":
DEBUG = True DEBUG = True
try: name = sys.argv[1]
room = int(sys.argv[1])
except ValueError:
pass
print("西瓜直播弹幕助手 by JerryYan") print("西瓜直播弹幕助手 by JerryYan")
api = XiGuaLiveApi.findRoomByUserId(room) api = XiGuaLiveApi(name)
if not api.isValidRoom: if not api.isValidRoom:
print(api.roomID) print(api.roomID)
input("房间不存在") input("房间不存在")

View File

@ -135,18 +135,15 @@ b = Bilibili()
b.login(config["b_u"], config["b_p"]) b.login(config["b_u"], config["b_p"])
if __name__ == "__main__": if __name__ == "__main__":
room = 97621754276 # 永恒 name = "永恒de草薙"
# room = 75366565294 # room = 75366565294
# room = 83940182312 #Dae # room = 83940182312 #Dae
# room = 5947850784 #⑦ # room = 5947850784 #⑦
# room = 58649240617 #戏 # room = 58649240617 #戏
if len(sys.argv) > 1: if len(sys.argv) > 1:
try: name = sys.argv[1]
room = int(sys.argv[1])
except ValueError:
pass
print("西瓜直播录播助手 by JerryYan") print("西瓜直播录播助手 by JerryYan")
api = downloader.findRoomByUserId(room) api = downloader(name)
print("进入", api.roomLiver, "的直播间") print("进入", api.roomLiver, "的直播间")
if not api.isValidRoom: if not api.isValidRoom:
input("房间不存在") input("房间不存在")