|
8 | 8 | from .common import request, NoValResult, Result |
9 | 9 | from .. import logger |
10 | 10 |
|
| 11 | +timeout_for_sse = aiohttp.ClientTimeout( |
| 12 | + total=None, # 整体无超时 |
| 13 | + sock_connect=None, # 连接无超时 |
| 14 | + sock_read=None # 读取无超时 |
| 15 | +) |
| 16 | + |
11 | 17 |
|
12 | 18 | class MessageType(enum.Enum): |
13 | 19 | Text = 0 |
@@ -105,29 +111,31 @@ async def get_message( |
105 | 111 | "Authorization": f"Bearer {session}", |
106 | 112 | } |
107 | 113 |
|
108 | | - async with aiohttp.ClientSession(headers=headers) as session: |
109 | | - async with session.get(api_address) as response: |
110 | | - if response.status != 200: |
111 | | - raise RuntimeError(f"Request failed with status: {response.status}") |
112 | | - |
113 | | - async for line in response.content: |
114 | | - # 解码成字符串 |
115 | | - line = line.decode('utf-8').strip() |
116 | | - if line.startswith('data:'): |
117 | | - # 提取消息内容 |
118 | | - message = line[len('data:'):].strip() |
119 | | - |
120 | | - data = json.loads(message) |
121 | | - logger.debug(f"Response data: {data}") |
122 | | - if data["result"]["code"] != 800: |
123 | | - raise RuntimeError(f"Request failed with code: {data['result']['code']}") |
124 | | - for msg in data["msg"]: |
125 | | - yield Message( |
126 | | - groupid=msg["groupid"], |
127 | | - msg=msg["msg"], |
128 | | - msgid=msg["msgid"], |
129 | | - time=msg["time"], |
130 | | - type=MessageType(msg["type"]), |
131 | | - username=msg["username"], |
132 | | - hash=msg.get("hash", None), |
133 | | - ) |
| 114 | + async with ( |
| 115 | + aiohttp.ClientSession(headers=headers, timeout=timeout_for_sse) as session, |
| 116 | + session.get(api_address) as response |
| 117 | + ): |
| 118 | + if response.status != 200: |
| 119 | + raise RuntimeError(f"Request failed with status: {response.status}") |
| 120 | + |
| 121 | + async for line in response.content: |
| 122 | + # 解码成字符串 |
| 123 | + line = line.decode('utf-8').strip() |
| 124 | + if line.startswith('data:'): |
| 125 | + # 提取消息内容 |
| 126 | + message = line[len('data:'):].strip() |
| 127 | + |
| 128 | + data = json.loads(message) |
| 129 | + logger.debug(f"Response data: {data}") |
| 130 | + if data["result"]["code"] != 800: |
| 131 | + raise RuntimeError(f"Request failed with code: {data['result']['code']}") |
| 132 | + for msg in data["msg"]: |
| 133 | + yield Message( |
| 134 | + groupid=msg["groupid"], |
| 135 | + msg=msg["msg"], |
| 136 | + msgid=msg["msgid"], |
| 137 | + time=msg["time"], |
| 138 | + type=MessageType(msg["type"]), |
| 139 | + username=msg["username"], |
| 140 | + hash=msg.get("hash", None), |
| 141 | + ) |
0 commit comments