Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: 更新 Ruff 并且应用新的样式 #107

Merged
merged 1 commit into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .release.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""用于发布新版本的脚本。"""

# ruff: noqa: S603, S607
import argparse
import json
Expand Down
1 change: 1 addition & 0 deletions alicebot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- `ConfigModel` => [`alicebot.config.ConfigModel`](./config#ConfigModel)
- `Depends` => [`alicebot.dependencies.Depends`](./dependencies#Depends)
"""

from alicebot.adapter import Adapter
from alicebot.bot import Bot
from alicebot.config import ConfigModel
Expand Down
7 changes: 3 additions & 4 deletions alicebot/adapter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

所有协议适配器都必须继承自 `Adapter` 基类。
"""

import os
from abc import ABC, abstractmethod
from typing import (
Expand Down Expand Up @@ -110,8 +111,7 @@ async def get(
event_type: None = None,
max_try_times: Optional[int] = None,
timeout: Optional[Union[int, float]] = None,
) -> EventT:
...
) -> EventT: ...

@overload
async def get(
Expand All @@ -121,8 +121,7 @@ async def get(
event_type: Type[_EventT],
max_try_times: Optional[int] = None,
timeout: Optional[Union[int, float]] = None,
) -> _EventT:
...
) -> _EventT: ...

@final
async def get(
Expand Down
7 changes: 4 additions & 3 deletions alicebot/adapter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

这里定义了一些在编写适配器时常用的基类,适配器开发者可以直接继承自这里的类或者用作参考。
"""

import asyncio
from abc import ABCMeta, abstractmethod
from typing import Literal, Optional, Union
Expand Down Expand Up @@ -177,9 +178,9 @@ class WebSocketAdapter(Adapter[EventT, ConfigT], metaclass=ABCMeta):
同时支持 WebSocket 客户端和服务端。
"""

websocket: Union[
web.WebSocketResponse, aiohttp.ClientWebSocketResponse, None
] = None
websocket: Union[web.WebSocketResponse, aiohttp.ClientWebSocketResponse, None] = (
None
)

# ws
session: Optional[aiohttp.ClientSession]
Expand Down
16 changes: 6 additions & 10 deletions alicebot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

AliceBot 的基础模块,每一个 AliceBot 机器人即是一个 `Bot` 实例。
"""

import asyncio
import json
import pkgutil
Expand Down Expand Up @@ -544,8 +545,7 @@ async def get(
adapter_type: None = None,
max_try_times: Optional[int] = None,
timeout: Optional[Union[int, float]] = None,
) -> Event[Any]:
...
) -> Event[Any]: ...

@overload
async def get(
Expand All @@ -556,8 +556,7 @@ async def get(
adapter_type: Type[Adapter[EventT, Any]],
max_try_times: Optional[int] = None,
timeout: Optional[Union[int, float]] = None,
) -> EventT:
...
) -> EventT: ...

@overload
async def get(
Expand All @@ -568,8 +567,7 @@ async def get(
adapter_type: Optional[Type[AdapterT]] = None,
max_try_times: Optional[int] = None,
timeout: Optional[Union[int, float]] = None,
) -> EventT:
...
) -> EventT: ...

