feat(horse_racing): 实现赛马消息更新替换与自动撤回

重构消息发送逻辑,引入消息类型区分和自动撤回机制。赛马进度更新现在会替换前一条更新消息,避免消息刷屏;比赛结果发送前自动撤回最后一条进度更新,提升聊天体验。同时支持配置不同消息类型的自动撤回时间。

- 新增 MessageService.send_with_recall 方法统一处理消息发送和撤回
- 添加 recall_previous_of_type 方法用于撤回特定类型的上一条消息
- 修改 _send_to_scope 函数支持消息类型参数
- 更新测试代码以适配新的消息发送接口
This commit is contained in:
2026-04-07 20:17:00 +08:00
parent 889cfc799b
commit 9895256064
3 changed files with 63 additions and 26 deletions

View File

@@ -1,6 +1,6 @@
import asyncio
from typing import Optional, Callable
from datetime import datetime, timedelta
from typing import Optional, Any
from nonebot.adapters.onebot.v11 import Bot, Message
from .config import Config
@@ -9,25 +9,45 @@ class MessageService:
def __init__(self, config: Config):
self.config = config
self.pending_recalls: dict[str, list[asyncio.Task]] = {}
self.last_messages: dict[str, dict[str, str]] = {} # scope -> {message_type -> message_id}
async def send_with_recall(
self,
bot: Bot,
scope: str,
message_type: str,
send_func: Callable,
*args,
**kwargs,
message: str | Message,
) -> Optional[str]:
"""Send message and schedule recall if configured."""
"""Send message and schedule recall if configured.
If it's a 'race_update', recall the previous one first."""
try:
message_id = await send_func(*args, **kwargs)
# For race_update, recall the previous one in the same scope
if message_type == "race_update":
await self.recall_previous_of_type(bot, scope, "race_update")
# Send the message
is_group = scope.startswith("group_")
result = await bot.send_msg(
message_type="group" if is_group else "private",
group_id=int(scope.split("_", 1)[1]) if is_group else None,
user_id=int(scope.split("_", 1)[1]) if not is_group else None,
message=message,
)
message_id = result.get("message_id") if isinstance(result, dict) else None
if not message_id:
return None
recall_time = self.config.MESSAGE_RECALL.get(message_type, 0)
if recall_time > 0:
# Track the last message of this type
if scope not in self.last_messages:
self.last_messages[scope] = {}
self.last_messages[scope][message_type] = message_id
# Schedule auto-recall if configured
recall_delay = self.config.MESSAGE_RECALL.get(message_type, 0)
if recall_delay > 0:
task = asyncio.create_task(
self._schedule_recall(scope, message_id, recall_time, send_func)
self._schedule_recall(bot, scope, message_id, recall_delay)
)
if scope not in self.pending_recalls:
self.pending_recalls[scope] = []
@@ -37,27 +57,40 @@ class MessageService:
except Exception as e:
return None
async def recall_previous_of_type(self, bot: Bot, scope: str, message_type: str):
"""Recall the previous message of a specific type in a scope."""
if scope in self.last_messages and message_type in self.last_messages[scope]:
old_message_id = self.last_messages[scope][message_type]
try:
await bot.delete_msg(message_id=old_message_id)
except Exception:
pass
del self.last_messages[scope][message_type]
async def _schedule_recall(
self,
bot: Bot,
scope: str,
message_id: str,
delay: int,
recall_func: Callable,
):
"""Schedule message recall."""
"""Schedule message recall after a delay."""
try:
await asyncio.sleep(delay)
await recall_func(message_id)
await bot.delete_msg(message_id=message_id)
except Exception:
pass
def clear_pending_recalls(self, scope: str):
"""Cancel all pending recall tasks for a scope."""
"""Cancel all pending recall tasks for a scope and clear last messages."""
if scope in self.pending_recalls:
for task in self.pending_recalls[scope]:
if not task.done():
task.cancel()
del self.pending_recalls[scope]
if scope in self.last_messages:
del self.last_messages[scope]
def clear_all_recalls(self):
"""Cancel all pending recall tasks."""