增强兼容性

This commit is contained in:
John Smith 2023-09-05 20:33:04 +08:00
parent e9d4bf47cf
commit 1db652246a
3 changed files with 25 additions and 13 deletions

View File

@ -165,17 +165,17 @@ class OpenLiveClient(ws_base.WebSocketClientBase):
{'code': self._room_owner_auth_code, 'app_id': self._app_id}
) as res:
if res.status != 200:
logger.warning('init_room() failed, status=%d, reason=%s', res.status, res.reason)
logger.warning('_start_game() failed, status=%d, reason=%s', res.status, res.reason)
return False
data = await res.json()
if data['code'] != 0:
logger.warning('init_room() failed, code=%d, message=%s, request_id=%s',
logger.warning('_start_game() failed, code=%d, message=%s, request_id=%s',
data['code'], data['message'], data['request_id'])
return False
if not self._parse_start_game(data['data']):
return False
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
logger.exception('init_room() failed:')
logger.exception('_start_game() failed:')
return False
return True
@ -247,6 +247,7 @@ class OpenLiveClient(ws_base.WebSocketClientBase):
return False
data = await res.json()
if data['code'] != 0:
# TODO 遇到7003则重新init_room
logger.warning('room=%d _send_game_heartbeat() failed, code=%d, message=%s, request_id=%s',
self._room_id, data['code'], data['message'], data['request_id'])
return False
@ -274,5 +275,4 @@ class OpenLiveClient(ws_base.WebSocketClientBase):
"""
发送认证包
"""
auth_body = json.loads(self._auth_body)
await self._websocket.send_bytes(self._make_packet(auth_body, ws_base.Operation.AUTH))
await self._websocket.send_bytes(self._make_packet(self._auth_body, ws_base.Operation.AUTH))

View File

@ -197,7 +197,7 @@ class WebSocketClientBase:
raise NotImplementedError
@staticmethod
def _make_packet(data: dict, operation: int) -> bytes:
def _make_packet(data: Union[dict, str, bytes], operation: int) -> bytes:
"""
创建一个要发送给服务器的包
@ -205,7 +205,12 @@ class WebSocketClientBase:
:param operation: 操作码见Operation
:return: 整个包的数据
"""
body = json.dumps(data).encode('utf-8')
if isinstance(data, dict):
body = json.dumps(data).encode('utf-8')
elif isinstance(data, str):
body = data.encode('utf-8')
else:
body = data
header = HEADER_STRUCT.pack(*HeaderTuple(
pack_len=HEADER_STRUCT.size + len(body),
raw_header_size=HEADER_STRUCT.size,
@ -351,8 +356,8 @@ class WebSocketClientBase:
try:
await self._parse_ws_message(message.data)
except (asyncio.CancelledError, AuthError):
# 正常停止、认证失败,让外层处理
except AuthError:
# 认证失败,让外层处理
raise
except Exception: # noqa
logger.exception('room=%d _parse_ws_message() error:', self.room_id)
@ -426,8 +431,6 @@ class WebSocketClientBase:
try:
body = json.loads(body.decode('utf-8'))
self._handle_command(body)
except asyncio.CancelledError:
raise
except Exception:
logger.error('room=%d, body=%s', self.room_id, body)
raise

View File

@ -161,6 +161,12 @@ class GiftMessage:
@classmethod
def from_command(cls, data: dict):
combo_info = data.get('combo_info', None)
if combo_info is None:
combo_info = ComboInfo()
else:
combo_info = ComboInfo.from_dict(combo_info)
return cls(
room_id=data['room_id'],
uid=data['uid'],
@ -179,8 +185,8 @@ class GiftMessage:
anchor_info=AnchorInfo.from_dict(data['anchor_info']),
msg_id=data['msg_id'],
gift_icon=data['gift_icon'],
combo_gift=data['combo_gift'],
combo_info=ComboInfo.from_dict(data['combo_info']),
combo_gift=data.get('combo_gift', False), # 官方的调试工具没发这个字段
combo_info=combo_info, # 官方的调试工具没发这个字段
)
@ -355,6 +361,8 @@ class LikeMessage:
"""粉丝勋章名"""
fans_medal_level: int = 0
"""对应房间勋章信息"""
msg_id: str = '' # 官方文档表格里没列出这个字段但是参考JSON里面有
"""消息唯一id"""
@classmethod
def from_command(cls, data: dict):
@ -368,4 +376,5 @@ class LikeMessage:
fans_medal_wearing_status=data['fans_medal_wearing_status'],
fans_medal_name=data['fans_medal_name'],
fans_medal_level=data['fans_medal_level'],
msg_id=data.get('msg_id', ''), # 官方文档表格里没列出这个字段但是参考JSON里面有
)