fix: qq_official websocket适配器发送消息收到None时现在会重试了 (#8977)#8979
fix: qq_official websocket适配器发送消息收到None时现在会重试了 (#8977)#8979shuiping233 wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Hey - I've found 1 issue
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/platform/sources/qqofficial/qqofficial_message_event.py" line_range="57" />
<code_context>
- reraise=True,
-)
+
+def _qqofficial_retry(max_attempts: int = 5):
+ """Retry decorator for QQ Official API transient errors (HTTP 500/504)"""
+ return retry(
</code_context>
<issue_to_address>
**issue (complexity):** Consider simplifying the retry logic by exposing a shared default retry decorator and using an explicit retry loop in `post_c2c_message` instead of nested decorated helper functions.
The main added complexity is in:
1. Turning `_qqofficial_retry` into a factory used everywhere as `@_qqofficial_retry()`.
2. Using a custom `APIReturnNoneError` + nested decorated `_do_request` for a single call site.
You can keep all new behavior but simplify usage and control flow.
---
### 1. Provide a simple shared decorator for the common case
Keep the factory for configurability, but expose a default decorator so most call sites don’t need `()`:
```python
class APIReturnNoneError(Exception):
pass
def _qqofficial_retry(max_attempts: int = 5):
"""Retry decorator for QQ Official API transient errors (HTTP 500/504)"""
return retry(
retry=retry_if_exception_type(
(
botpy.errors.ServerError,
botpy.errors.SequenceNumberError,
OSError,
asyncio.TimeoutError,
APIReturnNoneError,
)
),
stop=stop_after_attempt(max_attempts),
wait=wait_exponential(multiplier=2, min=2, max=30),
before_sleep=before_sleep_log(logger, logging.WARNING),
reraise=True,
)
# Default retry policy (5 attempts)
_qqofficial_retry_default = _qqofficial_retry()
```
Then common call sites use:
```python
@_qqofficial_retry_default
async def _do_upload():
...
```
Only places that truly need a different policy (e.g. fewer attempts) use the factory:
```python
@_qqofficial_retry(3)
async def _do_request():
...
```
This reduces boilerplate without removing configurability.
---
### 2. Replace the nested decorated function in `post_c2c_message` with an explicit retry loop
You can keep `APIReturnNoneError` support in the decorator for other potential uses, but for this single call site a direct loop is clearer and avoids the nested function + decorator indirection.
Current pattern:
```python
retry_times = 3
@_qqofficial_retry(retry_times)
async def _do_request():
result = await self.bot.api._http.request(route, json=payload)
if result is None:
err_msg = "发送消息API返回None,触发重试"
logger.warning(f"[QQOfficial] post_c2c_message: {err_msg}")
raise APIReturnNoneError(err_msg)
return result
result = None
try:
result = await _do_request()
except APIReturnNoneError:
logger.warning(
f"[QQOfficial] post_c2c_message: 发送消息失败,API 返回 None,共尝试{retry_times}次后放弃"
)
return None
```
A more direct version with equivalent behavior:
```python
retry_times = 3
result = None
for attempt in range(1, retry_times + 1):
result = await self.bot.api._http.request(route, json=payload)
if result is not None:
break
logger.warning(
"[QQOfficial] post_c2c_message: 发送消息API返回None,触发重试 "
f"(第 {attempt} 次,共 {retry_times} 次)"
)
if result is None:
logger.warning(
f"[QQOfficial] post_c2c_message: 发送消息失败,API 返回 None,共尝试{retry_times}次后放弃"
)
return None
if not isinstance(result, dict):
logger.error(f"[QQOfficial] post_c2c_message: 响应不是 dict: {result}")
return None
return message.Message(**result)
```
This keeps:
- Retry-on-`None` semantics.
- Logging on each retry and on final failure.
- The existing post-response validation.
while making the control flow easier to follow and reducing indirection.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
There was a problem hiding this comment.
Code Review
This pull request refactors the retry mechanism for the QQ Official API (_qqofficial_retry) to support a configurable number of attempts and introduces a new APIReturnNoneError exception. This exception is used in post_c2c_message to trigger retries when the API returns None. The reviewer suggests extending this behavior to upload_group_and_c2c_media by raising APIReturnNoneError when the upload API returns None, ensuring that media uploads also benefit from the retry mechanism.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
写完了,希望有大佬康康.jpg |
Modifications / 改动点
Screenshots or Test Results / 运行截图或测试结果
Checklist / 检查清单
😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
/ 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
/ 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in
requirements.txtandpyproject.toml./ 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到
requirements.txt和pyproject.toml文件相应位置。😮 My changes do not introduce malicious code.
/ 我的更改没有引入恶意代码。
Summary by Sourcery
Add retry handling to QQ Official websocket adapter when the send-message API returns None to mitigate transient failures.
Bug Fixes:
Enhancements: