Dev (#78)
* 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): 为跨平台消息处理添加异常捕获和日志
This commit is contained in:
28
.gitignore
vendored
28
.gitignore
vendored
@@ -115,7 +115,7 @@ env/
|
|||||||
venv/
|
venv/
|
||||||
ENV/
|
ENV/
|
||||||
env.bak/
|
env.bak/
|
||||||
venv.bak/
|
venv.bak()
|
||||||
|
|
||||||
# Spyder project settings
|
# Spyder project settings
|
||||||
.spyderproject
|
.spyderproject
|
||||||
@@ -138,6 +138,9 @@ dmypy.json
|
|||||||
# pytype static type analyzer
|
# pytype static type analyzer
|
||||||
.pytype/
|
.pytype/
|
||||||
|
|
||||||
|
# Cython
|
||||||
|
*.c
|
||||||
|
|
||||||
# End of https://www.toptal.com/developers/gitignore/api/python
|
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||||
|
|
||||||
# Build artifacts
|
# Build artifacts
|
||||||
@@ -146,4 +149,27 @@ build/
|
|||||||
# Scratch files
|
# Scratch files
|
||||||
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/*
|
/core/data/*
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
|||||||
@@ -88,6 +88,9 @@ class DiscordAdapter(discord.Client if DISCORD_AVAILABLE else object):
|
|||||||
await matcher.handle_event(mock_event.bot, mock_event)
|
await matcher.handle_event(mock_event.bot, mock_event)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"处理 Discord 消息时发生异常: {e}")
|
self.logger.error(f"处理 Discord 消息时发生异常: {e}")
|
||||||
|
# 记录详细的异常信息
|
||||||
|
import traceback
|
||||||
|
self.logger.error(f"异常堆栈: {traceback.format_exc()}")
|
||||||
|
|
||||||
async def start_redis_subscription(self):
|
async def start_redis_subscription(self):
|
||||||
"""启动 Redis 订阅以处理跨平台消息发送"""
|
"""启动 Redis 订阅以处理跨平台消息发送"""
|
||||||
@@ -386,16 +389,20 @@ class DiscordAdapter(discord.Client if DISCORD_AVAILABLE else object):
|
|||||||
"""
|
"""
|
||||||
self.logger.info(f"心跳机制已启动,间隔: {interval}秒")
|
self.logger.info(f"心跳机制已启动,间隔: {interval}秒")
|
||||||
|
|
||||||
while self.is_closed() is False:
|
while not self.is_closed():
|
||||||
try:
|
try:
|
||||||
await asyncio.sleep(interval)
|
await asyncio.sleep(interval)
|
||||||
|
|
||||||
# discord.py 的 ws 对象是 DiscordWebSocket,它没有 closed 属性
|
# 检查 WebSocket 连接状态
|
||||||
# 我们可以通过检查 self.is_closed() 或者 ws.open 来判断
|
if self.ws is not None:
|
||||||
if self.ws is not None and not getattr(self.ws, 'open', True):
|
# 正确检查 WebSocket 状态
|
||||||
self.logger.warning("检测到 WebSocket 连接已关闭,触发重连...")
|
if not getattr(self.ws, 'open', False):
|
||||||
await self.ws.close(4000)
|
self.logger.warning("检测到 WebSocket 连接已关闭,触发重连...")
|
||||||
break
|
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}")
|
self.logger.debug(f"心跳正常: {self.user}")
|
||||||
|
|
||||||
|
|||||||
@@ -84,117 +84,117 @@ class DiscordBotWrapper:
|
|||||||
content = ""
|
content = ""
|
||||||
files = []
|
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:
|
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:
|
if content or files:
|
||||||
# target is usually event, we can use event.bot.send
|
# target is usually event, we can use event.bot.send
|
||||||
if isinstance(target, GroupMessageEvent):
|
if isinstance(target, GroupMessageEvent):
|
||||||
@@ -209,6 +209,8 @@ class DiscordBotWrapper:
|
|||||||
await user.dm_channel.send(content=content, files=files if files else None)
|
await user.dm_channel.send(content=content, files=files if files else None)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"发送 Discord 合并转发消息失败: {e}")
|
logger.error(f"发送 Discord 合并转发消息失败: {e}")
|
||||||
|
import traceback
|
||||||
|
logger.error(f"异常堆栈: {traceback.format_exc()}")
|
||||||
|
|
||||||
class DiscordToOneBotConverter:
|
class DiscordToOneBotConverter:
|
||||||
"""
|
"""
|
||||||
@@ -416,45 +418,105 @@ class DiscordToOneBotConverter:
|
|||||||
content = ""
|
content = ""
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
# 统一转换为列表处理
|
try:
|
||||||
if not isinstance(message, list):
|
# 统一转换为列表处理
|
||||||
message = [message]
|
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))
|
|
||||||
|
|
||||||
if not matches:
|
import re
|
||||||
content += segment
|
|
||||||
continue
|
for segment in message:
|
||||||
|
if isinstance(segment, str):
|
||||||
|
# 尝试解析 CQ 码
|
||||||
|
cq_pattern = r'\[CQ:([^,]+)(?:,([^\]]+))?\]'
|
||||||
|
matches = list(re.finditer(cq_pattern, segment))
|
||||||
|
|
||||||
last_end = 0
|
if not matches:
|
||||||
for match in matches:
|
content += segment
|
||||||
# 添加 CQ 码之前的纯文本
|
continue
|
||||||
if match.start() > last_end:
|
|
||||||
content += segment[last_end:match.start()]
|
|
||||||
|
|
||||||
cq_type = match.group(1)
|
last_end = 0
|
||||||
cq_params_str = match.group(2) or ""
|
for match in matches:
|
||||||
|
# 添加 CQ 码之前的纯文本
|
||||||
# 解析参数
|
if match.start() > last_end:
|
||||||
params = {}
|
content += segment[last_end:match.start()]
|
||||||
if cq_params_str:
|
|
||||||
for param in cq_params_str.split(','):
|
cq_type = match.group(1)
|
||||||
if '=' in param:
|
cq_params_str = match.group(2) or ""
|
||||||
k, v = param.split('=', 1)
|
|
||||||
params[k] = v
|
# 解析参数
|
||||||
|
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"):
|
last_end = match.end()
|
||||||
file_url = params.get("url") or params.get("file")
|
|
||||||
|
# 添加最后一个 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 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}"
|
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):
|
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 base64
|
||||||
import io
|
import io
|
||||||
b64_data = str(file_url)
|
b64_data = str(file_url)
|
||||||
@@ -464,91 +526,31 @@ class DiscordToOneBotConverter:
|
|||||||
b64_data = b64_data.split(",", 1)[1]
|
b64_data = b64_data.split(",", 1)[1]
|
||||||
try:
|
try:
|
||||||
file_bytes = base64.b64decode(b64_data)
|
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))
|
files.append(discord.File(fp=io.BytesIO(file_bytes), filename=filename))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"解析 Base64 文件失败: {e}")
|
logger.error(f"解析 Base64 文件失败: {e}")
|
||||||
else:
|
else:
|
||||||
|
# 假设是本地文件路径
|
||||||
try:
|
try:
|
||||||
files.append(discord.File(file_url))
|
files.append(discord.File(file_url))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"无法读取本地文件 {file_url}: {e}")
|
logger.error(f"无法读取本地文件 {file_url}: {e}")
|
||||||
elif cq_type == "face":
|
elif seg_type == "face":
|
||||||
face_id = params.get("id")
|
face_id = seg_data.get("id")
|
||||||
content += f"[表情:{face_id}]"
|
content += f"[表情:{face_id}]"
|
||||||
elif cq_type == "at":
|
elif seg_type == "at":
|
||||||
qq_id = params.get("qq")
|
qq_id = seg_data.get("qq")
|
||||||
if qq_id == "all":
|
if qq_id == "all":
|
||||||
content += "@everyone "
|
content += "@everyone "
|
||||||
else:
|
else:
|
||||||
|
# 尝试将 QQ 号映射回 Discord ID (这里简单处理,直接拼接)
|
||||||
content += f"<@{qq_id}> "
|
content += f"<@{qq_id}> "
|
||||||
|
elif seg_type == "reply":
|
||||||
last_end = match.end()
|
# 忽略回复段,或者你可以尝试映射 message_id
|
||||||
|
pass
|
||||||
# 添加最后一个 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
|
|
||||||
|
|
||||||
# 发送消息到 Discord
|
# 发送消息到 Discord
|
||||||
try:
|
|
||||||
# 如果内容为空但有文件,Discord 允许发送
|
# 如果内容为空但有文件,Discord 允许发送
|
||||||
if content or files:
|
if content or files:
|
||||||
await channel.send(content=content, files=files if files else None)
|
await channel.send(content=content, files=files if files else None)
|
||||||
@@ -556,3 +558,5 @@ class DiscordToOneBotConverter:
|
|||||||
logger.warning("尝试发送空消息到 Discord,已拦截")
|
logger.warning("尝试发送空消息到 Discord,已拦截")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"发送 Discord 消息失败: {e}")
|
logger.error(f"发送 Discord 消息失败: {e}")
|
||||||
|
import traceback
|
||||||
|
logger.error(f"异常堆栈: {traceback.format_exc()}")
|
||||||
|
|||||||
@@ -38,10 +38,10 @@ class Config:
|
|||||||
:raises ConfigError: 如果加载配置时发生其他错误
|
:raises ConfigError: 如果加载配置时发生其他错误
|
||||||
"""
|
"""
|
||||||
if not self.path.exists():
|
if not self.path.exists():
|
||||||
error = ConfigNotFoundError(message=f"配置文件 {self.path} 未找到!")
|
self.logger.warning(f"配置文件 {self.path} 未找到,正在生成示例配置...")
|
||||||
self.logger.error(f"配置加载失败: {error.message}")
|
self._generate_example_config()
|
||||||
self.logger.log_custom_exception(error)
|
self.logger.success(f"示例配置已生成: {self.path}")
|
||||||
raise error
|
self.logger.info("请编辑配置文件后重新启动程序")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.logger.info(f"正在从 {self.path} 加载配置...")
|
self.logger.info(f"正在从 {self.path} 加载配置...")
|
||||||
@@ -86,6 +86,19 @@ class Config:
|
|||||||
self.logger.log_custom_exception(error)
|
self.logger.log_custom_exception(error)
|
||||||
raise 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
|
@property
|
||||||
def napcat_ws(self) -> NapCatWSModel:
|
def napcat_ws(self) -> NapCatWSModel:
|
||||||
|
|||||||
@@ -47,9 +47,12 @@ python setup_mypyc.py build_ext --inplace
|
|||||||
|
|
||||||
## 2. 连接架构
|
## 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 回复
|
调用 API 回复
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### 2. 反向 WebSocket 连接
|
||||||
|
OneBot 客户端主动连接 Bot 提供的 WebSocket 服务。
|
||||||
|
|
||||||
|
**流程**:
|
||||||
|
|
||||||
|
```
|
||||||
|
Bot 启动反向 WS 服务 (监听 0.0.0.0:3002)
|
||||||
|
↓
|
||||||
|
NapCatQQ 主动连接到 Bot
|
||||||
|
↓
|
||||||
|
监听消息事件
|
||||||
|
↓
|
||||||
|
分发到处理器
|
||||||
|
↓
|
||||||
|
调用 API 回复
|
||||||
|
```
|
||||||
|
|
||||||
## 3. 资源管理架构
|
## 3. 资源管理架构
|
||||||
|
|
||||||
### 单例管理器
|
### 单例管理器
|
||||||
|
|||||||
@@ -65,6 +65,34 @@
|
|||||||
* **记性好**: 模板用一次就记住,下次直接用缓存。
|
* **记性好**: 模板用一次就记住,下次直接用缓存。
|
||||||
* **自动借还**: 它会自动找 `BrowserManager` 借页面,你只管 `render_template` 就行。
|
* **自动借还**: 它会自动找 `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`
|
`import`
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
* [架构设计](./core-concepts/architecture.md) - 了解框架的设计理念
|
* [架构设计](./core-concepts/architecture.md) - 了解框架的设计理念
|
||||||
* [性能优化](./core-concepts/performance.md) - JIT、Mypyc、页面池等优化技术
|
* [性能优化](./core-concepts/performance.md) - JIT、Mypyc、页面池等优化技术
|
||||||
* [事件流程](./core-concepts/event-flow.md) - 一条消息从接收到回复的完整流程
|
* [事件流程](./core-concepts/event-flow.md) - 一条消息从接收到回复的完整流程
|
||||||
* [核心管理器](./core-concepts/singleton-managers.md) - matcher、权限管理、浏览器池等
|
* [核心管理器](./core-concepts/singleton-managers.md) - matcher、权限管理、浏览器池、数据库等
|
||||||
* [Redis原子操作](./core-concepts/redis-atomic-operations.md) - 权限管理的分布式实现
|
* [Redis原子操作](./core-concepts/redis-atomic-operations.md) - 权限管理的分布式实现
|
||||||
* [多线程架构](./core-concepts/multithreading.md) - 线程池和线程安全设计
|
* [多线程架构](./core-concepts/multithreading.md) - 线程池和线程安全设计
|
||||||
* [错误处理](./core-concepts/error-handling.md) - 异常处理和错误码体系
|
* [错误处理](./core-concepts/error-handling.md) - 异常处理和错误码体系
|
||||||
@@ -29,6 +29,12 @@
|
|||||||
* [账号 API](./api/account.md) - 机器人自身信息获取
|
* [账号 API](./api/account.md) - 机器人自身信息获取
|
||||||
* [媒体 API](./api/media.md) - 图片、语音、视频处理
|
* [媒体 API](./api/media.md) - 图片、语音、视频处理
|
||||||
|
|
||||||
|
### 🌟 特色功能
|
||||||
|
* **多平台互通** - 支持 Discord 与 QQ 频道的跨平台消息互通
|
||||||
|
* **本地文件服务** - 内置轻量级 HTTP 文件服务器,方便传输大文件和媒体
|
||||||
|
* **多数据库支持** - 同时支持 Redis 缓存和 MySQL 持久化存储
|
||||||
|
* **反向 WebSocket** - 支持 OneBot 客户端主动连接 Bot
|
||||||
|
|
||||||
### 📚 插件开发
|
### 📚 插件开发
|
||||||
* [插件入门](./plugin-development/index.md) - 写你的第一个插件
|
* [插件入门](./plugin-development/index.md) - 写你的第一个插件
|
||||||
* [指令处理](./plugin-development/command-handling.md) - 参数解析、权限控制等
|
* [指令处理](./plugin-development/command-handling.md) - 参数解析、权限控制等
|
||||||
|
|||||||
@@ -4,41 +4,50 @@
|
|||||||
|
|
||||||
```
|
```
|
||||||
.
|
.
|
||||||
|
├── adapters/ # 适配器层(多平台支持)
|
||||||
|
│ ├── discord_adapter.py # Discord 适配器
|
||||||
|
│ └── router.py # 消息路由
|
||||||
|
│
|
||||||
├── core/ # 核心代码,别乱动
|
├── core/ # 核心代码,别乱动
|
||||||
│ ├── api/ # OneBot API 封装(消息、群组、好友、账号、媒体)
|
│ ├── api/ # OneBot API 封装(消息、群组、好友、账号、媒体)
|
||||||
│ ├── handlers/ # 底层事件处理器
|
│ ├── handlers/ # 底层事件处理器
|
||||||
│ ├── managers/ # 全局单例管理器
|
│ ├── managers/ # 全局单例管理器
|
||||||
│ │ ├── command_manager.py # 指令分发和事件处理
|
│ │ ├── bot_manager.py # Bot 实例管理
|
||||||
│ │ ├── plugin_manager.py # 插件加载和热重载
|
|
||||||
│ │ ├── permission_manager.py # 权限管理(Admin/User两级)
|
|
||||||
│ │ ├── browser_manager.py # Playwright页面池
|
│ │ ├── browser_manager.py # Playwright页面池
|
||||||
|
│ │ ├── command_manager.py # 指令分发和事件处理
|
||||||
│ │ ├── image_manager.py # 图片/HTML模板渲染
|
│ │ ├── 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/ # 工具函数和异常类
|
│ ├── utils/ # 工具函数和异常类
|
||||||
|
│ │ ├── error_codes.py # 错误码定义
|
||||||
|
│ │ ├── exceptions.py # 自定义异常类
|
||||||
|
│ │ ├── executor.py # 代码沙箱执行引擎(Docker)
|
||||||
│ │ ├── logger.py # 日志系统(Loguru)
|
│ │ ├── logger.py # 日志系统(Loguru)
|
||||||
│ │ ├── performance.py # 性能分析工具
|
│ │ ├── performance.py # 性能分析工具
|
||||||
│ │ ├── executor.py # 代码沙箱执行引擎(Docker)
|
|
||||||
│ │ ├── exceptions.py # 自定义异常类
|
|
||||||
│ │ └── singleton.py # 单例模式基类
|
│ │ └── singleton.py # 单例模式基类
|
||||||
│ ├── ws.py # WebSocket 连接和消息处理(已Mypyc编译)
|
│ ├── ws.py # WebSocket 连接和消息处理
|
||||||
│ ├── bot.py # Bot 核心实例
|
│ ├── bot.py # Bot 核心实例
|
||||||
│ ├── config_loader.py # 配置文件加载
|
│ ├── config_loader.py # 配置文件加载
|
||||||
│ ├── config_models.py # 配置数据模型
|
│ ├── config_models.py # 配置数据模型
|
||||||
│ └── permission.py # 权限枚举类
|
│ └── permission.py # 权限枚举类
|
||||||
│
|
│
|
||||||
├── data/ # 持久化数据
|
|
||||||
│ ├── admin.json # 管理员列表
|
|
||||||
│ └── permissions.json # 用户权限配置
|
|
||||||
│
|
|
||||||
├── models/ # 数据模型
|
├── models/ # 数据模型
|
||||||
│ ├── events/ # OneBot 11 事件模型
|
│ ├── events/ # OneBot 11 事件模型
|
||||||
|
│ │ ├── base.py # 基础事件模型
|
||||||
|
│ │ ├── factory.py # 事件工厂
|
||||||
│ │ ├── message.py # 消息事件
|
│ │ ├── message.py # 消息事件
|
||||||
|
│ │ ├── meta.py # 元事件
|
||||||
│ │ ├── notice.py # 通知事件
|
│ │ ├── notice.py # 通知事件
|
||||||
│ │ ├── request.py # 请求事件
|
│ │ └── request.py # 请求事件
|
||||||
│ │ └── factory.py # 事件工厂
|
|
||||||
│ ├── message.py # 消息段(CQ码)
|
│ ├── message.py # 消息段(CQ码)
|
||||||
│ ├── sender.py # 发送者信息
|
│ ├── objects.py # API响应对象(群信息、用户信息等)
|
||||||
│ └── objects.py # API响应对象(群信息、用户信息等)
|
│ └── sender.py # 发送者信息
|
||||||
│
|
│
|
||||||
├── plugins/ # 你的插件都放这(最常修改的地方)
|
├── plugins/ # 你的插件都放这(最常修改的地方)
|
||||||
│ ├── admin.py # 权限管理(Admin/User两级权限)
|
│ ├── admin.py # 权限管理(Admin/User两级权限)
|
||||||
@@ -46,66 +55,79 @@
|
|||||||
│ ├── bot_status.py # Bot运行状态查询(图片形式)
|
│ ├── bot_status.py # Bot运行状态查询(图片形式)
|
||||||
│ ├── broadcast.py # 管理员专用广播功能(隐藏插件)
|
│ ├── broadcast.py # 管理员专用广播功能(隐藏插件)
|
||||||
│ ├── code_py.py # Python代码沙箱执行(多行输入、图片输出)
|
│ ├── code_py.py # Python代码沙箱执行(多行输入、图片输出)
|
||||||
|
│ ├── discord-cross/ # Discord 跨平台互通插件
|
||||||
│ ├── echo.py # Echo和点赞功能
|
│ ├── echo.py # Echo和点赞功能
|
||||||
│ ├── furry.py # Furry图片获取
|
│ ├── furry.py # Furry图片获取
|
||||||
│ ├── github_parser.py # GitHub仓库链接自动解析
|
│ ├── github_parser.py # GitHub仓库链接自动解析
|
||||||
|
│ ├── group_welcome.py # 群欢迎插件
|
||||||
│ ├── jrcd.py # 今日人品/长度查询(随机生成)
|
│ ├── jrcd.py # 今日人品/长度查询(随机生成)
|
||||||
|
│ ├── mirror_avatar.py # 镜像头像获取
|
||||||
|
│ ├── osu!_plugin/ # osu! 相关功能插件
|
||||||
|
│ ├── resource/ # 插件资源文件
|
||||||
│ ├── thpic.py # 东方Project随机图片
|
│ ├── thpic.py # 东方Project随机图片
|
||||||
│ ├── web_parser/ # 综合Web链接解析系统
|
│ ├── weather.py # 天气查询插件
|
||||||
│ │ ├── __init__.py # 主入口,自动检测链接
|
│ └── web_parser/ # 综合Web链接解析系统
|
||||||
│ │ ├── parsers/ # 各平台解析器
|
│ ├── __init__.py # 主入口,自动检测链接
|
||||||
│ │ │ ├── bili.py # B站视频/直播解析
|
│ ├── base.py # 解析器基类
|
||||||
│ │ │ ├── douyin.py # 抖音视频解析
|
│ ├── parsers/ # 各平台解析器
|
||||||
│ │ │ └── github.py # GitHub仓库解析
|
│ │ ├── bili.py # B站视频/直播解析
|
||||||
│ │ └── utils.py # 解析工具函数
|
│ │ ├── douyin.py # 抖音视频解析
|
||||||
│ ├── sync_async_test_plugin.py # 异步同步混用测试(开发用)
|
│ │ └── github.py # GitHub仓库解析
|
||||||
│ └── resource/ # 插件资源文件
|
│ └── utils.py # 解析工具函数
|
||||||
│
|
│
|
||||||
├── templates/ # Jinja2 HTML模板
|
├── templates/ # Jinja2 HTML模板
|
||||||
│ ├── code_execution.html # 代码执行结果展示
|
│ ├── code_execution.html # 代码执行结果展示
|
||||||
│ ├── github_repo.html # GitHub仓库信息展示
|
│ ├── github_repo.html # GitHub仓库信息展示
|
||||||
│ ├── help.html # 帮助页面
|
│ ├── help.html # 帮助页面
|
||||||
│ └── status.html # Bot状态页面
|
│ ├── status.html # Bot状态页面
|
||||||
|
│ └── weather.html # 天气展示页面
|
||||||
│
|
│
|
||||||
├── web_static/ # 静态资源
|
├── web_static/ # 静态资源
|
||||||
|
│ ├── changelog.html # 更新日志页面
|
||||||
|
│ ├── changelog_generator/# 更新日志生成器
|
||||||
│ └── html/ # HTML资源文件
|
│ └── html/ # HTML资源文件
|
||||||
│
|
│
|
||||||
├── logs/ # 日志输出目录
|
|
||||||
│ └── bot.log # 主日志文件
|
|
||||||
│
|
|
||||||
├── tests/ # 单元测试
|
├── tests/ # 单元测试
|
||||||
│ ├── test_api.py # API功能测试
|
│ ├── test_api.py # API功能测试
|
||||||
|
│ ├── test_basic.py # 基础测试
|
||||||
│ ├── test_bot.py # Bot核心测试
|
│ ├── test_bot.py # Bot核心测试
|
||||||
│ ├── test_command_manager.py # 指令管理器测试
|
│ ├── 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_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/ # 开发文档
|
├── docs/ # 开发文档
|
||||||
│ ├── index.md # 文档首页
|
|
||||||
│ ├── getting-started.md # 快速上手
|
|
||||||
│ ├── project-structure.md # 项目结构(本文件)
|
|
||||||
│ ├── deployment.md # 生产环境部署
|
|
||||||
│ ├── core-concepts/ # 核心概念详解
|
|
||||||
│ ├── api/ # API参考文档
|
│ ├── api/ # API参考文档
|
||||||
│ └── plugin-development/ # 插件开发指南
|
│ ├── core-concepts/ # 核心概念详解
|
||||||
|
│ ├── plugin-development/ # 插件开发指南
|
||||||
|
│ ├── deployment.md # 生产环境部署
|
||||||
|
│ ├── development-standards.md # 开发规范
|
||||||
|
│ ├── getting-started.md # 快速上手
|
||||||
|
│ ├── index.md # 文档首页
|
||||||
|
│ └── project-structure.md # 项目结构(本文件)
|
||||||
│
|
│
|
||||||
├── scripts/ # 工具脚本
|
├── scripts/ # 工具脚本
|
||||||
|
│ ├── add_plugins.py # 添加插件脚本
|
||||||
│ ├── check_python_env.py # Python环境检查
|
│ ├── check_python_env.py # Python环境检查
|
||||||
│ ├── compile_machine_code.py # 机器码编译
|
│ ├── compile_machine_code.py # 机器码编译
|
||||||
│ └── export_requirements.py # 依赖导出
|
│ └── export_requirements.py # 依赖导出
|
||||||
│
|
│
|
||||||
├── venv/ # Python 虚拟环境(git忽略)
|
├── bili_login.py # B站登录脚本
|
||||||
├── __pycache__/ # Python缓存(git忽略)
|
├── DEEPSEEK_API_SETUP.md # DeepSeek API 设置文档
|
||||||
├── .gitignore # Git忽略配置
|
|
||||||
├── main.py # 启动入口
|
├── main.py # 启动入口
|
||||||
├── config.toml # 配置文件(包含WS、Redis、Docker配置)
|
├── pyproject.toml # 项目配置
|
||||||
├── pytest.ini # 测试配置
|
|
||||||
├── requirements.txt # Python依赖列表
|
├── requirements.txt # Python依赖列表
|
||||||
├── requirements-dev.txt # 开发依赖(包括pytest、mypy等)
|
├── requirements-dev.txt # 开发依赖
|
||||||
├── setup_mypyc.py # Mypyc编译脚本(可选性能优化)
|
|
||||||
├── check_syntax.py # 语法检查脚本
|
|
||||||
├── profile_main.py # 性能分析脚本
|
|
||||||
├── test_performance_simple.py # 简单性能测试
|
|
||||||
├── sandbox.Dockerfile # 代码沙箱Docker镜像
|
├── sandbox.Dockerfile # 代码沙箱Docker镜像
|
||||||
├── LICENSE # 许可证
|
├── LICENSE # 许可证
|
||||||
└── README.md # 项目README
|
└── README.md # 项目README
|
||||||
|
|||||||
@@ -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())
|
|
||||||
@@ -51,195 +51,205 @@ async def handle_qq_message(
|
|||||||
@matcher.on_message()
|
@matcher.on_message()
|
||||||
async def handle_qq_group_message(event: GroupMessageEvent):
|
async def handle_qq_group_message(event: GroupMessageEvent):
|
||||||
"""处理 QQ 群消息,转发到 Discord"""
|
"""处理 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:
|
try:
|
||||||
group_info = await event.bot.get_group_info(event.group_id)
|
if not config.ENABLE_CROSS_PLATFORM:
|
||||||
group_name = group_info.get("group_name", "")
|
return
|
||||||
except Exception:
|
|
||||||
group_name = f"群{group_id}"
|
group_id = event.group_id
|
||||||
|
mapped_channel = None
|
||||||
await handle_qq_message(
|
for discord_channel_id, info in config.CROSS_PLATFORM_MAP.items():
|
||||||
nickname=event.sender.nickname or event.sender.card or str(event.user_id),
|
if info["qq_group_id"] == group_id:
|
||||||
user_id=event.user_id,
|
mapped_channel = discord_channel_id
|
||||||
group_name=group_name,
|
break
|
||||||
group_id=group_id,
|
|
||||||
content=content,
|
if mapped_channel is None:
|
||||||
attachments=attachments
|
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()
|
@matcher.on_message()
|
||||||
async def handle_discord_message_event(event: Any):
|
async def handle_discord_message_event(event: Any):
|
||||||
"""处理 Discord 消息事件(通过适配器注入)"""
|
"""处理 Discord 消息事件(通过适配器注入)"""
|
||||||
if not config.ENABLE_CROSS_PLATFORM:
|
try:
|
||||||
return
|
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}")
|
logger.debug(f"[CrossPlatform] 开始处理 Discord 事件消息: channel_id={discord_channel_id}")
|
||||||
if not hasattr(event, '_is_discord_message'):
|
|
||||||
logger.debug(f"[CrossPlatform] 事件没有 _is_discord_message 属性,跳过")
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.debug(f"[CrossPlatform] 检测到 Discord 事件")
|
if hasattr(event, 'message') and isinstance(event.message, list):
|
||||||
discord_channel_id = getattr(event, 'discord_channel_id', None)
|
has_text_content = False
|
||||||
if discord_channel_id is None:
|
for segment in event.message:
|
||||||
logger.debug(f"[CrossPlatform] discord_channel_id 为 None")
|
if isinstance(segment, MessageSegment):
|
||||||
return
|
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 = content.strip()
|
||||||
attachments = []
|
|
||||||
|
# 如果 content 为空但有附件(如只有表情),使用 raw_message 作为 content
|
||||||
logger.debug(f"[CrossPlatform] 开始处理 Discord 事件消息: channel_id={discord_channel_id}")
|
if not content and attachments:
|
||||||
|
content = event.raw_message or ""
|
||||||
if hasattr(event, 'message') and isinstance(event.message, list):
|
|
||||||
has_text_content = False
|
logger.debug(f"[CrossPlatform] Discord 消息内容: '{content}', 附件数量: {len(attachments)}")
|
||||||
for segment in event.message:
|
|
||||||
if isinstance(segment, MessageSegment):
|
discord_username = getattr(event, 'discord_username', 'Unknown')
|
||||||
if segment.type == "text":
|
discord_discriminator = getattr(event, 'discord_discriminator', '')
|
||||||
content += segment.data.get("text", "")
|
|
||||||
has_text_content = True
|
logger.debug(f"[CrossPlatform] 调用 handle_discord_message: username={discord_username}, channel_id={discord_channel_id}")
|
||||||
elif segment.type == "image":
|
await handle_discord_message(
|
||||||
file_url = segment.data.get("url") or segment.data.get("file")
|
username=discord_username,
|
||||||
file_name = segment.data.get("filename")
|
discriminator=discord_discriminator,
|
||||||
if file_url:
|
content=content,
|
||||||
file_name = file_name or os.path.basename(str(file_url).split('?')[0]) or "image"
|
channel_id=discord_channel_id,
|
||||||
attachment_item = {"type": "image", "url": str(file_url), "filename": file_name}
|
attachments=attachments,
|
||||||
if attachment_item not in attachments:
|
embed=None
|
||||||
attachments.append(attachment_item)
|
)
|
||||||
content += f"\n[图片: {file_name}]\n"
|
except Exception as e:
|
||||||
elif segment.type == "video":
|
logger.error(f"[CrossPlatform] 处理 Discord 消息事件失败: {e}")
|
||||||
file_url = segment.data.get("url") or segment.data.get("file")
|
import traceback
|
||||||
file_name = segment.data.get("filename")
|
logger.error(f"[CrossPlatform] 异常堆栈: {traceback.format_exc()}")
|
||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
@matcher.command("cross_config", "跨平台配置", permission=Permission.ADMIN)
|
@matcher.command("cross_config", "跨平台配置", permission=Permission.ADMIN)
|
||||||
async def cross_config_command(event: MessageEvent):
|
async def cross_config_command(event: MessageEvent):
|
||||||
|
|||||||
91
pyproject.toml
Normal file
91
pyproject.toml
Normal file
@@ -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"]
|
||||||
Reference in New Issue
Block a user