Пример #1
0
 def getDanmaku(self):
     """
     获取弹幕
     """
     self.updRoomInfo()
     _formatData = {"TIMESTAMP": time.time() * 1000, "roomId": self.roomID}
     _COMMON = COMMON_GET_PARAM.format_map(_formatData)
     _formatData['COMMON'] = _COMMON
     _formatData['WEBCAST'] = WEBCAST_GET_PARAMS
     _url = DANMAKU_GET_API.format_map(_formatData)
     p = self.s.post(
         _url,
         data="room_id={roomId}&fetch_rule=0&cursor={cursor}&"
         "resp_content_type=protobuf&live_id=3&user_id=0&identity=audience&"
         "last_rtt=85&internal_ext={ext}".format_map({
             "roomId": self.roomID,
             "cursor": self._cursor,
             "ext": self._ext
         }),
         headers={"Content-Type": "application/x-www-form-urlencoded"})
     if p.status_code != 200:
         return
     data = XiguaLive()
     data.ParseFromString(p.content)
     self._cursor = data.cursor
     self._ext = data.internal_ext
     for _each in data.data:
         if _each.method == "WebcastGiftMessage":
             _gift = Gift(_each.raw)
             if _gift.isAnimate() or _gift.isFinished:
                 self.onPresentEnd(_gift)
             else:
                 self.onPresent(_gift)
         elif _each.method == "WebcastChatMessage":
             _chat = Chat(_each.raw)
             self.onChat(_chat)
         elif _each.method == "WebcastControlMessage":
             # 下播的时候会有个这个
             self.onLeave(None)
         elif _each.method == "WebcastSocialMessage":
             _socialMessage = SocialMessage()
             _socialMessage.ParseFromString(_each.raw)
             _user = User(_socialMessage.user)
             self.onSubscribe(_user)
         elif _each.method == "WebcastFansclubMessage":
             _fansClubMessage = FansClubMessage()
             _fansClubMessage.ParseFromString(_each.raw)
             # 升级是1,加入是2
             if _fansClubMessage.type == 2:
                 _user = User(_fansClubMessage.user)
                 self.onJoin(_user)
             else:
                 self.onMessage(_fansClubMessage.content)
         else:
             pass
Пример #2
0
 def __init__(self, name=None):
     """
     Api类
     Init Function
     :param name: class:str|User: 主播名
     """
     if name is None:
         name = "永恒de草薙"
     self.broadcaster = None
     self.isValidUser = False
     self.name = str(name)
     if type(name) == User:
         self.broadcaster = name
         self.name = name.name
     elif str(name).isdigit():
         self.broadcaster = User()
         self.isValidUser = True
         self.broadcaster.ID = int(name)
     else:
         self.name = str(name)
     self.isLive = False
     self._rawRoomInfo = {}
     self.roomID = 0
     self.roomPopularity = 0
     self.s = requests.session()
     self.s.headers.update(COMMON_HEADERS)
     self._updRoomAt = datetime.fromtimestamp(0)
     self.updRoomInfo()
     self._ext = ""
     self._cursor = "0"
Пример #3
0
 def _forceSearchUser(self):
     """
     搜索主播名
     :return:
     """
     _formatData = {"TIMESTAMP": time.time() * 1000, "keyword": self.name}
     _COMMON = COMMON_GET_PARAM.format_map(_formatData)
     _formatData['COMMON'] = _COMMON
     _url = SEARCH_USER_API.format_map(_formatData)
     d = self.getJson(_url)
     if d is None:
         print("搜索接口请求失败")
         return False
     self.broadcaster = None
     self.isValidUser = False
     if "data" in d and d["data"] is not None:
         for i in d["data"]:
             if self.broadcaster is not None:
                 break
             if i["block_type"] != 2:
                 continue
             if "cells" not in i or len(i["cells"]) == 0:
                 break
             for _j in i["cells"]:
                 if "room" in _j:
                     _user = User(_j["room"])
                     self.roomID = _j["room"]["room_id"]
                     self.isLive = _j["room"]["is_living"]
                     if self._checkUsernameIsMatched(_user):
                         self.isValidUser = True
                         self.broadcaster = _user
                         break
     self._updRoomAt = datetime.now()
     return self._updateUserInfo()
