重构服务模块,优化消息处理逻辑,移除冗余功能,更新数据模型适配
This commit is contained in:
@@ -1,66 +0,0 @@
|
||||
"""配置服务模块
|
||||
|
||||
提供配置读取的核心功能。
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from src.common.logger import get_logger
|
||||
from src.config.config import global_config
|
||||
|
||||
logger = get_logger("config_service")
|
||||
|
||||
|
||||
def get_global_config(key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
安全地从全局配置中获取一个值。
|
||||
|
||||
Args:
|
||||
key: 命名空间式配置键名,使用嵌套访问,如 "section.subsection.key",大小写敏感
|
||||
default: 如果配置不存在时返回的默认值
|
||||
|
||||
Returns:
|
||||
Any: 配置值或默认值
|
||||
"""
|
||||
keys = key.split(".")
|
||||
current = global_config
|
||||
|
||||
try:
|
||||
for k in keys:
|
||||
if hasattr(current, k):
|
||||
current = getattr(current, k)
|
||||
else:
|
||||
raise KeyError(f"配置中不存在子空间或键 '{k}'")
|
||||
return current
|
||||
except Exception as e:
|
||||
logger.warning(f"[ConfigService] 获取全局配置 {key} 失败: {e}")
|
||||
return default
|
||||
|
||||
|
||||
def get_plugin_config(plugin_config: dict, key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
从插件配置中获取值,支持嵌套键访问
|
||||
|
||||
Args:
|
||||
plugin_config: 插件配置字典
|
||||
key: 配置键名,支持嵌套访问如 "section.subsection.key",大小写敏感
|
||||
default: 如果配置不存在时返回的默认值
|
||||
|
||||
Returns:
|
||||
Any: 配置值或默认值
|
||||
"""
|
||||
keys = key.split(".")
|
||||
current = plugin_config
|
||||
|
||||
try:
|
||||
for k in keys:
|
||||
if isinstance(current, dict) and k in current:
|
||||
current = current[k]
|
||||
elif hasattr(current, k):
|
||||
current = getattr(current, k)
|
||||
else:
|
||||
raise KeyError(f"配置中不存在子空间或键 '{k}'")
|
||||
return current
|
||||
except Exception as e:
|
||||
logger.warning(f"[ConfigService] 获取插件配置 {key} 失败: {e}")
|
||||
return default
|
||||
@@ -154,22 +154,6 @@ def get_messages_before_time_in_chat(
|
||||
return _normalize_messages(messages)
|
||||
|
||||
|
||||
def get_recent_messages(
|
||||
chat_id: str, hours: float = 24.0, limit: int = 100, limit_mode: str = "latest", filter_mai: bool = False
|
||||
) -> List[SessionMessage]:
|
||||
if not isinstance(hours, (int, float)) or hours < 0:
|
||||
raise ValueError("hours 不能是负数")
|
||||
if not isinstance(limit, int) or limit < 0:
|
||||
raise ValueError("limit 必须是非负整数")
|
||||
if not chat_id:
|
||||
raise ValueError("chat_id 不能为空")
|
||||
if not isinstance(chat_id, str):
|
||||
raise ValueError("chat_id 必须是字符串类型")
|
||||
now = time.time()
|
||||
start_time = now - hours * 3600
|
||||
return get_messages_by_time_in_chat(chat_id, start_time, now, limit, limit_mode, filter_mai)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 消息计数函数
|
||||
# =============================================================================
|
||||
@@ -221,14 +205,14 @@ def build_readable_messages(
|
||||
line = f"{line[:200]}......(内容太长了)"
|
||||
lines.append(line)
|
||||
if show_actions and normalized_messages:
|
||||
action_lines = build_readable_actions(
|
||||
if action_lines := ActionUtils.build_readable_action_records(
|
||||
get_actions_by_timestamp_with_chat(
|
||||
normalized_messages[0].session_id,
|
||||
normalized_messages[0].timestamp.timestamp(),
|
||||
normalized_messages[-1].timestamp.timestamp(),
|
||||
)
|
||||
)
|
||||
if action_lines:
|
||||
),
|
||||
"relative",
|
||||
):
|
||||
lines.append(action_lines)
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -260,19 +244,24 @@ def build_readable_messages_with_id(
|
||||
lines.append(line)
|
||||
message_id_list.append((message.message_id, message))
|
||||
if show_actions and normalized_messages:
|
||||
action_lines = build_readable_actions(
|
||||
if action_lines := ActionUtils.build_readable_action_records(
|
||||
get_actions_by_timestamp_with_chat(
|
||||
normalized_messages[0].session_id,
|
||||
normalized_messages[0].timestamp.timestamp(),
|
||||
normalized_messages[-1].timestamp.timestamp(),
|
||||
)
|
||||
)
|
||||
if action_lines:
|
||||
),
|
||||
"relative",
|
||||
):
|
||||
lines.append(action_lines)
|
||||
return "\n".join(lines), message_id_list
|
||||
|
||||
|
||||
def get_actions_by_timestamp_with_chat(chat_id: str, timestamp_start: float, timestamp_end: float) -> List[MaiActionRecord]:
|
||||
def get_actions_by_timestamp_with_chat(
|
||||
chat_id: str,
|
||||
timestamp_start: float,
|
||||
timestamp_end: float,
|
||||
limit: Optional[int] = None,
|
||||
) -> List[MaiActionRecord]:
|
||||
with get_db_session() as session:
|
||||
statement = (
|
||||
select(ActionRecord)
|
||||
@@ -281,13 +270,11 @@ def get_actions_by_timestamp_with_chat(chat_id: str, timestamp_start: float, tim
|
||||
.where(col(ActionRecord.timestamp) <= datetime.fromtimestamp(timestamp_end))
|
||||
.order_by(col(ActionRecord.timestamp))
|
||||
)
|
||||
if limit is not None:
|
||||
statement = statement.limit(limit)
|
||||
return [MaiActionRecord.from_db_instance(item) for item in session.exec(statement).all()]
|
||||
|
||||
|
||||
def build_readable_actions(actions: List[MaiActionRecord], timestamp_mode: str = "relative") -> str:
|
||||
return ActionUtils.build_readable_action_records(actions, timestamp_mode)
|
||||
|
||||
|
||||
def replace_user_references(text: str, platform: str, replace_bot_name: bool = False) -> str:
|
||||
del platform
|
||||
if not text:
|
||||
@@ -312,9 +299,4 @@ def translate_pid_to_description(pid: str) -> str:
|
||||
else None
|
||||
)
|
||||
image = session.exec(statement).first() if statement is not None else None
|
||||
description = ""
|
||||
if image and image.description and image.description.strip():
|
||||
description = image.description.strip()
|
||||
else:
|
||||
description = "[图片]"
|
||||
return description
|
||||
return image.description.strip() if image and image.description and image.description.strip() else "[图片]"
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
提供发送各种类型消息的核心功能。
|
||||
"""
|
||||
|
||||
import traceback
|
||||
import time
|
||||
from typing import Optional, Union, Dict, List, TYPE_CHECKING
|
||||
import traceback
|
||||
from typing import Dict, List, Optional, TYPE_CHECKING
|
||||
|
||||
from maim_message import BaseMessageInfo, GroupInfo as MaimGroupInfo, MessageBase, Seg, UserInfo as MaimUserInfo
|
||||
|
||||
@@ -61,7 +61,7 @@ async def _send_to_target(
|
||||
|
||||
anchor_message: Optional[MaiMessage] = None
|
||||
if reply_message:
|
||||
anchor_message = db_message_to_mai_message(reply_message)
|
||||
anchor_message = reply_message.deepcopy()
|
||||
if anchor_message:
|
||||
logger.debug(
|
||||
f"[SendService] 找到匹配的回复消息,发送者: {anchor_message.message_info.user_info.user_id}"
|
||||
@@ -127,11 +127,6 @@ async def _send_to_target(
|
||||
return False
|
||||
|
||||
|
||||
def db_message_to_mai_message(message_obj: "SessionMessage") -> Optional[MaiMessage]:
|
||||
"""将数据库消息重建为 MaiMessage 对象,用于回复引用。"""
|
||||
return message_obj.deepcopy()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 公共函数 - 预定义类型的发送函数
|
||||
# =============================================================================
|
||||
@@ -197,23 +192,6 @@ async def image_to_stream(
|
||||
)
|
||||
|
||||
|
||||
async def command_to_stream(
|
||||
command: Union[str, dict],
|
||||
stream_id: str,
|
||||
storage_message: bool = True,
|
||||
display_message: str = "",
|
||||
) -> bool:
|
||||
"""向指定流发送命令"""
|
||||
return await _send_to_target(
|
||||
message_segment=Seg(type="command", data=command), # type: ignore
|
||||
stream_id=stream_id,
|
||||
display_message=display_message,
|
||||
typing=False,
|
||||
storage_message=storage_message,
|
||||
set_reply=False,
|
||||
)
|
||||
|
||||
|
||||
async def custom_to_stream(
|
||||
message_type: str,
|
||||
content: str | Dict,
|
||||
|
||||
Reference in New Issue
Block a user