async def get(
self,
Expand Down Expand Up @@ -860,12 +858,10 @@ def load_adapters(self, *adapters: Union[Type[Adapter[Any, Any]], str]) -> None:
self._load_adapters(*adapters)

@overload
def get_adapter(self, adapter: str) -> Adapter[Any, Any]:
...
def get_adapter(self, adapter: str) -> Adapter[Any, Any]: ...

@overload
def get_adapter(self, adapter: Type[AdapterT]) -> AdapterT:
...
def get_adapter(self, adapter: Type[AdapterT]) -> AdapterT: ...

def get_adapter(
self, adapter: Union[str, Type[AdapterT]]
Expand Down
1 change: 1 addition & 0 deletions alicebot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

AliceBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 来读取配置。
"""

from typing import Set, Union

from pydantic import BaseModel, ConfigDict, DirectoryPath, Field
Expand Down
3 changes: 2 additions & 1 deletion alicebot/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

实现依赖注入相关功能。
"""

import inspect
from contextlib import AsyncExitStack, asynccontextmanager, contextmanager
from typing import (
Expand Down Expand Up @@ -107,7 +108,7 @@ async def solve_dependencies(
):
assert isinstance(sub_dependent, InnerDepends)
if sub_dependent.dependency is None:
dependent_ann = ann.get(name, None)
dependent_ann = ann.get(name)
if dependent_ann is None:
raise TypeError("can not solve dependent")
sub_dependent.dependency = dependent_ann
Expand Down
1 change: 1 addition & 0 deletions alicebot/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

事件类的基类。适配器开发者应实现此事件类基类的子类。
"""

from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Generic, Optional, Union
from typing_extensions import Self
Expand Down
1 change: 1 addition & 0 deletions alicebot/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
AliceBot 使用 [loguru](https://github.com/Delgan/loguru) 来记录日志信息。
自定义 logger 请参考 [loguru](https://github.com/Delgan/loguru) 文档。
"""

from loguru import logger as _logger

__all__ = ["logger"]
Expand Down
7 changes: 3 additions & 4 deletions alicebot/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
实现了常用的基本消息 `Message` 和消息字段 `MessageSegment` 模型供适配器使用。
适配器开发者可以根据需要实现此模块中消息类的子类或定义与此不同的消息类型,但建议若可行的话应尽量使用此模块中消息类的子类。
"""

from abc import ABC, abstractmethod
from typing import (
Any,
Expand Down Expand Up @@ -247,14 +248,12 @@ def endswith(
)

@overload
def replace(self, old: str, new: str, count: int = -1) -> Self:
...
def replace(self, old: str, new: str, count: int = -1) -> Self: ...

@overload
def replace(
self, old: MessageSegmentT, new: Optional[MessageSegmentT], count: int = -1
) -> Self:
...
) -> Self: ...

def replace(
self,
Expand Down
1 change: 1 addition & 0 deletions alicebot/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

所有 AliceBot 插件的基类。所有用户编写的插件必须继承自 `Plugin` 类。
"""

import inspect
from abc import ABC, abstractmethod
from enum import Enum
Expand Down
1 change: 1 addition & 0 deletions alicebot/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

此模块定义了部分 AliceBot 使用的类型。
"""

# ruff: noqa: TCH001
from typing import TYPE_CHECKING, Awaitable, Callable, Optional, TypeVar

Expand Down
3 changes: 2 additions & 1 deletion alicebot/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""AliceBot 内部使用的实用工具。"""

import asyncio
import importlib
import inspect
Expand Down Expand Up @@ -271,7 +272,7 @@ def get_annotations(
# class
obj_dict = getattr(obj, "__dict__", None)
if obj_dict and hasattr(obj_dict, "get"):
ann = obj_dict.get("__annotations__", None)
ann = obj_dict.get("__annotations__")
if isinstance(ann, GetSetDescriptorType):
ann = None
else:
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/advanced/state-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ from alicebot import Plugin

class GlobalStateTest1(Plugin):
async def handle(self) -> None:
if self.bot.global_state.get("count", None) is None:
if self.bot.global_state.get("count") is None:
self.bot.global_state["count"] = 0
self.bot.global_state["count"] += 1
await self.event.reply(f'add: {self.bot.global_state["count"]}')
Expand All @@ -119,7 +119,7 @@ from alicebot import Plugin

class GlobalStateTest2(Plugin):
async def handle(self) -> None:
if self.bot.global_state.get("count", None) is None:
if self.bot.global_state.get("count") is None:
self.bot.global_state["count"] = 0
self.bot.global_state["count"] -= 1
await self.event.reply(f"sub: {self.bot.global_state['count']}")
Expand Down
1 change: 1 addition & 0 deletions examples/adapters/console_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

用于接收命令行输入的适配器示例。
"""

import asyncio
import sys
from typing_extensions import Self
Expand Down
1 change: 1 addition & 0 deletions examples/adapters/http_server_test_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

这里是一个最简单可以直接使用的 HTTP 服务端适配器示例。
"""

from aiohttp import web

from alicebot.adapter.utils import HttpServerAdapter
Expand Down
2 changes: 1 addition & 1 deletion examples/plugins/global_state_test1.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class GlobalStateTest1(Plugin):
async def handle(self) -> None:
if self.bot.global_state.get("count", None) is None:
if self.bot.global_state.get("count") is None:
self.bot.global_state["count"] = 0
self.bot.global_state["count"] += 1
await self.event.reply(f'add: {self.bot.global_state["count"]}')
Expand Down
2 changes: 1 addition & 1 deletion examples/plugins/global_state_test2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class GlobalStateTest2(Plugin):
async def handle(self) -> None:
if self.bot.global_state.get("count", None) is None:
if self.bot.global_state.get("count") is None:
self.bot.global_state["count"] = 0
self.bot.global_state["count"] -= 1
await self.event.reply(f'sub: {self.bot.global_state["count"]}')
Expand Down
1 change: 1 addition & 0 deletions examples/test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""启动 AliceBot。"""

from alicebot import Bot

bot = Bot(hot_reload=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
本适配器用于实现定时任务,适配器将使用 APScheduler 实现定时任务,在设定的时间产生一个事件供插件处理。
APScheduler 使用方法请参考:[APScheduler](https://apscheduler.readthedocs.io/)。
"""

import inspect
from functools import wraps
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Type, Union
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""APScheduler 适配器配置。"""

from typing import Any, Dict

from pydantic import Field
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""APScheduler 适配器事件。"""

from typing import TYPE_CHECKING, Any, Dict, Optional, Type, Union

from apscheduler.job import Job
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
本适配器适配了 OneBot v11 协议。
协议详情请参考:[OneBot](https://github.com/howmanybots/onebot/blob/master/README.md)。
"""

import asyncio
import inspect
import json
Expand Down Expand Up @@ -162,9 +163,9 @@ def get_event_model(
对应的事件类。
"""
event_model = (
cls.event_models.get((post_type, detail_type, sub_type), None)
or cls.event_models.get((post_type, detail_type, None), None)
or cls.event_models.get((post_type, None, None), None)
cls.event_models.get((post_type, detail_type, sub_type))
or cls.event_models.get((post_type, detail_type, None))
or cls.event_models.get((post_type, None, None))
)
return event_model or cls.event_models[(None, None, None)]

Expand All @@ -174,14 +175,14 @@ async def handle_cqhttp_event(self, msg: Dict[str, Any]) -> None:
Args:
msg: 接收到的信息。
"""
post_type = msg.get("post_type", None)
post_type = msg.get("post_type")
if post_type is None:
event_class = self.get_event_model(None, None, None)
else:
event_class = self.get_event_model(
post_type,
msg.get(post_type + "_type", None),
msg.get("sub_type", None),
msg.get(post_type + "_type"),
msg.get("sub_type"),
)

cqhttp_event = event_class(adapter=self, **msg)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""CQHTTP 适配器配置。"""

from typing import Literal

from alicebot.config import ConfigModel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,13 @@ def get_event_type(cls) -> Tuple[Optional[str], Optional[str], Optional[str]]:
Returns:
事件类型。
"""
post_type = _get_literal_field(cls.model_fields.get("post_type", None))
post_type = _get_literal_field(cls.model_fields.get("post_type"))
if post_type is None:
return (None, None, None)
return (
post_type,
_get_literal_field(cls.model_fields.get(post_type + "_type", None)),
_get_literal_field(cls.model_fields.get("sub_type", None)),
_get_literal_field(cls.model_fields.get(post_type + "_type")),
_get_literal_field(cls.model_fields.get("sub_type")),
)


Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""CQHTTP 适配器异常。"""

from typing import Any, ClassVar, Dict

from alicebot.exceptions import AdapterException
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""CQHTTP 适配器消息。"""

from typing import Literal, Optional, Type, Union
from typing_extensions import Self

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
本适配器适配了钉钉企业自建机器人协议。
协议详情请参考:[钉钉开放平台](https://open.dingtalk.com/document/robots/robot-overview)。
"""

import base64
import hashlib
import hmac
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""DingTalk 适配器配置。"""

from alicebot.config import ConfigModel

__all__ = ["Config"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""DingTalk 适配器事件。"""

import time
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
from typing_extensions import Self
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""DingTalk 适配器异常。"""

from alicebot.exceptions import AdapterException

__all__ = ["DingTalkException", "NetworkError", "WebhookExpiredError"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""DingTalk 适配器消息。"""

from typing import Any, Dict, List, Optional

from pydantic import model_serializer
Expand Down
Loading
Loading