Пример #4
0
 def _updateRoomOnly(self):
     """
     仅更新房间,不重新获取信息
     :return:
     """
     try:
         p = s.post("https://i.snssdk.com/videolive/room/enter?version_code=730"
                    "&device_platform=android",
                    data="room_id={roomID}&version_code=730"
                         "&device_platform=android".format(roomID=self.roomID),
                    headers={"Content-Type": "application/x-www-form-urlencoded"})
         d = p.json()
     except Exception as e:
         self.apiChangedError("更新房间接口错误", e.__str__())
         return False
     self.isValidRoom = d["base_resp"]["status_code"] == 0
     if d["base_resp"]["status_code"] != 0:
         self.apiChangedError("更新房间信息接口返回非0状态值", d)
         return False
     if "room" not in d and d["room"] is None:
         self.apiChangedError("Api发生改变,请及时联系我", d)
         return False
     self.roomLiver = User(d)
     if not self._checkUsernameIsMatched():
         self.isLive = False
         return False
     self._rawRoomInfo = d["room"]
     self.isLive = d["room"]["status"] == 2
     self.roomTitle = d["room"]["title"]
     self.roomPopularity = d["room"]["user_count"]
     l = Lottery(d)
     if l.isActive:
         self.lottery = l
     return True
Пример #5
0
 def _forceSearchUser(self):
     """
     搜索主播名
     :return:
     """
     try:
         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()
     except json.decoder.JSONDecodeError as e:
         self.apiChangedError("搜索接口错误", e.__str__())
         return
     if "data" in d and d["data"] is not None:
         for i in d["data"]:
             if i["block_type"] != 0:
                 continue
             if "cells" not in i or len(i["cells"]) == 0:
                 return
             self.isValidRoom = True
             if "is_living" in i["cells"][0]["anchor"]["user_info"]:
                 self.isLive = i["cells"][0]["anchor"]["user_info"]["is_living"]
             else:
                 self.isLive = False
             if "room_id" in i["cells"][0]["anchor"]:
                 self.roomID = int(i["cells"][0]["anchor"]["room_id"])
             else:
                 self.isLive = False
             self.roomLiver = User(i["cells"][0])
     if self.isLive:
         return self._updateRoomOnly()
     else:
         return False
Пример #6
0
 def _updateUserInfo(self):
     """
     获取用户信息
     :return:
     """
     if self.broadcaster is None:
         self.isValidUser = False
         return False
     self.isLive = False
     _formatData = {
         "TIMESTAMP": time.time() * 1000,
         "userId": self.broadcaster.ID
     }
     _COMMON = COMMON_GET_PARAM.format_map(_formatData)
     _formatData['COMMON'] = _COMMON
     _url = USER_INFO_API.format_map(_formatData)
     d = self.getJson(_url)
     if d is None:
         print("获取用户信息失败")
         return False
     self.isValidUser = d["status"] == 0
     _d = d.get('data', {})
     if "user_home_info" not in _d and _d['user_home_info'][
             'user_info'] is None:
         self.apiChangedError("Api发生改变,请及时联系我", d)
         return False
     self._updRoomAt = datetime.now()
     self.broadcaster = User(_d['user_home_info'])
     if not self._checkUsernameIsMatched():
         self.isLive = False
         return False
     self.isLive = 'user_live_info_list' in _d
     if self.isLive and len(_d['user_live_info_list']) != 0:
         # 既然有长度,默认个0应该没事
         self._rawRoomInfo = _d['user_live_info_list'][0]['live_info']
     else:
         self.isLive = False
     if self.isLive:
         self.roomID = self._rawRoomInfo['room_id']
         return self._getRoomInfo(True)
     return self.isLive
Пример #7
0
 def _updateUserInfo(self):
     """
     获取用户信息
     :return:
     """
     if self.broadcaster is None:
         self.isValidUser = False
         return False
     _formatData = {
         "TIMESTAMP": time.time() * 1000,
         "userId": self.broadcaster.ID
     }
     _COMMON = COMMON_GET_PARAM.format_map(_formatData)
     _formatData['COMMON'] = _COMMON
     _url = USER_INFO_API.format_map(_formatData)
     d = self.getJson(_url)
     if d is None:
         print("获取用户信息失败")
         return False
     self.isValidUser = d["status"] == 0
     if "user_info" not in d and d["user_info"] is None:
         self.apiChangedError("Api发生改变,请及时联系我", d)
         return False
     self._updRoomAt = datetime.now()
     self.broadcaster = User(d)
     if not self._checkUsernameIsMatched():
         self.isLive = False
         return False
     self.isLive = d["user_info"]["is_living"]
     if d["user_info"]['live_info'] is None:
         if d["live_data"] is None:
             self.isLive = False
         else:
             self._rawRoomInfo = d["live_data"]['live_info']
     else:
         self._rawRoomInfo = d["user_info"]['live_info']
     if self.isLive:
         self.roomID = self._rawRoomInfo['room_id']
         return self._getRoomInfo(True)
     return self.isLive
