diff --git a/nonebot/adapters/satori/adapter.py b/nonebot/adapters/satori/adapter.py index 618d23b..c5dc1f7 100644 --- a/nonebot/adapters/satori/adapter.py +++ b/nonebot/adapters/satori/adapter.py @@ -5,13 +5,7 @@ from pydantic import parse_raw_as from nonebot.utils import escape_tag from nonebot.exception import WebSocketClosed -from nonebot.drivers import ( - Driver, - Request, - WebSocket, - HTTPClientMixin, - WebSocketClientMixin, -) +from nonebot.drivers import Driver, Request, WebSocket, HTTPClientMixin, WebSocketClientMixin from nonebot.adapters import Adapter as BaseAdapter @@ -20,14 +14,7 @@ from .config import Config, ClientInfo from .exception import ApiNotAvailable from .models import Event as SatoriEvent -from .event import ( - EVENT_CLASSES, - Event, - MessageEvent, - LoginAddedEvent, - LoginRemovedEvent, - LoginUpdatedEvent, -) +from .event import EVENT_CLASSES, Event, MessageEvent, LoginAddedEvent, LoginRemovedEvent, LoginUpdatedEvent from .models import ( Payload, LoginStatus, @@ -91,9 +78,7 @@ async def shutdown(self) -> None: @staticmethod def payload_to_json(payload: Payload) -> str: - return payload.__config__.json_dumps( - payload.dict(), default=payload.__json_encoder__ - ) + return payload.__config__.json_dumps(payload.dict(), default=payload.__json_encoder__) async def receive_payload(self, info: ClientInfo, ws: WebSocket) -> Payload: payload = parse_raw_as(PayloadType, await ws.receive()) @@ -101,9 +86,7 @@ async def receive_payload(self, info: ClientInfo, ws: WebSocket) -> Payload: self.sequences[info.identity] = payload.body.id return payload - async def _authenticate( - self, info: ClientInfo, ws: WebSocket - ) -> Optional[Literal[True]]: + async def _authenticate(self, info: ClientInfo, ws: WebSocket) -> Optional[Literal[True]]: """鉴权连接""" payload = IdentifyPayload.parse_obj( { @@ -120,8 +103,7 @@ async def _authenticate( except Exception as e: log( "ERROR", - "Error while sending " - + "Identify event", + "Error while sending " + "Identify event", e, ) return @@ -130,8 +112,7 @@ async def _authenticate( if not isinstance(resp, ReadyPayload): log( "ERROR", - "Received unexpected payload while authenticating: " - f"{escape_tag(repr(resp))}", + "Received unexpected payload while authenticating: " f"{escape_tag(repr(resp))}", ) return for login in resp.body.logins: @@ -174,8 +155,7 @@ async def ws(self, info: ClientInfo) -> None: async with self.websocket(req) as ws: log( "DEBUG", - f"WebSocket Connection to " - f"{escape_tag(str(ws_url))} established", + f"WebSocket Connection to " f"{escape_tag(str(ws_url))} established", ) try: if not await self._authenticate(info, ws): @@ -255,8 +235,7 @@ async def _loop(self, info: ClientInfo, ws: WebSocket): if not (bot := self.bots.get(event.self_id)): log( "WARNING", - f"Received event for unknown bot " - f"{escape_tag(event.self_id)}", + f"Received event for unknown bot " f"{escape_tag(event.self_id)}", ) continue if isinstance(event, MessageEvent): diff --git a/nonebot/adapters/satori/bot.py b/nonebot/adapters/satori/bot.py index 78d9c45..7ffcb31 100644 --- a/nonebot/adapters/satori/bot.py +++ b/nonebot/adapters/satori/bot.py @@ -92,11 +92,7 @@ def _is_at_me_seg(segment: MessageSegment) -> bool: # check the last segment i = -1 last_msg_seg = message[i] - if ( - last_msg_seg.type == "text" - and not last_msg_seg.data["text"].strip() - and len(message) >= 2 - ): + if last_msg_seg.type == "text" and not last_msg_seg.data["text"].strip() and len(message) >= 2: i -= 1 last_msg_seg = message[i] @@ -137,9 +133,7 @@ class Bot(BaseBot): adapter: "Adapter" @override - def __init__( - self, adapter: "Adapter", self_id: str, platform: str, info: ClientInfo - ): + def __init__(self, adapter: "Adapter", self_id: str, platform: str, info: ClientInfo): super().__init__(adapter, self_id) # Bot 配置信息 @@ -161,9 +155,7 @@ def ready(self) -> bool: def self_info(self) -> User: """Bot 自身信息,仅当 Bot 连接鉴权完成后可用""" if self._self_info is None: - raise RuntimeError( - f"Bot {self.self_id} of {self.platform} is not connected!" - ) + raise RuntimeError(f"Bot {self.self_id} of {self.platform} is not connected!") return self._self_info def on_ready(self, user: User) -> None: @@ -249,9 +241,7 @@ async def update_message( message_id: 要更新的消息 ID message: 要更新的消息 """ - return await self.message_update( - channel_id=channel_id, message_id=message_id, content=str(message) - ) + return await self.message_update(channel_id=channel_id, message_id=message_id, content=str(message)) @API async def message_create( @@ -403,9 +393,7 @@ async def guild_approve(self, *, request_id: str, approve: bool, comment: str): await self._request(request) @API - async def guild_member_list( - self, *, guild_id: str, next_token: Optional[str] = None - ): + async def guild_member_list(self, *, guild_id: str, next_token: Optional[str] = None): request = Request( "POST", self.info.api_base / "guild.member.list", @@ -423,9 +411,7 @@ async def guild_member_get(self, *, guild_id: str, user_id: str): return OuterMember.parse_obj(await self._request(request)) @API - async def guild_member_kick( - self, *, guild_id: str, user_id: str, permanent: bool = False - ): + async def guild_member_kick(self, *, guild_id: str, user_id: str, permanent: bool = False): request = Request( "POST", self.info.api_base / "guild.member.kick", @@ -434,9 +420,7 @@ async def guild_member_kick( await self._request(request) @API - async def guild_member_approve( - self, *, request_id: str, approve: bool, comment: str - ): + async def guild_member_approve(self, *, request_id: str, approve: bool, comment: str): request = Request( "POST", self.info.api_base / "guild.member.approve", @@ -454,9 +438,7 @@ async def guild_member_role_set(self, *, guild_id: str, user_id: str, role_id: s await self._request(request) @API - async def guild_member_role_unset( - self, *, guild_id: str, user_id: str, role_id: str - ): + async def guild_member_role_unset(self, *, guild_id: str, user_id: str, role_id: str): request = Request( "POST", self.info.api_base / "guild.member.role.unset", diff --git a/nonebot/adapters/satori/event.py b/nonebot/adapters/satori/event.py index 1d4462f..16b6a28 100644 --- a/nonebot/adapters/satori/event.py +++ b/nonebot/adapters/satori/event.py @@ -328,10 +328,7 @@ def get_event_description(self) -> str: class PrivateMessageDeletedEvent(MessageDeletedEvent, PrivateMessageEvent): @override def get_event_description(self) -> str: - return escape_tag( - f"Message {self.msg_id} from " - f"{self.user.name or ''}({self.channel.id}) deleted" - ) + return escape_tag(f"Message {self.msg_id} from " f"{self.user.name or ''}({self.channel.id}) deleted") class PublicMessageDeletedEvent(MessageDeletedEvent, PublicMessageEvent): @@ -397,9 +394,7 @@ class ReactionAddedEvent(ReactionEvent): @override def get_event_description(self) -> str: - return escape_tag( - f"Reaction added to {self.msg_id} by {self.user.name}({self.channel.id})" - ) + return escape_tag(f"Reaction added to {self.msg_id} by {self.user.name}({self.channel.id})") @register_event_class diff --git a/nonebot/adapters/satori/message.py b/nonebot/adapters/satori/message.py index 9ff0fb7..72b3f93 100644 --- a/nonebot/adapters/satori/message.py +++ b/nonebot/adapters/satori/message.py @@ -87,11 +87,7 @@ def image( elif path: data = {"src": Path(path).as_uri()} elif raw: - bd = ( - raw["data"] - if isinstance(raw["data"], bytes) - else raw["data"].getvalue() - ) + bd = raw["data"] if isinstance(raw["data"], bytes) else raw["data"].getvalue() data = {"src": f"data:{raw['mime']};base64,{b64encode(bd).decode()}"} else: raise ValueError("image need at least one of url, path and raw") @@ -114,11 +110,7 @@ def audio( elif path: data = {"src": Path(path).as_uri()} elif raw: - bd = ( - raw["data"] - if isinstance(raw["data"], bytes) - else raw["data"].getvalue() - ) + bd = raw["data"] if isinstance(raw["data"], bytes) else raw["data"].getvalue() data = {"src": f"data:{raw['mime']};base64,{b64encode(bd).decode()}"} else: raise ValueError("audio need at least one of url, path and raw") @@ -141,11 +133,7 @@ def video( elif path: data = {"src": Path(path).as_uri()} elif raw: - bd = ( - raw["data"] - if isinstance(raw["data"], bytes) - else raw["data"].getvalue() - ) + bd = raw["data"] if isinstance(raw["data"], bytes) else raw["data"].getvalue() data = {"src": f"data:{raw['mime']};base64,{b64encode(bd).decode()}"} else: raise ValueError("video need at least one of url, path and raw") @@ -168,11 +156,7 @@ def file( elif path: data = {"src": Path(path).as_uri()} elif raw: - bd = ( - raw["data"] - if isinstance(raw["data"], bytes) - else raw["data"].getvalue() - ) + bd = raw["data"] if isinstance(raw["data"], bytes) else raw["data"].getvalue() data = {"src": f"data:{raw['mime']};base64,{b64encode(bd).decode()}"} else: raise ValueError("file need at least one of url, path and raw") @@ -566,20 +550,12 @@ def get_segment_class(cls) -> Type[MessageSegment]: return MessageSegment @override - def __add__( - self, other: Union[str, MessageSegment, Iterable[MessageSegment]] - ) -> "Message": - return super().__add__( - MessageSegment.text(other) if isinstance(other, str) else other - ) + def __add__(self, other: Union[str, MessageSegment, Iterable[MessageSegment]]) -> "Message": + return super().__add__(MessageSegment.text(other) if isinstance(other, str) else other) @override - def __radd__( - self, other: Union[str, MessageSegment, Iterable[MessageSegment]] - ) -> "Message": - return super().__radd__( - MessageSegment.text(other) if isinstance(other, str) else other - ) + def __radd__(self, other: Union[str, MessageSegment, Iterable[MessageSegment]]) -> "Message": + return super().__radd__(MessageSegment.text(other) if isinstance(other, str) else other) @staticmethod @override diff --git a/nonebot/adapters/satori/models.py b/nonebot/adapters/satori/models.py index a004cb9..35691da 100644 --- a/nonebot/adapters/satori/models.py +++ b/nonebot/adapters/satori/models.py @@ -135,8 +135,7 @@ def ensure_content(cls, values): return values log( "WARNING", - "received message without content, " - "this may be caused by a bug of Satori Server.", + "received message without content, " "this may be caused by a bug of Satori Server.", ) return {**values, "content": "Unknown"} diff --git a/nonebot/adapters/satori/utils.py b/nonebot/adapters/satori/utils.py index 3d0bfac..6a2791a 100644 --- a/nonebot/adapters/satori/utils.py +++ b/nonebot/adapters/satori/utils.py @@ -29,21 +29,11 @@ def escape(text: str) -> str: - return ( - text.replace('"', """) - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - ) + return text.replace('"', """).replace("&", "&").replace("<", "<").replace(">", ">") def unescape(text: str) -> str: - return ( - text.replace(""", '"') - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - ) + return text.replace(""", '"').replace("&", "&").replace("<", "<").replace(">", ">") class Element(BaseModel): @@ -141,9 +131,7 @@ def rollback(i: int): while index < len(stack) and stack[index].type != tkn.type: index += 1 if index == len(stack): - stack[0].children.append( - Element(type="text", attrs={"text": tkn.source}) - ) + stack[0].children.append(Element(type="text", attrs={"text": tkn.source})) else: rollback(index) elm = stack.pop(0) diff --git a/pyproject.toml b/pyproject.toml index 496d4c2..265739d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,14 +34,14 @@ dev = [ includes = ["nonebot"] [tool.black] -line-length = 88 +line-length = 110 include = '\.pyi?$' extend-exclude = ''' ''' [tool.isort] profile = "black" -line_length = 88 +line_length = 110 length_sort = true skip_gitignore = true force_sort_within_sections = true @@ -51,7 +51,7 @@ extra_standard_library = ["typing_extensions"] select = ["E", "W", "F", "UP", "C", "T", "Q"] ignore = ["E402", "F403", "F405", "C901", "UP037"] -line-length = 88 +line-length = 110 target-version = "py38" [tool.pyright]