mirror of
https://github.com/nonebot/nonebot2.git
synced 2024-11-24 00:55:07 +08:00
🎨 impove typing
This commit is contained in:
parent
629eed08b6
commit
6b3f6a46e6
@ -28,11 +28,11 @@ import importlib
|
||||
import pkg_resources
|
||||
from typing import Dict, Type, Optional
|
||||
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.drivers import Driver
|
||||
from nonebot.utils import escape_tag
|
||||
from nonebot.config import Env, Config
|
||||
from nonebot.adapters import BaseBot as Bot
|
||||
from nonebot.log import logger, default_filter
|
||||
from nonebot.drivers import BaseDriver as Driver
|
||||
|
||||
_dist: pkg_resources.Distribution = pkg_resources.get_distribution("nonebot2")
|
||||
__version__ = _dist.version
|
||||
|
@ -15,10 +15,10 @@ from pydantic import BaseModel
|
||||
from nonebot.config import Config
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.drivers import BaseDriver as Driver, BaseWebSocket as WebSocket
|
||||
from nonebot.drivers import Driver, WebSocket
|
||||
|
||||
|
||||
class BaseBot(abc.ABC):
|
||||
class Bot(abc.ABC):
|
||||
"""
|
||||
Bot 基类。用于处理上报消息,并提供 API 调用接口。
|
||||
"""
|
||||
@ -141,7 +141,7 @@ class BaseBot(abc.ABC):
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
|
||||
class BaseEvent(abc.ABC, Generic[T]):
|
||||
class Event(abc.ABC, Generic[T]):
|
||||
"""
|
||||
Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。
|
||||
"""
|
||||
@ -304,7 +304,7 @@ class BaseEvent(abc.ABC, Generic[T]):
|
||||
|
||||
|
||||
@dataclass
|
||||
class BaseMessageSegment(abc.ABC):
|
||||
class MessageSegment(abc.ABC):
|
||||
"""消息段基类"""
|
||||
type: str
|
||||
"""
|
||||
@ -349,7 +349,7 @@ class BaseMessageSegment(abc.ABC):
|
||||
return cls("text", {"text": text})
|
||||
|
||||
|
||||
class BaseMessage(list, abc.ABC):
|
||||
class Message(list, abc.ABC):
|
||||
"""消息数组"""
|
||||
|
||||
def __init__(self,
|
||||
|
@ -10,8 +10,8 @@ import httpx
|
||||
from nonebot.log import logger
|
||||
from nonebot.config import Config
|
||||
from nonebot.typing import overrides
|
||||
from nonebot.adapters import BaseBot
|
||||
from nonebot.message import handle_event
|
||||
from nonebot.adapters import Bot as BaseBot
|
||||
from nonebot.exception import RequestDenied
|
||||
|
||||
from .event import Event
|
||||
|
@ -2,7 +2,7 @@ import asyncio
|
||||
from typing import Any, Dict, List, Union, Optional
|
||||
|
||||
from nonebot.config import Config
|
||||
from nonebot.adapters import BaseBot
|
||||
from nonebot.adapters import Bot as BaseBot
|
||||
from nonebot.drivers import BaseDriver as Driver, BaseWebSocket as WebSocket
|
||||
|
||||
from .event import Event
|
||||
|
@ -1,7 +1,7 @@
|
||||
from typing import Optional
|
||||
|
||||
from nonebot.typing import overrides
|
||||
from nonebot.adapters import BaseEvent
|
||||
from nonebot.adapters import Event as BaseEvent
|
||||
|
||||
from .message import Message
|
||||
|
||||
|
@ -2,7 +2,7 @@ import re
|
||||
from typing import Any, Dict, Union, Tuple, Iterable, Optional
|
||||
|
||||
from nonebot.typing import overrides
|
||||
from nonebot.adapters import BaseMessage, BaseMessageSegment
|
||||
from nonebot.adapters import Message as BaseMessage, MessageSegment as BaseMessageSegment
|
||||
|
||||
from .utils import log, escape, unescape, _b2s
|
||||
|
||||
|
@ -6,8 +6,8 @@ from typing import Any, Union, Optional, TYPE_CHECKING
|
||||
import httpx
|
||||
from nonebot.log import logger
|
||||
from nonebot.config import Config
|
||||
from nonebot.adapters import BaseBot
|
||||
from nonebot.message import handle_event
|
||||
from nonebot.adapters import Bot as BaseBot
|
||||
from nonebot.exception import RequestDenied
|
||||
|
||||
from .utils import log
|
||||
|
@ -1,6 +1,6 @@
|
||||
from typing import Union, Optional
|
||||
|
||||
from nonebot.adapters import BaseEvent
|
||||
from nonebot.adapters import Event as BaseEvent
|
||||
|
||||
from .message import Message
|
||||
from .model import MessageModel, ConversationType, TextMessage
|
||||
|
@ -1,6 +1,6 @@
|
||||
from typing import Any, Dict, Union, Iterable
|
||||
|
||||
from nonebot.adapters import BaseMessage, BaseMessageSegment
|
||||
from nonebot.adapters import Message as BaseMessage, MessageSegment as BaseMessageSegment
|
||||
|
||||
from .utils import log
|
||||
from .model import TextMessage
|
||||
|
@ -12,10 +12,10 @@ from nonebot.log import logger
|
||||
from nonebot.config import Env, Config
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.adapters import BaseBot as Bot
|
||||
from nonebot.adapters import Bot
|
||||
|
||||
|
||||
class BaseDriver(abc.ABC):
|
||||
class Driver(abc.ABC):
|
||||
"""
|
||||
Driver 基类。将后端框架封装,以满足适配器使用。
|
||||
"""
|
||||
@ -140,7 +140,7 @@ class BaseDriver(abc.ABC):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class BaseWebSocket(object):
|
||||
class WebSocket(object):
|
||||
"""WebSocket 连接封装,统一接口方便外部调用。"""
|
||||
|
||||
@abc.abstractmethod
|
||||
|
@ -23,7 +23,7 @@ from nonebot.typing import overrides
|
||||
from nonebot.config import Env, Config
|
||||
from nonebot.utils import DataclassEncoder
|
||||
from nonebot.exception import RequestDenied
|
||||
from nonebot.drivers import BaseDriver, BaseWebSocket
|
||||
from nonebot.drivers import Driver as BaseDriver, WebSocket as BaseWebSocket
|
||||
|
||||
|
||||
class Driver(BaseDriver):
|
||||
|
@ -20,9 +20,7 @@ from nonebot.typing import State, Handler, ArgsParser
|
||||
from nonebot.exception import PausedException, RejectedException, FinishedException
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.adapters import (BaseBot as Bot, BaseEvent as Event,
|
||||
BaseMessage as Message, BaseMessageSegment as
|
||||
MessageSegment)
|
||||
from nonebot.adapters import Bot, Event, Message, MessageSegment
|
||||
|
||||
matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
|
||||
"""
|
||||
|
@ -17,7 +17,7 @@ from nonebot.exception import IgnoredException, StopPropagation
|
||||
from nonebot.typing import State, EventPreProcessor, RunPreProcessor, EventPostProcessor, RunPostProcessor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.adapters import BaseBot as Bot, BaseEvent as Event
|
||||
from nonebot.adapters import Bot, Event
|
||||
|
||||
_event_preprocessors: Set[EventPreProcessor] = set()
|
||||
_event_postprocessors: Set[EventPostProcessor] = set()
|
||||
|
@ -16,7 +16,7 @@ from nonebot.utils import run_sync
|
||||
from nonebot.typing import PermissionChecker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.adapters import BaseBot as Bot, BaseEvent as Event
|
||||
from nonebot.adapters import Bot, Event
|
||||
|
||||
|
||||
class Permission:
|
||||
|
@ -27,8 +27,8 @@ plugins: Dict[str, "Plugin"] = {}
|
||||
:说明: 已加载的插件
|
||||
"""
|
||||
|
||||
_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ContextVar("_tmp_matchers")
|
||||
_export: ContextVar["Export"] = ContextVar("_export")
|
||||
_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ContextVar("_tmp_matchers")
|
||||
|
||||
|
||||
class Export(dict):
|
||||
|
@ -10,8 +10,8 @@ from nonebot.typing import State, Handler, RuleChecker
|
||||
|
||||
plugins: Dict[str, "Plugin"] = ...
|
||||
|
||||
_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ...
|
||||
_export: ContextVar["Export"] = ...
|
||||
_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ...
|
||||
|
||||
|
||||
class Export(dict):
|
||||
|
@ -4,7 +4,7 @@ from nonebot.rule import to_me
|
||||
from nonebot.typing import State
|
||||
from nonebot.plugin import on_command
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.adapters import BaseBot as Bot, BaseEvent as Event, BaseMessageSegment as MessageSegment
|
||||
from nonebot.adapters import Bot, Event, MessageSegment
|
||||
|
||||
say = on_command("say", to_me(), permission=SUPERUSER)
|
||||
|
||||
|
@ -22,7 +22,7 @@ from nonebot.utils import run_sync
|
||||
from nonebot.typing import State, RuleChecker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.adapters import BaseBot as Bot, BaseEvent as Event
|
||||
from nonebot.adapters import Bot, Event
|
||||
|
||||
|
||||
class Rule:
|
||||
|
@ -18,18 +18,10 @@
|
||||
https://docs.python.org/3/library/typing.html
|
||||
"""
|
||||
|
||||
from types import ModuleType
|
||||
from typing import NoReturn, TYPE_CHECKING
|
||||
from typing import Any, Set, List, Dict, Type, Tuple, Mapping
|
||||
from typing import Union, TypeVar, Optional, Iterable, Callable, Awaitable, Generic
|
||||
from typing import Any, Dict, Union, Optional, Callable, Awaitable, TYPE_CHECKING
|
||||
|
||||
# import some modules needed when checking types
|
||||
if TYPE_CHECKING:
|
||||
from nonebot.rule import Rule as RuleClass
|
||||
from nonebot.drivers import BaseDriver, BaseWebSocket
|
||||
from nonebot.permission import Permission as PermissionClass
|
||||
from nonebot.adapters import BaseBot, BaseEvent, BaseMessage, BaseMessageSegment
|
||||
from nonebot.matcher import Matcher as MatcherClass
|
||||
from nonebot.rule import Rule
|
||||
|
||||
|
||||
def overrides(InterfaceClass: object):
|
||||
@ -42,56 +34,6 @@ def overrides(InterfaceClass: object):
|
||||
return overrider
|
||||
|
||||
|
||||
Driver = TypeVar("Driver", bound="BaseDriver")
|
||||
"""
|
||||
:类型: ``BaseDriver``
|
||||
|
||||
:说明:
|
||||
|
||||
所有 Driver 的基类。
|
||||
"""
|
||||
WebSocket = TypeVar("WebSocket", bound="BaseWebSocket")
|
||||
"""
|
||||
:类型: ``BaseWebSocket``
|
||||
|
||||
:说明:
|
||||
|
||||
所有 WebSocket 的基类。
|
||||
"""
|
||||
|
||||
Bot = TypeVar("Bot", bound="BaseBot")
|
||||
"""
|
||||
:类型: ``BaseBot``
|
||||
|
||||
:说明:
|
||||
|
||||
所有 Bot 的基类。
|
||||
"""
|
||||
Event = TypeVar("Event", bound="BaseEvent")
|
||||
"""
|
||||
:类型: ``BaseEvent``
|
||||
|
||||
:说明:
|
||||
|
||||
所有 Event 的基类。
|
||||
"""
|
||||
Message = TypeVar("Message", bound="BaseMessage")
|
||||
"""
|
||||
:类型: ``BaseMessage``
|
||||
|
||||
:说明:
|
||||
|
||||
所有 Message 的基类。
|
||||
"""
|
||||
MessageSegment = TypeVar("MessageSegment", bound="BaseMessageSegment")
|
||||
"""
|
||||
:类型: ``BaseMessageSegment``
|
||||
|
||||
:说明:
|
||||
|
||||
所有 MessageSegment 的基类。
|
||||
"""
|
||||
|
||||
State = Dict[Any, Any]
|
||||
"""
|
||||
:类型: ``Dict[Any, Any]``
|
||||
@ -134,22 +76,6 @@ RunPostProcessor = Callable[["Matcher", Optional[Exception], Bot, Event, State],
|
||||
事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在)
|
||||
"""
|
||||
|
||||
Matcher = TypeVar("Matcher", bound="MatcherClass")
|
||||
"""
|
||||
:类型: ``Matcher``
|
||||
|
||||
:说明:
|
||||
|
||||
Matcher 即响应事件的处理类。通过 Rule 判断是否响应事件,运行 Handler。
|
||||
"""
|
||||
Rule = TypeVar("Rule", bound="RuleClass")
|
||||
"""
|
||||
:类型: ``Rule``
|
||||
|
||||
:说明:
|
||||
|
||||
Rule 即判断是否响应事件的处理类。内部存储 RuleChecker ,返回全为 True 则响应事件。
|
||||
"""
|
||||
RuleChecker = Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]]
|
||||
"""
|
||||
:类型: ``Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]]``
|
||||
@ -158,14 +84,6 @@ RuleChecker = Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]]
|
||||
|
||||
RuleChecker 即判断是否响应事件的处理函数。
|
||||
"""
|
||||
Permission = TypeVar("Permission", bound="PermissionClass")
|
||||
"""
|
||||
:类型: ``Permission``
|
||||
|
||||
:说明:
|
||||
|
||||
Permission 即判断是否响应消息的处理类。内部存储 PermissionChecker ,返回只要有一个 True 则响应消息。
|
||||
"""
|
||||
PermissionChecker = Callable[[Bot, Event], Union[bool, Awaitable[bool]]]
|
||||
"""
|
||||
:类型: ``Callable[[Bot, Event], Union[bool, Awaitable[bool]]]``
|
||||
|
@ -1,14 +1,15 @@
|
||||
import asyncio
|
||||
|
||||
from nonebot import on_message
|
||||
from nonebot.typing import State
|
||||
from nonebot.permission import USER
|
||||
from nonebot.typing import Bot, Event
|
||||
from nonebot.adapters import Bot, Event
|
||||
|
||||
a = on_message(priority=0, permission=USER(123123123), temp=True)
|
||||
|
||||
|
||||
@a.handle()
|
||||
async def test_a(bot: Bot, event: Event, state: dict):
|
||||
async def test_a(bot: Bot, event: Event, state: State):
|
||||
print("======== A Received ========")
|
||||
print("======== A Running Completed ========")
|
||||
|
||||
@ -17,7 +18,7 @@ b = on_message(priority=0, permission=USER(123456789), temp=True)
|
||||
|
||||
|
||||
@b.handle()
|
||||
async def test_b(bot: Bot, event: Event, state: dict):
|
||||
async def test_b(bot: Bot, event: Event, state: State):
|
||||
print("======== B Received ========")
|
||||
await asyncio.sleep(10)
|
||||
print("======== B Running Completed ========")
|
||||
@ -27,5 +28,5 @@ c = on_message(priority=0, permission=USER(1111111111))
|
||||
|
||||
|
||||
@c.handle()
|
||||
async def test_c(bot: Bot, event: Event, state: dict):
|
||||
async def test_c(bot: Bot, event: Event, state: State):
|
||||
print("======== C Received ========")
|
||||
|
@ -1,4 +1,5 @@
|
||||
from nonebot.typing import Bot, Event
|
||||
from nonebot.typing import State
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.permission import GROUP_OWNER
|
||||
|
||||
from . import cmd
|
||||
@ -7,5 +8,5 @@ test_1 = cmd.command("1", aliases={"test"}, permission=GROUP_OWNER)
|
||||
|
||||
|
||||
@test_1.handle()
|
||||
async def test1(bot: Bot, event: Event, state: dict):
|
||||
async def test1(bot: Bot, event: Event, state: State):
|
||||
await test_1.finish(event.raw_message)
|
||||
|
@ -1,9 +1,10 @@
|
||||
from nonebot.typing import Bot, Event
|
||||
from nonebot.typing import State
|
||||
from nonebot.adapters import Bot, Event
|
||||
|
||||
from . import match
|
||||
|
||||
|
||||
async def heartbeat(bot: Bot, event: Event, state: dict) -> bool:
|
||||
async def heartbeat(bot: Bot, event: Event, state: State) -> bool:
|
||||
return event.detail_type == "heartbeat"
|
||||
|
||||
|
||||
@ -11,5 +12,5 @@ test = match.on_metaevent(rule=heartbeat)
|
||||
|
||||
|
||||
@test.receive()
|
||||
async def handle_heartbeat(bot: Bot, event: Event, state: dict):
|
||||
async def handle_heartbeat(bot: Bot, event: Event, state: State):
|
||||
print("[i] Heartbeat")
|
||||
|
@ -1,8 +1,9 @@
|
||||
from nonebot.typing import Bot, Event
|
||||
from nonebot.typing import State
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.plugin import on_metaevent
|
||||
|
||||
|
||||
async def heartbeat(bot: Bot, event: Event, state: dict) -> bool:
|
||||
async def heartbeat(bot: Bot, event: Event, state: State) -> bool:
|
||||
return event.detail_type == "heartbeat"
|
||||
|
||||
|
||||
|
@ -1,13 +1,13 @@
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.typing import Event
|
||||
from nonebot.typing import State
|
||||
from nonebot.plugin import on_command
|
||||
from nonebot.adapters.cqhttp import Bot
|
||||
from nonebot.adapters.cqhttp import Bot, Event
|
||||
|
||||
test_command = on_command("帮助", to_me())
|
||||
|
||||
|
||||
@test_command.handle()
|
||||
async def test_handler(bot: Bot, event: Event, state: dict):
|
||||
async def test_handler(bot: Bot, event: Event, state: State):
|
||||
args = str(event.message).strip()
|
||||
print("[!] Command:", state["_prefix"], "Args:", args)
|
||||
if args:
|
||||
@ -17,7 +17,7 @@ async def test_handler(bot: Bot, event: Event, state: dict):
|
||||
|
||||
|
||||
@test_command.got("help", prompt="你要帮助的命令是?")
|
||||
async def test_handler(bot: Bot, event: Event, state: dict):
|
||||
async def test_handler(bot: Bot, event: Event, state: State):
|
||||
print("[!] Command 帮助:", state["help"])
|
||||
if state["help"] not in ["test1", "test2"]:
|
||||
await test_command.reject(f"{state['help']} 不支持,请重新输入!")
|
||||
|
@ -1,18 +1,18 @@
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.typing import Event
|
||||
from nonebot.typing import State
|
||||
from nonebot.plugin import on_startswith
|
||||
from nonebot.adapters.cqhttp import Bot
|
||||
from nonebot.adapters.ding import Bot as DingBot, Event as DingEvent
|
||||
from nonebot.permission import GROUP_ADMIN
|
||||
from nonebot.adapters.ding import Bot as DingBot, Event as DingEvent
|
||||
from nonebot.adapters.cqhttp import Bot as CQHTTPBot, Event as CQHTTPEvent
|
||||
|
||||
test_command = on_startswith("hello", to_me(), permission=GROUP_ADMIN)
|
||||
|
||||
|
||||
@test_command.handle()
|
||||
async def test_handler(bot: Bot, event: Event, state: dict):
|
||||
async def test_handler(bot: CQHTTPBot, event: CQHTTPEvent, state: State):
|
||||
await test_command.finish("cqhttp hello")
|
||||
|
||||
|
||||
@test_command.handle()
|
||||
async def test_handler(bot: DingBot, event: DingEvent, state: dict):
|
||||
async def test_handler(bot: DingBot, event: DingEvent, state: State):
|
||||
await test_command.finish("ding hello")
|
||||
|
@ -1,13 +1,15 @@
|
||||
from nonebot.typing import Bot, Event, Matcher
|
||||
from nonebot.typing import State
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.message import event_preprocessor, run_preprocessor
|
||||
|
||||
|
||||
@event_preprocessor
|
||||
async def handle(bot: Bot, event: Event, state: dict):
|
||||
async def handle(bot: Bot, event: Event, state: State):
|
||||
state["preprocessed"] = True
|
||||
print(event)
|
||||
|
||||
|
||||
@run_preprocessor
|
||||
async def run(matcher: Matcher, bot: Bot, event: Event, state: dict):
|
||||
async def run(matcher: Matcher, bot: Bot, event: Event, state: State):
|
||||
print(matcher)
|
||||
|
@ -1,12 +1,13 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.typing import Bot, Event
|
||||
from nonebot.typing import State
|
||||
from nonebot.adapters import Bot, Event
|
||||
|
||||
weather = on_command("天气", rule=to_me(), priority=1)
|
||||
|
||||
|
||||
@weather.handle()
|
||||
async def handle_first_receive(bot: Bot, event: Event, state: dict):
|
||||
async def handle_first_receive(bot: Bot, event: Event, state: State):
|
||||
args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海
|
||||
print(f"==={args}===")
|
||||
if args:
|
||||
@ -14,7 +15,7 @@ async def handle_first_receive(bot: Bot, event: Event, state: dict):
|
||||
|
||||
|
||||
@weather.got("city", prompt="你想查询哪个城市的天气呢?")
|
||||
async def handle_city(bot: Bot, event: Event, state: dict):
|
||||
async def handle_city(bot: Bot, event: Event, state: State):
|
||||
city = state["city"]
|
||||
if city not in ["上海", "北京"]:
|
||||
await weather.reject("你想查询的城市暂不支持,请重新输入!")
|
||||
|
Loading…
Reference in New Issue
Block a user