Пример #8
0
 def getDanmaku(self):
     """
     获取弹幕
     """
     if not self.isValidRoom:
         self.updRoomInfo()
         return
     p = s.get(
         "https://i.snssdk.com/videolive/im/get_msg?cursor={cursor}&room_id={roomID}"
         "&version_code=730&device_platform=android".format(
             roomID=self.roomID, cursor=self._cursor))
     d = p.json()
     if "data" not in d or "extra" not in d or "cursor" not in d["extra"]:
         if DEBUG:
             print(d)
         if "base_resp" in d:
             if d["base_resp"]["status_code"] != 10038:
                 print(d["base_resp"]["status_message"])
         else:
             self.apiChangedError("数据结构改变,请与我联系")
         return
     else:
         self._cursor = d["extra"]["cursor"]
         if DEBUG:
             print("Cursor", self._cursor)
     for i in d['data']:
         if DEBUG:
             print(i)
         if "common" not in i and "method" not in i["common"]:
             continue
         if i["common"]['method'] == "VideoLivePresentMessage":
             self.onPresent(Gift(i))
         elif i["common"]['method'] == "VideoLivePresentEndTipMessage":
             self.onPresentEnd(Gift(i))
         elif i["common"]['method'] == "VideoLiveRoomAdMessage":
             self.onAd(i)
         elif i["common"]['method'] == "VideoLiveChatMessage":
             self.onChat(Chat(i, self.lottery))
         elif i["common"]['method'] == "VideoLiveMemberMessage":
             self._updateRoomInfo(i)
             self.onEnter(MemberMsg(i))
         elif i["common"]['method'] == "VideoLiveSocialMessage":
             self.onSubscribe(User(i))
         elif i["common"]['method'] == "VideoLiveJoinDiscipulusMessage":
             self.onJoin(User(i))
         elif i["common"]['method'] == "VideoLiveControlMessage":
             print("消息:", "主播离开一小会")
             # 这个消息代表主播下播了,直接更新房间信息
             self.updRoomInfo()
         elif i["common"]['method'] == "VideoLiveDiggMessage":
             self.onLike(User(i))
         else:
             pass
         if self.lottery is None or self.lottery.ID == 0:
             self.lottery = Lottery(i)
     self._updRoomCount += 1
     # 更新抽奖信息
     if self.lottery is not None and self.lottery.ID != 0:
         self.lottery.update()
         if self.lottery.isFinished:
             self.onLottery(self.lottery)
             self.lottery = None
     # 2分钟自动更新下房间信息
     if self._updRoomCount > 120 or len(d['data']) == 0:
         self.updRoomInfo()
         self._updRoomCount = 0
         return
Пример #9
0
 def updRoomInfo(self):
     """
     更新房间信息(可能写的很垃圾)
     :return:
     """
     if self.isLive:
         try:
             p = s.post(
                 "https://i.snssdk.com/videolive/room/enter?version_code=730"
                 "&device_platform=android",
                 data="room_id={roomID}&version_code=730"
                 "&device_platform=android".format(roomID=self.roomID),
                 headers={
                     "Content-Type": "application/x-www-form-urlencoded"
                 })
             d = p.json()
         except Exception as e:
             if DEBUG:
                 print("ReqError@UpdRoomInfo")
                 print(e.__str__())
                 if p:
                     print(p.status_code)
                     print(p.text)
             return False
         self.isValidRoom = d["base_resp"]["status_code"] == 0
         if d["base_resp"]["status_code"] != 0:
             if DEBUG:
                 print("CodeIsnot0@UpdRoomInfo")
                 print(d)
             return False
         if "room" not in d and d["room"] is None:
             self.apiChangedError("Api发生改变,请及时联系我", d)
             return False
         self._rawRoomInfo = d["room"]
         self.isLive = d["room"]["status"] == 2
         self.roomLiver = User(d)
         self.roomTitle = d["room"]["title"]
         self.roomPopularity = d["room"]["user_count"]
         l = Lottery(d)
         if l.isActive:
             self.lottery = l
         return True
     else:
         try:
             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()
         except json.decoder.JSONDecodeError as e:
             if DEBUG:
                 print(e.__str__())
                 if p:
                     print(p.status_code)
                     print(p.text)
             return
         if "data" in d and d["data"] is not None:
             for i in d["data"]:
                 if i["block_type"] != 0:
                     continue
                 if "cells" not in i or len(i["cells"]) == 0:
                     return
                 self.isValidRoom = True
                 if "is_living" in i["cells"][0]["anchor"]["user_info"]:
                     self.isLive = i["cells"][0]["anchor"]["user_info"][
                         "is_living"]
                 else:
                     self.isLive = False
                 if "room_id" in i["cells"][0]["anchor"]:
                     self.roomID = int(i["cells"][0]["anchor"]["room_id"])
                 else:
                     self.isLive = False
                 self.roomLiver = User(i["cells"][0])
         if self.isLive:
             return self.updRoomInfo()
         else:
             return False