re-style: 格式化代码

This commit is contained in:
John Richard
2025-10-02 20:26:01 +08:00
parent ecb02cae31
commit 7923eafef3
263 changed files with 3103 additions and 3123 deletions

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Bilibili 插件包
提供B站视频观看体验功能像真实用户一样浏览和评价视频

View File

@@ -1,16 +1,17 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Bilibili 工具基础模块
提供 B 站视频信息获取和视频分析功能
"""
import re
import aiohttp
import asyncio
from typing import Optional, Dict, Any
from src.common.logger import get_logger
import re
from typing import Any
import aiohttp
from src.chat.utils.utils_video import get_video_analyzer
from src.common.logger import get_logger
logger = get_logger("bilibili_tool")
@@ -25,7 +26,7 @@ class BilibiliVideoAnalyzer:
"Referer": "https://www.bilibili.com/",
}
def extract_bilibili_url(self, text: str) -> Optional[str]:
def extract_bilibili_url(self, text: str) -> str | None:
"""从文本中提取哔哩哔哩视频链接"""
# 哔哩哔哩短链接模式
short_pattern = re.compile(r"https?://b23\.tv/[\w]+", re.IGNORECASE)
@@ -44,7 +45,7 @@ class BilibiliVideoAnalyzer:
return None
async def get_video_info(self, url: str) -> Optional[Dict[str, Any]]:
async def get_video_info(self, url: str) -> dict[str, Any] | None:
"""获取哔哩哔哩视频基本信息"""
try:
logger.info(f"🔍 解析视频URL: {url}")
@@ -127,7 +128,7 @@ class BilibiliVideoAnalyzer:
logger.exception("详细错误信息:")
return None
async def get_video_stream_url(self, aid: int, cid: int) -> Optional[str]:
async def get_video_stream_url(self, aid: int, cid: int) -> str | None:
"""获取视频流URL"""
try:
logger.info(f"🎥 获取视频流URL: aid={aid}, cid={cid}")
@@ -164,7 +165,7 @@ class BilibiliVideoAnalyzer:
return stream_url
# 降级到FLV格式
if "durl" in play_data and play_data["durl"]:
if play_data.get("durl"):
logger.info("📹 使用FLV格式视频流")
stream_url = play_data["durl"][0].get("url")
if stream_url:
@@ -185,7 +186,7 @@ class BilibiliVideoAnalyzer:
logger.exception("详细错误信息:")
return None
async def download_video_bytes(self, stream_url: str, max_size_mb: int = 100) -> Optional[bytes]:
async def download_video_bytes(self, stream_url: str, max_size_mb: int = 100) -> bytes | None:
"""下载视频字节数据
Args:
@@ -244,7 +245,7 @@ class BilibiliVideoAnalyzer:
logger.exception("详细错误信息:")
return None
async def analyze_bilibili_video(self, url: str, prompt: str = None) -> Dict[str, Any]:
async def analyze_bilibili_video(self, url: str, prompt: str = None) -> dict[str, Any]:
"""分析哔哩哔哩视频并返回详细信息和AI分析结果"""
try:
logger.info(f"🎬 开始分析哔哩哔哩视频: {url}")
@@ -322,10 +323,10 @@ class BilibiliVideoAnalyzer:
return result
except Exception as e:
error_msg = f"分析哔哩哔哩视频时发生异常: {str(e)}"
error_msg = f"分析哔哩哔哩视频时发生异常: {e!s}"
logger.error(f"{error_msg}")
logger.exception("详细错误信息:") # 记录完整的异常堆栈
return {"error": f"分析失败: {str(e)}"}
return {"error": f"分析失败: {e!s}"}
# 全局实例

View File

