这是一个批量整理提交,包含以下主要改动: 1. 删除多处冗余的空行和未使用的导入 2. 修复文件末尾缺少换行符的问题 3. 调整部分模块的导入顺序与代码排版 4. 修复部分配置默认值与策略逻辑 5. 新增多个功能模块与辅助工具 6. 完善异常处理与日志记录 7. 修复速率限制、消息缓存、权限校验等逻辑bug 8. 废弃部分旧有API与配置项并添加警告提示
68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from collections import OrderedDict
|
|
from typing import Any, TYPE_CHECKING
|
|
|
|
|
|
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 clear_channel(self, channel_id: str) -> None:
|
|
async with self._lock:
|
|
self._cache.pop(channel_id, None)
|