chore: perform widespread code cleanup and formatting

Perform a comprehensive code cleanup across multiple modules to improve code quality, consistency, and maintainability.

Key changes include:
- Removing numerous unused imports.
- Standardizing import order.
- Eliminating trailing whitespace and inconsistent newlines.
- Updating legacy type hints to modern syntax (e.g., `List` -> `list`).
- Making minor improvements for code robustness and style.
This commit is contained in:
minecraft1024a
2025-11-15 17:12:46 +08:00
parent bd45899dce
commit 6f62073630
26 changed files with 109 additions and 117 deletions

View File

@@ -1,6 +1,6 @@
import asyncio
import time
from typing import Any, TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from src.chat.planner_actions.action_manager import ChatterActionManager
from src.common.logger import get_logger

View File

@@ -6,7 +6,7 @@
import asyncio
import time
from typing import Any, TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from src.chat.energy_system import energy_manager
from src.common.data_models.database_data_model import DatabaseMessages

View File

@@ -5,7 +5,7 @@
import asyncio
import time
from typing import Any, TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from src.chat.chatter_manager import ChatterManager
from src.chat.energy_system import energy_manager
@@ -115,12 +115,12 @@ class StreamLoopManager:
if not context:
logger.warning(f"无法获取流上下文: {stream_id}")
return False
# 快速路径:如果流已存在且不是强制启动,无需处理
if not force and context.stream_loop_task and not context.stream_loop_task.done():
logger.debug(f"🔄 [流循环] stream={stream_id[:8]}, 循环已在运行,跳过启动")
return True
# 获取或创建该流的启动锁
if stream_id not in self._stream_start_locks:
self._stream_start_locks[stream_id] = asyncio.Lock()

View File

@@ -12,7 +12,6 @@ from src.common.data_models.database_data_model import DatabaseMessages
from src.common.database.core import get_db_session
from src.common.database.core.models import Images, Messages
from src.common.logger import get_logger
from src.config.config import global_config
from .chat_stream import ChatStream
from .message import MessageSending

View File

@@ -242,9 +242,9 @@ class ChatterActionManager:
}
else:
# 检查目标消息是否为表情包消息以及配置是否允许回复表情包
if target_message and getattr(target_message, 'is_emoji', False):
if target_message and getattr(target_message, "is_emoji", False):
# 如果是表情包消息且配置不允许回复表情包,则跳过回复
if not getattr(global_config.chat, 'allow_reply_to_emoji', True):
if not getattr(global_config.chat, "allow_reply_to_emoji", True):
logger.info(f"{log_prefix} 目标消息为表情包且配置不允许回复表情包,跳过回复")
return {"action_type": action_name, "success": True, "reply_text": "", "skip_reason": "emoji_not_allowed"}

View File

@@ -376,7 +376,7 @@ class DefaultReplyer:
if not prompt:
logger.warning("构建prompt失败跳过回复生成")
return False, None, None
from src.plugin_system.core.event_manager import event_manager
# 触发 POST_LLM 事件(请求 LLM 之前)
if not from_plugin:
@@ -1878,8 +1878,8 @@ class DefaultReplyer:
async def build_relation_info(self, sender: str, target: str):
# 获取用户ID
if sender == f"{global_config.bot.nickname}(你)":
return f"你将要回复的是你自己发送的消息。"
return "你将要回复的是你自己发送的消息。"
person_info_manager = get_person_info_manager()
person_id = await person_info_manager.get_person_id_by_person_name(sender)

View File

