From 393227fdd26122ca106f2fb77ba4f6b429528b47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=95=80=E9=93=AC=E9=85=B8=E9=92=BE?= <148796996+K2cr2O1@users.noreply.github.com> Date: Mon, 23 Mar 2026 16:52:15 +0800 Subject: [PATCH 1/2] Dev (#77) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(discord): 修复 WebSocket 连接检测并增强跨平台文件处理 修复 Discord WebSocket 连接检测逻辑,使用正确的属性检查连接状态 为跨平台消息处理添加文件类型支持,并增加详细的调试日志 优化附件处理逻辑,确保所有文件类型都能正确识别和转发 * feat(跨平台): 优化消息处理并添加纯文本提取功能 添加 extract_text_only 函数过滤非文本标记 修改翻译逻辑仅处理纯文本内容 完善附件处理和消息内容拼接 修复仅包含表情时的消息处理问题 * refactor(discord-cross): 使用模块专用日志记录器替换全局日志记录器 将各模块中的全局日志记录器替换为模块专用日志记录器,以提供更清晰的日志来源标识 同时在适配器中添加会话状态检查和重连机制,提升消息发送的可靠性 * feat(翻译): 改进翻译功能,同时显示原文和译文 修改翻译功能,不再替换原文而是同时显示原文和翻译内容,方便用户对照 更新 DeepSeek API 配置为官方地址和模型 优化 Discord 适配器的重连逻辑,直接关闭 WebSocket 触发重连 修复 Discord 频道 ID 转换逻辑,简化处理流程 * feat(cross-platform): 添加跨平台功能支持及配置优化 - 新增跨平台配置模型和全局配置支持 - 优化 Discord 适配器的连接管理和错误处理 - 添加 watchdog 和 discord.py 依赖 - 创建 DeepSeek API 配置文档 - 移除重复的同步帮助图片代码 - 改进跨平台插件配置加载逻辑 * fix(jrcd): 修正群组ID检查条件 删除不再使用的示例插件文件 --- DEEPSEEK_API_SETUP.md | 32 ++++++++++ adapters/discord_adapter.py | 53 ++++++++++++++-- core/config_loader.py | 9 ++- core/config_models.py | 19 +++++- main.py | 5 -- plugins/class_style_example.py | 38 ------------ plugins/discord-cross/config.py | 100 ++++++++++++++++++++---------- plugins/jrcd.py | 2 +- plugins/simple_style_example.py | 41 ------------ plugins/sync_async_test_plugin.py | 88 -------------------------- requirements.txt | 2 + 11 files changed, 174 insertions(+), 215 deletions(-) create mode 100644 DEEPSEEK_API_SETUP.md delete mode 100644 plugins/class_style_example.py delete mode 100644 plugins/simple_style_example.py delete mode 100644 plugins/sync_async_test_plugin.py diff --git a/DEEPSEEK_API_SETUP.md b/DEEPSEEK_API_SETUP.md new file mode 100644 index 0000000..27081c7 --- /dev/null +++ b/DEEPSEEK_API_SETUP.md @@ -0,0 +1,32 @@ +# DeepSeek API 配置示例 + +将以下环境变量添加到你的系统环境变量或 .env 文件中: + +```bash +# DeepSeek API Key (从 https://platform.deepseek.com 获取) +DEEPSEEK_API_KEY=sk-你的实际API密钥 + +# DeepSeek API URL (可选,默认为官方 API) +DEEPSEEK_API_URL=https://api.deepseek.com/v1/chat/completions + +# DeepSeek 模型名称 (可选,默认为 deepseek-chat) +DEEPSEEK_MODEL=deepseek-chat +``` + +或者在 Windows 系统中,可以通过以下方式设置环境变量: + +**临时设置(仅当前会话有效):** +```powershell +$env:DEEPSEEK_API_KEY="sk-你的实际API密钥" +$env:DEEPSEEK_API_URL="https://api.deepseek.com/v1/chat/completions" +$env:DEEPSEEK_MODEL="deepseek-chat" +``` + +**永久设置(需要管理员权限):** +```powershell +[Environment]::SetEnvironmentVariable("DEEPSEEK_API_KEY", "sk-你的实际API密钥", "User") +[Environment]::SetEnvironmentVariable("DEEPSEEK_API_URL", "https://api.deepseek.com/v1/chat/completions", "User") +[Environment]::SetEnvironmentVariable("DEEPSEEK_MODEL", "deepseek-chat", "User") +``` + +设置完成后,重启终端或 IDE 使环境变量生效。 diff --git a/adapters/discord_adapter.py b/adapters/discord_adapter.py index f4c94b4..172d435 100644 --- a/adapters/discord_adapter.py +++ b/adapters/discord_adapter.py @@ -96,7 +96,7 @@ class DiscordAdapter(discord.Client if DISCORD_AVAILABLE else object): return try: - channel_name = "neobot_discord_send" + channel_name = "neobot_cross_platform" pubsub = redis_manager.redis.pubsub() await pubsub.subscribe(channel_name) @@ -319,23 +319,64 @@ class DiscordAdapter(discord.Client if DISCORD_AVAILABLE else object): except asyncio.CancelledError: self.logger.info("连接被取消") break + except discord.ConnectionClosed as e: + retry_count += 1 + self.logger.warning(f"Discord 连接关闭: code={e.code}, reason={e.reason}") + + # 如果是正常关闭,不计入重连次数 + if e.code == 1000: + self.logger.info("连接正常关闭,等待重新连接...") + continue + + if max_retries != -1 and retry_count >= max_retries: + self.logger.error(f"已达到最大重连次数 ({max_retries}),停止重连") + break + + self.logger.info(f"将在 {retry_delay} 秒后重连 ({retry_count}/{max_retries if max_retries != -1 else '无限'})...") + await self._cleanup_connection() + await asyncio.sleep(retry_delay) except Exception as e: retry_count += 1 - self.logger.error(f"Discord 连接失败: {e}") + self.logger.error(f"Discord 连接异常: {e}") if max_retries != -1 and retry_count >= max_retries: self.logger.error(f"已达到最大重连次数 ({max_retries}),停止重连") break self.logger.info(f"将在 {retry_delay} 秒后重连 ({retry_count}/{max_retries if max_retries != -1 else '无限'})...") - # 清理旧的连接状态 - if hasattr(self, 'http') and self.http: - await self.http.close() - self.clear() + await self._cleanup_connection() await asyncio.sleep(retry_delay) self.logger.info("Discord 客户端已停止") + async def _cleanup_connection(self): + """ + 清理旧的连接状态 + """ + try: + # 停止心跳任务 + if hasattr(self, 'heartbeat_task') and not self.heartbeat_task.done(): + self.heartbeat_task.cancel() + try: + await self.heartbeat_task + except asyncio.CancelledError: + pass + except Exception as e: + self.logger.error(f"清理心跳任务时出错: {e}") + + try: + # 清理 HTTP 连接 + if hasattr(self, 'http') and self.http: + await self.http.close() + except Exception as e: + self.logger.error(f"清理 HTTP 连接时出错: {e}") + + try: + # 清理客户端状态 + self.clear() + except Exception as e: + self.logger.error(f"清理客户端状态时出错: {e}") + async def start_heartbeat(self, interval: int = 30): """ 启动心跳机制,定期检查连接状态 diff --git a/core/config_loader.py b/core/config_loader.py index 1fdd706..f2b506f 100644 --- a/core/config_loader.py +++ b/core/config_loader.py @@ -7,7 +7,7 @@ from pathlib import Path import tomllib from pydantic import ValidationError -from .config_models import ConfigModel, NapCatWSModel, BotModel, RedisModel, DockerModel, ImageManagerModel, MySQLModel, ReverseWSModel, ThreadingModel, BilibiliModel, LocalFileServerModel, DiscordModel, LoggingModel +from .config_models import ConfigModel, NapCatWSModel, BotModel, RedisModel, DockerModel, ImageManagerModel, MySQLModel, ReverseWSModel, ThreadingModel, BilibiliModel, LocalFileServerModel, DiscordModel, CrossPlatformModel, LoggingModel from .utils.logger import ModuleLogger from .utils.exceptions import ConfigError, ConfigNotFoundError, ConfigValidationError @@ -164,6 +164,13 @@ class Config: """ return self._model.discord + @property + def cross_platform(self) -> CrossPlatformModel: + """ + 获取跨平台配置 + """ + return self._model.cross_platform + @property def logging(self) -> LoggingModel: """ diff --git a/core/config_models.py b/core/config_models.py index e97978c..48e6c41 100644 --- a/core/config_models.py +++ b/core/config_models.py @@ -13,7 +13,7 @@ class NapCatWSModel(BaseModel): 对应 `config.toml` 中的 `[napcat_ws]` 配置块。 """ uri: str - token: str + token: str = "" reconnect_interval: int = 5 @@ -117,6 +117,22 @@ class DiscordModel(BaseModel): proxy_type: str = "http" +class CrossPlatformMapping(BaseModel): + """ + 跨平台映射配置 + """ + qq_group_id: int + name: str + + +class CrossPlatformModel(BaseModel): + """ + 对应 `config.toml` 中的 `[cross_platform]` 配置块。 + """ + enabled: bool = False + mappings: Optional[dict[int, CrossPlatformMapping]] = None + + class LoggingModel(BaseModel): """ 对应 `config.toml` 中的 `[logging]` 配置块。 @@ -141,6 +157,7 @@ class ConfigModel(BaseModel): bilibili: BilibiliModel = Field(default_factory=BilibiliModel) local_file_server: LocalFileServerModel = Field(default_factory=LocalFileServerModel) discord: DiscordModel = Field(default_factory=DiscordModel) + cross_platform: CrossPlatformModel = Field(default_factory=CrossPlatformModel) logging: LoggingModel = Field(default_factory=LoggingModel) diff --git a/main.py b/main.py index 852a978..a6793eb 100644 --- a/main.py +++ b/main.py @@ -120,16 +120,11 @@ async def main(): # 同步帮助图片 await matcher.sync_help_pic() - # 同步帮助图片 - await matcher.sync_help_pic() - # 初始化权限管理器(包含了管理员管理功能) await permission_manager.initialize() # 初始化浏览器管理器 (使用页面池) await browser_manager.init_pool(size=3) - - # 启动反向 WebSocket 服务端(如果启用) if config.reverse_ws.enabled: logger.info("正在启动反向 WebSocket 服务端...") asyncio.create_task(reverse_ws_manager.start( diff --git a/plugins/class_style_example.py b/plugins/class_style_example.py deleted file mode 100644 index 7a7c54a..0000000 --- a/plugins/class_style_example.py +++ /dev/null @@ -1,38 +0,0 @@ -from core.plugin import Plugin, command, on_message -from models.events.message import MessageEvent -from core.permission import Permission - -# 插件元信息 -__plugin_meta__ = { - "name": "类风格插件示例", - "description": "演示如何使用类风格编写插件", - "usage": "/hello - 打招呼\n/echo - 复读消息", -} - -class MyPlugin(Plugin): - def __init__(self): - super().__init__() - # 可以在这里初始化一些状态 - self.count = 0 - - @command("hello") - async def hello(self, event: MessageEvent, args: list[str]): - self.count += 1 - await self.reply(event, f"Hello from class-based plugin! (Called {self.count} times)") - - @command("echo", permission=Permission.USER) - async def echo(self, event: MessageEvent, args: list[str]): - if args: - await self.reply(event, " ".join(args)) - else: - await self.reply(event, "请输入要复读的内容。") - - @on_message() - async def handle_message(self, event: MessageEvent): - # 这是一个通用的消息处理器,会处理所有消息 - # 注意:这可能会与命令冲突,通常需要过滤 - if "特定关键词" in event.raw_message: - await self.reply(event, "检测到特定关键词!") - -# 实例化插件以注册 -plugin = MyPlugin() diff --git a/plugins/discord-cross/config.py b/plugins/discord-cross/config.py index e1a2153..f4737f6 100644 --- a/plugins/discord-cross/config.py +++ b/plugins/discord-cross/config.py @@ -5,6 +5,7 @@ import os from typing import Dict, Any from core.utils.logger import ModuleLogger +from core.config_loader import global_config # 创建模块专用日志记录器 logger = ModuleLogger("CrossPlatformConfig") @@ -15,50 +16,81 @@ class CrossPlatformConfig: self.CROSS_PLATFORM_CHANNEL = "neobot_cross_platform" self.ENABLE_CROSS_PLATFORM = True - # DeepSeek API 配置 - self.DEEPSEEK_API_KEY = "sk-7b824b05e85445f8a9ceef6c849388a9" - self.DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions" - self.DEEPSEEK_MODEL = "deepseek-chat" + # DeepSeek API 配置 - 从环境变量或配置文件加载 + self.DEEPSEEK_API_KEY = os.environ.get("DEEPSEEK_API_KEY", "") + self.DEEPSEEK_API_URL = os.environ.get("DEEPSEEK_API_URL", "https://api.deepseek.com/v1/chat/completions") + self.DEEPSEEK_MODEL = os.environ.get("DEEPSEEK_MODEL", "deepseek-chat") # 是否启用翻译功能 self.ENABLE_TRANSLATION = True + + # 从全局配置加载 + self.load_from_global_config() + + def load_from_global_config(self): + """从全局配置加载跨平台配置""" + if global_config and hasattr(global_config, 'cross_platform'): + cross_platform_config = global_config.cross_platform + if cross_platform_config: + self.ENABLE_CROSS_PLATFORM = getattr(cross_platform_config, 'enabled', True) + self.CROSS_PLATFORM_MAP = {} + + # 加载 mappings + if hasattr(cross_platform_config, 'mappings') and cross_platform_config.mappings: + for discord_id, mapping in cross_platform_config.mappings.items(): + if isinstance(mapping, dict): + self.CROSS_PLATFORM_MAP[discord_id] = { + "qq_group_id": int(mapping.get("qq_group_id", 0)), + "name": mapping.get("name", "") + } + elif hasattr(mapping, 'qq_group_id'): + self.CROSS_PLATFORM_MAP[discord_id] = { + "qq_group_id": int(mapping.qq_group_id), + "name": getattr(mapping, 'name', "") + } + logger.success(f"[CrossPlatform] 从全局配置加载了 {len(self.CROSS_PLATFORM_MAP)} 个映射") async def reload(self): """重新加载配置""" try: - config_path = os.path.join(os.path.dirname(__file__), "..", "..", "config.toml") + # 优先使用全局配置 + self.load_from_global_config() - if os.path.exists(config_path): - try: - import tomllib - except ImportError: - import tomli as tomllib + # 如果全局配置不可用,尝试从文件加载 + if not self.CROSS_PLATFORM_MAP: + config_path = os.path.join(os.path.dirname(__file__), "..", "..", "config.toml") - with open(config_path, "rb") as f: - config_data = tomllib.load(f) + if os.path.exists(config_path): + try: + import tomllib + except ImportError: + import tomli as tomllib - cross_platform_config = config_data.get("cross_platform", {}) - self.ENABLE_CROSS_PLATFORM = cross_platform_config.get("enabled", True) - - # 重新加载映射配置 - mappings = cross_platform_config.get("mappings", {}) - self.CROSS_PLATFORM_MAP.clear() - - if isinstance(mappings, dict) and mappings: - for key, value in mappings.items(): - if isinstance(value, dict) and "qq_group_id" in value: - try: - # 直接将 key 转换为整数 - discord_id = int(str(key)) - self.CROSS_PLATFORM_MAP[discord_id] = { - "qq_group_id": int(value.get("qq_group_id", 0)), - "name": value.get("name", "") - } - except (ValueError, AttributeError): - logger.warning(f"[CrossPlatform] 无效的 Discord 频道 ID: {key}") - continue - - logger.success(f"[CrossPlatform] 配置已重新加载: {len(self.CROSS_PLATFORM_MAP)} 个映射") + with open(config_path, "rb") as f: + config_data = tomllib.load(f) + + cross_platform_config = config_data.get("cross_platform", {}) + self.ENABLE_CROSS_PLATFORM = cross_platform_config.get("enabled", True) + + # 重新加载映射配置 + mappings = cross_platform_config.get("mappings", {}) + self.CROSS_PLATFORM_MAP.clear() + + if isinstance(mappings, dict) and mappings: + for key, value in mappings.items(): + if isinstance(value, dict) and "qq_group_id" in value: + try: + # 直接将 key 转换为整数 + discord_id = int(str(key)) + self.CROSS_PLATFORM_MAP[discord_id] = { + "qq_group_id": int(value.get("qq_group_id", 0)), + "name": value.get("name", "") + } + except (ValueError, AttributeError): + logger.warning(f"[CrossPlatform] 无效的 Discord 频道 ID: {key}") + continue + + logger.success(f"[CrossPlatform] 配置已重新加载: {len(self.CROSS_PLATFORM_MAP)} 个映射") except Exception as e: logger.error(f"[CrossPlatform] 重新加载配置失败: {e}") diff --git a/plugins/jrcd.py b/plugins/jrcd.py index ffc6436..7364f2b 100644 --- a/plugins/jrcd.py +++ b/plugins/jrcd.py @@ -129,7 +129,7 @@ async def handle_jrcd_stats(bot: Bot, event: MessageEvent, args: list[str]): @matcher.command("bbcd") async def handle_bbcd(bot: Bot, event: MessageEvent, args: list[str]): - if event.id == 831797331: + if event.group_id == 831797331: return None """ 处理 bbcd 指令,比较两位用户的“长度”。 diff --git a/plugins/simple_style_example.py b/plugins/simple_style_example.py deleted file mode 100644 index 6fa9df2..0000000 --- a/plugins/simple_style_example.py +++ /dev/null @@ -1,41 +0,0 @@ -from core.plugin import SimplePlugin -from models.events.message import MessageEvent - -# 插件元信息 -__plugin_meta__ = { - "name": "极简插件示例", - "description": "演示面向新手的极简插件写法", - "usage": "/ping - 测试\n/add - 加法\n/greet - 问候", -} - -class MySimplePlugin(SimplePlugin): - - async def ping(self, event: MessageEvent): - """ - 发送 /ping 即可调用 - """ - return "Pong! (来自极简插件)" - - async def greet(self, event: MessageEvent, name: str): - """ - 发送 /greet Neo 即可调用 - """ - return f"你好, {name}!" - - async def add(self, event: MessageEvent, a: int, b: int): - """ - 发送 /add 10 20 即可调用 - 自动处理类型转换 - """ - return f"{a} + {b} = {a + b}" - - async def echo_all(self, event: MessageEvent, msg: str): - """ - 只有一个参数时,会自动捕获所有剩余文本 - 发送 /echo_all 这是一个 测试 消息 - msg 将会是 "这是一个 测试 消息" - """ - return f"复读: {msg}" - -# 实例化插件以生效 -plugin = MySimplePlugin() diff --git a/plugins/sync_async_test_plugin.py b/plugins/sync_async_test_plugin.py deleted file mode 100644 index ffaa1a8..0000000 --- a/plugins/sync_async_test_plugin.py +++ /dev/null @@ -1,88 +0,0 @@ -""" -同步/异步函数测试插件 - -用于演示 SyncHandlerError 异常以及如何将同步函数放入线程池执行。 -""" -import time -from typing import Any -from core.managers.command_manager import matcher -from core.utils.executor import run_in_thread_pool -from core.bot import Bot -from core.utils.logger import logger - -# 插件元数据 -__plugin_meta__ = { - "name": "SyncAsyncTestPlugin", - "description": "用于测试同步/异步函数处理的插件。", - "usage": ( - "/test_sync_error - 尝试注册一个同步函数作为异步处理器,会触发错误。\n" - "/test_blocking_task - 演示将同步阻塞任务放入线程池执行。" - ), -} - -# --- 示例 1: 触发 SyncHandlerError (此函数不会被成功注册) --- - -# 这是一个同步函数,如果直接用 @matcher.message_handler 装饰, -# 并且 event_handler 检查到它是同步的,就会抛出 SyncHandlerError。 -# 注意:为了演示错误,我们不会真正注册它,因为注册会失败。 -def _sync_function_that_should_fail(bot: Bot, event: Any): - """ - 一个同步函数,如果直接作为异步事件处理器注册,会触发 SyncHandlerError。 - """ - logger.info("这个同步函数不应该被直接调用。") - return "这是一个同步函数的结果。" - -# --- 示例 2: 将同步阻塞任务放入线程池运行 --- - -def _blocking_task(duration: int) -> str: - """ - 一个模拟耗时操作的同步函数。 - Args: - duration (int): 模拟阻塞的秒数。 - Returns: - str: 任务完成消息。 - """ - logger.info(f"同步阻塞任务开始,持续 {duration} 秒...") - time.sleep(duration) - logger.info("同步阻塞任务结束。") - return f"阻塞任务完成,耗时 {duration} 秒。" - -@matcher.message_handler.command("test_blocking_task") -async def test_blocking_task_handler(bot: Bot, event: Any, args: list): - """ - 处理 /test_blocking_task 命令,将同步阻塞任务放入线程池执行。 - Args: - bot (Bot): 机器人实例。 - event (Any): 接收到的事件对象。 - args (list): 命令参数列表。 - """ - if not args: - await bot.send(event, "请提供阻塞时长,例如:/test_blocking_task 5") - return - - try: - duration = int(args[0]) - if duration <= 0: - raise ValueError("时长必须是正整数。") - except ValueError: - await bot.send(event, "无效的时长,请提供一个正整数。") - return - - await bot.send(event, f"开始执行同步阻塞任务,预计耗时 {duration} 秒...") - - # 将同步函数放入线程池执行 - result = await run_in_thread_pool(_blocking_task, duration) - - await bot.send(event, f"同步阻塞任务已完成:{result}") - -# --- 示例 3: 尝试注册一个同步函数作为异步处理器 (会失败) --- -# 这个函数不会被成功注册,因为 event_handler 会检测到它是同步的并抛出 SyncHandlerError。 -# 插件管理器会捕获这个错误并跳过加载此插件。 -# 为了演示,我们故意尝试注册它。 -# @matcher.message_handler.command("test_sync_error") -# def test_sync_error_handler(bot: Bot, event: Any): -# """ -# 这个同步函数尝试作为异步处理器注册,会触发 SyncHandlerError。 -# """ -# logger.error("这个同步函数不应该被直接注册为异步处理器。") -# return "这个消息不应该被看到。" diff --git a/requirements.txt b/requirements.txt index e7ccb63..6fad1ff 100644 --- a/requirements.txt +++ b/requirements.txt @@ -85,6 +85,7 @@ sympy==1.14.0 trove_classifiers==2026.1.14.14 urllib3_secure_extra==0.1.0 uvloop==0.22.1 +watchdog==6.0.0 websocket_client==1.9.0 Werkzeug==3.1.6 winloop==0.5.0 @@ -92,3 +93,4 @@ wmi==1.5.1 xmlrpclib==1.0.1 xx==3.3.2 zope==5.13 +discord.py==2.3.2 From 6b9bdeeff2ac5feab2eb385b45cf0433ef89776a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=95=80=E9=93=AC=E9=85=B8=E9=92=BE?= <148796996+K2cr2O1@users.noreply.github.com> Date: Tue, 24 Mar 2026 14:01:30 +0800 Subject: [PATCH 2/2] Dev (#78) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(discord): 修复 WebSocket 连接检测并增强跨平台文件处理 修复 Discord WebSocket 连接检测逻辑,使用正确的属性检查连接状态 为跨平台消息处理添加文件类型支持,并增加详细的调试日志 优化附件处理逻辑,确保所有文件类型都能正确识别和转发 * feat(跨平台): 优化消息处理并添加纯文本提取功能 添加 extract_text_only 函数过滤非文本标记 修改翻译逻辑仅处理纯文本内容 完善附件处理和消息内容拼接 修复仅包含表情时的消息处理问题 * refactor(discord-cross): 使用模块专用日志记录器替换全局日志记录器 将各模块中的全局日志记录器替换为模块专用日志记录器,以提供更清晰的日志来源标识 同时在适配器中添加会话状态检查和重连机制,提升消息发送的可靠性 * feat(翻译): 改进翻译功能,同时显示原文和译文 修改翻译功能,不再替换原文而是同时显示原文和翻译内容,方便用户对照 更新 DeepSeek API 配置为官方地址和模型 优化 Discord 适配器的重连逻辑,直接关闭 WebSocket 触发重连 修复 Discord 频道 ID 转换逻辑,简化处理流程 * feat(cross-platform): 添加跨平台功能支持及配置优化 - 新增跨平台配置模型和全局配置支持 - 优化 Discord 适配器的连接管理和错误处理 - 添加 watchdog 和 discord.py 依赖 - 创建 DeepSeek API 配置文档 - 移除重复的同步帮助图片代码 - 改进跨平台插件配置加载逻辑 * fix(jrcd): 修正群组ID检查条件 删除不再使用的示例插件文件 * feat: 改进配置加载逻辑并更新项目配置 当配置文件不存在时自动生成示例配置 添加pyproject.toml作为项目构建配置 更新.gitignore忽略更多文件类型 删除不再使用的反向WebSocket示例文件 * docs: 更新架构文档和项目结构说明 添加反向WebSocket连接模式说明 补充核心管理器文档 更新项目结构文件 在文档首页添加特色功能说明 * fix(discord): 修复WebSocket连接检查并添加错误日志 refactor(config): 更新配置文件的网络和认证信息 feat(cross-platform): 为跨平台消息处理添加异常捕获和日志 --- .gitignore | 28 +- adapters/discord_adapter.py | 21 +- adapters/router.py | 430 ++++++++++++----------- core/config_loader.py | 21 +- docs/core-concepts/architecture.md | 24 +- docs/core-concepts/singleton-managers.md | 28 ++ docs/index.md | 8 +- docs/project-structure.md | 112 +++--- examples/reverse_ws_example.py | 58 --- plugins/discord-cross/handlers.py | 372 ++++++++++---------- pyproject.toml | 91 +++++ 11 files changed, 681 insertions(+), 512 deletions(-) delete mode 100644 examples/reverse_ws_example.py create mode 100644 pyproject.toml diff --git a/.gitignore b/.gitignore index 866e375..9cab923 100644 --- a/.gitignore +++ b/.gitignore @@ -115,7 +115,7 @@ env/ venv/ ENV/ env.bak/ -venv.bak/ +venv.bak() # Spyder project settings .spyderproject @@ -138,6 +138,9 @@ dmypy.json # pytype static type analyzer .pytype/ +# Cython +*.c + # End of https://www.toptal.com/developers/gitignore/api/python # Build artifacts @@ -146,4 +149,27 @@ build/ # Scratch files scratch_files/ +# Sensitive files (should never be committed) +config.toml +config.example.toml +ca/* +*.pem +*.key + +# Data directory (may contain sensitive data) /core/data/* + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Logs +logs/ +*.log diff --git a/adapters/discord_adapter.py b/adapters/discord_adapter.py index 172d435..0a7fb39 100644 --- a/adapters/discord_adapter.py +++ b/adapters/discord_adapter.py @@ -88,6 +88,9 @@ class DiscordAdapter(discord.Client if DISCORD_AVAILABLE else object): await matcher.handle_event(mock_event.bot, mock_event) except Exception as e: self.logger.error(f"处理 Discord 消息时发生异常: {e}") + # 记录详细的异常信息 + import traceback + self.logger.error(f"异常堆栈: {traceback.format_exc()}") async def start_redis_subscription(self): """启动 Redis 订阅以处理跨平台消息发送""" @@ -386,16 +389,20 @@ class DiscordAdapter(discord.Client if DISCORD_AVAILABLE else object): """ self.logger.info(f"心跳机制已启动,间隔: {interval}秒") - while self.is_closed() is False: + while not self.is_closed(): try: await asyncio.sleep(interval) - # discord.py 的 ws 对象是 DiscordWebSocket,它没有 closed 属性 - # 我们可以通过检查 self.is_closed() 或者 ws.open 来判断 - if self.ws is not None and not getattr(self.ws, 'open', True): - self.logger.warning("检测到 WebSocket 连接已关闭,触发重连...") - await self.ws.close(4000) - break + # 检查 WebSocket 连接状态 + if self.ws is not None: + # 正确检查 WebSocket 状态 + if not getattr(self.ws, 'open', False): + self.logger.warning("检测到 WebSocket 连接已关闭,触发重连...") + try: + await self.ws.close(code=4000) + except Exception as close_error: + self.logger.error(f"关闭 WebSocket 连接时出错: {close_error}") + break self.logger.debug(f"心跳正常: {self.user}") diff --git a/adapters/router.py b/adapters/router.py index 46a5844..e1c97ef 100644 --- a/adapters/router.py +++ b/adapters/router.py @@ -84,117 +84,117 @@ class DiscordBotWrapper: content = "" files = [] - for node in nodes: - if node.get("type") == "node": - node_data = node.get("data", {}) - node_content = node_data.get("content", []) - - if isinstance(node_content, str): - import re - cq_pattern = r'\[CQ:([^,]+)(?:,([^\]]+))?\]' - matches = list(re.finditer(cq_pattern, node_content)) - - if not matches: - content += f"{node_content}\n" - else: - last_end = 0 - for match in matches: - if match.start() > last_end: - content += node_content[last_end:match.start()] - - cq_type = match.group(1) - cq_params_str = match.group(2) or "" - - params = {} - if cq_params_str: - for param in cq_params_str.split(','): - if '=' in param: - k, v = param.split('=', 1) - params[k] = v - - if cq_type in ("image", "video", "record"): - file_url = params.get("url") or params.get("file") - if file_url: - if str(file_url).startswith("http"): - content += f"\n{file_url}\n" - elif str(file_url).startswith("base64://"): - import base64 - import io - b64_data = str(file_url)[9:] - if b64_data.startswith("data:image") or b64_data.startswith("data:audio") or b64_data.startswith("data:video"): - b64_data = b64_data.split(",", 1)[1] - try: - file_bytes = base64.b64decode(b64_data) - filename = "file.png" if cq_type == "image" else ("file.mp4" if cq_type == "video" else "file.ogg") - files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) - except Exception as e: - logger.error(f"解析 Base64 文件失败: {e}") - else: - try: - files.append(discord.File(file_url)) - except Exception as e: - logger.error(f"无法读取本地文件 {file_url}: {e}") - elif cq_type == "face": - # QQ 表情,简单转为文本 - face_id = params.get("id") - content += f"[表情:{face_id}]" - elif cq_type == "at": - qq_id = params.get("qq") - if qq_id == "all": - content += "@everyone " - else: - content += f"<@{qq_id}> " - - last_end = match.end() - - if last_end < len(node_content): - content += node_content[last_end:] - content += "\n" - elif isinstance(node_content, list): - for seg in node_content: - if isinstance(seg, dict): - seg_type = seg.get("type") - seg_data = seg.get("data", {}) - - if seg_type == "text": - content += seg_data.get("text", "") - elif seg_type in ("image", "video", "record"): - file_url = seg_data.get("url") or seg_data.get("file") - if file_url: - if isinstance(file_url, bytes): - import io - try: - filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") - files.append(discord.File(fp=io.BytesIO(file_url), filename=filename)) - except Exception as e: - logger.error(f"解析 bytes 文件失败: {e}") - elif str(file_url).startswith("http"): - content += f"\n{file_url}\n" - elif str(file_url).startswith("base64://") or "data:image" in str(file_url) or "data:audio" in str(file_url) or "data:video" in str(file_url): - import base64 - import io - b64_data = str(file_url) - if b64_data.startswith("base64://"): - b64_data = b64_data[9:] - if b64_data.startswith("data:image") or b64_data.startswith("data:audio") or b64_data.startswith("data:video"): - b64_data = b64_data.split(",", 1)[1] - try: - file_bytes = base64.b64decode(b64_data) - filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") - files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) - except Exception as e: - logger.error(f"解析 Base64 文件失败: {e}") - else: - try: - files.append(discord.File(file_url)) - except Exception as e: - logger.error(f"无法读取本地文件 {file_url}: {e}") - elif seg_type == "face": - face_id = seg_data.get("id") - content += f"[表情:{face_id}]" - content += "\n" - try: + for node in nodes: + if node.get("type") == "node": + node_data = node.get("data", {}) + node_content = node_data.get("content", []) + + if isinstance(node_content, str): + import re + cq_pattern = r'\[CQ:([^,]+)(?:,([^\]]+))?\]' + matches = list(re.finditer(cq_pattern, node_content)) + + if not matches: + content += f"{node_content}\n" + else: + last_end = 0 + for match in matches: + if match.start() > last_end: + content += node_content[last_end:match.start()] + + cq_type = match.group(1) + cq_params_str = match.group(2) or "" + + params = {} + if cq_params_str: + for param in cq_params_str.split(','): + if '=' in param: + k, v = param.split('=', 1) + params[k] = v + + if cq_type in ("image", "video", "record"): + file_url = params.get("url") or params.get("file") + if file_url: + if str(file_url).startswith("http"): + content += f"\n{file_url}\n" + elif str(file_url).startswith("base64://"): + import base64 + import io + b64_data = str(file_url)[9:] + if b64_data.startswith("data:image") or b64_data.startswith("data:audio") or b64_data.startswith("data:video"): + b64_data = b64_data.split(",", 1)[1] + try: + file_bytes = base64.b64decode(b64_data) + filename = "file.png" if cq_type == "image" else ("file.mp4" if cq_type == "video" else "file.ogg") + files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) + except Exception as e: + logger.error(f"解析 Base64 文件失败: {e}") + else: + try: + files.append(discord.File(file_url)) + except Exception as e: + logger.error(f"无法读取本地文件 {file_url}: {e}") + elif cq_type == "face": + # QQ 表情,简单转为文本 + face_id = params.get("id") + content += f"[表情:{face_id}]" + elif cq_type == "at": + qq_id = params.get("qq") + if qq_id == "all": + content += "@everyone " + else: + content += f"<@{qq_id}> " + + last_end = match.end() + + if last_end < len(node_content): + content += node_content[last_end:] + content += "\n" + elif isinstance(node_content, list): + for seg in node_content: + if isinstance(seg, dict): + seg_type = seg.get("type") + seg_data = seg.get("data", {}) + + if seg_type == "text": + content += seg_data.get("text", "") + elif seg_type in ("image", "video", "record"): + file_url = seg_data.get("url") or seg_data.get("file") + if file_url: + if isinstance(file_url, bytes): + import io + try: + filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") + files.append(discord.File(fp=io.BytesIO(file_url), filename=filename)) + except Exception as e: + logger.error(f"解析 bytes 文件失败: {e}") + elif str(file_url).startswith("http"): + content += f"\n{file_url}\n" + elif str(file_url).startswith("base64://") or "data:image" in str(file_url) or "data:audio" in str(file_url) or "data:video" in str(file_url): + import base64 + import io + b64_data = str(file_url) + if b64_data.startswith("base64://"): + b64_data = b64_data[9:] + if b64_data.startswith("data:image") or b64_data.startswith("data:audio") or b64_data.startswith("data:video"): + b64_data = b64_data.split(",", 1)[1] + try: + file_bytes = base64.b64decode(b64_data) + filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") + files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) + except Exception as e: + logger.error(f"解析 Base64 文件失败: {e}") + else: + try: + files.append(discord.File(file_url)) + except Exception as e: + logger.error(f"无法读取本地文件 {file_url}: {e}") + elif seg_type == "face": + face_id = seg_data.get("id") + content += f"[表情:{face_id}]" + content += "\n" + if content or files: # target is usually event, we can use event.bot.send if isinstance(target, GroupMessageEvent): @@ -209,6 +209,8 @@ class DiscordBotWrapper: await user.dm_channel.send(content=content, files=files if files else None) except Exception as e: logger.error(f"发送 Discord 合并转发消息失败: {e}") + import traceback + logger.error(f"异常堆栈: {traceback.format_exc()}") class DiscordToOneBotConverter: """ @@ -416,45 +418,105 @@ class DiscordToOneBotConverter: content = "" files = [] - # 统一转换为列表处理 - if not isinstance(message, list): - message = [message] - - import re - - for segment in message: - if isinstance(segment, str): - # 尝试解析 CQ 码 - cq_pattern = r'\[CQ:([^,]+)(?:,([^\]]+))?\]' - matches = list(re.finditer(cq_pattern, segment)) + try: + # 统一转换为列表处理 + if not isinstance(message, list): + message = [message] - if not matches: - content += segment - continue + import re + + for segment in message: + if isinstance(segment, str): + # 尝试解析 CQ 码 + cq_pattern = r'\[CQ:([^,]+)(?:,([^\]]+))?\]' + matches = list(re.finditer(cq_pattern, segment)) - last_end = 0 - for match in matches: - # 添加 CQ 码之前的纯文本 - if match.start() > last_end: - content += segment[last_end:match.start()] + if not matches: + content += segment + continue - cq_type = match.group(1) - cq_params_str = match.group(2) or "" - - # 解析参数 - params = {} - if cq_params_str: - for param in cq_params_str.split(','): - if '=' in param: - k, v = param.split('=', 1) - params[k] = v + last_end = 0 + for match in matches: + # 添加 CQ 码之前的纯文本 + if match.start() > last_end: + content += segment[last_end:match.start()] + + cq_type = match.group(1) + cq_params_str = match.group(2) or "" + + # 解析参数 + params = {} + if cq_params_str: + for param in cq_params_str.split(','): + if '=' in param: + k, v = param.split('=', 1) + params[k] = v + + if cq_type in ("image", "video", "record"): + file_url = params.get("url") or params.get("file") + if file_url: + if str(file_url).startswith("http"): + content += f"\n{file_url}" + elif str(file_url).startswith("base64://") or "data:image" in str(file_url) or "data:audio" in str(file_url) or "data:video" in str(file_url): + import base64 + import io + b64_data = str(file_url) + if b64_data.startswith("base64://"): + b64_data = b64_data[9:] + if b64_data.startswith("data:image") or b64_data.startswith("data:audio") or b64_data.startswith("data:video"): + b64_data = b64_data.split(",", 1)[1] + try: + file_bytes = base64.b64decode(b64_data) + filename = "file.png" if cq_type == "image" else ("file.mp4" if cq_type == "video" else "file.ogg") + files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) + except Exception as e: + logger.error(f"解析 Base64 文件失败: {e}") + else: + try: + files.append(discord.File(file_url)) + except Exception as e: + logger.error(f"无法读取本地文件 {file_url}: {e}") + elif cq_type == "face": + face_id = params.get("id") + content += f"[表情:{face_id}]" + elif cq_type == "at": + qq_id = params.get("qq") + if qq_id == "all": + content += "@everyone " + else: + content += f"<@{qq_id}> " - if cq_type in ("image", "video", "record"): - file_url = params.get("url") or params.get("file") + last_end = match.end() + + # 添加最后一个 CQ 码之后的纯文本 + if last_end < len(segment): + content += segment[last_end:] + + elif isinstance(segment, OneBotMessageSegment): + # 解析 OneBot 的 MessageSegment + seg_type = segment.type + seg_data = segment.data + + if seg_type == "text": + content += seg_data.get("text", "") + elif seg_type in ("image", "video", "record"): + # OneBot 的图片/视频/语音通常有 file (URL或本地路径) 或 url 字段 + file_url = seg_data.get("url") or seg_data.get("file") + if file_url: - if str(file_url).startswith("http"): + # 处理 bytes 类型 + if isinstance(file_url, bytes): + import io + try: + filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") + files.append(discord.File(fp=io.BytesIO(file_url), filename=filename)) + except Exception as e: + logger.error(f"解析 bytes 文件失败: {e}") + elif str(file_url).startswith("http"): + # 如果是网络 URL,直接拼接到文本中,Discord 会自动解析预览 content += f"\n{file_url}" elif str(file_url).startswith("base64://") or "data:image" in str(file_url) or "data:audio" in str(file_url) or "data:video" in str(file_url): + # 处理 Base64 文件 (需要解码并作为文件上传) import base64 import io b64_data = str(file_url) @@ -464,91 +526,31 @@ class DiscordToOneBotConverter: b64_data = b64_data.split(",", 1)[1] try: file_bytes = base64.b64decode(b64_data) - filename = "file.png" if cq_type == "image" else ("file.mp4" if cq_type == "video" else "file.ogg") + filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) except Exception as e: logger.error(f"解析 Base64 文件失败: {e}") else: + # 假设是本地文件路径 try: files.append(discord.File(file_url)) except Exception as e: logger.error(f"无法读取本地文件 {file_url}: {e}") - elif cq_type == "face": - face_id = params.get("id") + elif seg_type == "face": + face_id = seg_data.get("id") content += f"[表情:{face_id}]" - elif cq_type == "at": - qq_id = params.get("qq") + elif seg_type == "at": + qq_id = seg_data.get("qq") if qq_id == "all": content += "@everyone " else: + # 尝试将 QQ 号映射回 Discord ID (这里简单处理,直接拼接) content += f"<@{qq_id}> " - - last_end = match.end() - - # 添加最后一个 CQ 码之后的纯文本 - if last_end < len(segment): - content += segment[last_end:] - - elif isinstance(segment, OneBotMessageSegment): - # 解析 OneBot 的 MessageSegment - seg_type = segment.type - seg_data = segment.data - - if seg_type == "text": - content += seg_data.get("text", "") - elif seg_type in ("image", "video", "record"): - # OneBot 的图片/视频/语音通常有 file (URL或本地路径) 或 url 字段 - file_url = seg_data.get("url") or seg_data.get("file") - - if file_url: - # 处理 bytes 类型 - if isinstance(file_url, bytes): - import io - try: - filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") - files.append(discord.File(fp=io.BytesIO(file_url), filename=filename)) - except Exception as e: - logger.error(f"解析 bytes 文件失败: {e}") - elif str(file_url).startswith("http"): - # 如果是网络 URL,直接拼接到文本中,Discord 会自动解析预览 - content += f"\n{file_url}" - elif str(file_url).startswith("base64://") or "data:image" in str(file_url) or "data:audio" in str(file_url) or "data:video" in str(file_url): - # 处理 Base64 文件 (需要解码并作为文件上传) - import base64 - import io - b64_data = str(file_url) - if b64_data.startswith("base64://"): - b64_data = b64_data[9:] - if b64_data.startswith("data:image") or b64_data.startswith("data:audio") or b64_data.startswith("data:video"): - b64_data = b64_data.split(",", 1)[1] - try: - file_bytes = base64.b64decode(b64_data) - filename = "file.png" if seg_type == "image" else ("file.mp4" if seg_type == "video" else "file.ogg") - files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename)) - except Exception as e: - logger.error(f"解析 Base64 文件失败: {e}") - else: - # 假设是本地文件路径 - try: - files.append(discord.File(file_url)) - except Exception as e: - logger.error(f"无法读取本地文件 {file_url}: {e}") - elif seg_type == "face": - face_id = seg_data.get("id") - content += f"[表情:{face_id}]" - elif seg_type == "at": - qq_id = seg_data.get("qq") - if qq_id == "all": - content += "@everyone " - else: - # 尝试将 QQ 号映射回 Discord ID (这里简单处理,直接拼接) - content += f"<@{qq_id}> " - elif seg_type == "reply": - # 忽略回复段,或者你可以尝试映射 message_id - pass + elif seg_type == "reply": + # 忽略回复段,或者你可以尝试映射 message_id + pass - # 发送消息到 Discord - try: + # 发送消息到 Discord # 如果内容为空但有文件,Discord 允许发送 if content or files: await channel.send(content=content, files=files if files else None) @@ -556,3 +558,5 @@ class DiscordToOneBotConverter: logger.warning("尝试发送空消息到 Discord,已拦截") except Exception as e: logger.error(f"发送 Discord 消息失败: {e}") + import traceback + logger.error(f"异常堆栈: {traceback.format_exc()}") diff --git a/core/config_loader.py b/core/config_loader.py index f2b506f..ad332aa 100644 --- a/core/config_loader.py +++ b/core/config_loader.py @@ -38,10 +38,10 @@ class Config: :raises ConfigError: 如果加载配置时发生其他错误 """ if not self.path.exists(): - error = ConfigNotFoundError(message=f"配置文件 {self.path} 未找到!") - self.logger.error(f"配置加载失败: {error.message}") - self.logger.log_custom_exception(error) - raise error + self.logger.warning(f"配置文件 {self.path} 未找到,正在生成示例配置...") + self._generate_example_config() + self.logger.success(f"示例配置已生成: {self.path}") + self.logger.info("请编辑配置文件后重新启动程序") try: self.logger.info(f"正在从 {self.path} 加载配置...") @@ -86,6 +86,19 @@ class Config: self.logger.log_custom_exception(error) raise error + def _generate_example_config(self): + """ + 生成示例配置文件 + """ + example_path = Path("config.example.toml") + + if not example_path.exists(): + self.logger.error(f"示例配置文件 {example_path} 不存在,无法生成配置") + raise ConfigNotFoundError(message=f"示例配置文件 {example_path} 不存在") + + content = example_path.read_text() + self.path.write_text(content) + # 通过属性访问配置 @property def napcat_ws(self) -> NapCatWSModel: diff --git a/docs/core-concepts/architecture.md b/docs/core-concepts/architecture.md index d1c1dc7..27e905b 100644 --- a/docs/core-concepts/architecture.md +++ b/docs/core-concepts/architecture.md @@ -47,9 +47,12 @@ python setup_mypyc.py build_ext --inplace ## 2. 连接架构 -### 正向 WebSocket 连接 +### WebSocket 连接模式 -NEO Bot 采用**正向 WebSocket 连接**模式:Bot 主动连接 OneBot 实现(如 NapCatQQ)。 +NEO Bot 支持两种 WebSocket 连接模式,可根据需求在 `config.toml` 中配置: + +#### 1. 正向 WebSocket 连接 (默认) +Bot 主动连接 OneBot 实现(如 NapCatQQ)。 **流程**: @@ -63,6 +66,23 @@ Bot 启动 → 连接到 NapCatQQ (ws://127.0.0.1:3001) 调用 API 回复 ``` +#### 2. 反向 WebSocket 连接 +OneBot 客户端主动连接 Bot 提供的 WebSocket 服务。 + +**流程**: + +``` +Bot 启动反向 WS 服务 (监听 0.0.0.0:3002) + ↓ +NapCatQQ 主动连接到 Bot + ↓ + 监听消息事件 + ↓ + 分发到处理器 + ↓ + 调用 API 回复 +``` + ## 3. 资源管理架构 ### 单例管理器 diff --git a/docs/core-concepts/singleton-managers.md b/docs/core-concepts/singleton-managers.md index 9801c3b..ce98f82 100644 --- a/docs/core-concepts/singleton-managers.md +++ b/docs/core-concepts/singleton-managers.md @@ -65,6 +65,34 @@ * **记性好**: 模板用一次就记住,下次直接用缓存。 * **自动借还**: 它会自动找 `BrowserManager` 借页面,你只管 `render_template` 就行。 +### 8. `BotManager` (`bot_manager`) + +* **怎么找**: `from core.managers.bot_manager import bot_manager` +* **管啥**: + * **Bot 实例管理**: 统一管理 Bot 实例,方便在任何地方获取当前运行的 Bot。 + * **生命周期**: 协助管理 Bot 的启动和关闭流程。 + +### 9. `MysqlManager` (`mysql_manager`) + +* **怎么找**: `from core.managers.mysql_manager import mysql_manager` +* **管啥**: + * **数据库连接**: 管理与 MySQL 数据库的异步连接池。 + * **数据持久化**: 提供执行 SQL 语句的接口,用于需要长期保存的数据。 + +### 10. `ReverseWsManager` (`reverse_ws_manager`) + +* **怎么找**: `from core.managers.reverse_ws_manager import reverse_ws_manager` +* **管啥**: + * **反向 WS 服务**: 启动并管理反向 WebSocket 服务器,允许 OneBot 客户端主动连接 Bot。 + * **连接管理**: 处理客户端的连接、断开和消息接收。 + +### 11. `ThreadManager` (`thread_manager`) + +* **怎么找**: `from core.managers.thread_manager import thread_manager` +* **管啥**: + * **线程池管理**: 提供全局的线程池执行器,用于执行阻塞的同步任务。 + * **异步桥接**: 方便地将同步函数转换为异步调用,避免阻塞事件循环。 + ## 咋用? `import` diff --git a/docs/index.md b/docs/index.md index c9c848b..2ef6b32 100644 --- a/docs/index.md +++ b/docs/index.md @@ -16,7 +16,7 @@ * [架构设计](./core-concepts/architecture.md) - 了解框架的设计理念 * [性能优化](./core-concepts/performance.md) - JIT、Mypyc、页面池等优化技术 * [事件流程](./core-concepts/event-flow.md) - 一条消息从接收到回复的完整流程 -* [核心管理器](./core-concepts/singleton-managers.md) - matcher、权限管理、浏览器池等 +* [核心管理器](./core-concepts/singleton-managers.md) - matcher、权限管理、浏览器池、数据库等 * [Redis原子操作](./core-concepts/redis-atomic-operations.md) - 权限管理的分布式实现 * [多线程架构](./core-concepts/multithreading.md) - 线程池和线程安全设计 * [错误处理](./core-concepts/error-handling.md) - 异常处理和错误码体系 @@ -29,6 +29,12 @@ * [账号 API](./api/account.md) - 机器人自身信息获取 * [媒体 API](./api/media.md) - 图片、语音、视频处理 +### 🌟 特色功能 +* **多平台互通** - 支持 Discord 与 QQ 频道的跨平台消息互通 +* **本地文件服务** - 内置轻量级 HTTP 文件服务器,方便传输大文件和媒体 +* **多数据库支持** - 同时支持 Redis 缓存和 MySQL 持久化存储 +* **反向 WebSocket** - 支持 OneBot 客户端主动连接 Bot + ### 📚 插件开发 * [插件入门](./plugin-development/index.md) - 写你的第一个插件 * [指令处理](./plugin-development/command-handling.md) - 参数解析、权限控制等 diff --git a/docs/project-structure.md b/docs/project-structure.md index 51a6da9..43bc987 100644 --- a/docs/project-structure.md +++ b/docs/project-structure.md @@ -4,41 +4,50 @@ ``` . +├── adapters/ # 适配器层(多平台支持) +│ ├── discord_adapter.py # Discord 适配器 +│ └── router.py # 消息路由 +│ ├── core/ # 核心代码,别乱动 │ ├── api/ # OneBot API 封装(消息、群组、好友、账号、媒体) │ ├── handlers/ # 底层事件处理器 │ ├── managers/ # 全局单例管理器 -│ │ ├── command_manager.py # 指令分发和事件处理 -│ │ ├── plugin_manager.py # 插件加载和热重载 -│ │ ├── permission_manager.py # 权限管理(Admin/User两级) +│ │ ├── bot_manager.py # Bot 实例管理 │ │ ├── browser_manager.py # Playwright页面池 +│ │ ├── command_manager.py # 指令分发和事件处理 │ │ ├── image_manager.py # 图片/HTML模板渲染 -│ │ └── redis_manager.py # Redis缓存管理 +│ │ ├── mysql_manager.py # MySQL 数据库管理 +│ │ ├── permission_manager.py # 权限管理(Admin/User两级) +│ │ ├── plugin_manager.py # 插件加载和热重载 +│ │ ├── redis_manager.py # Redis缓存管理 +│ │ ├── reverse_ws_manager.py # 反向 WebSocket 管理 +│ │ └── thread_manager.py # 线程池管理 +│ ├── services/ # 核心服务 +│ │ └── local_file_server.py # 本地文件服务 │ ├── utils/ # 工具函数和异常类 +│ │ ├── error_codes.py # 错误码定义 +│ │ ├── exceptions.py # 自定义异常类 +│ │ ├── executor.py # 代码沙箱执行引擎(Docker) │ │ ├── logger.py # 日志系统(Loguru) │ │ ├── performance.py # 性能分析工具 -│ │ ├── executor.py # 代码沙箱执行引擎(Docker) -│ │ ├── exceptions.py # 自定义异常类 │ │ └── singleton.py # 单例模式基类 -│ ├── ws.py # WebSocket 连接和消息处理(已Mypyc编译) +│ ├── ws.py # WebSocket 连接和消息处理 │ ├── bot.py # Bot 核心实例 │ ├── config_loader.py # 配置文件加载 │ ├── config_models.py # 配置数据模型 │ └── permission.py # 权限枚举类 │ -├── data/ # 持久化数据 -│ ├── admin.json # 管理员列表 -│ └── permissions.json # 用户权限配置 -│ ├── models/ # 数据模型 │ ├── events/ # OneBot 11 事件模型 +│ │ ├── base.py # 基础事件模型 +│ │ ├── factory.py # 事件工厂 │ │ ├── message.py # 消息事件 +│ │ ├── meta.py # 元事件 │ │ ├── notice.py # 通知事件 -│ │ ├── request.py # 请求事件 -│ │ └── factory.py # 事件工厂 +│ │ └── request.py # 请求事件 │ ├── message.py # 消息段(CQ码) -│ ├── sender.py # 发送者信息 -│ └── objects.py # API响应对象(群信息、用户信息等) +│ ├── objects.py # API响应对象(群信息、用户信息等) +│ └── sender.py # 发送者信息 │ ├── plugins/ # 你的插件都放这(最常修改的地方) │ ├── admin.py # 权限管理(Admin/User两级权限) @@ -46,66 +55,79 @@ │ ├── bot_status.py # Bot运行状态查询(图片形式) │ ├── broadcast.py # 管理员专用广播功能(隐藏插件) │ ├── code_py.py # Python代码沙箱执行(多行输入、图片输出) +│ ├── discord-cross/ # Discord 跨平台互通插件 │ ├── echo.py # Echo和点赞功能 │ ├── furry.py # Furry图片获取 │ ├── github_parser.py # GitHub仓库链接自动解析 +│ ├── group_welcome.py # 群欢迎插件 │ ├── jrcd.py # 今日人品/长度查询(随机生成) +│ ├── mirror_avatar.py # 镜像头像获取 +│ ├── osu!_plugin/ # osu! 相关功能插件 +│ ├── resource/ # 插件资源文件 │ ├── thpic.py # 东方Project随机图片 -│ ├── web_parser/ # 综合Web链接解析系统 -│ │ ├── __init__.py # 主入口,自动检测链接 -│ │ ├── parsers/ # 各平台解析器 -│ │ │ ├── bili.py # B站视频/直播解析 -│ │ │ ├── douyin.py # 抖音视频解析 -│ │ │ └── github.py # GitHub仓库解析 -│ │ └── utils.py # 解析工具函数 -│ ├── sync_async_test_plugin.py # 异步同步混用测试(开发用) -│ └── resource/ # 插件资源文件 +│ ├── weather.py # 天气查询插件 +│ └── web_parser/ # 综合Web链接解析系统 +│ ├── __init__.py # 主入口,自动检测链接 +│ ├── base.py # 解析器基类 +│ ├── parsers/ # 各平台解析器 +│ │ ├── bili.py # B站视频/直播解析 +│ │ ├── douyin.py # 抖音视频解析 +│ │ └── github.py # GitHub仓库解析 +│ └── utils.py # 解析工具函数 │ ├── templates/ # Jinja2 HTML模板 │ ├── code_execution.html # 代码执行结果展示 │ ├── github_repo.html # GitHub仓库信息展示 │ ├── help.html # 帮助页面 -│ └── status.html # Bot状态页面 +│ ├── status.html # Bot状态页面 +│ └── weather.html # 天气展示页面 │ ├── web_static/ # 静态资源 +│ ├── changelog.html # 更新日志页面 +│ ├── changelog_generator/# 更新日志生成器 │ └── html/ # HTML资源文件 │ -├── logs/ # 日志输出目录 -│ └── bot.log # 主日志文件 -│ ├── tests/ # 单元测试 │ ├── test_api.py # API功能测试 +│ ├── test_basic.py # 基础测试 │ ├── test_bot.py # Bot核心测试 │ ├── test_command_manager.py # 指令管理器测试 +│ ├── test_config_loader.py # 配置加载测试 +│ ├── test_core_managers.py # 核心管理器测试 +│ ├── test_event_factory.py # 事件工厂测试 +│ ├── test_event_handler.py # 事件处理器测试 +│ ├── test_executor.py # 执行器测试 +│ ├── test_models.py # 模型测试 │ ├── test_performance.py # 性能测试 -│ └── ... # 其他测试文件 +│ ├── test_plugin_manager_coverage.py # 插件管理器覆盖率测试 +│ ├── test_plugin_reload_meta.py # 插件重载测试 +│ ├── test_redis_manager.py # Redis管理器测试 +│ ├── test_thread_manager.py # 线程管理器测试 +│ ├── test_ws.py # WebSocket测试 +│ └── test_ws_pool.py # WebSocket池测试 │ ├── docs/ # 开发文档 -│ ├── index.md # 文档首页 -│ ├── getting-started.md # 快速上手 -│ ├── project-structure.md # 项目结构(本文件) -│ ├── deployment.md # 生产环境部署 -│ ├── core-concepts/ # 核心概念详解 │ ├── api/ # API参考文档 -│ └── plugin-development/ # 插件开发指南 +│ ├── core-concepts/ # 核心概念详解 +│ ├── plugin-development/ # 插件开发指南 +│ ├── deployment.md # 生产环境部署 +│ ├── development-standards.md # 开发规范 +│ ├── getting-started.md # 快速上手 +│ ├── index.md # 文档首页 +│ └── project-structure.md # 项目结构(本文件) │ ├── scripts/ # 工具脚本 +│ ├── add_plugins.py # 添加插件脚本 │ ├── check_python_env.py # Python环境检查 │ ├── compile_machine_code.py # 机器码编译 │ └── export_requirements.py # 依赖导出 │ -├── venv/ # Python 虚拟环境(git忽略) -├── __pycache__/ # Python缓存(git忽略) -├── .gitignore # Git忽略配置 +├── bili_login.py # B站登录脚本 +├── DEEPSEEK_API_SETUP.md # DeepSeek API 设置文档 ├── main.py # 启动入口 -├── config.toml # 配置文件(包含WS、Redis、Docker配置) -├── pytest.ini # 测试配置 +├── pyproject.toml # 项目配置 ├── requirements.txt # Python依赖列表 -├── requirements-dev.txt # 开发依赖(包括pytest、mypy等) -├── setup_mypyc.py # Mypyc编译脚本(可选性能优化) -├── check_syntax.py # 语法检查脚本 -├── profile_main.py # 性能分析脚本 -├── test_performance_simple.py # 简单性能测试 +├── requirements-dev.txt # 开发依赖 ├── sandbox.Dockerfile # 代码沙箱Docker镜像 ├── LICENSE # 许可证 └── README.md # 项目README diff --git a/examples/reverse_ws_example.py b/examples/reverse_ws_example.py deleted file mode 100644 index f3c9b23..0000000 --- a/examples/reverse_ws_example.py +++ /dev/null @@ -1,58 +0,0 @@ -""" -反向 WebSocket 使用示例 - -该文件展示了如何使用反向 WebSocket 功能。 -""" - -from core.managers import reverse_ws_manager - - -async def example_usage(): - """ - 使用示例 - """ - # 1. 启动反向 WebSocket 服务端 - await reverse_ws_manager.start(host="0.0.0.0", port=3002) - - # 2. 等待客户端连接 - # 此时 OneBot 实现(如 NapCat)应该连接到 ws://your-server-ip:3002 - - # 3. 查看已连接的客户端 - connected_clients = reverse_ws_manager.get_connected_clients() - print(f"已连接的客户端: {connected_clients}") - - # 4. 查看健康的客户端 - healthy_clients = reverse_ws_manager.get_healthy_clients() - print(f"健康的客户端: {healthy_clients}") - - # 5. 调用 API(使用负载均衡) - response = await reverse_ws_manager.call_api( - action="get_login_info", - params={}, - use_load_balance=True # 启用负载均衡 - ) - print(f"API 响应: {response}") - - # 6. 调用 API(向特定客户端发送) - if connected_clients: - client_id = list(connected_clients.keys())[0] - response = await reverse_ws_manager.call_api( - action="get_login_info", - params={}, - client_id=client_id, - use_load_balance=False # 不使用负载均衡 - ) - print(f"特定客户端 API 响应: {response}") - - # 7. 获取负载最低的客户端 - least_load_client = reverse_ws_manager.get_client_with_least_load() - if least_load_client: - print(f"负载最低的客户端: {least_load_client}") - - # 8. 停止服务端 - await reverse_ws_manager.stop() - - -if __name__ == "__main__": - import asyncio - asyncio.run(example_usage()) diff --git a/plugins/discord-cross/handlers.py b/plugins/discord-cross/handlers.py index fe2efff..0ed3a2e 100644 --- a/plugins/discord-cross/handlers.py +++ b/plugins/discord-cross/handlers.py @@ -51,195 +51,205 @@ async def handle_qq_message( @matcher.on_message() async def handle_qq_group_message(event: GroupMessageEvent): """处理 QQ 群消息,转发到 Discord""" - if not config.ENABLE_CROSS_PLATFORM: - return - - group_id = event.group_id - mapped_channel = None - for discord_channel_id, info in config.CROSS_PLATFORM_MAP.items(): - if info["qq_group_id"] == group_id: - mapped_channel = discord_channel_id - break - - if mapped_channel is None: - return - - content = "" - attachments = [] - - if isinstance(event.message, list): - has_forward_node = any(isinstance(seg, MessageSegment) and seg.type == "node" for seg in event.message) - - if has_forward_node: - forward_nodes = [seg for seg in event.message if isinstance(seg, MessageSegment) and seg.type == "node"] - forward_nodes_dict = [{"type": seg.type, "data": seg.data} for seg in forward_nodes] - content, attachments = await parse_forward_nodes(forward_nodes_dict) - else: - for segment in event.message: - if isinstance(segment, MessageSegment): - if segment.type == "text": - content += segment.data.get("text", "") - elif segment.type == "image": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_url = html.unescape(str(file_url)) - if not file_name: - file_name = os.path.basename(file_url.split('?')[0]) or f"image_{len(attachments)}.jpg" - attachments.append({"type": "image", "url": file_url, "filename": file_name}) - elif segment.type == "video": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_url = html.unescape(str(file_url)) - if not file_name: - file_name = os.path.basename(file_url.split('?')[0]) or f"video_{len(attachments)}.mp4" - attachments.append({"type": "video", "url": file_url, "filename": file_name}) - elif segment.type == "record": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_url = html.unescape(str(file_url)) - if not file_name: - file_name = os.path.basename(file_url.split('?')[0]) or f"record_{len(attachments)}.amr" - attachments.append({"type": "record", "url": file_url, "filename": file_name}) - content += f"\n[语音: {file_name}]\n" - elif segment.type == "file": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_url = html.unescape(str(file_url)) - if not file_name: - file_name = os.path.basename(file_url.split('?')[0]) or f"file_{len(attachments)}" - attachments.append({"type": "file", "url": file_url, "filename": file_name}) - content += f"\n[文件: {file_name}]\n" - logger.debug(f"[CrossPlatform] QQ 消息识别到文件: {file_name}, URL: {file_url}") - elif segment.type == "at": - qq_id = segment.data.get("qq") - if qq_id and qq_id != "all": - content += f"@{qq_id} " - elif qq_id == "all": - content += "@所有人 " - elif isinstance(segment, str): - content += segment - elif isinstance(event.message, str): - content = event.message - - import re - local_file_pattern = r'(http://[\w\.-]+:\d+/download\?id=file_[a-zA-Z0-9_]+)' - matches = re.finditer(local_file_pattern, content) - for match in matches: - file_url = match.group(1) - file_name = f"video_{len(attachments)}.mp4" - attachments.append({"type": "video", "url": file_url, "filename": file_name}) - - content = content.strip() - - group_name = "" try: - group_info = await event.bot.get_group_info(event.group_id) - group_name = group_info.get("group_name", "") - except Exception: - group_name = f"群{group_id}" - - await handle_qq_message( - nickname=event.sender.nickname or event.sender.card or str(event.user_id), - user_id=event.user_id, - group_name=group_name, - group_id=group_id, - content=content, - attachments=attachments - ) + if not config.ENABLE_CROSS_PLATFORM: + return + + group_id = event.group_id + mapped_channel = None + for discord_channel_id, info in config.CROSS_PLATFORM_MAP.items(): + if info["qq_group_id"] == group_id: + mapped_channel = discord_channel_id + break + + if mapped_channel is None: + return + + content = "" + attachments = [] + + if isinstance(event.message, list): + has_forward_node = any(isinstance(seg, MessageSegment) and seg.type == "node" for seg in event.message) + + if has_forward_node: + forward_nodes = [seg for seg in event.message if isinstance(seg, MessageSegment) and seg.type == "node"] + forward_nodes_dict = [{"type": seg.type, "data": seg.data} for seg in forward_nodes] + content, attachments = await parse_forward_nodes(forward_nodes_dict) + else: + for segment in event.message: + if isinstance(segment, MessageSegment): + if segment.type == "text": + content += segment.data.get("text", "") + elif segment.type == "image": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_url = html.unescape(str(file_url)) + if not file_name: + file_name = os.path.basename(file_url.split('?')[0]) or f"image_{len(attachments)}.jpg" + attachments.append({"type": "image", "url": file_url, "filename": file_name}) + elif segment.type == "video": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_url = html.unescape(str(file_url)) + if not file_name: + file_name = os.path.basename(file_url.split('?')[0]) or f"video_{len(attachments)}.mp4" + attachments.append({"type": "video", "url": file_url, "filename": file_name}) + elif segment.type == "record": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_url = html.unescape(str(file_url)) + if not file_name: + file_name = os.path.basename(file_url.split('?')[0]) or f"record_{len(attachments)}.amr" + attachments.append({"type": "record", "url": file_url, "filename": file_name}) + content += f"\n[语音: {file_name}]\n" + elif segment.type == "file": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_url = html.unescape(str(file_url)) + if not file_name: + file_name = os.path.basename(file_url.split('?')[0]) or f"file_{len(attachments)}" + attachments.append({"type": "file", "url": file_url, "filename": file_name}) + content += f"\n[文件: {file_name}]\n" + logger.debug(f"[CrossPlatform] QQ 消息识别到文件: {file_name}, URL: {file_url}") + elif segment.type == "at": + qq_id = segment.data.get("qq") + if qq_id and qq_id != "all": + content += f"@{qq_id} " + elif qq_id == "all": + content += "@所有人 " + elif isinstance(segment, str): + content += segment + elif isinstance(event.message, str): + content = event.message + + import re + local_file_pattern = r'(http://[\w\.-]+:\d+/download\?id=file_[a-zA-Z0-9_]+)' + matches = re.finditer(local_file_pattern, content) + for match in matches: + file_url = match.group(1) + file_name = f"video_{len(attachments)}.mp4" + attachments.append({"type": "video", "url": file_url, "filename": file_name}) + + content = content.strip() + + group_name = "" + try: + group_info = await event.bot.get_group_info(event.group_id) + group_name = group_info.get("group_name", "") + except Exception: + group_name = f"群{group_id}" + + await handle_qq_message( + nickname=event.sender.nickname or event.sender.card or str(event.user_id), + user_id=event.user_id, + group_name=group_name, + group_id=group_id, + content=content, + attachments=attachments + ) + except Exception as e: + logger.error(f"[CrossPlatform] 处理 QQ 群消息失败: {e}") + import traceback + logger.error(f"[CrossPlatform] 异常堆栈: {traceback.format_exc()}") @matcher.on_message() async def handle_discord_message_event(event: Any): """处理 Discord 消息事件(通过适配器注入)""" - if not config.ENABLE_CROSS_PLATFORM: - return + try: + if not config.ENABLE_CROSS_PLATFORM: + return + + logger.debug(f"[CrossPlatform] handle_discord_message_event 触发: {event}") + if not hasattr(event, '_is_discord_message'): + logger.debug(f"[CrossPlatform] 事件没有 _is_discord_message 属性,跳过") + return + + logger.debug(f"[CrossPlatform] 检测到 Discord 事件") + discord_channel_id = getattr(event, 'discord_channel_id', None) + if discord_channel_id is None: + logger.debug(f"[CrossPlatform] discord_channel_id 为 None") + return + + content = "" + attachments = [] - logger.debug(f"[CrossPlatform] handle_discord_message_event 触发: {event}") - if not hasattr(event, '_is_discord_message'): - logger.debug(f"[CrossPlatform] 事件没有 _is_discord_message 属性,跳过") - return + logger.debug(f"[CrossPlatform] 开始处理 Discord 事件消息: channel_id={discord_channel_id}") - logger.debug(f"[CrossPlatform] 检测到 Discord 事件") - discord_channel_id = getattr(event, 'discord_channel_id', None) - if discord_channel_id is None: - logger.debug(f"[CrossPlatform] discord_channel_id 为 None") - return + if hasattr(event, 'message') and isinstance(event.message, list): + has_text_content = False + for segment in event.message: + if isinstance(segment, MessageSegment): + if segment.type == "text": + content += segment.data.get("text", "") + has_text_content = True + elif segment.type == "image": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "image" + attachment_item = {"type": "image", "url": str(file_url), "filename": file_name} + if attachment_item not in attachments: + attachments.append(attachment_item) + content += f"\n[图片: {file_name}]\n" + elif segment.type == "video": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "video" + attachment_item = {"type": "video", "url": str(file_url), "filename": file_name} + if attachment_item not in attachments: + attachments.append(attachment_item) + content += f"\n[视频: {file_name}]\n" + elif segment.type == "record": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "record" + attachment_item = {"type": "record", "url": str(file_url), "filename": file_name} + if attachment_item not in attachments: + attachments.append(attachment_item) + content += f"\n[语音: {file_name}]\n" + elif segment.type == "file": + file_url = segment.data.get("url") or segment.data.get("file") + file_name = segment.data.get("filename") + if file_url: + file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "file" + attachment_item = {"type": "file", "url": str(file_url), "filename": file_name} + if attachment_item not in attachments: + attachments.append(attachment_item) + content += f"\n[文件: {file_name}]\n" + logger.debug(f"[CrossPlatform] Discord 消息识别到文件: {file_name}, URL: {file_url}") + else: + content = event.raw_message or "" - content = "" - attachments = [] - - logger.debug(f"[CrossPlatform] 开始处理 Discord 事件消息: channel_id={discord_channel_id}") - - if hasattr(event, 'message') and isinstance(event.message, list): - has_text_content = False - for segment in event.message: - if isinstance(segment, MessageSegment): - if segment.type == "text": - content += segment.data.get("text", "") - has_text_content = True - elif segment.type == "image": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "image" - attachment_item = {"type": "image", "url": str(file_url), "filename": file_name} - if attachment_item not in attachments: - attachments.append(attachment_item) - content += f"\n[图片: {file_name}]\n" - elif segment.type == "video": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "video" - attachment_item = {"type": "video", "url": str(file_url), "filename": file_name} - if attachment_item not in attachments: - attachments.append(attachment_item) - content += f"\n[视频: {file_name}]\n" - elif segment.type == "record": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "record" - attachment_item = {"type": "record", "url": str(file_url), "filename": file_name} - if attachment_item not in attachments: - attachments.append(attachment_item) - content += f"\n[语音: {file_name}]\n" - elif segment.type == "file": - file_url = segment.data.get("url") or segment.data.get("file") - file_name = segment.data.get("filename") - if file_url: - file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "file" - attachment_item = {"type": "file", "url": str(file_url), "filename": file_name} - if attachment_item not in attachments: - attachments.append(attachment_item) - content += f"\n[文件: {file_name}]\n" - logger.debug(f"[CrossPlatform] Discord 消息识别到文件: {file_name}, URL: {file_url}") - else: - content = event.raw_message or "" - - content = content.strip() - - # 如果 content 为空但有附件(如只有表情),使用 raw_message 作为 content - if not content and attachments: - content = event.raw_message or "" - - logger.debug(f"[CrossPlatform] Discord 消息内容: '{content}', 附件数量: {len(attachments)}") - - discord_username = getattr(event, 'discord_username', 'Unknown') - discord_discriminator = getattr(event, 'discord_discriminator', '') - - logger.debug(f"[CrossPlatform] 调用 handle_discord_message: username={discord_username}, channel_id={discord_channel_id}") - await handle_discord_message( - username=discord_username, - discriminator=discord_discriminator, - content=content, - channel_id=discord_channel_id, - attachments=attachments, - embed=None - ) + content = content.strip() + + # 如果 content 为空但有附件(如只有表情),使用 raw_message 作为 content + if not content and attachments: + content = event.raw_message or "" + + logger.debug(f"[CrossPlatform] Discord 消息内容: '{content}', 附件数量: {len(attachments)}") + + discord_username = getattr(event, 'discord_username', 'Unknown') + discord_discriminator = getattr(event, 'discord_discriminator', '') + + logger.debug(f"[CrossPlatform] 调用 handle_discord_message: username={discord_username}, channel_id={discord_channel_id}") + await handle_discord_message( + username=discord_username, + discriminator=discord_discriminator, + content=content, + channel_id=discord_channel_id, + attachments=attachments, + embed=None + ) + except Exception as e: + logger.error(f"[CrossPlatform] 处理 Discord 消息事件失败: {e}") + import traceback + logger.error(f"[CrossPlatform] 异常堆栈: {traceback.format_exc()}") @matcher.command("cross_config", "跨平台配置", permission=Permission.ADMIN) async def cross_config_command(event: MessageEvent): diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..dd735b5 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,91 @@ +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "neobot" +version = "0.1.0" +description = "NEO Bot Framework - A high-performance bot framework" +readme = "README.md" +requires-python = ">=3.14" +license = {text = "MIT"} +authors = [ + {name = "Neo", email = "neo@example.com"} +] +keywords = ["bot", "discord", "qq", "onebot"] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.14", +] + +dependencies = [ + "aiohttp>=3.9.0", + "websockets>=12.0", + "playwright>=1.40.0", + "redis>=5.0.0", + "orjson>=3.9.0", + "loguru>=0.7.0", + "tomlkit>=0.12.0", + "watchdog>=3.0.0", + "discord.py>=2.0.0", + "aiohappyeyeballs>=2.6.1", + "aiomysql>=0.2.0", + "beautifulsoup4>=4.12.0", + "requests>=2.31.0", + "cython>=3.0.0", +] + +[project.optional-dependencies] +dev = [ + "pyinstrument>=4.5.0", + "memory-profiler>=0.61.0", + "psutil>=5.9.8", + "pytest>=7.4.0", + "pytest-asyncio>=0.21.0", + "flake8>=7.0.0", + "mypy>=1.5.0", +] + +[project.urls] +Homepage = "https://github.com/yourusername/neobot" +Documentation = "https://github.com/yourusername/neobot#readme" +Repository = "https://github.com/yourusername/neobot" +"Bug Tracker" = "https://github.com/yourusername/neobot/issues" + +[tool.setuptools] +packages = ["core", "models", "plugins", "adapters"] +package-dir = {"" = "."} + +[tool.setuptools.package-data] +"core" = ["py.typed"] +"plugins" = ["**/*.py"] +"models" = ["**/*.py"] + +[tool.setuptools.exclude-package-data] +"*" = [ + "config.toml", + "config.example.toml", + "ca/*", + "*.pem", + "*.key", +] + +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py"] +asyncio_mode = "auto" + +[tool.mypy] +python_version = "3.14" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = true +check_untyped_defs = true +no_implicit_optional = true +warn_redundant_casts = true +warn_subclassing = true +strict_optional = true +plugins = ["mypy.plugins.asyncio"]