ForcePilot/backend/package/yuxi/channels/adapters/urbit/history.py
Kris 80e3f66974 refactor(urbit): 整理导入顺序并修复多处代码细节
1.  统一调整多个文件的导入排序,将TYPE_CHECKING相关导入放在正确位置
2.  修复rate_limiter中当限制数<=0时直接返回false的逻辑
3.  为message_cache新增更新消息内容的方法
4.  重构extract_graph_content支持日记类型内容提取
5.  调整@提及匹配的正则表达式,避免误匹配
6.  完善invite_manager,添加客户端和凭据支持并实现自动接受群邀请逻辑
7.  调整adapter.py中的导入顺序和初始化逻辑
8.  修复monitor中的编辑事件处理,改为异步处理并实现消息更新缓存
9.  调整datetime导入顺序,统一使用UTC在前的格式
2026-05-13 16:16:27 +08:00

75 lines
2.5 KiB
Python

from __future__ import annotations
import asyncio
from collections import OrderedDict
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
pass
_MAX_CACHE_SIZE = 100
class MessageCache:
def __init__(self):
self._cache: dict[str, OrderedDict[str, dict[str, Any]]] = {}
self._sent_ids: OrderedDict[str, float] = OrderedDict()
self._sent_max = 200
self._lock = asyncio.Lock()
async def cache_message(self, msg_id: str, channel_id: str, content: str, author: str) -> None:
entry = {
"id": msg_id,
"author": author,
"content": content,
}
async with self._lock:
if channel_id not in self._cache:
self._cache[channel_id] = OrderedDict()
if msg_id:
self._cache[channel_id][msg_id] = entry
self._cache[channel_id].move_to_end(msg_id)
if len(self._cache[channel_id]) > _MAX_CACHE_SIZE:
self._cache[channel_id].popitem(last=False)
async def get_channel_history(self, channel_id: str, limit: int = 50) -> list[dict[str, Any]]:
async with self._lock:
if channel_id not in self._cache:
return []
items = list(self._cache[channel_id].values())
return items[-limit:]
async def get_recent(self, channel_id: str, limit: int = 50) -> list[dict[str, Any]]:
async with self._lock:
if channel_id not in self._cache:
return []
items = list(self._cache[channel_id].values())
return items[-limit:]
async def track_sent_message(self, msg_id: str) -> None:
import time
async with self._lock:
self._sent_ids[msg_id] = time.monotonic()
self._sent_ids.move_to_end(msg_id)
if len(self._sent_ids) > self._sent_max:
self._sent_ids.popitem(last=False)
async def is_sent(self, msg_id: str) -> bool:
async with self._lock:
return msg_id in self._sent_ids
async def update_message(self, msg_id: str, new_content: str) -> bool:
async with self._lock:
for channel_cache in self._cache.values():
if msg_id in channel_cache:
channel_cache[msg_id]["content"] = new_content
return True
return False
async def clear_channel(self, channel_id: str) -> None:
async with self._lock:
self._cache.pop(channel_id, None)