style: 统一代码风格并进行现代化改进
对整个代码库进行了一次全面的风格统一和现代化改进。主要变更包括:
- 将 `hasattr` 等内置函数中的字符串参数从单引号 `'` 统一为双引号 `"`。
- 采用现代类型注解,例如将 `Optional[T]` 替换为 `T | None`,`List[T]` 替换为 `list[T]` 等。
- 移除不再需要的 Python 2 兼容性声明 `# -*- coding: utf-8 -*-`。
- 清理了多余的空行、注释和未使用的导入。
- 统一了文件末尾的换行符。
- 优化了部分日志输出和字符串格式化 (`f"{e!s}"`)。
这些改动旨在提升代码的可读性、一致性和可维护性,使其更符合现代 Python 编码规范。
This commit is contained in:
@@ -49,7 +49,6 @@ from .base import (
|
||||
ToolParamType,
|
||||
create_plus_command_adapter,
|
||||
)
|
||||
|
||||
from .utils.dependency_config import configure_dependency_settings, get_dependency_config
|
||||
|
||||
# 导入依赖管理模块
|
||||
|
||||
@@ -113,7 +113,7 @@ class BaseInterestCalculator(ABC):
|
||||
try:
|
||||
self._enabled = True
|
||||
return True
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
self._enabled = False
|
||||
return False
|
||||
|
||||
@@ -170,7 +170,7 @@ class BaseInterestCalculator(ABC):
|
||||
if not self._enabled:
|
||||
return InterestCalculationResult(
|
||||
success=False,
|
||||
message_id=getattr(message, 'message_id', ''),
|
||||
message_id=getattr(message, "message_id", ""),
|
||||
interest_value=0.0,
|
||||
error_message="组件未启用"
|
||||
)
|
||||
@@ -184,9 +184,9 @@ class BaseInterestCalculator(ABC):
|
||||
except Exception as e:
|
||||
result = InterestCalculationResult(
|
||||
success=False,
|
||||
message_id=getattr(message, 'message_id', ''),
|
||||
message_id=getattr(message, "message_id", ""),
|
||||
interest_value=0.0,
|
||||
error_message=f"计算执行失败: {str(e)}",
|
||||
error_message=f"计算执行失败: {e!s}",
|
||||
calculation_time=time.time() - start_time
|
||||
)
|
||||
self._update_statistics(result)
|
||||
@@ -201,7 +201,7 @@ class BaseInterestCalculator(ABC):
|
||||
Returns:
|
||||
InterestCalculatorInfo: 生成的兴趣计算器信息对象
|
||||
"""
|
||||
name = getattr(cls, 'component_name', cls.__name__.lower().replace('calculator', ''))
|
||||
name = getattr(cls, "component_name", cls.__name__.lower().replace("calculator", ""))
|
||||
if "." in name:
|
||||
logger.error(f"InterestCalculator名称 '{name}' 包含非法字符 '.',请使用下划线替代")
|
||||
raise ValueError(f"InterestCalculator名称 '{name}' 包含非法字符 '.',请使用下划线替代")
|
||||
@@ -209,12 +209,12 @@ class BaseInterestCalculator(ABC):
|
||||
return InterestCalculatorInfo(
|
||||
name=name,
|
||||
component_type=ComponentType.INTEREST_CALCULATOR,
|
||||
description=getattr(cls, 'component_description', cls.__doc__ or "兴趣度计算器"),
|
||||
enabled_by_default=getattr(cls, 'enabled_by_default', True),
|
||||
description=getattr(cls, "component_description", cls.__doc__ or "兴趣度计算器"),
|
||||
enabled_by_default=getattr(cls, "enabled_by_default", True),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (f"{self.__class__.__name__}("
|
||||
f"name={self.component_name}, "
|
||||
f"version={self.component_version}, "
|
||||
f"enabled={self._enabled})")
|
||||
f"enabled={self._enabled})")
|
||||
|
||||
@@ -43,21 +43,21 @@ class BasePlugin(PluginBase):
|
||||
对应类型的ComponentInfo对象
|
||||
"""
|
||||
if component_type == ComponentType.COMMAND:
|
||||
if hasattr(component_class, 'get_command_info'):
|
||||
if hasattr(component_class, "get_command_info"):
|
||||
return component_class.get_command_info()
|
||||
else:
|
||||
logger.warning(f"Command类 {component_class.__name__} 缺少 get_command_info 方法")
|
||||
return None
|
||||
|
||||
elif component_type == ComponentType.ACTION:
|
||||
if hasattr(component_class, 'get_action_info'):
|
||||
if hasattr(component_class, "get_action_info"):
|
||||
return component_class.get_action_info()
|
||||
else:
|
||||
logger.warning(f"Action类 {component_class.__name__} 缺少 get_action_info 方法")
|
||||
return None
|
||||
|
||||
elif component_type == ComponentType.INTEREST_CALCULATOR:
|
||||
if hasattr(component_class, 'get_interest_calculator_info'):
|
||||
if hasattr(component_class, "get_interest_calculator_info"):
|
||||
return component_class.get_interest_calculator_info()
|
||||
else:
|
||||
logger.warning(f"InterestCalculator类 {component_class.__name__} 缺少 get_interest_calculator_info 方法")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class PluginMetadata:
|
||||
@@ -11,15 +12,15 @@ class PluginMetadata:
|
||||
usage: str # 插件使用方法
|
||||
|
||||
# 以下为可选字段,参考自 _manifest.json 和 NoneBot 设计
|
||||
type: Optional[str] = None # 插件类别: "library", "application"
|
||||
type: str | None = None # 插件类别: "library", "application"
|
||||
|
||||
# 从原 _manifest.json 迁移的字段
|
||||
version: str = "1.0.0" # 插件版本
|
||||
author: str = "" # 作者名称
|
||||
license: Optional[str] = None # 开源协议
|
||||
repository_url: Optional[str] = None # 仓库地址
|
||||
keywords: List[str] = field(default_factory=list) # 关键词
|
||||
categories: List[str] = field(default_factory=list) # 分类
|
||||
license: str | None = None # 开源协议
|
||||
repository_url: str | None = None # 仓库地址
|
||||
keywords: list[str] = field(default_factory=list) # 关键词
|
||||
categories: list[str] = field(default_factory=list) # 分类
|
||||
|
||||
# 扩展字段
|
||||
extra: Dict[str, Any] = field(default_factory=dict) # 其他任意信息
|
||||
extra: dict[str, Any] = field(default_factory=dict) # 其他任意信息
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import importlib
|
||||
import os
|
||||
import traceback
|
||||
from importlib.util import module_from_spec, spec_from_file_location
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
@@ -104,7 +103,7 @@ class PluginManager:
|
||||
return False, 1
|
||||
|
||||
module = self.plugin_modules.get(plugin_name)
|
||||
|
||||
|
||||
if not module or not hasattr(module, "__plugin_meta__"):
|
||||
self.failed_plugins[plugin_name] = "插件模块中缺少 __plugin_meta__"
|
||||
logger.error(f"❌ 插件加载失败: {plugin_name} - 缺少 __plugin_meta__")
|
||||
@@ -288,7 +287,7 @@ class PluginManager:
|
||||
|
||||
return loaded_count, failed_count
|
||||
|
||||
def _load_plugin_module_file(self, plugin_file: str) -> Optional[Any]:
|
||||
def _load_plugin_module_file(self, plugin_file: str) -> Any | None:
|
||||
# sourcery skip: extract-method
|
||||
"""加载单个插件模块文件
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import inspect
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from src.chat.message_receive.chat_stream import get_chat_manager
|
||||
from src.chat.utils.prompt import Prompt, global_prompt_manager
|
||||
from src.common.cache_manager import tool_cache
|
||||
from src.common.logger import get_logger
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
插件系统工具模块
|
||||
|
||||
提供插件开发和管理的实用工具
|
||||
"""
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user