ForcePilot/backend/package/yuxi/channels/adapters/bluebubbles/history.py
Kris 6aa1d52a8b feat(bluebubbles): 实现完整的BlueBubbles适配器基础组件
新增BlueBubbles适配器全套核心工具类与服务,包含会话管理、消息去重、Webhook验证、缓存系统、账号配置解析、聊天消息处理等完整功能模块,支持iMessage消息收发、群管理、反应特效、语音合成等能力,提供完善的健康检查与配置校验流程。
2026-05-12 00:42:57 +08:00

49 lines
1.6 KiB
Python

from __future__ import annotations
import time
from typing import Any
class MessageHistory:
MAX_MESSAGES = 500
TTL_SECONDS = 3600
def __init__(self) -> None:
self._history: dict[str, list[dict[str, Any]]] = {}
def add(self, chat_guid: str, message: dict[str, Any]) -> None:
if chat_guid not in self._history:
self._history[chat_guid] = []
self._history[chat_guid].append(
{
**message,
"_recorded_at": time.monotonic(),
}
)
self._trim(chat_guid)
def get(self, chat_guid: str, limit: int = 50) -> list[dict[str, Any]]:
messages = self._history.get(chat_guid, [])
self._evict_expired(chat_guid)
return messages[-limit:]
def get_since(self, chat_guid: str, since_ts: float) -> list[dict[str, Any]]:
messages = self._history.get(chat_guid, [])
self._evict_expired(chat_guid)
return [m for m in messages if m.get("_recorded_at", 0) >= since_ts]
def _trim(self, chat_guid: str) -> None:
messages = self._history.get(chat_guid, [])
if len(messages) > self.MAX_MESSAGES:
self._history[chat_guid] = messages[-self.MAX_MESSAGES :]
def _evict_expired(self, chat_guid: str) -> None:
messages = self._history.get(chat_guid, [])
if not messages:
return
now = time.monotonic()
self._history[chat_guid] = [m for m in messages if now - m.get("_recorded_at", now) < self.TTL_SECONDS]
def clear(self, chat_guid: str) -> None:
self._history.pop(chat_guid, None)