Compare commits
5 Commits
v4.5.4
...
refactor/a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
381f7f4405 | ||
|
|
8f38e748cd | ||
|
|
f83484a8c0 | ||
|
|
56e3ddd62a | ||
|
|
80948be41d |
@@ -1,8 +1,9 @@
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
# github actions
|
||||
# github acions
|
||||
.github/
|
||||
.*ignore
|
||||
.git/
|
||||
# User-specific stuff
|
||||
.idea/
|
||||
# Byte-compiled / optimized / DLL files
|
||||
@@ -14,6 +15,7 @@ env/
|
||||
venv*/
|
||||
ENV/
|
||||
.conda/
|
||||
README*.md
|
||||
dashboard/
|
||||
data/
|
||||
changelogs/
|
||||
|
||||
@@ -12,20 +12,19 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
bash \
|
||||
ffmpeg \
|
||||
curl \
|
||||
gnupg \
|
||||
git \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN apt-get update && apt-get install -y curl gnupg && \
|
||||
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - && \
|
||||
apt-get install -y nodejs && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN python -m pip install uv
|
||||
RUN uv pip install -r requirements.txt --no-cache-dir --system
|
||||
RUN uv pip install socksio uv pilk --no-cache-dir --system
|
||||
|
||||
EXPOSE 6185
|
||||
EXPOSE 6186
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
CMD [ "python", "main.py" ]
|
||||
|
||||
35
Dockerfile_with_node
Normal file
35
Dockerfile_with_node
Normal file
@@ -0,0 +1,35 @@
|
||||
FROM python:3.10-slim
|
||||
|
||||
WORKDIR /AstrBot
|
||||
|
||||
COPY . /AstrBot/
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
build-essential \
|
||||
python3-dev \
|
||||
libffi-dev \
|
||||
libssl-dev \
|
||||
curl \
|
||||
unzip \
|
||||
ca-certificates \
|
||||
bash \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Installation of Node.js
|
||||
ENV NVM_DIR="/root/.nvm"
|
||||
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.2/install.sh | bash && \
|
||||
. "$NVM_DIR/nvm.sh" && \
|
||||
nvm install 22 && \
|
||||
nvm use 22
|
||||
RUN /bin/bash -c ". \"$NVM_DIR/nvm.sh\" && node -v && npm -v"
|
||||
|
||||
RUN python -m pip install uv
|
||||
RUN uv pip install -r requirements.txt --no-cache-dir --system
|
||||
RUN uv pip install socksio uv pyffmpeg --no-cache-dir --system
|
||||
|
||||
EXPOSE 6185
|
||||
EXPOSE 6186
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
114
README.md
114
README.md
@@ -119,73 +119,83 @@ uv run main.py
|
||||
|
||||
<a href="https://discord.gg/hAVk6tgV36"><img alt="Discord_community" src="https://img.shields.io/badge/Discord-AstrBot-purple?style=for-the-badge&color=76bad9"></a>
|
||||
|
||||
## 支持的消息平台
|
||||
## ⚡ 消息平台支持情况
|
||||
|
||||
**官方维护**
|
||||
|
||||
- QQ (官方平台 & OneBot)
|
||||
- Telegram
|
||||
- 企微应用 & 企微智能机器人
|
||||
- 微信客服 & 微信公众号
|
||||
- 飞书
|
||||
- 钉钉
|
||||
- Slack
|
||||
- Discord
|
||||
- Satori
|
||||
- Misskey
|
||||
- Whatsapp (将支持)
|
||||
- LINE (将支持)
|
||||
| 平台 | 支持性 |
|
||||
| -------- | ------- |
|
||||
| QQ(官方平台) | ✔ |
|
||||
| QQ(OneBot) | ✔ |
|
||||
| Telegram | ✔ |
|
||||
| 企微应用 | ✔ |
|
||||
| 企微智能机器人 | ✔ |
|
||||
| 微信客服 | ✔ |
|
||||
| 微信公众号 | ✔ |
|
||||
| 飞书 | ✔ |
|
||||
| 钉钉 | ✔ |
|
||||
| Slack | ✔ |
|
||||
| Discord | ✔ |
|
||||
| Satori | ✔ |
|
||||
| Misskey | ✔ |
|
||||
| Whatsapp | 将支持 |
|
||||
| LINE | 将支持 |
|
||||
|
||||
**社区维护**
|
||||
|
||||
- [KOOK](https://github.com/wuyan1003/astrbot_plugin_kook_adapter)
|
||||
- [VoceChat](https://github.com/HikariFroya/astrbot_plugin_vocechat)
|
||||
- [Bilibili 私信](https://github.com/Hina-Chat/astrbot_plugin_bilibili_adapter)
|
||||
- [wxauto](https://github.com/luosheng520qaq/wxauto-repost-onebotv11)
|
||||
| 平台 | 支持性 |
|
||||
| -------- | ------- |
|
||||
| [KOOK](https://github.com/wuyan1003/astrbot_plugin_kook_adapter) | ✔ |
|
||||
| [VoceChat](https://github.com/HikariFroya/astrbot_plugin_vocechat) | ✔ |
|
||||
| [Bilibili 私信](https://github.com/Hina-Chat/astrbot_plugin_bilibili_adapter) | ✔ |
|
||||
| [wxauto](https://github.com/luosheng520qaq/wxauto-repost-onebotv11) | ✔ |
|
||||
|
||||
## 支持的模型服务
|
||||
## ⚡ 提供商支持情况
|
||||
|
||||
**大模型服务**
|
||||
|
||||
- OpenAI 及兼容服务
|
||||
- Anthropic
|
||||
- Google Gemini
|
||||
- Moonshot AI
|
||||
- 智谱 AI
|
||||
- DeepSeek
|
||||
- Ollama (本地部署)
|
||||
- LM Studio (本地部署)
|
||||
- [优云智算](https://www.compshare.cn/?ytag=GPU_YY-gh_astrbot&referral_code=FV7DcGowN4hB5UuXKgpE74)
|
||||
- [302.AI](https://share.302.ai/rr1M3l)
|
||||
- [小马算力](https://www.tokenpony.cn/3YPyf)
|
||||
- [硅基流动](https://docs.siliconflow.cn/cn/usercases/use-siliconcloud-in-astrbot)
|
||||
- [PPIO 派欧云](https://ppio.com/user/register?invited_by=AIOONE)
|
||||
- ModelScope
|
||||
- OneAPI
|
||||
|
||||
**LLMOps 平台**
|
||||
|
||||
- Dify
|
||||
- 阿里云百炼应用
|
||||
- Coze
|
||||
| 名称 | 支持性 | 备注 |
|
||||
| -------- | ------- | ------- |
|
||||
| OpenAI | ✔ | 支持任何兼容 OpenAI API 的服务 |
|
||||
| Anthropic | ✔ | |
|
||||
| Google Gemini | ✔ | |
|
||||
| Moonshot AI | ✔ | |
|
||||
| 智谱 AI | ✔ | |
|
||||
| DeepSeek | ✔ | |
|
||||
| Ollama | ✔ | 本地部署 DeepSeek 等开源语言模型 |
|
||||
| LM Studio | ✔ | 本地部署 DeepSeek 等开源语言模型 |
|
||||
| [优云智算](https://www.compshare.cn/?ytag=GPU_YY-gh_astrbot&referral_code=FV7DcGowN4hB5UuXKgpE74) | ✔ | |
|
||||
| [302.AI](https://share.302.ai/rr1M3l) | ✔ | |
|
||||
| [小马算力](https://www.tokenpony.cn/3YPyf) | ✔ | |
|
||||
| 硅基流动 | ✔ | |
|
||||
| PPIO 派欧云 | ✔ | |
|
||||
| ModelScope | ✔ | |
|
||||
| OneAPI | ✔ | |
|
||||
| Dify | ✔ | |
|
||||
| 阿里云百炼应用 | ✔ | |
|
||||
| Coze | ✔ | |
|
||||
|
||||
**语音转文本服务**
|
||||
|
||||
- OpenAI Whisper
|
||||
- SenseVoice
|
||||
| 名称 | 支持性 | 备注 |
|
||||
| -------- | ------- | ------- |
|
||||
| Whisper | ✔ | 支持 API、本地部署 |
|
||||
| SenseVoice | ✔ | 本地部署 |
|
||||
|
||||
**文本转语音服务**
|
||||
|
||||
- OpenAI TTS
|
||||
- Gemini TTS
|
||||
- GPT-Sovits-Inference
|
||||
- GPT-Sovits
|
||||
- FishAudio
|
||||
- Edge TTS
|
||||
- 阿里云百炼 TTS
|
||||
- Azure TTS
|
||||
- Minimax TTS
|
||||
- 火山引擎 TTS
|
||||
| 名称 | 支持性 | 备注 |
|
||||
| -------- | ------- | ------- |
|
||||
| OpenAI TTS | ✔ | |
|
||||
| Gemini TTS | ✔ | |
|
||||
| GSVI | ✔ | GPT-Sovits-Inference |
|
||||
| GPT-SoVITs | ✔ | GPT-Sovits |
|
||||
| FishAudio | ✔ | |
|
||||
| Edge TTS | ✔ | Edge 浏览器的免费 TTS |
|
||||
| 阿里云百炼 TTS | ✔ | |
|
||||
| Azure TTS | ✔ | |
|
||||
| Minimax TTS | ✔ | |
|
||||
| 火山引擎 TTS | ✔ | |
|
||||
|
||||
## ❤️ 贡献
|
||||
|
||||
@@ -219,7 +229,7 @@ pre-commit install
|
||||
|
||||
## ⭐ Star History
|
||||
|
||||
> [!TIP]
|
||||
> [!TIP]
|
||||
> 如果本项目对您的生活 / 工作产生了帮助,或者您关注本项目的未来发展,请给项目 Star,这是我们维护这个开源项目的动力 <3
|
||||
|
||||
<div align="center">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import anyio
|
||||
import click
|
||||
from filelock import FileLock, Timeout
|
||||
|
||||
@@ -48,7 +48,7 @@ def init() -> None:
|
||||
|
||||
try:
|
||||
with lock.acquire():
|
||||
asyncio.run(initialize_astrbot(astrbot_root))
|
||||
anyio.run(initialize_astrbot, astrbot_root)
|
||||
except Timeout:
|
||||
raise click.ClickException("无法获取锁文件,请检查是否有其他实例正在运行")
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
import anyio
|
||||
import click
|
||||
from filelock import FileLock, Timeout
|
||||
|
||||
from ..utils import check_astrbot_root, check_dashboard, get_astrbot_root
|
||||
|
||||
|
||||
async def run_astrbot(astrbot_root: Path):
|
||||
async def run_astrbot(astrbot_root: Path) -> None:
|
||||
"""运行 AstrBot"""
|
||||
from astrbot.core import LogBroker, LogManager, db_helper, logger
|
||||
from astrbot.core.initial_loader import InitialLoader
|
||||
@@ -53,7 +53,7 @@ def run(reload: bool, port: str) -> None:
|
||||
lock_file = astrbot_root / "astrbot.lock"
|
||||
lock = FileLock(lock_file, timeout=5)
|
||||
with lock.acquire():
|
||||
asyncio.run(run_astrbot(astrbot_root))
|
||||
anyio.run(run_astrbot, astrbot_root)
|
||||
except KeyboardInterrupt:
|
||||
click.echo("AstrBot 已关闭...")
|
||||
except Timeout:
|
||||
|
||||
@@ -55,6 +55,14 @@ class FunctionTool(ToolSchema, Generic[TContext]):
|
||||
def __repr__(self):
|
||||
return f"FuncTool(name={self.name}, parameters={self.parameters}, description={self.description})"
|
||||
|
||||
def __dict__(self) -> dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"parameters": self.parameters,
|
||||
"description": self.description,
|
||||
"active": self.active,
|
||||
}
|
||||
|
||||
async def call(
|
||||
self, context: ContextWrapper[TContext], **kwargs
|
||||
) -> str | mcp.types.CallToolResult:
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
import os
|
||||
|
||||
from astrbot.cdefaore.utils.astrbot_path import get_astrbot_data_path
|
||||
from astrbot.core.utils.astrbot_path import get_astrbot_data_path
|
||||
|
||||
VERSION = "4.5.4"
|
||||
VERSION = "4.5.1"
|
||||
DB_PATH = os.path.join(get_astrbot_data_path(), "data_v4.db")
|
||||
|
||||
# 默认配置
|
||||
|
||||
@@ -14,7 +14,8 @@ import os
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from asyncio import Queue
|
||||
|
||||
import anyio
|
||||
|
||||
from astrbot.core import LogBroker, logger, sp
|
||||
from astrbot.core.astrbot_config_mgr import AstrBotConfigManager
|
||||
@@ -104,7 +105,9 @@ class AstrBotCoreLifecycle:
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
# 初始化事件队列
|
||||
self.event_queue = Queue()
|
||||
self._event_queue_send, self.event_queue = anyio.create_memory_object_stream[
|
||||
object
|
||||
](0)
|
||||
|
||||
# 初始化人格管理器
|
||||
self.persona_mgr = PersonaManager(self.db, self.astrbot_config_mgr)
|
||||
@@ -118,7 +121,9 @@ class AstrBotCoreLifecycle:
|
||||
)
|
||||
|
||||
# 初始化平台管理器
|
||||
self.platform_manager = PlatformManager(self.astrbot_config, self.event_queue)
|
||||
self.platform_manager = PlatformManager(
|
||||
self.astrbot_config, self._event_queue_send
|
||||
)
|
||||
|
||||
# 初始化对话管理器
|
||||
self.conversation_manager = ConversationManager(self.db)
|
||||
@@ -131,7 +136,7 @@ class AstrBotCoreLifecycle:
|
||||
|
||||
# 初始化提供给插件的上下文
|
||||
self.star_context = Context(
|
||||
self.event_queue,
|
||||
self._event_queue_send,
|
||||
self.astrbot_config,
|
||||
self.db,
|
||||
self.provider_manager,
|
||||
|
||||
@@ -271,7 +271,7 @@ class SQLiteDatabase(BaseDatabase):
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
delete(ConversationV2).where(
|
||||
col(ConversationV2.user_id) == user_id
|
||||
col(ConversationV2.user_id) == user_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""事件总线, 用于处理事件的分发和处理
|
||||
"""事件总线, 用于处理事件的分发和处理.
|
||||
|
||||
事件总线是一个异步队列, 用于接收各种消息事件, 并将其发送到Scheduler调度器进行处理
|
||||
其中包含了一个无限循环的调度函数, 用于从事件队列中获取新的事件, 并创建一个新的异步任务来执行管道调度器的处理逻辑
|
||||
|
||||
@@ -10,8 +11,8 @@ class:
|
||||
2. 无限循环的调度函数, 从事件队列中获取新的事件, 打印日志并创建一个新的异步任务来执行管道调度器的处理逻辑
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from asyncio import Queue
|
||||
import anyio
|
||||
from anyio.streams.memory import MemoryObjectReceiveStream
|
||||
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.astrbot_config_mgr import AstrBotConfigManager
|
||||
@@ -25,28 +26,29 @@ class EventBus:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
event_queue: Queue,
|
||||
event_queue: MemoryObjectReceiveStream[AstrMessageEvent],
|
||||
pipeline_scheduler_mapping: dict[str, PipelineScheduler],
|
||||
astrbot_config_mgr: AstrBotConfigManager = None,
|
||||
):
|
||||
astrbot_config_mgr: AstrBotConfigManager | None = None,
|
||||
) -> None:
|
||||
self.event_queue = event_queue # 事件队列
|
||||
# abconf uuid -> scheduler
|
||||
self.pipeline_scheduler_mapping = pipeline_scheduler_mapping
|
||||
self.astrbot_config_mgr = astrbot_config_mgr
|
||||
|
||||
async def dispatch(self):
|
||||
async def dispatch(self) -> None:
|
||||
while True:
|
||||
event: AstrMessageEvent = await self.event_queue.get()
|
||||
event: AstrMessageEvent = await self.event_queue.receive()
|
||||
conf_info = self.astrbot_config_mgr.get_conf_info(event.unified_msg_origin)
|
||||
self._print_event(event, conf_info["name"])
|
||||
scheduler = self.pipeline_scheduler_mapping.get(conf_info["id"])
|
||||
asyncio.create_task(scheduler.execute(event))
|
||||
anyio.create_task(scheduler.execute(event))
|
||||
|
||||
def _print_event(self, event: AstrMessageEvent, conf_name: str):
|
||||
def _print_event(self, event: AstrMessageEvent, conf_name: str) -> None:
|
||||
"""用于记录事件信息
|
||||
|
||||
Args:
|
||||
event (AstrMessageEvent): 事件对象
|
||||
event: 事件对象
|
||||
conf_name: 配置名称
|
||||
|
||||
"""
|
||||
# 如果有发送者名称: [平台名] 发送者名称/发送者ID: 消息概要
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import asyncio
|
||||
import os
|
||||
import platform
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
import anyio
|
||||
|
||||
|
||||
class FileTokenService:
|
||||
"""维护一个简单的基于令牌的文件下载服务,支持超时和懒清除。"""
|
||||
|
||||
def __init__(self, default_timeout: float = 300):
|
||||
self.lock = asyncio.Lock()
|
||||
self.staged_files = {} # token: (file_path, expire_time)
|
||||
def __init__(self, default_timeout: float = 300) -> None:
|
||||
self.lock = anyio.Lock()
|
||||
self.staged_files: dict = {} # token: (file_path, expire_time)
|
||||
self.default_timeout = default_timeout
|
||||
|
||||
async def _cleanup_expired_tokens(self):
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from collections.abc import AsyncGenerator
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import anyio
|
||||
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.config.astrbot_config import RateLimitStrategy
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
@@ -19,11 +20,11 @@ class RateLimitStage(Stage):
|
||||
如果触发限流,将 stall 流水线,直到下一个时间窗口来临时自动唤醒。
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
# 存储每个会话的请求时间队列
|
||||
self.event_timestamps: defaultdict[str, deque[datetime]] = defaultdict(deque)
|
||||
# 为每个会话设置一个锁,避免并发冲突
|
||||
self.locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
||||
self.locks: defaultdict[str, anyio.Lock] = defaultdict(anyio.Lock)
|
||||
# 限流参数
|
||||
self.rate_limit_count: int = 0
|
||||
self.rate_limit_time: timedelta = timedelta(0)
|
||||
@@ -74,7 +75,7 @@ class RateLimitStage(Stage):
|
||||
logger.info(
|
||||
f"会话 {session_id} 被限流。根据限流策略,此会话处理将被暂停 {stall_duration:.2f} 秒。",
|
||||
)
|
||||
await asyncio.sleep(stall_duration)
|
||||
await anyio.sleep(stall_duration)
|
||||
now = datetime.now()
|
||||
case RateLimitStrategy.DISCARD.value:
|
||||
logger.info(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import traceback
|
||||
from asyncio import Queue
|
||||
|
||||
from anyio.streams.memory import MemoryObjectSendStream
|
||||
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
@@ -12,7 +13,7 @@ from .sources.webchat.webchat_adapter import WebChatAdapter
|
||||
|
||||
|
||||
class PlatformManager:
|
||||
def __init__(self, config: AstrBotConfig, event_queue: Queue):
|
||||
def __init__(self, config: AstrBotConfig, event_queue: MemoryObjectSendStream):
|
||||
self.platform_insts: list[Platform] = []
|
||||
"""加载的 Platform 的实例"""
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import abc
|
||||
import uuid
|
||||
from asyncio import Queue
|
||||
from collections.abc import Awaitable
|
||||
from typing import Any
|
||||
|
||||
from anyio.streams.memory import MemoryObjectSendStream
|
||||
|
||||
from astrbot.core.message.message_event_result import MessageChain
|
||||
from astrbot.core.utils.metrics import Metric
|
||||
|
||||
@@ -13,7 +14,7 @@ from .platform_metadata import PlatformMetadata
|
||||
|
||||
|
||||
class Platform(abc.ABC):
|
||||
def __init__(self, event_queue: Queue):
|
||||
def __init__(self, event_queue: MemoryObjectSendStream):
|
||||
super().__init__()
|
||||
# 维护了消息平台的事件队列,EventBus 会从这里取出事件并处理。
|
||||
self._event_queue = event_queue
|
||||
@@ -45,7 +46,7 @@ class Platform(abc.ABC):
|
||||
|
||||
def commit_event(self, event: AstrMessageEvent):
|
||||
"""提交一个事件到事件队列。"""
|
||||
self._event_queue.put_nowait(event)
|
||||
self._event_queue.send_nowait(event)
|
||||
|
||||
def get_client(self):
|
||||
"""获取平台的客户端对象。"""
|
||||
|
||||
@@ -107,7 +107,7 @@ class AiocqhttpAdapter(Platform):
|
||||
)
|
||||
await super().send_by_session(session, message_chain)
|
||||
|
||||
async def convert_message(self, event: Event) -> AstrBotMessage | None:
|
||||
async def convert_message(self, event: Event) -> AstrBotMessage:
|
||||
logger.debug(f"[aiocqhttp] RawMessage {event}")
|
||||
|
||||
if event["post_type"] == "message":
|
||||
@@ -222,7 +222,7 @@ class AiocqhttpAdapter(Platform):
|
||||
err = f"aiocqhttp: 无法识别的消息类型: {event.message!s},此条消息将被忽略。如果您在使用 go-cqhttp,请将其配置文件中的 message.post-format 更改为 array。"
|
||||
logger.critical(err)
|
||||
try:
|
||||
await self.bot.send(event, err)
|
||||
self.bot.send(event, err)
|
||||
except BaseException as e:
|
||||
logger.error(f"回复消息失败: {e}")
|
||||
return None
|
||||
|
||||
@@ -216,7 +216,7 @@ class DingtalkPlatformAdapter(Platform):
|
||||
client=self.client,
|
||||
)
|
||||
|
||||
self._event_queue.put_nowait(event)
|
||||
self._event_queue.send_nowait(event)
|
||||
|
||||
async def run(self):
|
||||
# await self.client_.start()
|
||||
|
||||
@@ -90,7 +90,7 @@ class DiscordPlatformAdapter(Platform):
|
||||
)
|
||||
message_obj.self_id = self.client_self_id
|
||||
message_obj.session_id = session.session_id
|
||||
message_obj.message = message_chain.chain
|
||||
message_obj.message = message_chain
|
||||
|
||||
# 创建临时事件对象来发送消息
|
||||
temp_event = DiscordPlatformEvent(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import sys
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
@@ -184,7 +183,7 @@ class DiscordPlatformEvent(AstrMessageEvent):
|
||||
BytesIO(img_bytes),
|
||||
filename=filename or "image.png",
|
||||
)
|
||||
except (ValueError, TypeError, binascii.Error):
|
||||
except (ValueError, TypeError, base64.binascii.Error):
|
||||
logger.debug(
|
||||
f"[Discord] 裸 Base64 解码失败,作为本地路径处理: {file_content}",
|
||||
)
|
||||
|
||||
@@ -224,7 +224,7 @@ class LarkPlatformAdapter(Platform):
|
||||
bot=self.lark_api,
|
||||
)
|
||||
|
||||
self._event_queue.put_nowait(event)
|
||||
self._event_queue.send_nowait(event)
|
||||
|
||||
async def run(self):
|
||||
# self.client.start()
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
|
||||
import anyio
|
||||
from quart import Quart, Response, request
|
||||
from slack_sdk.socket_mode.aiohttp import SocketModeClient
|
||||
from slack_sdk.socket_mode.request import SocketModeRequest
|
||||
@@ -40,7 +40,7 @@ class SlackWebhookClient:
|
||||
logging.getLogger("quart.app").setLevel(logging.WARNING)
|
||||
logging.getLogger("quart.serving").setLevel(logging.WARNING)
|
||||
|
||||
self.shutdown_event = asyncio.Event()
|
||||
self.shutdown_event = anyio.Event()
|
||||
|
||||
def _setup_routes(self):
|
||||
"""设置路由"""
|
||||
|
||||
@@ -82,7 +82,7 @@ class SlackAdapter(Platform):
|
||||
session: MessageSesion,
|
||||
message_chain: MessageChain,
|
||||
):
|
||||
blocks, text = await SlackMessageEvent._parse_slack_blocks(
|
||||
blocks, text = SlackMessageEvent._parse_slack_blocks(
|
||||
message_chain=message_chain,
|
||||
web_client=self.web_client,
|
||||
)
|
||||
|
||||
@@ -10,7 +10,7 @@ import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
import random
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
@@ -139,12 +139,6 @@ class PKCS7Encoder:
|
||||
class Prpcrypt:
|
||||
"""提供接收和推送给企业微信消息的加解密接口"""
|
||||
|
||||
# 16位随机字符串的范围常量
|
||||
# randbelow(RANDOM_RANGE) 返回 [0, 8999999999999999](两端都包含,即包含0和8999999999999999)
|
||||
# 加上 MIN_RANDOM_VALUE 后得到 [1000000000000000, 9999999999999999](两端都包含)即16位数字
|
||||
MIN_RANDOM_VALUE = 1000000000000000 # 最小值: 1000000000000000 (16位)
|
||||
RANDOM_RANGE = 9000000000000000 # 范围大小: 确保最大值为 9999999999999999 (16位)
|
||||
|
||||
def __init__(self, key):
|
||||
# self.key = base64.b64decode(key+"=")
|
||||
self.key = key
|
||||
@@ -213,9 +207,7 @@ class Prpcrypt:
|
||||
"""随机生成16位字符串
|
||||
@return: 16位字符串
|
||||
"""
|
||||
return str(
|
||||
secrets.randbelow(self.RANDOM_RANGE) + self.MIN_RANDOM_VALUE
|
||||
).encode()
|
||||
return str(random.randint(1000000000000000, 9999999999999999)).encode()
|
||||
|
||||
|
||||
class WXBizJsonMsgCrypt:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""企业微信智能机器人 API 客户端
|
||||
"""企业微信智能机器人 API 客户端.
|
||||
|
||||
处理消息加密解密、API 调用等
|
||||
"""
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
处理企业微信智能机器人的 HTTP 回调请求
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
import anyio
|
||||
import quart
|
||||
|
||||
from astrbot.api import logger
|
||||
@@ -41,7 +41,7 @@ class WecomAIBotServer:
|
||||
self.app = quart.Quart(__name__)
|
||||
self._setup_routes()
|
||||
|
||||
self.shutdown_event = asyncio.Event()
|
||||
self.shutdown_event = anyio.Event()
|
||||
|
||||
def _setup_routes(self):
|
||||
"""设置 Quart 路由"""
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
import random
|
||||
import string
|
||||
from typing import Any
|
||||
|
||||
@@ -53,7 +53,7 @@ def generate_random_string(length: int = 10) -> str:
|
||||
|
||||
"""
|
||||
letters = string.ascii_letters + string.digits
|
||||
return "".join(secrets.choice(letters) for _ in range(length))
|
||||
return "".join(random.choice(letters) for _ in range(length))
|
||||
|
||||
|
||||
def calculate_image_md5(image_data: bytes) -> str:
|
||||
|
||||
@@ -7,6 +7,7 @@ from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
import anyio
|
||||
|
||||
from astrbot import logger
|
||||
from astrbot.core import sp
|
||||
@@ -98,7 +99,7 @@ class FunctionToolManager:
|
||||
self.func_list: list[FuncTool] = []
|
||||
self.mcp_client_dict: dict[str, MCPClient] = {}
|
||||
"""MCP 服务列表"""
|
||||
self.mcp_client_event: dict[str, asyncio.Event] = {}
|
||||
self.mcp_client_event: dict[str, anyio.Event] = {}
|
||||
|
||||
def empty(self) -> bool:
|
||||
return len(self.func_list) == 0
|
||||
@@ -206,7 +207,7 @@ class FunctionToolManager:
|
||||
for name in mcp_server_json_obj:
|
||||
cfg = mcp_server_json_obj[name]
|
||||
if cfg.get("active", True):
|
||||
event = asyncio.Event()
|
||||
event = anyio.Event()
|
||||
asyncio.create_task(
|
||||
self._init_mcp_client_task_wrapper(name, cfg, event),
|
||||
)
|
||||
@@ -216,7 +217,7 @@ class FunctionToolManager:
|
||||
self,
|
||||
name: str,
|
||||
cfg: dict,
|
||||
event: asyncio.Event,
|
||||
event: anyio.Event,
|
||||
ready_future: asyncio.Future | None = None,
|
||||
) -> None:
|
||||
"""初始化 MCP 客户端的包装函数,用于捕获异常"""
|
||||
@@ -307,7 +308,7 @@ class FunctionToolManager:
|
||||
self,
|
||||
name: str,
|
||||
config: dict,
|
||||
event: asyncio.Event | None = None,
|
||||
event: anyio.Event | None = None,
|
||||
ready_future: asyncio.Future | None = None,
|
||||
timeout: int = 30,
|
||||
) -> None:
|
||||
@@ -316,7 +317,7 @@ class FunctionToolManager:
|
||||
Args:
|
||||
name (str): The name of the MCP server.
|
||||
config (dict): Configuration for the MCP server.
|
||||
event (asyncio.Event): Event to signal when the MCP client is ready.
|
||||
event (anyio.Event): Event to signal when the MCP client is ready.
|
||||
ready_future (asyncio.Future): Future to signal when the MCP client is ready.
|
||||
timeout (int): Timeout for the initialization.
|
||||
|
||||
@@ -326,7 +327,7 @@ class FunctionToolManager:
|
||||
|
||||
"""
|
||||
if not event:
|
||||
event = asyncio.Event()
|
||||
event = anyio.Event()
|
||||
if not ready_future:
|
||||
ready_future = asyncio.Future()
|
||||
if name in self.mcp_client_dict:
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -54,9 +54,7 @@ class OTTSProvider:
|
||||
async def _generate_signature(self) -> str:
|
||||
await self._sync_time()
|
||||
timestamp = int(time.time()) + self.time_offset
|
||||
nonce = "".join(
|
||||
secrets.choice("abcdefghijklmnopqrstuvwxyz0123456789") for _ in range(10)
|
||||
)
|
||||
nonce = "".join(random.choices("abcdefghijklmnopqrstuvwxyz0123456789", k=10))
|
||||
path = re.sub(r"^https?://[^/]+", "", self.api_url) or "/"
|
||||
return f"{timestamp}-{nonce}-0-{hashlib.md5(f'{path}-{timestamp}-{nonce}-0-{self.skey}'.encode()).hexdigest()}"
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import logging
|
||||
from asyncio import Queue
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from anyio.streams.memory import MemoryObjectSendStream
|
||||
from deprecated import deprecated
|
||||
|
||||
from astrbot.core.astrbot_config_mgr import AstrBotConfigManager
|
||||
@@ -50,7 +50,7 @@ class Context:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
event_queue: Queue,
|
||||
event_queue: MemoryObjectSendStream,
|
||||
config: AstrBotConfig,
|
||||
db: BaseDatabase,
|
||||
provider_manager: ProviderManager,
|
||||
@@ -193,7 +193,7 @@ class Context:
|
||||
"""获取 AstrBot 数据库。"""
|
||||
return self._db
|
||||
|
||||
def get_event_queue(self) -> Queue:
|
||||
def get_event_queue(self) -> MemoryObjectSendStream:
|
||||
"""获取事件队列。"""
|
||||
return self._event_queue
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ class CommandGroupFilter(HandlerFilter):
|
||||
prefix + "│ ",
|
||||
event=event,
|
||||
cfg=cfg,
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
return "".join(parts)
|
||||
|
||||
@@ -680,18 +680,11 @@ class PluginManager:
|
||||
|
||||
return plugin_info
|
||||
|
||||
async def uninstall_plugin(
|
||||
self,
|
||||
plugin_name: str,
|
||||
delete_config: bool = False,
|
||||
delete_data: bool = False,
|
||||
):
|
||||
async def uninstall_plugin(self, plugin_name: str):
|
||||
"""卸载指定的插件。
|
||||
|
||||
Args:
|
||||
plugin_name (str): 要卸载的插件名称
|
||||
delete_config (bool): 是否删除插件配置文件,默认为 False
|
||||
delete_data (bool): 是否删除插件数据,默认为 False
|
||||
|
||||
Raises:
|
||||
Exception: 当插件不存在、是保留插件时,或删除插件文件夹失败时抛出异常
|
||||
@@ -721,7 +714,6 @@ class PluginManager:
|
||||
|
||||
await self._unbind_plugin(plugin_name, plugin.module_path)
|
||||
|
||||
# 删除插件文件夹
|
||||
try:
|
||||
remove_dir(os.path.join(ppath, root_dir_name))
|
||||
except Exception as e:
|
||||
@@ -729,51 +721,6 @@ class PluginManager:
|
||||
f"移除插件成功,但是删除插件文件夹失败: {e!s}。您可以手动删除该文件夹,位于 addons/plugins/ 下。",
|
||||
)
|
||||
|
||||
# 删除插件配置文件
|
||||
if delete_config and root_dir_name:
|
||||
config_file = os.path.join(
|
||||
self.plugin_config_path,
|
||||
f"{root_dir_name}_config.json",
|
||||
)
|
||||
if os.path.exists(config_file):
|
||||
try:
|
||||
os.remove(config_file)
|
||||
logger.info(f"已删除插件 {plugin_name} 的配置文件")
|
||||
except Exception as e:
|
||||
logger.warning(f"删除插件配置文件失败: {e!s}")
|
||||
|
||||
# 删除插件持久化数据
|
||||
# 注意:需要检查两个可能的目录名(plugin_data 和 plugins_data)
|
||||
# data/temp 目录可能被多个插件共享,不自动删除以防误删
|
||||
if delete_data and root_dir_name:
|
||||
data_base_dir = os.path.dirname(ppath) # data/
|
||||
|
||||
# 删除 data/plugin_data 下的插件持久化数据(单数形式,新版本)
|
||||
plugin_data_dir = os.path.join(
|
||||
data_base_dir, "plugin_data", root_dir_name
|
||||
)
|
||||
if os.path.exists(plugin_data_dir):
|
||||
try:
|
||||
remove_dir(plugin_data_dir)
|
||||
logger.info(
|
||||
f"已删除插件 {plugin_name} 的持久化数据 (plugin_data)"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"删除插件持久化数据失败 (plugin_data): {e!s}")
|
||||
|
||||
# 删除 data/plugins_data 下的插件持久化数据(复数形式,旧版本兼容)
|
||||
plugins_data_dir = os.path.join(
|
||||
data_base_dir, "plugins_data", root_dir_name
|
||||
)
|
||||
if os.path.exists(plugins_data_dir):
|
||||
try:
|
||||
remove_dir(plugins_data_dir)
|
||||
logger.info(
|
||||
f"已删除插件 {plugin_name} 的持久化数据 (plugins_data)"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"删除插件持久化数据失败 (plugins_data): {e!s}")
|
||||
|
||||
async def _unbind_plugin(self, plugin_name: str, plugin_module_path: str):
|
||||
"""解绑并移除一个插件。
|
||||
|
||||
|
||||
@@ -30,7 +30,9 @@ class UmopConfigRouter:
|
||||
if len(p1_ls) != 3 or len(p2_ls) != 3:
|
||||
return False # 非法格式
|
||||
|
||||
return all(p == "" or p == "*" or p == t for p, t in zip(p1_ls, p2_ls))
|
||||
return all(
|
||||
p == "" or p == "*" or p == t for p, t in zip(p1_ls, p2_ls, strict=False)
|
||||
)
|
||||
|
||||
def get_conf_id_for_umop(self, umo: str) -> str | None:
|
||||
"""根据 UMO 获取对应的配置文件 ID
|
||||
|
||||
@@ -105,31 +105,16 @@ async def download_image_by_url(
|
||||
f.write(await resp.read())
|
||||
return path
|
||||
except (aiohttp.ClientConnectorSSLError, aiohttp.ClientConnectorCertificateError):
|
||||
# 关闭SSL验证(仅在证书验证失败时作为fallback)
|
||||
logger.warning(
|
||||
f"SSL certificate verification failed for {url}. "
|
||||
"Disabling SSL verification (CERT_NONE) as a fallback. "
|
||||
"This is insecure and exposes the application to man-in-the-middle attacks. "
|
||||
"Please investigate and resolve certificate issues."
|
||||
)
|
||||
# 关闭SSL验证
|
||||
ssl_context = ssl.create_default_context()
|
||||
ssl_context.check_hostname = False
|
||||
ssl_context.verify_mode = ssl.CERT_NONE
|
||||
ssl_context.set_ciphers("DEFAULT")
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if post:
|
||||
async with session.post(url, json=post_data, ssl=ssl_context) as resp:
|
||||
if not path:
|
||||
return save_temp_img(await resp.read())
|
||||
with open(path, "wb") as f:
|
||||
f.write(await resp.read())
|
||||
return path
|
||||
async with session.get(url, ssl=ssl_context) as resp:
|
||||
return save_temp_img(await resp.read())
|
||||
else:
|
||||
async with session.get(url, ssl=ssl_context) as resp:
|
||||
if not path:
|
||||
return save_temp_img(await resp.read())
|
||||
with open(path, "wb") as f:
|
||||
f.write(await resp.read())
|
||||
return path
|
||||
return save_temp_img(await resp.read())
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
@@ -172,19 +157,9 @@ async def download_file(url: str, path: str, show_progress: bool = False):
|
||||
end="",
|
||||
)
|
||||
except (aiohttp.ClientConnectorSSLError, aiohttp.ClientConnectorCertificateError):
|
||||
# 关闭SSL验证(仅在证书验证失败时作为fallback)
|
||||
logger.warning(
|
||||
"SSL 证书验证失败,已关闭 SSL 验证(不安全,仅用于临时下载)。请检查目标服务器的证书配置。"
|
||||
)
|
||||
logger.warning(
|
||||
f"SSL certificate verification failed for {url}. "
|
||||
"Falling back to unverified connection (CERT_NONE). "
|
||||
"This is insecure and exposes the application to man-in-the-middle attacks. "
|
||||
"Please investigate certificate issues with the remote server."
|
||||
)
|
||||
# 关闭SSL验证
|
||||
ssl_context = ssl.create_default_context()
|
||||
ssl_context.check_hostname = False
|
||||
ssl_context.verify_mode = ssl.CERT_NONE
|
||||
ssl_context.set_ciphers("DEFAULT")
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, ssl=ssl_context, timeout=120) as resp:
|
||||
total_size = int(resp.headers.get("content-length", 0))
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""会话控制"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import asyncio
|
||||
import copy
|
||||
@@ -8,11 +10,13 @@ import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import anyio
|
||||
|
||||
import astrbot.core.message.components as Comp
|
||||
from astrbot.core.platform import AstrMessageEvent
|
||||
|
||||
USER_SESSIONS: dict[str, "SessionWaiter"] = {} # 存储 SessionWaiter 实例
|
||||
FILTERS: list["SessionFilter"] = [] # 存储 SessionFilter 实例
|
||||
USER_SESSIONS: dict[str, SessionWaiter] = {} # 存储 SessionWaiter 实例
|
||||
FILTERS: list[SessionFilter] = [] # 存储 SessionFilter 实例
|
||||
|
||||
|
||||
class SessionController:
|
||||
@@ -20,16 +24,16 @@ class SessionController:
|
||||
|
||||
def __init__(self):
|
||||
self.future = asyncio.Future()
|
||||
self.current_event: asyncio.Event = None
|
||||
self.current_event: anyio.Event | None = None
|
||||
"""当前正在等待的所用的异步事件"""
|
||||
self.ts: float = None
|
||||
self.ts: float | None = None
|
||||
"""上次保持(keep)开始时的时间"""
|
||||
self.timeout: float | int = None
|
||||
self.timeout: float | int | None = None
|
||||
"""上次保持(keep)开始时的超时时间"""
|
||||
|
||||
self.history_chains: list[list[Comp.BaseMessageComponent]] = []
|
||||
|
||||
def stop(self, error: Exception = None):
|
||||
def stop(self, error: Exception | None = None):
|
||||
"""立即结束这个会话"""
|
||||
if not self.future.done():
|
||||
if error:
|
||||
@@ -53,7 +57,9 @@ class SessionController:
|
||||
self.stop()
|
||||
return
|
||||
else:
|
||||
left_timeout = self.timeout - (new_ts - self.ts)
|
||||
current_timeout = self.timeout if self.timeout is not None else 0
|
||||
current_ts = self.ts if self.ts is not None else new_ts
|
||||
left_timeout = current_timeout - (new_ts - current_ts)
|
||||
timeout = left_timeout + timeout
|
||||
if timeout <= 0:
|
||||
self.stop()
|
||||
@@ -62,18 +68,19 @@ class SessionController:
|
||||
if self.current_event and not self.current_event.is_set():
|
||||
self.current_event.set() # 通知上一个 keep 结束
|
||||
|
||||
new_event = asyncio.Event()
|
||||
new_event = anyio.Event()
|
||||
self.ts = new_ts
|
||||
self.current_event = new_event
|
||||
self.timeout = timeout
|
||||
|
||||
asyncio.create_task(self._holding(new_event, timeout)) # 开始新的 keep
|
||||
anyio.create_task(self._holding(new_event, timeout)) # 开始新的 keep
|
||||
|
||||
async def _holding(self, event: asyncio.Event, timeout: int):
|
||||
async def _holding(self, event: anyio.Event, timeout_seconds: float):
|
||||
"""等待事件结束或超时"""
|
||||
try:
|
||||
await asyncio.wait_for(event.wait(), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
with anyio.move_on_after(timeout_seconds):
|
||||
await event.wait()
|
||||
except TimeoutError:
|
||||
if not self.future.done():
|
||||
self.future.set_exception(TimeoutError("等待超时"))
|
||||
except asyncio.CancelledError:
|
||||
@@ -105,10 +112,12 @@ class SessionWaiter:
|
||||
session_filter: SessionFilter,
|
||||
session_id: str,
|
||||
record_history_chains: bool,
|
||||
):
|
||||
) -> None:
|
||||
self.session_id = session_id
|
||||
self.session_filter = session_filter
|
||||
self.handler: Callable[[str], Awaitable[Any]] | None = None # 处理函数
|
||||
self.handler: (
|
||||
Callable[[SessionController, AstrMessageEvent], Awaitable[Any]] | None
|
||||
) = None # 处理函数
|
||||
|
||||
self.session_controller = SessionController()
|
||||
self.record_history_chains = record_history_chains
|
||||
@@ -119,15 +128,15 @@ class SessionWaiter:
|
||||
|
||||
async def register_wait(
|
||||
self,
|
||||
handler: Callable[[str], Awaitable[Any]],
|
||||
timeout: int = 30,
|
||||
handler: Callable[[SessionController, AstrMessageEvent], Awaitable[Any]],
|
||||
timeout_seconds: int = 30,
|
||||
) -> Any:
|
||||
"""等待外部输入并处理"""
|
||||
self.handler = handler
|
||||
USER_SESSIONS[self.session_id] = self
|
||||
|
||||
# 开始一个会话保持事件
|
||||
self.session_controller.keep(timeout, reset_timeout=True)
|
||||
self.session_controller.keep(timeout_seconds, reset_timeout=True)
|
||||
|
||||
try:
|
||||
return await self.session_controller.future
|
||||
@@ -137,7 +146,7 @@ class SessionWaiter:
|
||||
finally:
|
||||
self._cleanup()
|
||||
|
||||
def _cleanup(self, error: Exception = None):
|
||||
def _cleanup(self, error: Exception | None = None):
|
||||
"""清理会话"""
|
||||
USER_SESSIONS.pop(self.session_id, None)
|
||||
try:
|
||||
@@ -153,6 +162,10 @@ class SessionWaiter:
|
||||
if not session or session.session_controller.future.done():
|
||||
return
|
||||
|
||||
# 此时 session 不会是 None,因为上面的检查
|
||||
if session is None:
|
||||
return
|
||||
|
||||
async with session._lock:
|
||||
if not session.session_controller.future.done():
|
||||
if session.record_history_chains:
|
||||
@@ -161,7 +174,8 @@ class SessionWaiter:
|
||||
)
|
||||
try:
|
||||
# TODO: 这里使用 create_task,跟踪 task,防止超时后这里 handler 仍然在执行
|
||||
await session.handler(session.session_controller, event)
|
||||
if session.handler is not None:
|
||||
await session.handler(session.session_controller, event)
|
||||
except Exception as e:
|
||||
session.session_controller.stop(e)
|
||||
|
||||
@@ -173,11 +187,13 @@ def session_waiter(timeout: int = 30, record_history_chains: bool = False):
|
||||
:param record_history_chain: 是否自动记录历史消息链。可以通过 controller.get_history_chains() 获取。深拷贝。
|
||||
"""
|
||||
|
||||
def decorator(func: Callable[[str], Awaitable[Any]]):
|
||||
def decorator(
|
||||
func: Callable[[SessionController, AstrMessageEvent], Awaitable[Any]],
|
||||
):
|
||||
@functools.wraps(func)
|
||||
async def wrapper(
|
||||
event: AstrMessageEvent,
|
||||
session_filter: SessionFilter = None,
|
||||
session_filter: SessionFilter | None = None,
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
|
||||
import anyio
|
||||
import jwt
|
||||
from quart import request
|
||||
|
||||
@@ -44,7 +44,7 @@ class AuthRoute(Route):
|
||||
)
|
||||
.__dict__
|
||||
)
|
||||
await asyncio.sleep(3)
|
||||
await anyio.sleep(3)
|
||||
return Response().error("用户名或密码错误").__dict__
|
||||
|
||||
async def edit_account(self):
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import anyio
|
||||
from quart import Response as QuartResponse
|
||||
from quart import g, make_response, request
|
||||
|
||||
@@ -188,8 +189,8 @@ class ChatRoute(Route):
|
||||
|
||||
try:
|
||||
if not client_disconnected:
|
||||
await asyncio.sleep(0.05)
|
||||
except asyncio.CancelledError:
|
||||
await anyio.sleep(0.05)
|
||||
except anyio.get_cancelled_exc_class():
|
||||
logger.debug(f"[WebChat] 用户 {username} 断开聊天长连接。")
|
||||
client_disconnected = True
|
||||
|
||||
|
||||
@@ -817,7 +817,8 @@ class ConfigRoute(Route):
|
||||
cached_token = self._logo_token_cache[cache_key]
|
||||
# 确保platform_default_tmpl[platform.name]存在且为字典
|
||||
if platform.name not in platform_default_tmpl or not isinstance(
|
||||
platform_default_tmpl[platform.name], dict
|
||||
platform_default_tmpl[platform.name],
|
||||
dict,
|
||||
):
|
||||
platform_default_tmpl[platform.name] = {}
|
||||
platform_default_tmpl[platform.name]["logo_token"] = cached_token
|
||||
@@ -846,7 +847,8 @@ class ConfigRoute(Route):
|
||||
|
||||
# 确保platform_default_tmpl[platform.name]存在且为字典
|
||||
if platform.name not in platform_default_tmpl or not isinstance(
|
||||
platform_default_tmpl[platform.name], dict
|
||||
platform_default_tmpl[platform.name],
|
||||
dict,
|
||||
):
|
||||
platform_default_tmpl[platform.name] = {}
|
||||
|
||||
|
||||
@@ -395,15 +395,9 @@ class PluginRoute(Route):
|
||||
|
||||
post_data = await request.json
|
||||
plugin_name = post_data["name"]
|
||||
delete_config = post_data.get("delete_config", False)
|
||||
delete_data = post_data.get("delete_data", False)
|
||||
try:
|
||||
logger.info(f"正在卸载插件 {plugin_name}")
|
||||
await self.plugin_manager.uninstall_plugin(
|
||||
plugin_name,
|
||||
delete_config=delete_config,
|
||||
delete_data=delete_data,
|
||||
)
|
||||
await self.plugin_manager.uninstall_plugin(plugin_name)
|
||||
logger.info(f"卸载插件 {plugin_name} 成功")
|
||||
return Response().ok(None, "卸载成功").__dict__
|
||||
except Exception as e:
|
||||
|
||||
@@ -296,15 +296,7 @@ class ToolsRoute(Route):
|
||||
"""获取所有注册的工具列表"""
|
||||
try:
|
||||
tools = self.tool_mgr.func_list
|
||||
tools_dict = [
|
||||
{
|
||||
"name": tool.name,
|
||||
"description": tool.description,
|
||||
"parameters": tool.parameters,
|
||||
"active": tool.active,
|
||||
}
|
||||
for tool in tools
|
||||
]
|
||||
tools_dict = [tool.__dict__() for tool in tools]
|
||||
return Response().ok(data=tools_dict).__dict__
|
||||
except Exception as e:
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
## What's Changed
|
||||
|
||||
1. 修复:>= Python 3.12 版本下可能导致 LLM Tool 注册错误的问题。
|
||||
2. 优化:更好地适配 Class 方式注册 LLM Tool 的场景。引入 `call` 方法。
|
||||
3. 新增:`ConversationManager` 类支持 `add_message_pair` 方法,简化对话消息的添加操作。
|
||||
4. 新增:增加对 Tool Parameters 的参数验证,确保工具参数符合 JSON Schema 标准。
|
||||
5. 新增:增加 LLM Message Schema 定义,提升消息结构的规范性和一致性。
|
||||
6. 新增:支持对 WebUI 的侧边栏模块进行自定义配置(入口在侧边栏下方的设置页中)。
|
||||
@@ -1,5 +0,0 @@
|
||||
## What's Changed
|
||||
|
||||
> hotfix version of 4.5.2
|
||||
|
||||
1. 修复:修正 `get_tool_list` 方法中工具字典推导式的错误导致的 WebUI MCP 页面工具列表无法显示的问题。
|
||||
@@ -1,5 +0,0 @@
|
||||
## What's Changed
|
||||
|
||||
1. 修复:Docker 镜像部分依赖问题导致某些情况下无法启动容器的问题;
|
||||
2. 优化:插件卡片样式
|
||||
3. 修复:部分情况下 Windows 一键启动部署时,更新 / 部署失败的问题;
|
||||
3
dashboard/.gitignore
vendored
3
dashboard/.gitignore
vendored
@@ -1,3 +1,2 @@
|
||||
node_modules/
|
||||
.DS_Store
|
||||
dist/
|
||||
.DS_Store
|
||||
@@ -2,7 +2,6 @@
|
||||
import { ref, computed, inject } from 'vue';
|
||||
import { useCustomizerStore } from "@/stores/customizer";
|
||||
import { useModuleI18n } from '@/i18n/composables';
|
||||
import UninstallConfirmDialog from './UninstallConfirmDialog.vue';
|
||||
|
||||
const props = defineProps({
|
||||
extension: {
|
||||
@@ -32,7 +31,6 @@ const emit = defineEmits([
|
||||
]);
|
||||
|
||||
const reveal = ref(false);
|
||||
const showUninstallDialog = ref(false);
|
||||
|
||||
// 国际化
|
||||
const { tm } = useModuleI18n('features/extension');
|
||||
@@ -57,11 +55,19 @@ const installExtension = async () => {
|
||||
};
|
||||
|
||||
const uninstallExtension = async () => {
|
||||
showUninstallDialog.value = true;
|
||||
};
|
||||
if (typeof $confirm !== "function") {
|
||||
console.error(tm("card.errors.confirmNotRegistered"));
|
||||
return;
|
||||
}
|
||||
|
||||
const handleUninstallConfirm = (options: { deleteConfig: boolean; deleteData: boolean }) => {
|
||||
emit("uninstall", props.extension, options);
|
||||
const confirmed = await $confirm({
|
||||
title: tm("dialogs.uninstall.title"),
|
||||
message: tm("dialogs.uninstall.message"),
|
||||
});
|
||||
|
||||
if (confirmed) {
|
||||
emit("uninstall", props.extension);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleActivation = () => {
|
||||
@@ -214,12 +220,6 @@ const viewReadme = () => {
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
|
||||
<!-- 卸载确认对话框 -->
|
||||
<UninstallConfirmDialog
|
||||
v-model="showUninstallDialog"
|
||||
@confirm="handleUninstallConfirm"
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -1,290 +0,0 @@
|
||||
<template>
|
||||
<div style="margin-top: 16px;">
|
||||
<v-btn
|
||||
color="primary"
|
||||
variant="outlined"
|
||||
size="small"
|
||||
@click="openDialog"
|
||||
style="margin-bottom: 8px;"
|
||||
>
|
||||
{{ t('features.settings.sidebar.customize.title') }}
|
||||
</v-btn>
|
||||
|
||||
<v-dialog v-model="dialog" max-width="700px">
|
||||
<v-card>
|
||||
<v-card-title class="d-flex justify-space-between align-center">
|
||||
<span>{{ t('features.settings.sidebar.customize.title') }}</span>
|
||||
<v-btn
|
||||
icon="mdi-close"
|
||||
variant="text"
|
||||
@click="dialog = false"
|
||||
></v-btn>
|
||||
</v-card-title>
|
||||
|
||||
<v-card-text>
|
||||
<p class="text-body-2 mb-4">{{ t('features.settings.sidebar.customize.subtitle') }}</p>
|
||||
|
||||
<v-row>
|
||||
<v-col cols="12" md="6">
|
||||
<div class="mb-2 font-weight-medium">{{ t('features.settings.sidebar.customize.mainItems') }}</div>
|
||||
<v-list
|
||||
density="compact"
|
||||
class="custom-list"
|
||||
@dragover.prevent
|
||||
@drop="handleDropToList($event, 'main')"
|
||||
>
|
||||
<v-list-item
|
||||
v-for="(item, index) in mainItems"
|
||||
:key="item.title"
|
||||
class="mb-1 draggable-item"
|
||||
draggable="true"
|
||||
@dragstart="handleDragStart($event, 'main', index)"
|
||||
@dragover.prevent
|
||||
@drop.stop="handleDrop($event, 'main', index)"
|
||||
>
|
||||
<template v-slot:prepend>
|
||||
<v-icon :icon="item.icon" size="small" class="mr-2"></v-icon>
|
||||
</template>
|
||||
<v-list-item-title>{{ t(item.title) }}</v-list-item-title>
|
||||
<template v-slot:append>
|
||||
<v-btn
|
||||
icon="mdi-arrow-right"
|
||||
variant="text"
|
||||
size="x-small"
|
||||
@click="moveToMore(index)"
|
||||
></v-btn>
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</v-col>
|
||||
|
||||
<v-col cols="12" md="6">
|
||||
<div class="mb-2 font-weight-medium">{{ t('features.settings.sidebar.customize.moreItems') }}</div>
|
||||
<v-list
|
||||
density="compact"
|
||||
class="custom-list"
|
||||
@dragover.prevent
|
||||
@drop="handleDropToList($event, 'more')"
|
||||
>
|
||||
<v-list-item
|
||||
v-for="(item, index) in moreItems"
|
||||
:key="item.title"
|
||||
class="mb-1 draggable-item"
|
||||
draggable="true"
|
||||
@dragstart="handleDragStart($event, 'more', index)"
|
||||
@dragover.prevent
|
||||
@drop.stop="handleDrop($event, 'more', index)"
|
||||
>
|
||||
<template v-slot:prepend>
|
||||
<v-icon :icon="item.icon" size="small" class="mr-2"></v-icon>
|
||||
</template>
|
||||
<v-list-item-title>{{ t(item.title) }}</v-list-item-title>
|
||||
<template v-slot:append>
|
||||
<v-btn
|
||||
icon="mdi-arrow-left"
|
||||
variant="text"
|
||||
size="x-small"
|
||||
@click="moveToMain(index)"
|
||||
></v-btn>
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-card-text>
|
||||
|
||||
<v-card-actions>
|
||||
<v-btn
|
||||
color="error"
|
||||
variant="text"
|
||||
@click="resetToDefault"
|
||||
>
|
||||
{{ t('features.settings.sidebar.customize.reset') }}
|
||||
</v-btn>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn
|
||||
color="primary"
|
||||
@click="saveCustomization"
|
||||
>
|
||||
{{ t('core.actions.save') }}
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useI18n } from '@/i18n/composables';
|
||||
import sidebarItems from '@/layouts/full/vertical-sidebar/sidebarItem';
|
||||
import {
|
||||
getSidebarCustomization,
|
||||
setSidebarCustomization,
|
||||
clearSidebarCustomization
|
||||
} from '@/utils/sidebarCustomization';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const dialog = ref(false);
|
||||
const mainItems = ref([]);
|
||||
const moreItems = ref([]);
|
||||
const draggedItem = ref(null);
|
||||
|
||||
function initializeItems() {
|
||||
const customization = getSidebarCustomization();
|
||||
|
||||
if (customization) {
|
||||
// Load from customization
|
||||
const allItemsMap = new Map();
|
||||
|
||||
sidebarItems.forEach(item => {
|
||||
if (item.children) {
|
||||
item.children.forEach(child => {
|
||||
allItemsMap.set(child.title, child);
|
||||
});
|
||||
} else {
|
||||
allItemsMap.set(item.title, item);
|
||||
}
|
||||
});
|
||||
|
||||
mainItems.value = customization.mainItems
|
||||
.map(title => allItemsMap.get(title))
|
||||
.filter(item => item);
|
||||
|
||||
moreItems.value = customization.moreItems
|
||||
.map(title => allItemsMap.get(title))
|
||||
.filter(item => item);
|
||||
} else {
|
||||
// Load default structure
|
||||
mainItems.value = sidebarItems.filter(item => !item.children);
|
||||
|
||||
const moreGroup = sidebarItems.find(item => item.title === 'core.navigation.groups.more');
|
||||
moreItems.value = moreGroup ? [...moreGroup.children] : [];
|
||||
}
|
||||
}
|
||||
|
||||
function openDialog() {
|
||||
initializeItems();
|
||||
dialog.value = true;
|
||||
}
|
||||
|
||||
function handleDragStart(event, listType, index) {
|
||||
draggedItem.value = {
|
||||
type: listType,
|
||||
index: index,
|
||||
item: listType === 'main' ? mainItems.value[index] : moreItems.value[index]
|
||||
};
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
}
|
||||
|
||||
function handleDrop(event, targetListType, targetIndex) {
|
||||
event.preventDefault();
|
||||
|
||||
if (!draggedItem.value) return;
|
||||
|
||||
const sourceListType = draggedItem.value.type;
|
||||
const sourceIndex = draggedItem.value.index;
|
||||
const item = draggedItem.value.item;
|
||||
|
||||
// Remove from source
|
||||
if (sourceListType === 'main') {
|
||||
mainItems.value.splice(sourceIndex, 1);
|
||||
} else {
|
||||
moreItems.value.splice(sourceIndex, 1);
|
||||
}
|
||||
|
||||
// Add to target
|
||||
if (targetListType === 'main') {
|
||||
mainItems.value.splice(targetIndex, 0, item);
|
||||
} else {
|
||||
moreItems.value.splice(targetIndex, 0, item);
|
||||
}
|
||||
|
||||
draggedItem.value = null;
|
||||
}
|
||||
|
||||
function handleDropToList(event, targetListType) {
|
||||
event.preventDefault();
|
||||
|
||||
if (!draggedItem.value) return;
|
||||
|
||||
const sourceListType = draggedItem.value.type;
|
||||
const sourceIndex = draggedItem.value.index;
|
||||
const item = draggedItem.value.item;
|
||||
|
||||
// Remove from source
|
||||
if (sourceListType === 'main') {
|
||||
mainItems.value.splice(sourceIndex, 1);
|
||||
} else {
|
||||
moreItems.value.splice(sourceIndex, 1);
|
||||
}
|
||||
|
||||
// Add to target list at the end
|
||||
if (targetListType === 'main') {
|
||||
mainItems.value.push(item);
|
||||
} else {
|
||||
moreItems.value.push(item);
|
||||
}
|
||||
|
||||
draggedItem.value = null;
|
||||
}
|
||||
|
||||
function moveToMore(index) {
|
||||
const item = mainItems.value.splice(index, 1)[0];
|
||||
moreItems.value.push(item);
|
||||
}
|
||||
|
||||
function moveToMain(index) {
|
||||
const item = moreItems.value.splice(index, 1)[0];
|
||||
mainItems.value.push(item);
|
||||
}
|
||||
|
||||
function saveCustomization() {
|
||||
const config = {
|
||||
mainItems: mainItems.value.map(item => item.title),
|
||||
moreItems: moreItems.value.map(item => item.title)
|
||||
};
|
||||
|
||||
setSidebarCustomization(config);
|
||||
|
||||
// Notify the sidebar to reload
|
||||
window.dispatchEvent(new CustomEvent('sidebar-customization-changed'));
|
||||
|
||||
dialog.value = false;
|
||||
}
|
||||
|
||||
function resetToDefault() {
|
||||
clearSidebarCustomization();
|
||||
initializeItems();
|
||||
|
||||
// Notify the sidebar to reload
|
||||
window.dispatchEvent(new CustomEvent('sidebar-customization-changed'));
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
initializeItems();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.draggable-item {
|
||||
cursor: move;
|
||||
border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
|
||||
border-radius: 4px;
|
||||
background-color: rgba(var(--v-theme-surface));
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.draggable-item:hover {
|
||||
background-color: rgba(var(--v-theme-primary), 0.1);
|
||||
border-color: rgba(var(--v-theme-primary), 0.3);
|
||||
}
|
||||
|
||||
.custom-list {
|
||||
min-height: 200px;
|
||||
border: 1px dashed rgba(var(--v-border-color), var(--v-border-opacity));
|
||||
border-radius: 4px;
|
||||
padding: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,135 +0,0 @@
|
||||
<template>
|
||||
<v-dialog
|
||||
v-model="show"
|
||||
max-width="500"
|
||||
@click:outside="handleCancel"
|
||||
@keydown.esc="handleCancel"
|
||||
>
|
||||
<v-card>
|
||||
<v-card-title class="text-h5">
|
||||
{{ tm('dialogs.uninstall.title') }}
|
||||
</v-card-title>
|
||||
|
||||
<v-card-text>
|
||||
<div class="mb-4">
|
||||
{{ tm('dialogs.uninstall.message') }}
|
||||
</div>
|
||||
|
||||
<v-divider class="my-4"></v-divider>
|
||||
|
||||
<div class="text-subtitle-2 mb-3">{{ t('core.common.actions') }}:</div>
|
||||
|
||||
<v-checkbox
|
||||
v-model="deleteConfig"
|
||||
:label="tm('dialogs.uninstall.deleteConfig')"
|
||||
color="warning"
|
||||
hide-details
|
||||
class="mb-2"
|
||||
>
|
||||
<template v-slot:append>
|
||||
<v-tooltip location="top">
|
||||
<template v-slot:activator="{ props }">
|
||||
<v-icon v-bind="props" size="small" color="grey">mdi-information-outline</v-icon>
|
||||
</template>
|
||||
<span>{{ tm('dialogs.uninstall.configHint') }}</span>
|
||||
</v-tooltip>
|
||||
</template>
|
||||
</v-checkbox>
|
||||
|
||||
<v-checkbox
|
||||
v-model="deleteData"
|
||||
:label="tm('dialogs.uninstall.deleteData')"
|
||||
color="error"
|
||||
hide-details
|
||||
>
|
||||
<template v-slot:append>
|
||||
<v-tooltip location="top">
|
||||
<template v-slot:activator="{ props }">
|
||||
<v-icon v-bind="props" size="small" color="grey">mdi-information-outline</v-icon>
|
||||
</template>
|
||||
<span>{{ tm('dialogs.uninstall.dataHint') }}</span>
|
||||
</v-tooltip>
|
||||
</template>
|
||||
</v-checkbox>
|
||||
|
||||
<v-alert
|
||||
v-if="deleteConfig || deleteData"
|
||||
type="warning"
|
||||
variant="tonal"
|
||||
density="compact"
|
||||
class="mt-4"
|
||||
>
|
||||
<template v-slot:prepend>
|
||||
<v-icon>mdi-alert</v-icon>
|
||||
</template>
|
||||
{{ t('messages.validation.operation_cannot_be_undone') }}
|
||||
</v-alert>
|
||||
</v-card-text>
|
||||
|
||||
<v-card-actions>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn
|
||||
color="grey"
|
||||
variant="text"
|
||||
@click="handleCancel"
|
||||
>
|
||||
{{ t('core.common.cancel') }}
|
||||
</v-btn>
|
||||
<v-btn
|
||||
color="error"
|
||||
variant="elevated"
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ t('core.common.confirm') }}
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n, useModuleI18n } from '@/i18n/composables';
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(['update:modelValue', 'confirm', 'cancel']);
|
||||
|
||||
const { t } = useI18n();
|
||||
const { tm } = useModuleI18n('features/extension');
|
||||
|
||||
const show = ref(props.modelValue);
|
||||
const deleteConfig = ref(false);
|
||||
const deleteData = ref(false);
|
||||
|
||||
watch(() => props.modelValue, (val) => {
|
||||
show.value = val;
|
||||
if (val) {
|
||||
// 重置选项
|
||||
deleteConfig.value = false;
|
||||
deleteData.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
watch(show, (val) => {
|
||||
emit('update:modelValue', val);
|
||||
});
|
||||
|
||||
const handleConfirm = () => {
|
||||
emit('confirm', {
|
||||
deleteConfig: deleteConfig.value,
|
||||
deleteData: deleteData.value,
|
||||
});
|
||||
show.value = false;
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
emit('cancel');
|
||||
show.value = false;
|
||||
};
|
||||
</script>
|
||||
@@ -18,6 +18,5 @@
|
||||
"refresh": "Refresh",
|
||||
"submit": "Submit",
|
||||
"reset": "Reset",
|
||||
"clear": "Clear",
|
||||
"save": "Save"
|
||||
"clear": "Clear"
|
||||
}
|
||||
@@ -79,14 +79,6 @@
|
||||
"devDocs": "Extension Development Docs",
|
||||
"submitRepo": "Submit Extension Repository"
|
||||
},
|
||||
"sort": {
|
||||
"default": "Default",
|
||||
"stars": "Stars",
|
||||
"author": "Author",
|
||||
"updated": "Last Updated",
|
||||
"ascending": "Ascending",
|
||||
"descending": "Descending"
|
||||
},
|
||||
"tags": {
|
||||
"danger": "Danger"
|
||||
},
|
||||
@@ -105,11 +97,7 @@
|
||||
},
|
||||
"uninstall": {
|
||||
"title": "Confirm Deletion",
|
||||
"message": "Are you sure you want to delete this extension?",
|
||||
"deleteConfig": "Also delete plugin configuration file",
|
||||
"deleteData": "Also delete plugin persistent data",
|
||||
"configHint": "Configuration file located in data/config directory",
|
||||
"dataHint": "Deletes data in data/plugin_data and data/plugins_data"
|
||||
"message": "Are you sure you want to delete this extension?"
|
||||
},
|
||||
"install": {
|
||||
"title": "Install Extension",
|
||||
|
||||
@@ -19,15 +19,5 @@
|
||||
"subtitle": "If you encounter data compatibility issues, you can manually start the database migration assistant",
|
||||
"button": "Start Migration Assistant"
|
||||
}
|
||||
},
|
||||
"sidebar": {
|
||||
"title": "Sidebar",
|
||||
"customize": {
|
||||
"title": "Customize Sidebar",
|
||||
"subtitle": "Drag to reorder modules, or move modules in/out of the \"More Features\" group. Settings are saved locally in your browser.",
|
||||
"reset": "Reset to Default",
|
||||
"mainItems": "Main Modules",
|
||||
"moreItems": "More Features"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,5 @@
|
||||
"invalid_date": "Please enter a valid date",
|
||||
"date_range": "Invalid date range",
|
||||
"upload_failed": "File upload failed",
|
||||
"network_error": "Network connection error, please try again",
|
||||
"operation_cannot_be_undone": "⚠️ This operation cannot be undone, please choose carefully!"
|
||||
"network_error": "Network connection error, please try again"
|
||||
}
|
||||
@@ -18,6 +18,5 @@
|
||||
"refresh": "刷新",
|
||||
"submit": "提交",
|
||||
"reset": "重置",
|
||||
"clear": "清空",
|
||||
"save": "保存"
|
||||
"clear": "清空"
|
||||
}
|
||||
@@ -79,14 +79,6 @@
|
||||
"devDocs": "插件开发文档",
|
||||
"submitRepo": "提交插件仓库"
|
||||
},
|
||||
"sort": {
|
||||
"default": "默认排序",
|
||||
"stars": "Star数",
|
||||
"author": "作者名",
|
||||
"updated": "更新时间",
|
||||
"ascending": "升序",
|
||||
"descending": "降序"
|
||||
},
|
||||
"tags": {
|
||||
"danger": "危险"
|
||||
},
|
||||
@@ -105,11 +97,7 @@
|
||||
},
|
||||
"uninstall": {
|
||||
"title": "删除确认",
|
||||
"message": "你确定要删除当前插件吗?",
|
||||
"deleteConfig": "同时删除插件配置文件",
|
||||
"deleteData": "同时删除插件持久化数据",
|
||||
"configHint": "配置文件位于 data/config 目录",
|
||||
"dataHint": "删除 data/plugin_data 和 data/plugins_data 目录下的数据"
|
||||
"message": "你确定要删除当前插件吗?"
|
||||
},
|
||||
"install": {
|
||||
"title": "安装插件",
|
||||
|
||||
@@ -19,15 +19,5 @@
|
||||
"subtitle": "如果您遇到数据兼容性问题,可以手动启动数据库迁移助手",
|
||||
"button": "启动迁移助手"
|
||||
}
|
||||
},
|
||||
"sidebar": {
|
||||
"title": "侧边栏",
|
||||
"customize": {
|
||||
"title": "自定义侧边栏",
|
||||
"subtitle": "拖拽以调整模块顺序,或者将模块移入/移出\"更多功能\"分组。设置仅保存在浏览器本地。",
|
||||
"reset": "恢复默认",
|
||||
"mainItems": "主要模块",
|
||||
"moreItems": "更多功能"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,5 @@
|
||||
"invalid_date": "请输入有效的日期",
|
||||
"date_range": "日期范围无效",
|
||||
"upload_failed": "文件上传失败",
|
||||
"network_error": "网络连接错误,请重试",
|
||||
"operation_cannot_be_undone": "⚠️ 此操作无法撤销,请谨慎选择!"
|
||||
"network_error": "网络连接错误,请重试"
|
||||
}
|
||||
@@ -1,39 +1,15 @@
|
||||
<script setup>
|
||||
import { ref, shallowRef, onMounted, onUnmounted } from 'vue';
|
||||
import { ref, shallowRef } from 'vue';
|
||||
import { useCustomizerStore } from '../../../stores/customizer';
|
||||
import { useI18n } from '@/i18n/composables';
|
||||
import sidebarItems from './sidebarItem';
|
||||
import NavItem from './NavItem.vue';
|
||||
import { applySidebarCustomization } from '@/utils/sidebarCustomization';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const customizer = useCustomizerStore();
|
||||
const sidebarMenu = shallowRef(sidebarItems);
|
||||
|
||||
// Apply customization on mount and listen for storage changes
|
||||
const handleStorageChange = (e) => {
|
||||
if (e.key === 'astrbot_sidebar_customization') {
|
||||
sidebarMenu.value = applySidebarCustomization(sidebarItems);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCustomEvent = () => {
|
||||
sidebarMenu.value = applySidebarCustomization(sidebarItems);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
sidebarMenu.value = applySidebarCustomization(sidebarItems);
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
window.addEventListener('sidebar-customization-changed', handleCustomEvent);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('storage', handleStorageChange);
|
||||
window.removeEventListener('sidebar-customization-changed', handleCustomEvent);
|
||||
});
|
||||
|
||||
const showIframe = ref(false);
|
||||
const starCount = ref(null);
|
||||
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
// Utility for managing sidebar customization in localStorage
|
||||
const STORAGE_KEY = 'astrbot_sidebar_customization';
|
||||
|
||||
/**
|
||||
* Get the customized sidebar configuration from localStorage
|
||||
* @returns {Object|null} The customization config or null if not set
|
||||
*/
|
||||
export function getSidebarCustomization() {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored ? JSON.parse(stored) : null;
|
||||
} catch (error) {
|
||||
console.error('Error reading sidebar customization:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the sidebar customization to localStorage
|
||||
* @param {Object} config - The customization configuration
|
||||
* @param {Array} config.mainItems - Array of item titles for main sidebar
|
||||
* @param {Array} config.moreItems - Array of item titles for "More Features" group
|
||||
*/
|
||||
export function setSidebarCustomization(config) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(config));
|
||||
} catch (error) {
|
||||
console.error('Error saving sidebar customization:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the sidebar customization (reset to default)
|
||||
*/
|
||||
export function clearSidebarCustomization() {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('Error clearing sidebar customization:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply customization to sidebar items
|
||||
* @param {Array} defaultItems - Default sidebar items array
|
||||
* @returns {Array} Customized sidebar items array (new array, doesn't mutate input)
|
||||
*/
|
||||
export function applySidebarCustomization(defaultItems) {
|
||||
const customization = getSidebarCustomization();
|
||||
if (!customization) {
|
||||
return defaultItems;
|
||||
}
|
||||
|
||||
const { mainItems, moreItems } = customization;
|
||||
|
||||
// Create a map of all items by title for quick lookup
|
||||
// Deep clone items to avoid mutating originals
|
||||
const allItemsMap = new Map();
|
||||
defaultItems.forEach(item => {
|
||||
if (item.children) {
|
||||
// If it's the "More" group, add children to map
|
||||
item.children.forEach(child => {
|
||||
allItemsMap.set(child.title, { ...child });
|
||||
});
|
||||
} else {
|
||||
allItemsMap.set(item.title, { ...item });
|
||||
}
|
||||
});
|
||||
|
||||
const customizedItems = [];
|
||||
|
||||
// Add main items in custom order
|
||||
mainItems.forEach(title => {
|
||||
const item = allItemsMap.get(title);
|
||||
if (item) {
|
||||
customizedItems.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
// If there are items in moreItems, create the "More Features" group
|
||||
if (moreItems && moreItems.length > 0) {
|
||||
const moreGroup = {
|
||||
title: 'core.navigation.groups.more',
|
||||
icon: 'mdi-dots-horizontal',
|
||||
children: []
|
||||
};
|
||||
|
||||
moreItems.forEach(title => {
|
||||
const item = allItemsMap.get(title);
|
||||
if (item) {
|
||||
moreGroup.children.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
customizedItems.push(moreGroup);
|
||||
}
|
||||
|
||||
return customizedItems;
|
||||
}
|
||||
@@ -4,13 +4,12 @@ import AstrBotConfig from '@/components/shared/AstrBotConfig.vue';
|
||||
import ConsoleDisplayer from '@/components/shared/ConsoleDisplayer.vue';
|
||||
import ReadmeDialog from '@/components/shared/ReadmeDialog.vue';
|
||||
import ProxySelector from '@/components/shared/ProxySelector.vue';
|
||||
import UninstallConfirmDialog from '@/components/shared/UninstallConfirmDialog.vue';
|
||||
import axios from 'axios';
|
||||
import { pinyin } from 'pinyin-pro';
|
||||
import { useCommonStore } from '@/stores/common';
|
||||
import { useI18n, useModuleI18n } from '@/i18n/composables';
|
||||
|
||||
import { ref, computed, onMounted, reactive, inject, watch } from 'vue';
|
||||
import { ref, computed, onMounted, reactive } from 'vue';
|
||||
|
||||
|
||||
const commonStore = useCommonStore();
|
||||
@@ -53,18 +52,10 @@ const isListView = ref(false);
|
||||
const pluginSearch = ref("");
|
||||
const loading_ = ref(false);
|
||||
|
||||
// 分页相关
|
||||
const currentPage = ref(1);
|
||||
const itemsPerPage = ref(6); // 每页显示6个卡片 (2行 x 3列,避免滚动)
|
||||
|
||||
// 危险插件确认对话框
|
||||
const dangerConfirmDialog = ref(false);
|
||||
const selectedDangerPlugin = ref(null);
|
||||
|
||||
// 卸载插件确认对话框(列表模式用)
|
||||
const showUninstallDialog = ref(false);
|
||||
const pluginToUninstall = ref(null);
|
||||
|
||||
// 插件市场相关
|
||||
const extension_url = ref("");
|
||||
const dialog = ref(false);
|
||||
@@ -72,11 +63,8 @@ const upload_file = ref(null);
|
||||
const uploadTab = ref('file');
|
||||
const showPluginFullName = ref(false);
|
||||
const marketSearch = ref("");
|
||||
const debouncedMarketSearch = ref("");
|
||||
const filterKeys = ['name', 'desc', 'author'];
|
||||
const refreshingMarket = ref(false);
|
||||
const sortBy = ref('default'); // default, stars, author, updated
|
||||
const sortOrder = ref('desc'); // desc (降序) or asc (升序)
|
||||
|
||||
// 插件市场拼音搜索
|
||||
const normalizeStr = (s) => (s ?? '').toString().toLowerCase().trim();
|
||||
@@ -160,71 +148,6 @@ const pinnedPlugins = computed(() => {
|
||||
return pluginMarketData.value.filter(plugin => plugin?.pinned);
|
||||
});
|
||||
|
||||
// 过滤后的插件市场数据(带搜索)
|
||||
const filteredMarketPlugins = computed(() => {
|
||||
if (!debouncedMarketSearch.value) {
|
||||
return pluginMarketData.value;
|
||||
}
|
||||
|
||||
const search = debouncedMarketSearch.value.toLowerCase();
|
||||
return pluginMarketData.value.filter(plugin => {
|
||||
// 使用自定义过滤器
|
||||
return marketCustomFilter(plugin.name, search, plugin) ||
|
||||
marketCustomFilter(plugin.desc, search, plugin) ||
|
||||
marketCustomFilter(plugin.author, search, plugin);
|
||||
});
|
||||
});
|
||||
|
||||
// 所有插件列表,推荐插件排在前面
|
||||
const sortedPlugins = computed(() => {
|
||||
let plugins = [...filteredMarketPlugins.value];
|
||||
|
||||
// 根据排序选项排序
|
||||
if (sortBy.value === 'stars') {
|
||||
// 按 star 数排序
|
||||
plugins.sort((a, b) => {
|
||||
const starsA = a.stars ?? 0;
|
||||
const starsB = b.stars ?? 0;
|
||||
return sortOrder.value === 'desc' ? starsB - starsA : starsA - starsB;
|
||||
});
|
||||
} else if (sortBy.value === 'author') {
|
||||
// 按作者名字典序排序
|
||||
plugins.sort((a, b) => {
|
||||
const authorA = (a.author ?? '').toLowerCase();
|
||||
const authorB = (b.author ?? '').toLowerCase();
|
||||
const result = authorA.localeCompare(authorB);
|
||||
return sortOrder.value === 'desc' ? -result : result;
|
||||
});
|
||||
} else if (sortBy.value === 'updated') {
|
||||
// 按更新时间排序
|
||||
plugins.sort((a, b) => {
|
||||
const dateA = a.updated_at ? new Date(a.updated_at).getTime() : 0;
|
||||
const dateB = b.updated_at ? new Date(b.updated_at).getTime() : 0;
|
||||
return sortOrder.value === 'desc' ? dateB - dateA : dateA - dateB;
|
||||
});
|
||||
} else {
|
||||
// default: 推荐插件排在前面
|
||||
const pinned = plugins.filter(plugin => plugin?.pinned);
|
||||
const notPinned = plugins.filter(plugin => !plugin?.pinned);
|
||||
return [...pinned, ...notPinned];
|
||||
}
|
||||
|
||||
return plugins;
|
||||
});
|
||||
|
||||
// 分页计算属性
|
||||
const displayItemsPerPage = 9; // 固定每页显示6个卡片(2行)
|
||||
|
||||
const totalPages = computed(() => {
|
||||
return Math.ceil(sortedPlugins.value.length / displayItemsPerPage);
|
||||
});
|
||||
|
||||
const paginatedPlugins = computed(() => {
|
||||
const start = (currentPage.value - 1) * displayItemsPerPage;
|
||||
const end = start + displayItemsPerPage;
|
||||
return sortedPlugins.value.slice(start, end);
|
||||
});
|
||||
|
||||
// 方法
|
||||
const toggleShowReserved = () => {
|
||||
showReserved.value = !showReserved.value;
|
||||
@@ -290,35 +213,10 @@ const checkUpdate = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const uninstallExtension = async (extension_name, optionsOrSkipConfirm = false) => {
|
||||
let deleteConfig = false;
|
||||
let deleteData = false;
|
||||
let skipConfirm = false;
|
||||
|
||||
// 处理参数:可能是布尔值(旧的 skipConfirm)或对象(新的选项)
|
||||
if (typeof optionsOrSkipConfirm === 'boolean') {
|
||||
skipConfirm = optionsOrSkipConfirm;
|
||||
} else if (typeof optionsOrSkipConfirm === 'object' && optionsOrSkipConfirm !== null) {
|
||||
deleteConfig = optionsOrSkipConfirm.deleteConfig || false;
|
||||
deleteData = optionsOrSkipConfirm.deleteData || false;
|
||||
skipConfirm = true; // 如果传递了选项对象,说明已经确认过了
|
||||
}
|
||||
|
||||
// 如果没有跳过确认且没有传递选项对象,显示自定义卸载对话框
|
||||
if (!skipConfirm) {
|
||||
pluginToUninstall.value = extension_name;
|
||||
showUninstallDialog.value = true;
|
||||
return; // 等待对话框回调
|
||||
}
|
||||
|
||||
// 执行卸载
|
||||
const uninstallExtension = async (extension_name) => {
|
||||
toast(tm('messages.uninstalling') + " " + extension_name, "primary");
|
||||
try {
|
||||
const res = await axios.post('/api/plugin/uninstall', {
|
||||
name: extension_name,
|
||||
delete_config: deleteConfig,
|
||||
delete_data: deleteData,
|
||||
});
|
||||
const res = await axios.post('/api/plugin/uninstall', { name: extension_name });
|
||||
if (res.data.status === "error") {
|
||||
toast(res.data.message, "error");
|
||||
return;
|
||||
@@ -331,14 +229,6 @@ const uninstallExtension = async (extension_name, optionsOrSkipConfirm = false)
|
||||
}
|
||||
};
|
||||
|
||||
// 处理卸载确认对话框的确认事件
|
||||
const handleUninstallConfirm = (options) => {
|
||||
if (pluginToUninstall.value) {
|
||||
uninstallExtension(pluginToUninstall.value, options);
|
||||
pluginToUninstall.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const updateExtension = async (extension_name) => {
|
||||
loadingDialog.title = tm('status.loading');
|
||||
loadingDialog.show = true;
|
||||
@@ -606,7 +496,6 @@ const refreshPluginMarket = async () => {
|
||||
trimExtensionName();
|
||||
checkAlreadyInstalled();
|
||||
checkUpdate();
|
||||
currentPage.value = 1; // 重置到第一页
|
||||
|
||||
toast(tm('messages.refreshSuccess'), "success");
|
||||
} catch (err) {
|
||||
@@ -648,20 +537,6 @@ onMounted(async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 搜索防抖处理
|
||||
let searchDebounceTimer = null;
|
||||
watch(marketSearch, (newVal) => {
|
||||
if (searchDebounceTimer) {
|
||||
clearTimeout(searchDebounceTimer);
|
||||
}
|
||||
|
||||
searchDebounceTimer = setTimeout(() => {
|
||||
debouncedMarketSearch.value = newVal;
|
||||
// 搜索时重置到第一页
|
||||
currentPage.value = 1;
|
||||
}, 300); // 300ms 防抖延迟
|
||||
});
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
@@ -875,10 +750,8 @@ watch(marketSearch, (newVal) => {
|
||||
<v-row>
|
||||
<v-col cols="12" md="6" lg="4" v-for="extension in filteredPlugins" :key="extension.name"
|
||||
class="pb-2">
|
||||
<ExtensionCard :extension="extension" class="rounded-lg"
|
||||
style="background-color: rgb(var(--v-theme-mcpCardBg));"
|
||||
@configure="openExtensionConfig(extension.name)"
|
||||
@uninstall="(ext, options) => uninstallExtension(ext.name, options)"
|
||||
<ExtensionCard :extension="extension" class="rounded-lg" style="background-color: rgb(var(--v-theme-mcpCardBg));"
|
||||
@configure="openExtensionConfig(extension.name)" @uninstall="uninstallExtension(extension.name)"
|
||||
@update="updateExtension(extension.name)" @reload="reloadPlugin(extension.name)"
|
||||
@toggle-activation="extension.activated ? pluginOff(extension) : pluginOn(extension)"
|
||||
@view-handlers="showPluginInfo(extension)" @view-readme="viewReadme(extension)">
|
||||
@@ -898,158 +771,85 @@ watch(marketSearch, (newVal) => {
|
||||
@click="dialog = true" color="darkprimary">
|
||||
</v-btn>
|
||||
|
||||
<div class="mt-4">
|
||||
<div class="d-flex align-center mb-2" style="justify-content: space-between; flex-wrap: wrap; gap: 8px;">
|
||||
<div class="d-flex align-center" style="gap: 6px;">
|
||||
<h2>{{ tm('market.allPlugins') }}({{ filteredMarketPlugins.length }})</h2>
|
||||
<v-btn icon variant="text" @click="refreshPluginMarket" :loading="refreshingMarket">
|
||||
<v-icon>mdi-refresh</v-icon>
|
||||
</v-btn>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-center" style="gap: 8px; flex-wrap: wrap;">
|
||||
<v-pagination v-model="currentPage" :length="totalPages" :total-visible="5" size="small"
|
||||
density="comfortable"></v-pagination>
|
||||
|
||||
<!-- 排序选择器 -->
|
||||
<v-select v-model="sortBy" :items="[
|
||||
{ title: tm('sort.default'), value: 'default' },
|
||||
{ title: tm('sort.stars'), value: 'stars' },
|
||||
{ title: tm('sort.author'), value: 'author' },
|
||||
{ title: tm('sort.updated'), value: 'updated' }
|
||||
]" density="compact" variant="outlined" hide-details style="max-width: 150px;">
|
||||
<template v-slot:prepend-inner>
|
||||
<v-icon size="small">mdi-sort</v-icon>
|
||||
</template>
|
||||
</v-select>
|
||||
|
||||
<!-- 排序方向切换按钮 -->
|
||||
<v-btn icon v-if="sortBy !== 'default'" @click="sortOrder = sortOrder === 'desc' ? 'asc' : 'desc'"
|
||||
variant="text" density="compact">
|
||||
<v-icon>{{ sortOrder === 'desc' ? 'mdi-sort-descending' : 'mdi-sort-ascending'
|
||||
}}</v-icon>
|
||||
<v-tooltip activator="parent" location="top">
|
||||
{{ sortOrder === 'desc' ? tm('sort.descending') : tm('sort.ascending') }}
|
||||
</v-tooltip>
|
||||
</v-btn>
|
||||
<!-- <v-switch v-model="showPluginFullName" :label="tm('market.showFullName')" hide-details
|
||||
density="compact" style="margin-left: 12px" /> -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<v-row style="min-height: 26rem;">
|
||||
<v-col v-for="plugin in paginatedPlugins" :key="plugin.name" cols="12" md="6" lg="4">
|
||||
<v-card class="rounded-lg d-flex flex-column" elevation="0"
|
||||
style=" height: 12rem; position: relative;">
|
||||
|
||||
<!-- 推荐标记 -->
|
||||
<v-chip v-if="plugin?.pinned" color="warning" size="x-small" label
|
||||
style="position: absolute; right: 8px; top: 8px; z-index: 10; height: 20px; font-weight: bold;">
|
||||
🥳 推荐
|
||||
</v-chip>
|
||||
|
||||
<v-card-text
|
||||
style="padding: 12px; padding-bottom: 8px; display: flex; gap: 12px; width: 100%; flex: 1; overflow: hidden;">
|
||||
<div v-if="plugin?.logo" style="flex-shrink: 0;">
|
||||
<img :src="plugin.logo" :alt="plugin.name"
|
||||
style="height: 75px; width: 75px; border-radius: 8px; object-fit: cover;" />
|
||||
</div>
|
||||
|
||||
<div style="flex: 1; overflow: hidden; display: flex; flex-direction: column;">
|
||||
<!-- Display Name -->
|
||||
<div class="font-weight-bold"
|
||||
style="margin-bottom: 4px; line-height: 1.3; font-size: 1.2rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
|
||||
<span style="overflow: hidden; text-overflow: ellipsis;">
|
||||
{{ plugin.display_name?.length ? plugin.display_name :
|
||||
(showPluginFullName ? plugin.name : plugin.trimmedName) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Author with link -->
|
||||
<div class="d-flex align-center" style="gap: 4px; margin-bottom: 6px;">
|
||||
<v-icon icon="mdi-account" size="x-small"
|
||||
style="color: rgba(var(--v-theme-on-surface), 0.5);"></v-icon>
|
||||
<a v-if="plugin?.social_link" :href="plugin.social_link" target="_blank"
|
||||
class="text-subtitle-2 font-weight-medium"
|
||||
style="text-decoration: none; color: rgb(var(--v-theme-primary)); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
|
||||
{{ plugin.author }}
|
||||
</a>
|
||||
<span v-else class="text-subtitle-2 font-weight-medium"
|
||||
style="color: rgb(var(--v-theme-primary)); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
|
||||
{{ plugin.author }}
|
||||
</span>
|
||||
<div class="d-flex align-center text-subtitle-2 ml-2"
|
||||
style="color: rgba(var(--v-theme-on-surface), 0.7);">
|
||||
<v-icon icon="mdi-source-branch" size="x-small" style="margin-right: 2px;"></v-icon>
|
||||
<span>{{ plugin.version }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<div class="text-caption"
|
||||
style="overflow: scroll; color: rgba(var(--v-theme-on-surface), 0.6); line-height: 1.3; margin-bottom: 6px; flex: 1;">
|
||||
{{ plugin.desc }}
|
||||
</div>
|
||||
|
||||
<!-- Stats: Stars & Updated & Version -->
|
||||
<div class="d-flex align-center" style="gap: 8px; margin-top: auto;">
|
||||
<div v-if="plugin.stars !== undefined" class="d-flex align-center text-subtitle-2"
|
||||
style="color: rgba(var(--v-theme-on-surface), 0.7);">
|
||||
<v-icon icon="mdi-star" size="x-small" style="margin-right: 2px;"></v-icon>
|
||||
<span>{{ plugin.stars }}</span>
|
||||
</div>
|
||||
<div v-if="plugin.updated_at" class="d-flex align-center text-subtitle-2"
|
||||
style="color: rgba(var(--v-theme-on-surface), 0.7);">
|
||||
<v-icon icon="mdi-clock-outline" size="x-small" style="margin-right: 2px;"></v-icon>
|
||||
<span>{{ new Date(plugin.updated_at).toLocaleString() }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</v-card-text>
|
||||
|
||||
<!-- Actions -->
|
||||
<v-card-actions style="gap: 6px; padding: 8px 12px; padding-top: 0;">
|
||||
<v-chip v-for="tag in plugin.tags?.slice(0, 2)" :key="tag"
|
||||
:color="tag === 'danger' ? 'error' : 'primary'" label size="x-small" style="height: 20px;">
|
||||
{{ tag === 'danger' ? tm('tags.danger') : tag }}
|
||||
</v-chip>
|
||||
<v-menu v-if="plugin.tags && plugin.tags.length > 2" open-on-hover offset-y>
|
||||
<template v-slot:activator="{ props: menuProps }">
|
||||
<v-chip v-bind="menuProps" color="grey" label size="x-small"
|
||||
style="height: 20px; cursor: pointer;">
|
||||
+{{ plugin.tags.length - 2 }}
|
||||
</v-chip>
|
||||
</template>
|
||||
<v-list density="compact">
|
||||
<v-list-item v-for="tag in plugin.tags.slice(2)" :key="tag">
|
||||
<v-chip :color="tag === 'danger' ? 'error' : 'primary'" label size="small">
|
||||
{{ tag === 'danger' ? tm('tags.danger') : tag }}
|
||||
</v-chip>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</v-menu>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn v-if="plugin?.repo" color="secondary" size="x-small" variant="tonal" :href="plugin.repo"
|
||||
target="_blank" style="height: 24px;">
|
||||
<v-icon icon="mdi-github" start size="x-small"></v-icon>
|
||||
仓库
|
||||
</v-btn>
|
||||
<v-btn v-if="!plugin?.installed" color="primary" size="x-small"
|
||||
@click="handleInstallPlugin(plugin)" variant="flat" style="height: 24px;">
|
||||
{{ tm('buttons.install') }}
|
||||
</v-btn>
|
||||
<v-chip v-else color="success" size="x-small" label style="height: 20px;">
|
||||
✓ {{ tm('status.installed') }}
|
||||
</v-chip>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
<div v-if="pinnedPlugins.length > 0" class="mt-4">
|
||||
<h2>{{ tm('market.recommended') }}</h2>
|
||||
<v-row style="margin-top: 8px;">
|
||||
<v-col cols="12" md="6" lg="6" v-for="plugin in pinnedPlugins" :key="plugin.name">
|
||||
<ExtensionCard :extension="plugin" class="h-120 rounded-lg" market-mode="true" :highlight="true"
|
||||
@install="handleInstallPlugin(plugin)" @view-readme="open(plugin.repo)">
|
||||
</ExtensionCard>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</div>
|
||||
|
||||
<!-- 底部分页控件 -->
|
||||
<div class="d-flex justify-center mt-4" v-if="totalPages > 1">
|
||||
<v-pagination v-model="currentPage" :length="totalPages" :total-visible="7" size="small"></v-pagination>
|
||||
<div class="mt-4">
|
||||
<div class="d-flex align-center mb-2" style="justify-content: space-between;">
|
||||
<h2>{{ tm('market.allPlugins') }}</h2>
|
||||
<div class="d-flex align-center">
|
||||
<v-btn variant="tonal" size="small" @click="refreshPluginMarket" :loading="refreshingMarket"
|
||||
class="mr-2">
|
||||
<v-icon>mdi-refresh</v-icon>
|
||||
{{ tm('buttons.refresh') }}
|
||||
</v-btn>
|
||||
<v-switch v-model="showPluginFullName" :label="tm('market.showFullName')" hide-details
|
||||
density="compact" style="margin-left: 12px" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<v-col cols="12" md="12" style="padding: 0px;">
|
||||
<v-data-table :headers="pluginMarketHeaders" :items="pluginMarketData" item-key="name" style="border-radius: 10px;"
|
||||
:loading="loading_" v-model:search="marketSearch" :filter-keys="filterKeys"
|
||||
:custom-filter="marketCustomFilter">
|
||||
<template v-slot:item.name="{ item }">
|
||||
<div class="d-flex align-center"
|
||||
style="overflow-x: auto; scrollbar-width: thin; scrollbar-track-color: transparent;">
|
||||
<img v-if="item.logo" :src="item.logo"
|
||||
style="height: 80px; width: 80px; margin-right: 8px; border-radius: 8px; margin-top: 8px; margin-bottom: 8px;"
|
||||
alt="logo">
|
||||
<a :href="item?.repo" style="color: var(--v-theme-primaryText, #000);
|
||||
text-decoration:none">
|
||||
<div v-if="item.display_name">
|
||||
<span class="d-block">{{ item.display_name }}</span>
|
||||
<small style="color: grey; font-size: 60%;">({{ item.name }})</small>
|
||||
</div>
|
||||
<span v-else>{{ showPluginFullName ? item.name : item.trimmedName }}</span>
|
||||
</a>
|
||||
</div>
|
||||
</template>
|
||||
<template v-slot:item.desc="{ item }">
|
||||
<small>
|
||||
{{ item.desc }}
|
||||
</small>
|
||||
</template>
|
||||
<template v-slot:item.author="{ item }">
|
||||
<div style="font-size: 12px;">
|
||||
<span v-if="item?.social_link"><a :href="item?.social_link">{{ item.author }}</a></span>
|
||||
<span v-else>{{ item.author }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-slot:item.stars="{ item }">
|
||||
<span>{{ item.stars }}</span>
|
||||
</template>
|
||||
<template v-slot:item.updated_at="{ item }">
|
||||
<small>{{ new Date(item.updated_at).toLocaleString() }}</small>
|
||||
</template>
|
||||
<template v-slot:item.tags="{ item }">
|
||||
<span v-if="item.tags.length === 0">-</span>
|
||||
<v-chip v-for="tag in item.tags" :key="tag" :color="tag === 'danger' ? 'error' : 'primary'"
|
||||
size="x-small" v-show="tag !== 'danger'" class="ma-1">
|
||||
{{ tag }}</v-chip>
|
||||
</template>
|
||||
<template v-slot:item.actions="{ item }">
|
||||
<v-btn class="text-none mr-2" size="x-small" icon variant="text"
|
||||
@click="open(item.repo)"><v-icon>mdi-github</v-icon></v-btn>
|
||||
<v-btn v-if="!item.installed" class="text-none mr-2" size="x-small" icon variant="text"
|
||||
@click="handleInstallPlugin(item)">
|
||||
<v-icon>mdi-download</v-icon></v-btn>
|
||||
<v-btn v-else class="text-none mr-2" size="x-small" icon variant="text"
|
||||
disabled><v-icon>mdi-check</v-icon></v-btn>
|
||||
</template>
|
||||
</v-data-table>
|
||||
</v-col>
|
||||
</div>
|
||||
</v-tab-item>
|
||||
|
||||
@@ -1062,7 +862,7 @@ watch(marketSearch, (newVal) => {
|
||||
</v-card>
|
||||
</v-col>
|
||||
|
||||
<v-col v-if="activeTab === 'market'" cols="12" md="12">
|
||||
<v-col v-if="activeTab === 'market'" style="margin-bottom: 16px;" cols="12" md="12">
|
||||
<small><a href="https://astrbot.app/dev/plugin.html">{{ tm('market.devDocs') }}</a></small> |
|
||||
<small> <a href="https://github.com/AstrBotDevs/AstrBot_Plugins_Collection">{{ tm('market.submitRepo')
|
||||
}}</a></small>
|
||||
@@ -1158,9 +958,6 @@ watch(marketSearch, (newVal) => {
|
||||
<ReadmeDialog v-model:show="readmeDialog.show" :plugin-name="readmeDialog.pluginName"
|
||||
:repo-url="readmeDialog.repoUrl" />
|
||||
|
||||
<!-- 卸载插件确认对话框(列表模式用) -->
|
||||
<UninstallConfirmDialog v-model="showUninstallDialog" @confirm="handleUninstallConfirm" />
|
||||
|
||||
<!-- 危险插件确认对话框 -->
|
||||
<v-dialog v-model="dangerConfirmDialog" width="500" persistent>
|
||||
<v-card>
|
||||
|
||||
@@ -9,12 +9,6 @@
|
||||
<ProxySelector></ProxySelector>
|
||||
</v-list-item>
|
||||
|
||||
<v-list-subheader>{{ tm('sidebar.title') }}</v-list-subheader>
|
||||
|
||||
<v-list-item :subtitle="tm('sidebar.customize.subtitle')" :title="tm('sidebar.customize.title')">
|
||||
<SidebarCustomizer></SidebarCustomizer>
|
||||
</v-list-item>
|
||||
|
||||
<v-list-subheader>{{ tm('system.title') }}</v-list-subheader>
|
||||
|
||||
<v-list-item :subtitle="tm('system.restart.subtitle')" :title="tm('system.restart.title')">
|
||||
@@ -39,7 +33,6 @@ import axios from 'axios';
|
||||
import WaitingForRestart from '@/components/shared/WaitingForRestart.vue';
|
||||
import ProxySelector from '@/components/shared/ProxySelector.vue';
|
||||
import MigrationDialog from '@/components/shared/MigrationDialog.vue';
|
||||
import SidebarCustomizer from '@/components/shared/SidebarCustomizer.vue';
|
||||
import { useModuleI18n } from '@/i18n/composables';
|
||||
|
||||
const { tm } = useModuleI18n('features/settings');
|
||||
|
||||
18
main.py
18
main.py
@@ -1,16 +1,20 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import anyio
|
||||
|
||||
from astrbot.core import LogBroker, LogManager, db_helper, logger
|
||||
from astrbot.core.config.default import VERSION
|
||||
from astrbot.core.initial_loader import InitialLoader
|
||||
from astrbot.core.utils.astrbot_path import get_astrbot_data_path
|
||||
from astrbot.core.utils.io import download_dashboard, get_dashboard_version
|
||||
|
||||
# uvloop 仅在非 Windows 平台可用
|
||||
backend_options = {"use_uvloop": True} if sys.platform != "win32" else {}
|
||||
|
||||
# 将父目录添加到 sys.path
|
||||
sys.path.append(Path(__file__).parent.as_posix())
|
||||
|
||||
@@ -93,7 +97,11 @@ if __name__ == "__main__":
|
||||
LogManager.set_queue_handler(logger, log_broker)
|
||||
|
||||
# 检查仪表板文件
|
||||
webui_dir = asyncio.run(check_dashboard_files(args.webui_dir))
|
||||
webui_dir = anyio.run(
|
||||
check_dashboard_files,
|
||||
args.webui_dir,
|
||||
backend_options=backend_options,
|
||||
)
|
||||
|
||||
db = db_helper
|
||||
|
||||
@@ -102,4 +110,8 @@ if __name__ == "__main__":
|
||||
|
||||
core_lifecycle = InitialLoader(db, log_broker)
|
||||
core_lifecycle.webui_dir = webui_dir
|
||||
asyncio.run(core_lifecycle.start())
|
||||
logger.info(
|
||||
"将按以下异步后端启动 AstrBot: %s",
|
||||
backend_options if backend_options else "asyncio",
|
||||
)
|
||||
anyio.run(core_lifecycle.start, backend_options=backend_options)
|
||||
|
||||
@@ -164,14 +164,14 @@ class ConversationCommands:
|
||||
"%m-%d %H:%M",
|
||||
)
|
||||
parts.append(
|
||||
f"{idx}. {conv['name']}({conv['id'][:4]})\n 上次更新:{ts_h}\n"
|
||||
f"{idx}. {conv['name']}({conv['id'][:4]})\n 上次更新:{ts_h}\n",
|
||||
)
|
||||
idx += 1
|
||||
if idx == 1:
|
||||
parts.append("没有找到任何对话。")
|
||||
dify_cid = provider.conversation_ids.get(message.unified_msg_origin, None)
|
||||
parts.append(
|
||||
f"\n\n用户: {message.unified_msg_origin}\n当前对话: {dify_cid}\n使用 /switch <序号> 切换对话。"
|
||||
f"\n\n用户: {message.unified_msg_origin}\n当前对话: {dify_cid}\n使用 /switch <序号> 切换对话。",
|
||||
)
|
||||
ret = "".join(parts)
|
||||
message.set_result(MessageEventResult().message(ret))
|
||||
@@ -211,7 +211,7 @@ class ConversationCommands:
|
||||
persona_id = persona["name"]
|
||||
title = _titles.get(conv.cid, "新对话")
|
||||
parts.append(
|
||||
f"{global_index}. {title}({conv.cid[:4]})\n 人格情景: {persona_id}\n 上次更新: {datetime.datetime.fromtimestamp(conv.updated_at).strftime('%m-%d %H:%M')}\n"
|
||||
f"{global_index}. {title}({conv.cid[:4]})\n 人格情景: {persona_id}\n 上次更新: {datetime.datetime.fromtimestamp(conv.updated_at).strftime('%m-%d %H:%M')}\n",
|
||||
)
|
||||
global_index += 1
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ class ProviderCommands:
|
||||
curr_model = prov.get_model() or "无"
|
||||
parts.append(f"\n当前模型: [{curr_model}]")
|
||||
parts.append(
|
||||
"\nTips: 使用 /model <模型名/编号>,即可实时更换模型。如目标模型不存在于上表,请输入模型名。"
|
||||
"\nTips: 使用 /model <模型名/编号>,即可实时更换模型。如目标模型不存在于上表,请输入模型名。",
|
||||
)
|
||||
|
||||
ret = "".join(parts)
|
||||
|
||||
@@ -9,6 +9,7 @@ from collections import defaultdict
|
||||
|
||||
import aiodocker
|
||||
import aiohttp
|
||||
import anyio
|
||||
|
||||
from astrbot.api import llm_tool, logger, star
|
||||
from astrbot.api.event import AstrMessageEvent, MessageEventResult, filter
|
||||
@@ -291,7 +292,7 @@ class Main(star.Star):
|
||||
self.user_waiting[uid] = time.time()
|
||||
tip = "文件"
|
||||
yield event.plain_result(f"代码执行器: 请在 60s 内上传一个{tip}。")
|
||||
await asyncio.sleep(60)
|
||||
await anyio.sleep(60)
|
||||
if uid in self.user_waiting:
|
||||
yield event.plain_result(
|
||||
f"代码执行器: {event.get_sender_name()}/{event.get_sender_id()} 未在规定时间内上传{tip}。",
|
||||
|
||||
@@ -2,6 +2,7 @@ import asyncio
|
||||
import random
|
||||
|
||||
import aiohttp
|
||||
import anyio
|
||||
from bs4 import BeautifulSoup
|
||||
from readability import Document
|
||||
|
||||
@@ -26,7 +27,7 @@ class Main(star.Star):
|
||||
def __init__(self, context: star.Context) -> None:
|
||||
self.context = context
|
||||
self.tavily_key_index = 0
|
||||
self.tavily_key_lock = asyncio.Lock()
|
||||
self.tavily_key_lock = anyio.Lock()
|
||||
|
||||
# 将 str 类型的 key 迁移至 list[str],并保存
|
||||
cfg = self.context.get_config()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "AstrBot"
|
||||
version = "4.5.4"
|
||||
description = "Easy-to-use multi-platform LLM chatbot and development framework"
|
||||
dynamic = ["version"]
|
||||
description = "易上手的多平台 LLM 聊天机器人及开发框架"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -63,6 +63,8 @@ dependencies = [
|
||||
"jieba>=0.42.1",
|
||||
"markitdown-no-magika[docx,xls,xlsx]>=0.1.2",
|
||||
"xinference-client",
|
||||
"anyio>=4.11.0",
|
||||
"uvloop>=0.22.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
@@ -98,8 +100,8 @@ select = [
|
||||
# "SIM", # flake8-simplify
|
||||
]
|
||||
ignore = [
|
||||
"F403",
|
||||
"F405",
|
||||
"F403",
|
||||
"F405",
|
||||
"E501",
|
||||
"ASYNC230" # TODO: handle ASYNC230 in AstrBot
|
||||
]
|
||||
@@ -111,3 +113,43 @@ reportMissingTypeStubs = false
|
||||
reportMissingImports = false
|
||||
include = ["astrbot","packages"]
|
||||
exclude = ["dashboard", "node_modules", "dist", "data", "tests"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = false
|
||||
disallow_incomplete_defs = false
|
||||
check_untyped_defs = true
|
||||
disallow_untyped_decorators = false
|
||||
no_implicit_optional = true
|
||||
warn_redundant_casts = true
|
||||
warn_unused_ignores = true
|
||||
warn_no_return = true
|
||||
warn_unreachable = true
|
||||
strict_equality = true
|
||||
show_error_codes = true
|
||||
ignore_missing_imports = true
|
||||
explicit_package_bases = true
|
||||
namespace_packages = true
|
||||
files = ["astrbot", "packages"]
|
||||
exclude = [
|
||||
"dashboard",
|
||||
"node_modules",
|
||||
"dist",
|
||||
"data",
|
||||
"tests",
|
||||
"packages/.*/.*",
|
||||
]
|
||||
|
||||
[tool.hatch.version]
|
||||
source = "uv-dynamic-versioning"
|
||||
|
||||
[tool.uv-dynamic-versioning]
|
||||
vcs = "git"
|
||||
style = "pep440"
|
||||
bump = true
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling", "uv-dynamic-versioning"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
550
requirements.txt
550
requirements.txt
@@ -1,54 +1,498 @@
|
||||
aiocqhttp>=1.4.4
|
||||
aiodocker>=0.24.0
|
||||
aiohttp>=3.11.18
|
||||
aiocqhttp>=1.4.4
|
||||
aiodocker>=0.24.0
|
||||
aiohttp>=3.11.18
|
||||
aiosqlite>=0.21.0
|
||||
anthropic>=0.51.0
|
||||
apscheduler>=3.11.0
|
||||
beautifulsoup4>=4.13.4
|
||||
certifi>=2025.4.26
|
||||
chardet~=5.1.0
|
||||
colorlog>=6.9.0
|
||||
cryptography>=44.0.3
|
||||
dashscope>=1.23.2
|
||||
defusedxml>=0.7.1
|
||||
deprecated>=1.2.18
|
||||
dingtalk-stream>=0.22.1
|
||||
docstring-parser>=0.16
|
||||
# This file was autogenerated by uv via the following command:
|
||||
# uv export --format requirements.txt --no-hashes --no-editable
|
||||
.
|
||||
aiocqhttp==1.4.4
|
||||
# via astrbot
|
||||
aiodocker==0.24.0
|
||||
# via astrbot
|
||||
aiofiles==25.1.0
|
||||
# via
|
||||
# astrbot
|
||||
# quart
|
||||
aiohappyeyeballs==2.6.1
|
||||
# via aiohttp
|
||||
aiohttp==3.13.2
|
||||
# via
|
||||
# aiodocker
|
||||
# astrbot
|
||||
# dashscope
|
||||
# dingtalk-stream
|
||||
# py-cord
|
||||
# qq-botpy
|
||||
# xinference-client
|
||||
aiosignal==1.4.0
|
||||
# via aiohttp
|
||||
aiosqlite==0.21.0
|
||||
# via astrbot
|
||||
annotated-types==0.7.0
|
||||
# via pydantic
|
||||
anthropic==0.72.0
|
||||
# via astrbot
|
||||
anyio==4.11.0
|
||||
# via
|
||||
# anthropic
|
||||
# astrbot
|
||||
# google-genai
|
||||
# httpx
|
||||
# mcp
|
||||
# openai
|
||||
# sse-starlette
|
||||
# starlette
|
||||
# watchfiles
|
||||
apscheduler==3.11.1
|
||||
# via
|
||||
# astrbot
|
||||
# qq-botpy
|
||||
argcomplete==3.6.3
|
||||
# via commitizen
|
||||
async-timeout==5.0.1 ; python_full_version < '3.11'
|
||||
# via aiohttp
|
||||
attrs==25.4.0
|
||||
# via
|
||||
# aiohttp
|
||||
# jsonschema
|
||||
# referencing
|
||||
audioop-lts==0.2.2 ; python_full_version >= '3.13'
|
||||
# via astrbot
|
||||
backports-asyncio-runner==1.2.0 ; python_full_version < '3.11'
|
||||
# via pytest-asyncio
|
||||
beautifulsoup4==4.14.2
|
||||
# via
|
||||
# astrbot
|
||||
# markdownify
|
||||
# markitdown-no-magika
|
||||
blinker==1.9.0
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
cachetools==6.2.1
|
||||
# via google-auth
|
||||
certifi==2025.10.5
|
||||
# via
|
||||
# astrbot
|
||||
# dashscope
|
||||
# httpcore
|
||||
# httpx
|
||||
# requests
|
||||
cffi==2.0.0
|
||||
# via
|
||||
# cryptography
|
||||
# silk-python
|
||||
chardet==5.1.0
|
||||
# via
|
||||
# astrbot
|
||||
# readability-lxml
|
||||
charset-normalizer==3.4.4
|
||||
# via
|
||||
# commitizen
|
||||
# markitdown-no-magika
|
||||
# requests
|
||||
click==8.3.0
|
||||
# via
|
||||
# astrbot
|
||||
# flask
|
||||
# quart
|
||||
# uvicorn
|
||||
cobble==0.1.4
|
||||
# via mammoth
|
||||
colorama==0.4.6
|
||||
# via
|
||||
# click
|
||||
# colorlog
|
||||
# commitizen
|
||||
# pytest
|
||||
# tqdm
|
||||
colorlog==6.10.1
|
||||
# via astrbot
|
||||
commitizen==4.9.1
|
||||
coverage==7.11.0
|
||||
# via pytest-cov
|
||||
cryptography==46.0.3
|
||||
# via
|
||||
# astrbot
|
||||
# dashscope
|
||||
cssselect==1.3.0
|
||||
# via readability-lxml
|
||||
dashscope==1.24.9
|
||||
# via astrbot
|
||||
decli==0.6.3
|
||||
# via commitizen
|
||||
defusedxml==0.7.1
|
||||
# via
|
||||
# astrbot
|
||||
# markitdown-no-magika
|
||||
deprecated==1.3.1
|
||||
# via
|
||||
# astrbot
|
||||
# commitizen
|
||||
dingtalk-stream==0.24.3
|
||||
# via astrbot
|
||||
distro==1.9.0
|
||||
# via
|
||||
# anthropic
|
||||
# openai
|
||||
docstring-parser==0.17.0
|
||||
# via
|
||||
# anthropic
|
||||
# astrbot
|
||||
et-xmlfile==2.0.0
|
||||
# via openpyxl
|
||||
exceptiongroup==1.3.0 ; python_full_version < '3.11'
|
||||
# via
|
||||
# anyio
|
||||
# hypercorn
|
||||
# pytest
|
||||
# taskgroup
|
||||
faiss-cpu==1.10.0
|
||||
filelock>=3.18.0
|
||||
google-genai>=1.14.0
|
||||
lark-oapi>=1.4.15
|
||||
lxml-html-clean>=0.4.2
|
||||
mcp>=1.8.0
|
||||
openai>=1.78.0
|
||||
ormsgpack>=1.9.1
|
||||
pillow>=11.2.1
|
||||
pip>=25.1.1
|
||||
psutil>=5.8.0
|
||||
py-cord>=2.6.1
|
||||
pydantic~=2.10.3
|
||||
pydub>=0.25.1
|
||||
pyjwt>=2.10.1
|
||||
python-telegram-bot>=22.0
|
||||
qq-botpy>=1.2.1
|
||||
quart>=0.20.0
|
||||
readability-lxml>=0.8.4.1
|
||||
silk-python>=0.2.6
|
||||
slack-sdk>=3.35.0
|
||||
sqlalchemy[asyncio]>=2.0.41
|
||||
sqlmodel>=0.0.24
|
||||
telegramify-markdown>=0.5.1
|
||||
watchfiles>=1.0.5
|
||||
websockets>=15.0.1
|
||||
wechatpy>=1.8.18
|
||||
audioop-lts ; python_full_version >= '3.13'
|
||||
click>=8.2.1
|
||||
pypdf>=6.1.1
|
||||
aiofiles>=25.1.0
|
||||
rank-bm25>=0.2.2
|
||||
jieba>=0.42.1
|
||||
markitdown-no-magika[docx,xls,xlsx]>=0.1.2
|
||||
xinference-client
|
||||
# via astrbot
|
||||
filelock==3.20.0
|
||||
# via astrbot
|
||||
flask==3.1.2
|
||||
# via quart
|
||||
frozenlist==1.8.0
|
||||
# via
|
||||
# aiohttp
|
||||
# aiosignal
|
||||
google-auth==2.42.1
|
||||
# via google-genai
|
||||
google-genai==1.47.0
|
||||
# via astrbot
|
||||
greenlet==3.2.4
|
||||
# via sqlalchemy
|
||||
h11==0.16.0
|
||||
# via
|
||||
# httpcore
|
||||
# hypercorn
|
||||
# uvicorn
|
||||
# wsproto
|
||||
h2==4.3.0
|
||||
# via hypercorn
|
||||
hpack==4.1.0
|
||||
# via h2
|
||||
httpcore==1.0.9
|
||||
# via httpx
|
||||
httpx==0.28.1
|
||||
# via
|
||||
# aiocqhttp
|
||||
# anthropic
|
||||
# google-genai
|
||||
# lark-oapi
|
||||
# mcp
|
||||
# openai
|
||||
# python-telegram-bot
|
||||
httpx-sse==0.4.3
|
||||
# via mcp
|
||||
hypercorn==0.17.3
|
||||
# via quart
|
||||
hyperframe==6.1.0
|
||||
# via h2
|
||||
idna==3.11
|
||||
# via
|
||||
# anyio
|
||||
# httpx
|
||||
# requests
|
||||
# yarl
|
||||
iniconfig==2.3.0
|
||||
# via pytest
|
||||
itsdangerous==2.2.0
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
jieba==0.42.1
|
||||
# via astrbot
|
||||
jinja2==3.1.6
|
||||
# via
|
||||
# commitizen
|
||||
# flask
|
||||
# quart
|
||||
jiter==0.11.1
|
||||
# via
|
||||
# anthropic
|
||||
# openai
|
||||
jsonschema==4.25.1
|
||||
# via mcp
|
||||
jsonschema-specifications==2025.9.1
|
||||
# via jsonschema
|
||||
lark-oapi==1.4.23
|
||||
# via astrbot
|
||||
lxml==6.0.2
|
||||
# via
|
||||
# lxml-html-clean
|
||||
# markitdown-no-magika
|
||||
# readability-lxml
|
||||
lxml-html-clean==0.4.3
|
||||
# via
|
||||
# astrbot
|
||||
# lxml
|
||||
# readability-lxml
|
||||
mammoth==1.11.0
|
||||
# via markitdown-no-magika
|
||||
markdownify==1.2.0
|
||||
# via markitdown-no-magika
|
||||
markitdown-no-magika==0.1.2
|
||||
# via astrbot
|
||||
markupsafe==3.0.3
|
||||
# via
|
||||
# flask
|
||||
# jinja2
|
||||
# quart
|
||||
# werkzeug
|
||||
mcp==1.12.4
|
||||
# via astrbot
|
||||
mistletoe==1.4.0
|
||||
# via telegramify-markdown
|
||||
multidict==6.7.0
|
||||
# via
|
||||
# aiohttp
|
||||
# yarl
|
||||
numpy==2.2.6 ; python_full_version < '3.11'
|
||||
# via
|
||||
# faiss-cpu
|
||||
# pandas
|
||||
# rank-bm25
|
||||
numpy==2.3.4 ; python_full_version >= '3.11'
|
||||
# via
|
||||
# faiss-cpu
|
||||
# pandas
|
||||
# rank-bm25
|
||||
openai==2.6.1
|
||||
# via astrbot
|
||||
openpyxl==3.1.5
|
||||
# via markitdown-no-magika
|
||||
optionaldict==0.1.2
|
||||
# via wechatpy
|
||||
ormsgpack==1.11.0
|
||||
# via astrbot
|
||||
packaging==25.0
|
||||
# via
|
||||
# commitizen
|
||||
# faiss-cpu
|
||||
# pytest
|
||||
pandas==2.3.3
|
||||
# via markitdown-no-magika
|
||||
pillow==12.0.0
|
||||
# via astrbot
|
||||
pip==25.3
|
||||
# via astrbot
|
||||
pluggy==1.6.0
|
||||
# via
|
||||
# pytest
|
||||
# pytest-cov
|
||||
priority==2.0.0
|
||||
# via hypercorn
|
||||
prompt-toolkit==3.0.51
|
||||
# via
|
||||
# commitizen
|
||||
# questionary
|
||||
propcache==0.4.1
|
||||
# via
|
||||
# aiohttp
|
||||
# yarl
|
||||
psutil==7.1.2
|
||||
# via astrbot
|
||||
py-cord==2.6.1
|
||||
# via astrbot
|
||||
pyasn1==0.6.1
|
||||
# via
|
||||
# pyasn1-modules
|
||||
# rsa
|
||||
pyasn1-modules==0.4.2
|
||||
# via google-auth
|
||||
pycparser==2.23 ; implementation_name != 'PyPy'
|
||||
# via cffi
|
||||
pycryptodome==3.23.0
|
||||
# via lark-oapi
|
||||
pydantic==2.10.6
|
||||
# via
|
||||
# anthropic
|
||||
# astrbot
|
||||
# google-genai
|
||||
# mcp
|
||||
# openai
|
||||
# pydantic-settings
|
||||
# sqlmodel
|
||||
# xinference-client
|
||||
pydantic-core==2.27.2
|
||||
# via pydantic
|
||||
pydantic-settings==2.11.0
|
||||
# via mcp
|
||||
pydub==0.25.1
|
||||
# via astrbot
|
||||
pygments==2.19.2
|
||||
# via pytest
|
||||
pyjwt==2.10.1
|
||||
# via astrbot
|
||||
pypdf==6.1.3
|
||||
# via astrbot
|
||||
pytest==8.4.2
|
||||
# via
|
||||
# pytest-asyncio
|
||||
# pytest-cov
|
||||
pytest-asyncio==1.2.0
|
||||
pytest-cov==7.0.0
|
||||
python-dateutil==2.9.0.post0
|
||||
# via
|
||||
# pandas
|
||||
# wechatpy
|
||||
python-dotenv==1.2.1
|
||||
# via pydantic-settings
|
||||
python-multipart==0.0.20
|
||||
# via mcp
|
||||
python-telegram-bot==22.5
|
||||
# via astrbot
|
||||
pytz==2025.2
|
||||
# via pandas
|
||||
pywin32==311 ; sys_platform == 'win32'
|
||||
# via mcp
|
||||
pyyaml==6.0.3
|
||||
# via
|
||||
# commitizen
|
||||
# qq-botpy
|
||||
qq-botpy==1.2.1
|
||||
# via astrbot
|
||||
quart==0.20.0
|
||||
# via
|
||||
# aiocqhttp
|
||||
# astrbot
|
||||
questionary==2.1.1
|
||||
# via commitizen
|
||||
rank-bm25==0.2.2
|
||||
# via astrbot
|
||||
readability-lxml==0.8.4.1
|
||||
# via astrbot
|
||||
referencing==0.37.0
|
||||
# via
|
||||
# jsonschema
|
||||
# jsonschema-specifications
|
||||
requests==2.32.5
|
||||
# via
|
||||
# dashscope
|
||||
# dingtalk-stream
|
||||
# google-genai
|
||||
# lark-oapi
|
||||
# markitdown-no-magika
|
||||
# requests-toolbelt
|
||||
# wechatpy
|
||||
# xinference-client
|
||||
requests-toolbelt==1.0.0
|
||||
# via lark-oapi
|
||||
rpds-py==0.28.0
|
||||
# via
|
||||
# jsonschema
|
||||
# referencing
|
||||
rsa==4.9.1
|
||||
# via google-auth
|
||||
ruff==0.14.3
|
||||
silk-python==0.2.7
|
||||
# via astrbot
|
||||
six==1.17.0
|
||||
# via
|
||||
# markdownify
|
||||
# python-dateutil
|
||||
# wechatpy
|
||||
slack-sdk==3.37.0
|
||||
# via astrbot
|
||||
sniffio==1.3.1
|
||||
# via
|
||||
# anthropic
|
||||
# anyio
|
||||
# openai
|
||||
soupsieve==2.8
|
||||
# via beautifulsoup4
|
||||
sqlalchemy==2.0.44
|
||||
# via
|
||||
# astrbot
|
||||
# sqlmodel
|
||||
sqlmodel==0.0.27
|
||||
# via astrbot
|
||||
sse-starlette==3.0.3
|
||||
# via mcp
|
||||
starlette==0.50.0
|
||||
# via mcp
|
||||
taskgroup==0.2.2 ; python_full_version < '3.11'
|
||||
# via hypercorn
|
||||
telegramify-markdown==0.5.2
|
||||
# via astrbot
|
||||
tenacity==9.1.2
|
||||
# via google-genai
|
||||
termcolor==3.2.0
|
||||
# via commitizen
|
||||
tomli==2.3.0 ; python_full_version <= '3.11'
|
||||
# via
|
||||
# coverage
|
||||
# hypercorn
|
||||
# pytest
|
||||
tomlkit==0.13.3
|
||||
# via commitizen
|
||||
tqdm==4.67.1
|
||||
# via openai
|
||||
typing-extensions==4.15.0
|
||||
# via
|
||||
# aiosignal
|
||||
# aiosqlite
|
||||
# anthropic
|
||||
# anyio
|
||||
# beautifulsoup4
|
||||
# commitizen
|
||||
# cryptography
|
||||
# exceptiongroup
|
||||
# google-genai
|
||||
# hypercorn
|
||||
# multidict
|
||||
# openai
|
||||
# py-cord
|
||||
# pydantic
|
||||
# pydantic-core
|
||||
# pypdf
|
||||
# pytest-asyncio
|
||||
# referencing
|
||||
# sqlalchemy
|
||||
# starlette
|
||||
# taskgroup
|
||||
# typing-inspection
|
||||
# uvicorn
|
||||
# xinference-client
|
||||
typing-inspection==0.4.2
|
||||
# via pydantic-settings
|
||||
tzdata==2025.2
|
||||
# via
|
||||
# pandas
|
||||
# tzlocal
|
||||
tzlocal==5.3.1
|
||||
# via apscheduler
|
||||
urllib3==2.5.0
|
||||
# via requests
|
||||
uvicorn==0.38.0 ; sys_platform != 'emscripten'
|
||||
# via mcp
|
||||
uvloop==0.22.1 ; sys_platform == 'linux'
|
||||
# via astrbot
|
||||
watchfiles==1.1.1
|
||||
# via astrbot
|
||||
wcwidth==0.2.14
|
||||
# via prompt-toolkit
|
||||
websocket-client==1.9.0
|
||||
# via dashscope
|
||||
websockets==15.0.1
|
||||
# via
|
||||
# astrbot
|
||||
# dingtalk-stream
|
||||
# google-genai
|
||||
# lark-oapi
|
||||
wechatpy==1.8.18
|
||||
# via astrbot
|
||||
werkzeug==3.1.3
|
||||
# via
|
||||
# flask
|
||||
# quart
|
||||
wrapt==2.0.0
|
||||
# via deprecated
|
||||
wsproto==1.2.0
|
||||
# via hypercorn
|
||||
xinference-client==1.11.0.post1
|
||||
# via astrbot
|
||||
xlrd==2.0.2
|
||||
# via markitdown-no-magika
|
||||
xmltodict==1.0.2
|
||||
# via wechatpy
|
||||
yarl==1.22.0
|
||||
# via aiohttp
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
"""Tests for security fixes - cryptographic random number generation and SSL context."""
|
||||
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
# Add project root to sys.path
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_wecom_crypto_uses_secrets():
|
||||
"""Test that WXBizJsonMsgCrypt uses secrets module instead of random."""
|
||||
from astrbot.core.platform.sources.wecom_ai_bot.WXBizJsonMsgCrypt import Prpcrypt
|
||||
|
||||
# Create an instance and test that random string generation works
|
||||
prpcrypt = Prpcrypt(b"test_key_32_bytes_long_value!")
|
||||
|
||||
# Generate multiple random strings and verify they are different and valid
|
||||
random_strings = [prpcrypt.get_random_str() for _ in range(10)]
|
||||
|
||||
# All strings should be 16 bytes long
|
||||
assert all(len(s) == 16 for s in random_strings)
|
||||
|
||||
# All strings should be different (extremely high probability with cryptographic random)
|
||||
assert len(set(random_strings)) == 10
|
||||
|
||||
# All strings should be numeric when decoded
|
||||
for s in random_strings:
|
||||
decoded = s.decode()
|
||||
assert decoded.isdigit()
|
||||
assert 1000000000000000 <= int(decoded) <= 9999999999999999
|
||||
|
||||
|
||||
def test_wecomai_utils_uses_secrets():
|
||||
"""Test that wecomai_utils uses secrets module for random string generation."""
|
||||
from astrbot.core.platform.sources.wecom_ai_bot.wecomai_utils import (
|
||||
generate_random_string,
|
||||
)
|
||||
|
||||
# Generate multiple random strings and verify they are different
|
||||
random_strings = [generate_random_string(10) for _ in range(20)]
|
||||
|
||||
# All strings should be 10 characters long
|
||||
assert all(len(s) == 10 for s in random_strings)
|
||||
|
||||
# All strings should be alphanumeric
|
||||
for s in random_strings:
|
||||
assert s.isalnum()
|
||||
|
||||
# All strings should be different (extremely high probability with cryptographic random)
|
||||
assert len(set(random_strings)) >= 19 # Allow for 1 collision in 20 (very unlikely)
|
||||
|
||||
|
||||
def test_azure_tts_signature_uses_secrets():
|
||||
"""Test that Azure TTS signature generation uses secrets module."""
|
||||
import asyncio
|
||||
|
||||
from astrbot.core.provider.sources.azure_tts_source import OTTSProvider
|
||||
|
||||
# Create a provider with test config
|
||||
config = {
|
||||
"OTTS_SKEY": "test_secret_key",
|
||||
"OTTS_URL": "https://example.com/api/tts",
|
||||
"OTTS_AUTH_TIME": "https://example.com/api/time",
|
||||
}
|
||||
|
||||
async def test_nonce_generation():
|
||||
async with OTTSProvider(config) as provider:
|
||||
# Mock time sync to avoid actual API calls
|
||||
provider.time_offset = 0
|
||||
provider.last_sync_time = 9999999999
|
||||
|
||||
# Generate multiple signatures and extract nonces
|
||||
signatures = []
|
||||
for _ in range(10):
|
||||
sig = await provider._generate_signature()
|
||||
signatures.append(sig)
|
||||
|
||||
# Extract nonces (second field in signature format: timestamp-nonce-0-hash)
|
||||
nonces = [sig.split("-")[1] for sig in signatures]
|
||||
|
||||
# All nonces should be 10 characters long
|
||||
assert all(len(n) == 10 for n in nonces)
|
||||
|
||||
# All nonces should be alphanumeric (lowercase letters and digits)
|
||||
for n in nonces:
|
||||
assert all(c in "abcdefghijklmnopqrstuvwxyz0123456789" for c in n)
|
||||
|
||||
# All nonces should be different (cryptographic random ensures uniqueness)
|
||||
assert len(set(nonces)) == 10
|
||||
|
||||
asyncio.run(test_nonce_generation())
|
||||
|
||||
|
||||
def test_ssl_context_fallback_explicit():
|
||||
"""Test that SSL context fallback is properly configured."""
|
||||
# This test verifies the SSL context configuration
|
||||
# We can't easily test the full io.py functions without network calls,
|
||||
# but we can verify that ssl.CERT_NONE and check_hostname=False are valid settings
|
||||
|
||||
# Create a context similar to what's used in io.py
|
||||
ssl_context = ssl.create_default_context()
|
||||
ssl_context.check_hostname = False
|
||||
ssl_context.verify_mode = ssl.CERT_NONE
|
||||
|
||||
# Verify the settings are applied correctly
|
||||
assert ssl_context.check_hostname is False
|
||||
assert ssl_context.verify_mode == ssl.CERT_NONE
|
||||
|
||||
# This configuration should work but is intentionally insecure for fallback
|
||||
# The actual code only uses this when certificate validation fails
|
||||
|
||||
|
||||
def test_io_module_has_ssl_imports():
|
||||
"""Verify that io.py properly imports ssl module."""
|
||||
from astrbot.core.utils import io
|
||||
|
||||
# Check that ssl is available in the module
|
||||
assert hasattr(io, "ssl")
|
||||
|
||||
# Check that CERT_NONE constant is accessible
|
||||
assert hasattr(io.ssl, "CERT_NONE")
|
||||
|
||||
|
||||
def test_secrets_module_randomness_quality():
|
||||
"""Test that secrets module provides high-quality randomness."""
|
||||
import secrets
|
||||
|
||||
# Generate a large set of random numbers
|
||||
random_numbers = [secrets.randbelow(100) for _ in range(1000)]
|
||||
|
||||
# Basic statistical test: should have good distribution
|
||||
unique_values = len(set(random_numbers))
|
||||
|
||||
# With 1000 random numbers from 0-99, we should see most values at least once
|
||||
# This is a very basic test - real cryptographic random should pass this easily
|
||||
assert unique_values >= 60 # Should see at least 60 different values out of 100
|
||||
|
||||
# Test secrets.choice for string generation
|
||||
chars = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
random_chars = [secrets.choice(chars) for _ in range(1000)]
|
||||
|
||||
# Should have good character distribution
|
||||
unique_chars = len(set(random_chars))
|
||||
assert unique_chars >= 20 # Should see at least 20 different characters
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
Reference in New Issue
Block a user