@@ -1,14 +1,15 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Bilibili 视频观看体验工具
支持哔哩哔哩视频链接解析和AI视频内容分析
"""
from typing import Dict, Any, List, Tuple, Type
from src.plugin_system import BaseTool, ToolParamType, BasePlugin, register_plugin, ComponentInfo, ConfigField
from .bilibli_base import get_bilibili_analyzer
from typing import Any
from src.common.logger import get_logger
from src.plugin_system import BasePlugin, BaseTool, ComponentInfo, ConfigField, ToolParamType, register_plugin
from .bilibli_base import get_bilibili_analyzer
logger = get_logger("bilibili_tool")
@@ -41,7 +42,7 @@ class BilibiliTool(BaseTool):
super().__init__(plugin_config)
self.analyzer = get_bilibili_analyzer()
async def execute(self, function_args: Dict[str, Any]) -> Dict[str, Any]:
async def execute(self, function_args: dict[str, Any]) -> dict[str, Any]:
"""执行哔哩哔哩视频观看体验"""
try:
url = function_args.get("url", "").strip()
@@ -83,7 +84,7 @@ class BilibiliTool(BaseTool):
return {"name": self.name, "content": content.strip()}
except Exception as e:
error_msg = f"😅 看视频的时候出了点问题: {str(e)}"
error_msg = f"😅 看视频的时候出了点问题: {e!s}"
logger.error(error_msg)
return {"name": self.name, "content": error_msg}
@@ -104,7 +105,7 @@ class BilibiliTool(BaseTool):
return base_prompt
def _format_watch_experience(self, video_info: Dict, ai_analysis: str, interest_focus: str = None) -> str:
def _format_watch_experience(self, video_info: dict, ai_analysis: str, interest_focus: str = None) -> str:
"""格式化观看体验报告"""
# 根据播放量生成热度评价
@@ -191,8 +192,8 @@ class BilibiliPlugin(BasePlugin):
# 插件基本信息
plugin_name: str = "bilibili_video_watcher"
enable_plugin: bool = True
dependencies: List[str] = []
python_dependencies: List[str] = []
dependencies: list[str] = []
python_dependencies: list[str] = []
config_file_name: str = "config.toml"
# 配置节描述
@@ -220,6 +221,6 @@ class BilibiliPlugin(BasePlugin):
},
}
def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]:
def get_plugin_components(self) -> list[tuple[ComponentInfo, type]]:
"""返回插件包含的工具组件"""
return [(BilibiliTool.get_tool_info(), BilibiliTool)]

View File

@@ -4,14 +4,15 @@ Echo 示例插件
展示增强命令系统的使用方法
"""
from typing import List, Tuple, Type, Optional, Union
from typing import Union
from src.plugin_system import (
BasePlugin,
PlusCommand,
CommandArgs,
PlusCommandInfo,
ConfigField,
ChatType,
CommandArgs,
ConfigField,
PlusCommand,
PlusCommandInfo,
register_plugin,
)
from src.plugin_system.base.component_types import PythonDependency
@@ -27,7 +28,7 @@ class EchoCommand(PlusCommand):
chat_type_allow = ChatType.ALL
intercept_message = True
async def execute(self, args: CommandArgs) -> Tuple[bool, Optional[str], bool]:
async def execute(self, args: CommandArgs) -> tuple[bool, str | None, bool]:
"""执行echo命令"""
if args.is_empty():
await self.send_text("❓ 请提供要回显的内容\n用法: /echo <内容>")
@@ -56,7 +57,7 @@ class HelloCommand(PlusCommand):
chat_type_allow = ChatType.ALL
intercept_message = True
async def execute(self, args: CommandArgs) -> Tuple[bool, Optional[str], bool]:
async def execute(self, args: CommandArgs) -> tuple[bool, str | None, bool]:
"""执行hello命令"""
if args.is_empty():
await self.send_text("👋 Hello! 很高兴见到你!")
@@ -77,7 +78,7 @@ class InfoCommand(PlusCommand):
chat_type_allow = ChatType.ALL
intercept_message = True
async def execute(self, args: CommandArgs) -> Tuple[bool, Optional[str], bool]:
async def execute(self, args: CommandArgs) -> tuple[bool, str | None, bool]:
"""执行info命令"""
info_text = (
"📋 Echo 示例插件信息\n"
@@ -105,7 +106,7 @@ class TestCommand(PlusCommand):
chat_type_allow = ChatType.ALL
intercept_message = True
async def execute(self, args: CommandArgs) -> Tuple[bool, Optional[str], bool]:
async def execute(self, args: CommandArgs) -> tuple[bool, str | None, bool]:
"""执行test命令"""
if args.is_empty():
help_text = (
@@ -166,8 +167,8 @@ class EchoExamplePlugin(BasePlugin):
plugin_name: str = "echo_example_plugin"
enable_plugin: bool = True
dependencies: List[str] = []
python_dependencies: List[Union[str, "PythonDependency"]] = []
dependencies: list[str] = []
python_dependencies: list[Union[str, "PythonDependency"]] = []
config_file_name: str = "config.toml"
config_schema = {
@@ -187,7 +188,7 @@ class EchoExamplePlugin(BasePlugin):
"commands": "命令相关配置",
}
def get_plugin_components(self) -> List[Tuple[PlusCommandInfo, Type]]:
def get_plugin_components(self) -> list[tuple[PlusCommandInfo, type]]:
"""获取插件组件"""
components = []

View File

@@ -1,20 +1,20 @@
from typing import List, Tuple, Type, Dict, Any, Optional
import logging
import random
from typing import Any
from src.plugin_system import (
BasePlugin,
register_plugin,
ComponentInfo,
BaseEventHandler,
EventType,
BaseTool,
PlusCommand,
CommandArgs,
ChatType,
BaseAction,
ActionActivationType,
BaseAction,
BaseEventHandler,
BasePlugin,
BaseTool,
ChatType,
CommandArgs,
ComponentInfo,
ConfigField,
EventType,
PlusCommand,
register_plugin,
)
from src.plugin_system.base.base_event import HandlerResult
@@ -39,7 +39,7 @@ class GetSystemInfoTool(BaseTool):
available_for_llm = True
parameters = []
async def execute(self, function_args: Dict[str, Any]) -> Dict[str, Any]:
async def execute(self, function_args: dict[str, Any]) -> dict[str, Any]:
return {"name": self.name, "content": "系统版本: 1.0.1, 状态: 运行正常"}
@@ -51,7 +51,7 @@ class HelloCommand(PlusCommand):
command_aliases = ["hi", "你好"]
chat_type_allow = ChatType.ALL
async def execute(self, args: CommandArgs) -> Tuple[bool, Optional[str], bool]:
async def execute(self, args: CommandArgs) -> tuple[bool, str | None, bool]:
greeting = str(self.get_config("greeting.message", "Hello, World! 我是一个由 MoFox_Bot 驱动的插件。"))
await self.send_text(greeting)
return True, "成功发送问候", True
@@ -67,7 +67,7 @@ class RandomEmojiAction(BaseAction):
action_require = ["当对话气氛轻松时", "可以用来回应简单的情感表达"]
associated_types = ["text"]
async def execute(self) -> Tuple[bool, str]:
async def execute(self) -> tuple[bool, str]:
emojis = ["😊", "😂", "👍", "🎉", "🤔", "🤖"]
await self.send_text(random.choice(emojis))
return True, "成功发送了一个随机表情"
@@ -99,9 +99,9 @@ class HelloWorldPlugin(BasePlugin):
},
}
def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]:
def get_plugin_components(self) -> list[tuple[ComponentInfo, type]]:
"""根据配置文件动态注册插件的功能组件。"""
components: List[Tuple[ComponentInfo, Type]] = []
components: list[tuple[ComponentInfo, type]] = []
components.append((StartupMessageHandler.get_handler_info(), StartupMessageHandler))
components.append((GetSystemInfoTool.get_tool_info(), GetSystemInfoTool))