@@ -47,10 +47,10 @@ class BlockShuffler:
# 复制上下文以避免修改原始字典
shuffled_context = context_data.copy()
# 示例:假设模板中的占位符格式为 {block_name}
# 我们需要解析模板,找到可重排的组,并重新构建模板字符串。
# 注意:这是一个复杂的逻辑,通常需要一个简单的模板引擎或正则表达式来完成。
# 为保持此函数职责单一,这里仅演示核心的重排逻辑,
# 完整的模板重建逻辑应在调用此函数的地方处理。
@@ -58,14 +58,14 @@ class BlockShuffler:
for group in BlockShuffler.SWAPPABLE_BLOCK_GROUPS:
# 过滤出在当前上下文中实际存在的、非空的block
existing_blocks = [
block for block in group if block in context_data and context_data[block]
block for block in group if context_data.get(block)
]
if len(existing_blocks) > 1:
# 随机打乱顺序
random.shuffle(existing_blocks)
logger.debug(f"重排block组: {group} -> {existing_blocks}")
# 这里的实现需要调用者根据 `existing_blocks` 的新顺序
# 去动态地重新组织 `prompt_template` 字符串。
# 例如,找到模板中与 `group` 相关的占位符部分,然后按新顺序替换它们。

View File

@@ -2,7 +2,6 @@ import asyncio
import copy
import re
from collections.abc import Awaitable, Callable
from typing import List
from src.chat.utils.prompt_params import PromptParameters
from src.common.logger import get_logger
@@ -119,7 +118,7 @@ class PromptComponentManager:
async def add_injection_rule(
self,
prompt_name: str,
rules: List[InjectionRule],
rules: list[InjectionRule],
content_provider: Callable[..., Awaitable[str]],
source: str = "runtime",
) -> bool:
@@ -521,7 +520,7 @@ class PromptComponentManager:
else:
for name, (rule, _, _) in rules_for_target.items():
target_copy[name] = rule
if target_copy:
rules_copy[target] = target_copy

View File

@@ -63,7 +63,7 @@ class PromptParameters:
action_descriptions: str = ""
notice_block: str = ""
group_chat_reminder_block: str = ""
# 可用动作信息
available_actions: dict[str, Any] | None = None

View File

@@ -228,9 +228,9 @@ class HTMLReportGenerator:
# 渲染模板
# 读取CSS和JS文件内容
async with aiofiles.open(os.path.join(self.jinja_env.loader.searchpath[0], "report.css"), "r", encoding="utf-8") as f:
async with aiofiles.open(os.path.join(self.jinja_env.loader.searchpath[0], "report.css"), encoding="utf-8") as f:
report_css = await f.read()
async with aiofiles.open(os.path.join(self.jinja_env.loader.searchpath[0], "report.js"), "r", encoding="utf-8") as f:
async with aiofiles.open(os.path.join(self.jinja_env.loader.searchpath[0], "report.js"), encoding="utf-8") as f:
report_js = await f.read()
# 渲染模板
template = self.jinja_env.get_template("report.html")

View File

@@ -3,8 +3,6 @@ from collections import defaultdict
from datetime import datetime, timedelta
from typing import Any
import aiofiles
from src.common.database.compatibility import db_get, db_query
from src.common.database.core.models import LLMUsage, Messages, OnlineTime
from src.common.logger import get_logger
@@ -16,7 +14,7 @@ logger = get_logger("maibot_statistic")
# 彻底异步化:删除原同步包装器 _sync_db_get所有数据库访问统一使用 await db_get。
from .report_generator import HTMLReportGenerator, format_online_time
from .report_generator import HTMLReportGenerator
from .statistic_keys import *

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
该模块用于存放统计数据相关的常量键名。
"""
@@ -61,4 +60,4 @@ STD_TIME_COST_BY_PROVIDER = "std_time_costs_by_provider"
PIE_CHART_COST_BY_PROVIDER = "pie_chart_cost_by_provider"
PIE_CHART_REQ_BY_PROVIDER = "pie_chart_req_by_provider"
BAR_CHART_COST_BY_MODEL = "bar_chart_cost_by_model"
BAR_CHART_REQ_BY_MODEL = "bar_chart_req_by_model"
BAR_CHART_REQ_BY_MODEL = "bar_chart_req_by_model"