format: code lint
(ruff, uv 是个好东西)
This commit is contained in:
1 parent
90df679a77
commit
c6bdac8835
66 files changed
+204
-162
No files matched your search
@@ -1,4 +1,11 @@
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
from astrbot import logger
|
||||
from astrbot.core.utils.personality import personalities
|
||||
from astrbot.core import html_renderer
|
||||
from astrbot.core import html_renderer
|
||||
|
||||
__all__ = [
|
||||
"AstrBotConfig",
|
||||
"logger",
|
||||
"personalities",
|
||||
"html_renderer"
|
||||
]
|
||||
+1
-1
@@ -37,4 +37,4 @@ from astrbot.core.platform import (
|
||||
|
||||
from astrbot.core.platform.register import register_platform_adapter
|
||||
|
||||
from .message_components import *
|
||||
from .message_components import *
|
||||
@@ -2,4 +2,8 @@ from astrbot.core.message.message_event_result import (
|
||||
MessageEventResult, MessageChain, CommandResult, EventResultType
|
||||
)
|
||||
|
||||
from astrbot.core.platform import AstrMessageEvent
|
||||
from astrbot.core.platform import AstrMessageEvent
|
||||
|
||||
__all__ = [
|
||||
'MessageEventResult', 'MessageChain', 'CommandResult', 'EventResultType', 'AstrMessageEvent'
|
||||
]
|
||||
@@ -9,4 +9,19 @@ from astrbot.core.star.register import (
|
||||
|
||||
from astrbot.core.star.filter.event_message_type import EventMessageTypeFilter, EventMessageType
|
||||
from astrbot.core.star.filter.platform_adapter_type import PlatformAdapterTypeFilter, PlatformAdapterType
|
||||
from astrbot.core.star.filter.permission import PermissionTypeFilter, PermissionType
|
||||
from astrbot.core.star.filter.permission import PermissionTypeFilter, PermissionType
|
||||
|
||||
__all__ = [
|
||||
'command',
|
||||
'command_group',
|
||||
'event_message_type',
|
||||
'regex',
|
||||
'platform_adapter_type',
|
||||
'permission_type',
|
||||
'EventMessageTypeFilter',
|
||||
'EventMessageType',
|
||||
'PlatformAdapterTypeFilter',
|
||||
'PlatformAdapterType',
|
||||
'PermissionTypeFilter',
|
||||
'PermissionType',
|
||||
]
|
||||
@@ -3,7 +3,7 @@ import json
|
||||
import logging
|
||||
import enum
|
||||
from .default import DEFAULT_CONFIG
|
||||
from typing import List, Dict
|
||||
from typing import Dict
|
||||
|
||||
ASTRBOT_CONFIG_PATH = "data/cmd_config.json"
|
||||
logger = logging.getLogger("astrbot")
|
||||
@@ -47,7 +47,7 @@ class AstrBotConfig(dict):
|
||||
conf[key] = value
|
||||
has_new = True
|
||||
else:
|
||||
if conf[key] == None:
|
||||
if conf[key] is None:
|
||||
conf[key] = value
|
||||
has_new = True
|
||||
elif isinstance(value, dict):
|
||||
|
||||
@@ -288,15 +288,6 @@ CONFIG_METADATA_2 = {
|
||||
"t2i": {"description": "文本转图像", "type": "bool", "hint": "启用后,超出一定长度的文本将会通过 AstrBot API 渲染成 Markdown 图片发送。可以缓解审核和消息过长刷屏的问题,并提高 Markdown 文本的可读性。"},
|
||||
"admins_id": {"description": "管理员 ID", "type": "list", "items": {"type": "int"}, "hint": "管理员 ID 列表,管理员可以使用一些特权命令,如 `update`, `plugin` 等。ID 可以通过 `/myid` 指令获得。回车添加,可添加多个。"},
|
||||
"http_proxy": {"description": "HTTP 代理", "type": "string", "hint": "启用后,会以添加环境变量的方式设置代理。格式为 `http://ip:port`"},
|
||||
"dashboard": {
|
||||
"description": "管理面板配置",
|
||||
"type": "object",
|
||||
"items": {
|
||||
"enable": {"description": "启用", "type": "bool"},
|
||||
"username": {"description": "用户名", "type": "string"},
|
||||
"password": {"description": "密码", "type": "string"},
|
||||
}
|
||||
},
|
||||
"log_level": {"description": "控制台日志级别", "type": "string", "hint": "控制台输出日志的级别。", "options": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]},
|
||||
"t2i_endpoint": {"description": "文本转图像服务接口", "type": "string", "hint": "为空时使用 AstrBot API 服务"},
|
||||
"pip_install_arg": {"description": "pip 安装参数", "type": "string", "hint": "安装插件依赖时,会使用 Python 的 pip 工具。这里可以填写额外的参数,如 `--break-system-package` 等。"},
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import asyncio, time, threading, os
|
||||
import asyncio
|
||||
import time
|
||||
import threading
|
||||
import os
|
||||
from .event_bus import EventBus
|
||||
from asyncio import Queue
|
||||
from typing import List
|
||||
|
||||
@@ -3,8 +3,6 @@ import os
|
||||
import time
|
||||
from astrbot.core.db.po import (
|
||||
Platform,
|
||||
Command,
|
||||
Provider,
|
||||
Stats,
|
||||
LLMHistory,
|
||||
ATRIVision
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import asyncio
|
||||
from asyncio import Queue
|
||||
from collections import defaultdict
|
||||
from typing import List
|
||||
from astrbot.core.pipeline.scheduler import PipelineScheduler
|
||||
from astrbot.core import logger
|
||||
from .platform import AstrMessageEvent
|
||||
from astrbot.core.message.components import Image, Plain
|
||||
|
||||
class EventBus:
|
||||
def __init__(self, event_queue: Queue, pipeline_scheduler: PipelineScheduler):
|
||||
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
import logging, colorlog, asyncio
|
||||
import logging
|
||||
import colorlog
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from asyncio import Queue
|
||||
from typing import List
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import enum, logging
|
||||
import enum
|
||||
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass, field
|
||||
from astrbot.core.message.components import *
|
||||
from astrbot.core.message.components import BaseMessageComponent, Plain, Image
|
||||
from typing_extensions import deprecated
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, EventResultType
|
||||
|
||||
from .waking_check.stage import WakingCheckStage
|
||||
from .whitelist_check.stage import WhitelistCheckStage
|
||||
from .content_safety_check.stage import ContentSafetyCheckStage
|
||||
from .process_stage.stage import ProcessStage
|
||||
from .result_decorate.stage import ResultDecorateStage
|
||||
from .respond.stage import RespondStage
|
||||
|
||||
STAGES_ORDER = [
|
||||
"WakingCheckStage", # 检查是否需要唤醒
|
||||
"WhitelistCheckStage", # 检查是否在群聊/私聊白名单
|
||||
@@ -10,9 +17,13 @@ STAGES_ORDER = [
|
||||
"RespondStage" # 发送消息
|
||||
]
|
||||
|
||||
from .waking_check.stage import WakingCheckStage
|
||||
from .whitelist_check.stage import WhitelistCheckStage
|
||||
from .content_safety_check.stage import ContentSafetyCheckStage
|
||||
from .process_stage.stage import ProcessStage
|
||||
from .result_decorate.stage import ResultDecorateStage
|
||||
from .respond.stage import RespondStage
|
||||
__all__ = [
|
||||
"WakingCheckStage",
|
||||
"WhitelistCheckStage",
|
||||
"ContentSafetyCheckStage",
|
||||
"ProcessStage",
|
||||
"ResultDecorateStage",
|
||||
"RespondStage",
|
||||
"MessageEventResult",
|
||||
"EventResultType"
|
||||
]
|
||||
@@ -1,7 +1,4 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from collections import defaultdict, deque
|
||||
from typing import DefaultDict, Deque, List, Union, AsyncGenerator
|
||||
from typing import Union, AsyncGenerator
|
||||
from ..stage import Stage, register_stage
|
||||
from ..context import PipelineContext
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
'''
|
||||
from . import ContentSafetyStrategy
|
||||
from aip import AipContentCensor
|
||||
from astrbot.core import logger
|
||||
|
||||
class BaiduAipStrategy(ContentSafetyStrategy):
|
||||
def __init__(self, appid: str, ak: str, sk: str) -> None:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import re, os, json, base64
|
||||
import re
|
||||
import os
|
||||
import json
|
||||
import base64
|
||||
from . import ContentSafetyStrategy
|
||||
from astrbot.core import logger
|
||||
|
||||
class KeywordsStrategy(ContentSafetyStrategy):
|
||||
def __init__(self, extra_keywords: list) -> None:
|
||||
@@ -17,5 +19,5 @@ class KeywordsStrategy(ContentSafetyStrategy):
|
||||
def check(self, content: str) -> bool:
|
||||
for keyword in self.keywords:
|
||||
if re.search(keyword, content):
|
||||
return False, f"内容安全检查不通过,匹配到敏感词。"
|
||||
return False, "内容安全检查不通过,匹配到敏感词。"
|
||||
return True, ""
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio, traceback, json
|
||||
from typing import DefaultDict, Deque, List, Union, AsyncGenerator
|
||||
import traceback
|
||||
from typing import Union, AsyncGenerator
|
||||
from ...context import PipelineContext
|
||||
from ..stage import Stage
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
@@ -7,7 +7,6 @@ from astrbot.core.message.message_event_result import MessageEventResult, Comman
|
||||
from astrbot.core.message.components import Image
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.utils.metrics import Metric
|
||||
from astrbot.core.provider.llm_response import LLMResponse
|
||||
|
||||
|
||||
class LLMRequestSubStage(Stage):
|
||||
@@ -62,7 +61,7 @@ class LLMRequestSubStage(Stage):
|
||||
# 执行后续步骤来发送消息
|
||||
yield
|
||||
|
||||
except BaseException as e:
|
||||
except BaseException:
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
except BaseException as e:
|
||||
|
||||
@@ -2,7 +2,7 @@ from ...context import PipelineContext
|
||||
from ..stage import Stage
|
||||
from typing import Dict, Any, List, AsyncGenerator, Union
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, CommandResult, EventResultType
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, CommandResult
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.star.star_handler import StarHandlerMetadata
|
||||
from astrbot.core.star.star import star_map
|
||||
@@ -36,7 +36,9 @@ class StarRequestSubStage(Stage):
|
||||
# 向下兼容
|
||||
ret = await handler.handler(event, self.ctx.plugin_manager.context, **params)
|
||||
else:
|
||||
logger.debug("calling star handler: %s" % handler.handler_full_name)
|
||||
ret = await handler.handler(star_cls_obj, event, **params)
|
||||
logger.debug("star handler %s called" % handler.handler_full_name)
|
||||
if ret:
|
||||
assert isinstance(ret, (MessageEventResult, CommandResult)), "如果有返回值,事件监听器的返回值必须是 MessageEventResult 或 CommandResult 类型。"
|
||||
event.stop_event()
|
||||
|
||||
@@ -4,11 +4,7 @@ from ..context import PipelineContext
|
||||
from .method.llm_request import LLMRequestSubStage
|
||||
from .method.star_request import StarRequestSubStage
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, CommandResult, EventResultType
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.star.star_handler import StarHandlerMetadata
|
||||
from astrbot.core.message.components import *
|
||||
from astrbot.core import html_renderer
|
||||
|
||||
@register_stage
|
||||
class ProcessStage(Stage):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from collections import defaultdict, deque
|
||||
from typing import DefaultDict, Deque, List, Union, AsyncGenerator
|
||||
from typing import DefaultDict, Deque, Union, AsyncGenerator
|
||||
from ..stage import Stage, register_stage
|
||||
from ..context import PipelineContext
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from collections import defaultdict, deque
|
||||
from typing import DefaultDict, Deque, List, Union, AsyncGenerator
|
||||
from ..stage import Stage, register_stage
|
||||
from typing import Union, AsyncGenerator
|
||||
from ..stage import register_stage
|
||||
from ..context import PipelineContext
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.message.message_event_result import MessageEventResult
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.config.astrbot_config import RateLimitStrategy
|
||||
|
||||
@register_stage
|
||||
class RespondStage:
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import asyncio, time
|
||||
from datetime import datetime, timedelta
|
||||
from collections import defaultdict, deque
|
||||
from typing import DefaultDict, Deque, List, Union, AsyncGenerator
|
||||
from ..stage import Stage, register_stage
|
||||
import time
|
||||
from typing import Union, AsyncGenerator
|
||||
from ..stage import register_stage
|
||||
from ..context import PipelineContext
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.message.message_event_result import MessageEventResult
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.config.astrbot_config import RateLimitStrategy
|
||||
from astrbot.core.message.components import Plain, Image
|
||||
from astrbot.core import html_renderer
|
||||
|
||||
@@ -44,6 +40,6 @@ class ResultDecorateStage:
|
||||
logger.error("文本转图片失败,使用文本发送。")
|
||||
return
|
||||
if time.time() - render_start > 3:
|
||||
logger.warning(f"文本转图片耗时超过了 3 秒,如果觉得很慢可以使用 /t2i 关闭文本转图片模式。")
|
||||
logger.warning("文本转图片耗时超过了 3 秒,如果觉得很慢可以使用 /t2i 关闭文本转图片模式。")
|
||||
if url:
|
||||
result.chain = [Image.fromURL(url)]
|
||||
@@ -1,9 +1,8 @@
|
||||
from . import STAGES_ORDER
|
||||
from .stage import registered_stages, Stage
|
||||
from .stage import registered_stages
|
||||
from .context import PipelineContext
|
||||
from typing import AsyncGenerator
|
||||
from astrbot.core.platform import AstrMessageEvent
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, EventResultType
|
||||
from astrbot.core import logger
|
||||
|
||||
class PipelineScheduler():
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
import abc
|
||||
from typing import List, Dict, AsyncGenerator, Union
|
||||
from typing import List, AsyncGenerator, Union
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from .context import PipelineContext
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ from ..stage import Stage, register_stage
|
||||
from ..context import PipelineContext
|
||||
from typing import Union, AsyncGenerator
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, EventResultType
|
||||
from astrbot.core.message.components import At, Plain
|
||||
from astrbot.core.message.message_event_result import MessageEventResult
|
||||
from astrbot.core.message.components import At
|
||||
from astrbot.core.star.star_handler import star_handlers_registry
|
||||
from astrbot.core.star.filter.command_group import CommandGroupFilter
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from ..stage import Stage, register_stage
|
||||
from ..context import PipelineContext
|
||||
from typing import List, Dict, AsyncGenerator, Union
|
||||
from typing import AsyncGenerator, Union
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.platform.message_type import MessageType
|
||||
from astrbot.core import logger
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import abc, logging
|
||||
import abc
|
||||
from dataclasses import dataclass
|
||||
from .astrbot_message import AstrBotMessage
|
||||
from .platform_metadata import PlatformMetadata
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, MessageChain, EventResultType
|
||||
from astrbot.core.message.message_event_result import MessageEventResult, MessageChain
|
||||
from astrbot.core.platform.message_type import MessageType
|
||||
from typing import List
|
||||
from astrbot.core.message.components import *
|
||||
from astrbot.core.message.components import Plain, Image, BaseMessageComponent, Face, At, AtAll, Forward
|
||||
from astrbot.core.utils.metrics import Metric
|
||||
|
||||
@dataclass
|
||||
@@ -69,7 +69,7 @@ class AstrMessageEvent(abc.ABC):
|
||||
outline += "[At:全体成员]"
|
||||
elif isinstance(i, Forward):
|
||||
# 转发消息
|
||||
outline += f"[转发消息]"
|
||||
outline += "[转发消息]"
|
||||
else:
|
||||
outline += f"[{i.type}]"
|
||||
return outline
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
from .platform import PlatformMetadata, Platform
|
||||
from .platform import Platform
|
||||
from typing import List
|
||||
from asyncio import Queue
|
||||
from .register import platform_registry, platform_cls_map
|
||||
from .register import platform_cls_map
|
||||
from astrbot.core import logger
|
||||
|
||||
|
||||
@@ -20,11 +20,11 @@ class PlatformManager():
|
||||
continue
|
||||
match platform['name']:
|
||||
case "aiocqhttp":
|
||||
from .sources.aiocqhttp.aiocqhttp_platform_adapter import AiocqhttpAdapter
|
||||
from .sources.aiocqhttp.aiocqhttp_platform_adapter import AiocqhttpAdapter # noqa: F401
|
||||
case "qqofficial":
|
||||
from .sources.qqofficial.qqofficial_platform_adapter import QQOfficialAdapter
|
||||
from .sources.qqofficial.qqofficial_platform_adapter import QQOfficialAdapter # noqa: F401
|
||||
case "vchat":
|
||||
from .sources.vchat.vchat_platform_adapter import VChatAdapter
|
||||
from .sources.vchat.vchat_platform_adapter import VChatAdapter # noqa: F401
|
||||
|
||||
async def initialize(self):
|
||||
for platform in self.platforms_config:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Type
|
||||
@dataclass
|
||||
class PlatformMetadata():
|
||||
name: str # 平台的名称
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import os, traceback, random, asyncio
|
||||
import os
|
||||
import random
|
||||
import asyncio
|
||||
|
||||
from astrbot.api.event import AstrMessageEvent, MessageChain
|
||||
from astrbot.api.message_components import Plain, Image
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import time
|
||||
import asyncio
|
||||
import traceback
|
||||
import logging
|
||||
from typing import Awaitable, Any
|
||||
from aiocqhttp import CQHttp, Event
|
||||
from astrbot.api.platform import Platform, AstrBotMessage, MessageMember, MessageType, PlatformMetadata
|
||||
from astrbot.api.event import MessageChain, MessageEventResult
|
||||
from astrbot.api.event import MessageChain
|
||||
from .aiocqhttp_message_event import *
|
||||
from astrbot.api.message_components import *
|
||||
from astrbot.api import logger
|
||||
from .aiocqhttp_message_event import AiocqhttpMessageEvent
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
from astrbot.core.platform.astr_message_event import MessageSesion
|
||||
from ...register import register_platform_adapter
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import os, traceback, base64, botpy
|
||||
import botpy
|
||||
import botpy.message
|
||||
import botpy.types
|
||||
import botpy.types.message
|
||||
|
||||
@@ -8,9 +8,8 @@ import botpy.types.message
|
||||
from botpy import Client
|
||||
from astrbot.api.platform import Platform, AstrBotMessage, MessageMember, MessageType, PlatformMetadata
|
||||
from astrbot.api.event import MessageChain
|
||||
from typing import Union, List, Dict
|
||||
from typing import Union, List
|
||||
from astrbot.api.message_components import *
|
||||
from astrbot.api import logger
|
||||
from astrbot.core.platform.astr_message_event import MessageSesion
|
||||
from .qqofficial_message_event import QQOfficialMessageEvent
|
||||
from ...register import register_platform_adapter
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import random, asyncio
|
||||
import random
|
||||
import asyncio
|
||||
from astrbot.core.utils.io import download_image_by_url
|
||||
from astrbot.api import logger
|
||||
from astrbot.api.event import AstrMessageEvent, MessageChain
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import sys, time, uuid
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import asyncio
|
||||
|
||||
from astrbot.api.platform import Platform, AstrBotMessage, MessageMember, MessageType, PlatformMetadata
|
||||
|
||||
@@ -1 +1,9 @@
|
||||
from .provider import Provider, Personality, ProviderMetaData
|
||||
from .provider import Provider, Personality
|
||||
|
||||
from .provider_metadata import ProviderMetaData
|
||||
|
||||
__all__ = [
|
||||
"Provider",
|
||||
"Personality",
|
||||
"ProviderMetaData",
|
||||
]
|
||||
@@ -4,7 +4,7 @@ from typing import List
|
||||
from astrbot.core.db import BaseDatabase
|
||||
from collections import defaultdict
|
||||
from astrbot.core.provider.tool import FuncCall
|
||||
from .register import provider_cls_map, provider_registry
|
||||
from .register import provider_cls_map
|
||||
from astrbot.core import logger
|
||||
|
||||
class ProviderManager():
|
||||
@@ -28,7 +28,8 @@ class ProviderManager():
|
||||
|
||||
match provider_cfg['type']:
|
||||
case "openai_chat_completion":
|
||||
from .sources.openai_source import ProviderOpenAIOfficial
|
||||
from .sources.openai_source import ProviderOpenAIOfficial # noqa: F401
|
||||
|
||||
|
||||
async def initialize(self):
|
||||
for provider_config in self.providers_config:
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import abc, json
|
||||
import abc
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from typing import List
|
||||
from astrbot.core.db import BaseDatabase
|
||||
from astrbot.core import logger
|
||||
from typing import TypedDict
|
||||
from .provider_metadata import ProviderMetaData
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.provider.tool import FuncCall
|
||||
from astrbot.core.provider.llm_response import LLMResponse
|
||||
from dataclasses import dataclass
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import asyncio
|
||||
import traceback
|
||||
import base64
|
||||
import json
|
||||
|
||||
from openai import AsyncOpenAI, NOT_GIVEN
|
||||
from openai.types.chat.chat_completion import ChatCompletion
|
||||
from openai._exceptions import *
|
||||
from openai._exceptions import NotFoundError
|
||||
from astrbot.core.utils.io import download_image_by_url
|
||||
|
||||
from astrbot.core.db import BaseDatabase
|
||||
@@ -13,7 +12,6 @@ from astrbot.api.provider import Provider
|
||||
from astrbot import logger
|
||||
from astrbot.core.provider.tool import FuncCall
|
||||
from typing import List
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from ..register import register_provider_adapter
|
||||
from astrbot.core.provider.llm_response import LLMResponse
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import List
|
||||
from .engine import SearchEngine, SearchResult
|
||||
from .config import HEADERS, USER_AGENT_BING
|
||||
from .config import USER_AGENT_BING
|
||||
|
||||
class Bing(SearchEngine):
|
||||
def __init__(self) -> None:
|
||||
|
||||
@@ -2,7 +2,6 @@ import os
|
||||
from googlesearch import search
|
||||
|
||||
from .engine import SearchEngine, SearchResult
|
||||
from .config import HEADERS, USER_AGENTS
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import random, re
|
||||
import random
|
||||
import re
|
||||
from bs4 import BeautifulSoup
|
||||
from .engine import SearchEngine, SearchResult
|
||||
from .config import HEADERS, USER_AGENTS
|
||||
from .config import USER_AGENTS
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
@@ -4,12 +4,11 @@ import os
|
||||
|
||||
from readability import Document
|
||||
from bs4 import BeautifulSoup
|
||||
from openai._exceptions import *
|
||||
from engines.config import HEADERS, USER_AGENTS
|
||||
from engines.bing import Bing
|
||||
from engines.sogo import Sogo
|
||||
from engines.google import Google
|
||||
from astrbot.api.event import AstrMessageEvent, MessageChain, MessageEventResult
|
||||
from astrbot.api.event import AstrMessageEvent, MessageEventResult
|
||||
from astrbot.api.provider import Provider
|
||||
from astrbot.api import logger
|
||||
|
||||
@@ -55,7 +54,7 @@ async def search_from_bing(keyword: str, event: AstrMessageEvent = None, provide
|
||||
logger.info(f"web_searcher - scraping web: {i.title} - {i.url}")
|
||||
try:
|
||||
site_result = await fetch_website_content(i.url)
|
||||
except:
|
||||
except BaseException:
|
||||
site_result = ""
|
||||
site_result = site_result[:600] + "..." if len(site_result) > 600 else site_result
|
||||
ret += f"{idx}. {i.title} \n{i.snippet}\n{site_result}\n\n"
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import heapq
|
||||
from asyncio import Queue
|
||||
from . import StarMetadata
|
||||
from typing import List, Dict, TypedDict, Union
|
||||
from typing import List, TypedDict, Union
|
||||
|
||||
from astrbot.core.platform import Platform
|
||||
from astrbot.core.provider import Provider
|
||||
from astrbot.core.db import BaseDatabase
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
|
||||
import re, inspect
|
||||
import re
|
||||
import inspect
|
||||
from . import HandlerFilter
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.config import AstrBotConfig
|
||||
from astrbot.core.utils.param_validation_mixin import ParameterValidationMixin
|
||||
from typing import Awaitable
|
||||
from ..star_handler import StarHandlerMetadata
|
||||
|
||||
# 标准指令受到 wake_prefix 的制约。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Awaitable, List, Union, Tuple
|
||||
from typing import List, Union, Tuple
|
||||
from . import HandlerFilter
|
||||
from .command import CommandFilter
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
@@ -27,7 +27,7 @@ class CommandGroupFilter(HandlerFilter):
|
||||
if cmd_th:
|
||||
result += f" ({cmd_th})"
|
||||
else:
|
||||
result += f" (无参数指令)"
|
||||
result += " (无参数指令)"
|
||||
|
||||
result += "\n"
|
||||
elif isinstance(sub_filter, CommandGroupFilter):
|
||||
|
||||
@@ -2,7 +2,6 @@ import enum
|
||||
from . import HandlerFilter
|
||||
from astrbot.core.platform.astr_message_event import AstrMessageEvent
|
||||
from astrbot.core.config import AstrBotConfig
|
||||
from astrbot.core.platform.message_type import MessageType
|
||||
|
||||
class PermissionType(enum.Flag):
|
||||
'''权限类型。当选择 MEMBER,ADMIN 也可以通过。
|
||||
|
||||
@@ -6,4 +6,14 @@ from .star_handler import (
|
||||
register_platform_adapter_type,
|
||||
register_regex,
|
||||
register_permission_type
|
||||
)
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'register_star',
|
||||
'register_command',
|
||||
'register_command_group',
|
||||
'register_event_message_type',
|
||||
'register_platform_adapter_type',
|
||||
'register_regex',
|
||||
'register_permission_type'
|
||||
]
|
||||
@@ -7,7 +7,7 @@ from ..filter.event_message_type import EventMessageTypeFilter, EventMessageType
|
||||
from ..filter.platform_adapter_type import PlatformAdapterTypeFilter, PlatformAdapterType
|
||||
from ..filter.permission import PermissionTypeFilter, PermissionType
|
||||
from ..filter.regex import RegexFilter
|
||||
from typing import Awaitable, List, Dict
|
||||
from typing import Awaitable
|
||||
|
||||
|
||||
def get_handler_full_name(awatable: Awaitable) -> str:
|
||||
|
||||
@@ -4,7 +4,7 @@ import traceback
|
||||
import yaml
|
||||
import logging
|
||||
from types import ModuleType
|
||||
from typing import List, Awaitable
|
||||
from typing import List
|
||||
from pip import main as pip_main
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
from astrbot.core import logger
|
||||
@@ -147,7 +147,7 @@ class PluginManager:
|
||||
for plugin_module in plugin_modules:
|
||||
try:
|
||||
module_str = plugin_module['module']
|
||||
module_path = plugin_module['module_path']
|
||||
# module_path = plugin_module['module_path']
|
||||
root_dir_name = plugin_module['pname']
|
||||
reserved = plugin_module.get('reserved', False)
|
||||
|
||||
@@ -158,7 +158,7 @@ class PluginManager:
|
||||
path += root_dir_name + "." + module_str
|
||||
try:
|
||||
module = __import__(path, fromlist=[module_str])
|
||||
except (ModuleNotFoundError, ImportError) as e:
|
||||
except (ModuleNotFoundError, ImportError):
|
||||
# 尝试安装依赖
|
||||
self._check_plugin_dept_update(target_plugin=root_dir_name)
|
||||
module = __import__(path, fromlist=[module_str])
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import os, zipfile, shutil
|
||||
import os
|
||||
import zipfile
|
||||
import shutil
|
||||
|
||||
from ..updator import RepoZipUpdator
|
||||
from astrbot.core.utils.io import remove_dir, on_error
|
||||
from ..star.star import StarMetadata
|
||||
from typing import Union
|
||||
from astrbot.core import logger
|
||||
|
||||
class PluginUpdator(RepoZipUpdator):
|
||||
@@ -65,6 +66,6 @@ class PluginUpdator(RepoZipUpdator):
|
||||
logger.info(f"删除临时更新文件: {zip_path} 和 {os.path.join(target_dir, update_dir)}")
|
||||
shutil.rmtree(os.path.join(target_dir, update_dir), onerror=on_error)
|
||||
os.remove(zip_path)
|
||||
except:
|
||||
except BaseException:
|
||||
logger.warning(f"删除更新文件失败,可以手动删除 {zip_path} 和 {os.path.join(target_dir, update_dir)}")
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import os, psutil, sys, time
|
||||
import os
|
||||
import psutil
|
||||
import sys
|
||||
import time
|
||||
from .zip_updator import ReleaseInfo, RepoZipUpdator
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.config.default import VERSION
|
||||
|
||||
@@ -25,7 +25,7 @@ def remove_dir(file_path) -> bool:
|
||||
try:
|
||||
shutil.rmtree(file_path, onerror=on_error)
|
||||
return True
|
||||
except BaseException as e:
|
||||
except BaseException:
|
||||
return False
|
||||
|
||||
def port_checker(port: int, host: str = "localhost"):
|
||||
@@ -76,7 +76,7 @@ async def download_image_by_url(url: str, post: bool = False, post_data: dict =
|
||||
else:
|
||||
async with session.get(url) as resp:
|
||||
return save_temp_img(await resp.read())
|
||||
except aiohttp.client_exceptions.ClientConnectorSSLError as e:
|
||||
except aiohttp.client_exceptions.ClientConnectorSSLError:
|
||||
# 关闭SSL验证
|
||||
ssl_context = ssl.create_default_context()
|
||||
ssl_context.set_ciphers('DEFAULT')
|
||||
@@ -118,7 +118,7 @@ def get_local_ip_addresses():
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(('8.8.8.8', 80))
|
||||
ip = s.getsockname()[0]
|
||||
except BaseException as e:
|
||||
except BaseException:
|
||||
pass
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
@@ -34,5 +34,5 @@ class Metric():
|
||||
async with session.post(base_url, json=payload, timeout=3) as response:
|
||||
if response.status != 200:
|
||||
pass
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,5 +1,5 @@
|
||||
import inspect
|
||||
from typing import Awaitable, List, Union, Dict, Any, Type
|
||||
from typing import List, Dict, Any, Type
|
||||
|
||||
class ParameterValidationMixin:
|
||||
def validate_and_convert_params(self, params: List[Any], param_type: Dict[str, Type]) -> Dict[str, Any]:
|
||||
|
||||
@@ -18,7 +18,7 @@ class LocalRenderStrategy(RenderStrategy):
|
||||
try:
|
||||
font = ImageFont.truetype(font, size)
|
||||
return font
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def render(self, text: str, return_url: bool=False) -> str:
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import aiohttp, os, zipfile, shutil
|
||||
import aiohttp
|
||||
import os
|
||||
import zipfile
|
||||
import shutil
|
||||
from astrbot.core.utils.io import on_error, download_file
|
||||
from astrbot.core import logger
|
||||
|
||||
@@ -29,14 +32,15 @@ class RepoZipUpdator():
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
result = await response.json()
|
||||
if not result: return []
|
||||
if not result:
|
||||
return []
|
||||
if latest:
|
||||
ret = self.github_api_release_parser([result[0]])
|
||||
else:
|
||||
ret = self.github_api_release_parser(result)
|
||||
except BaseException as e:
|
||||
logger.error(f"解析版本信息失败")
|
||||
raise Exception(f"解析版本信息失败")
|
||||
except BaseException:
|
||||
logger.error("解析版本信息失败")
|
||||
raise Exception("解析版本信息失败")
|
||||
return ret
|
||||
|
||||
def github_api_release_parser(self, releases: list) -> list:
|
||||
@@ -50,7 +54,8 @@ class RepoZipUpdator():
|
||||
commit_hash = ''
|
||||
# 规范是: v3.0.7.xxxxxx,其中xxxxxx为 commit hash
|
||||
_t = version.split(".")
|
||||
if len(_t) == 4: commit_hash = _t[3]
|
||||
if len(_t) == 4:
|
||||
commit_hash = _t[3]
|
||||
ret.append({
|
||||
"version": release['name'],
|
||||
"published_at": release['published_at'],
|
||||
@@ -149,7 +154,7 @@ class RepoZipUpdator():
|
||||
logger.info(f"删除临时更新文件: {zip_path} 和 {os.path.join(target_dir, update_dir)}")
|
||||
shutil.rmtree(os.path.join(target_dir, update_dir), onerror=on_error)
|
||||
os.remove(zip_path)
|
||||
except:
|
||||
except BaseException:
|
||||
logger.warn(f"删除更新文件失败,可以手动删除 {zip_path} 和 {os.path.join(target_dir, update_dir)}")
|
||||
|
||||
def format_repo_name(self, repo_url: str) -> str:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
from multiprocessing import Process
|
||||
from astrbot.core import logger
|
||||
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
|
||||
from .server import AstrBotDashboard
|
||||
@@ -19,6 +18,6 @@ class AstrBotDashBoardLifecycle:
|
||||
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError as e:
|
||||
except asyncio.CancelledError:
|
||||
logger.info("🌈 正在关闭 AstrBot...")
|
||||
await core_lifecycle.stop()
|
||||
@@ -1,6 +1,7 @@
|
||||
import jwt, datetime
|
||||
import jwt
|
||||
import datetime
|
||||
from .route import Route, Response, RouteContext
|
||||
from quart import Quart, request
|
||||
from quart import request
|
||||
from astrbot.core import WEBUI_SK
|
||||
|
||||
class AuthRoute(Route):
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import os, json, traceback
|
||||
import os
|
||||
import json
|
||||
import traceback
|
||||
from .route import Route, Response, RouteContext
|
||||
from quart import Quart, request
|
||||
from quart import request
|
||||
from astrbot.core.config.default import CONFIG_METADATA_2, DEFAULT_VALUE_MAP, PROVIDER_CONFIG_TEMPLATE, ADAPTER_CONFIG_TEMPLATE
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
from astrbot.core.star.config import update_config
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
from quart import websocket
|
||||
from astrbot.core import logger, LogBroker
|
||||
from .route import Route, Response, RouteContext
|
||||
from .route import Route, RouteContext
|
||||
|
||||
class LogRoute(Route):
|
||||
def __init__(self, context: RouteContext, log_broker: LogBroker) -> None:
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import threading, traceback, uuid
|
||||
import traceback
|
||||
import uuid
|
||||
from .route import Route, Response, RouteContext
|
||||
from astrbot.core import logger
|
||||
from quart import Quart, request
|
||||
from quart import request
|
||||
from astrbot.core.star.star_manager import PluginManager
|
||||
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import traceback, psutil, time, aiohttp
|
||||
import traceback
|
||||
import psutil
|
||||
import time
|
||||
import aiohttp
|
||||
from .route import Route, Response, RouteContext
|
||||
from astrbot.core import logger
|
||||
from quart import Quart, request
|
||||
from astrbot.core.config.astrbot_config import AstrBotConfig
|
||||
from quart import request
|
||||
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
|
||||
from astrbot.core.db import BaseDatabase
|
||||
from astrbot.core.config import VERSION
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import threading, traceback
|
||||
import threading
|
||||
import traceback
|
||||
from .route import Route, Response, RouteContext
|
||||
from quart import Quart, request
|
||||
from quart import request
|
||||
from astrbot.core.updator import AstrBotUpdator
|
||||
from astrbot.core import logger
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import logging, jwt
|
||||
import asyncio, os
|
||||
import logging
|
||||
import jwt
|
||||
import asyncio
|
||||
import os
|
||||
from quart import Quart, request
|
||||
from quart.logging import default_handler
|
||||
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
|
||||
@@ -8,7 +10,6 @@ from .routes.route import RouteContext, Response
|
||||
from astrbot.core import logger, WEBUI_SK
|
||||
from astrbot.core.db import BaseDatabase
|
||||
from astrbot.core.utils.io import get_local_ip_addresses
|
||||
from astrbot.core.db import BaseDatabase
|
||||
|
||||
DATAPATH = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../data"))
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@ import sys
|
||||
import mimetypes
|
||||
import aiohttp
|
||||
import zipfile
|
||||
from typing import List
|
||||
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
|
||||
from astrbot.core.config import DB_PATH
|
||||
from astrbot.dashboard import AstrBotDashBoardLifecycle
|
||||
from astrbot.core import db_helper
|
||||
from astrbot.core import logger, LogManager, LogBroker
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import aiohttp
|
||||
import astrbot.api.star as star
|
||||
import astrbot.api.event.filter as filter
|
||||
from typing import Dict
|
||||
from astrbot.api.event import AstrMessageEvent, MessageEventResult
|
||||
from astrbot.api.platform import MessageType
|
||||
from astrbot.api import logger
|
||||
from astrbot.api import personalities
|
||||
from astrbot.api.provider import Personality
|
||||
|
||||
@@ -14,15 +11,21 @@ from typing import Union
|
||||
class Main(star.Star):
|
||||
def __init__(self, context: star.Context) -> None:
|
||||
self.context = context
|
||||
|
||||
async def _query_astrbot_notice(self):
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get("https://astrbot.soulter.top/notice.json", timeout=2) as resp:
|
||||
return (await resp.json())["notice"]
|
||||
except BaseException:
|
||||
return ""
|
||||
|
||||
@filter.command("help")
|
||||
async def help(self, event: AstrMessageEvent):
|
||||
notice = ""
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get("https://astrbot.soulter.top/notice.json") as resp:
|
||||
notice = (await resp.json())["notice"]
|
||||
except BaseException as e:
|
||||
notice = await self._query_astrbot_notice()
|
||||
except BaseException:
|
||||
pass
|
||||
|
||||
msg = "已注册的 AstrBot 内置指令:\n"
|
||||
@@ -201,7 +204,7 @@ UID: {user_id} 此 ID 可用于设置管理员。/op <UID> 授权管理员, /deo
|
||||
@filter.command("key")
|
||||
async def key(self, message: AstrMessageEvent, index: int=None):
|
||||
|
||||
if index == None:
|
||||
if index is None:
|
||||
keys_data = self.context.get_using_provider().get_keys()
|
||||
curr_key = self.context.get_using_provider().get_current_key()
|
||||
ret = "Key:"
|
||||
|
||||
Reference in new issue
Block a user