Skip to content

Commit

Permalink
🎨 format
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Aug 15, 2024
1 parent 7a1f105 commit 959c1b1
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 158 deletions.
9 changes: 6 additions & 3 deletions nonebot/adapters/console/adapter.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import sys
import asyncio
from typing_extensions import override
from typing import Any, Dict, List, Callable, Optional, Awaitable
from typing import Any, Callable, Optional
from collections.abc import Awaitable

from textual.color import Color
from nonebot.drivers import Driver
Expand All @@ -18,16 +19,18 @@


class Adapter(BaseAdapter):
_frontend: Frontend[AdapterConsoleBackend]

@override
def __init__(self, driver: Driver, **kwargs: Any) -> None:
super().__init__(driver, **kwargs)
self.console_config = get_plugin_config(Config)
self.bot = Bot(self, BOT_ID)

self._task: Optional[asyncio.Task] = None
self._frontend: Optional[Frontend[AdapterConsoleBackend]] = None

self._stdout = sys.stdout
self.clients: List[Callable[[Bot, str, Dict[str, Any]], Awaitable[Any]]] = []
self.clients: list[Callable[[Bot, str, dict[str, Any]], Awaitable[Any]]] = []

self.setup()

Expand Down
15 changes: 7 additions & 8 deletions nonebot/adapters/console/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from nonechat import Backend
from nonechat.info import Robot
from nonechat.app import Frontend
from nonechat.message import Text, Emoji
from nonechat.info import Event as ConsoleEvent
from nonechat.message import Text, Emoji, Markup, Markdown
from nonechat.info import MessageEvent as ConsoleMessageEvent
from nonebot.log import logger, logger_id, default_filter, default_format

Expand All @@ -19,15 +19,14 @@


class AdapterConsoleBackend(Backend):
_adapter: "Adapter"

def __init__(self, frontend: "Frontend"):
super().__init__(frontend)
self.frontend.storage.current_user = replace(
self.frontend.storage.current_user, id="User"
)
self.frontend.storage.current_user = replace(self.frontend.storage.current_user, id="User")
self._stdout = sys.stdout
self._logger_id: Optional[int] = None
self._should_restore_logger: bool = False
self._adapter: Optional["Adapter"] = None # noqa: UP037

def set_adapter(self, adapter: "Adapter"):
self._adapter = adapter
Expand Down Expand Up @@ -75,9 +74,9 @@ async def post_event(self, event: ConsoleEvent):
elif isinstance(elem, Emoji):
message += MessageSegment.emoji(elem.name)
else:
message += MessageSegment(
type=elem.__class__.__name__.lower(), data=asdict(elem) # noqa
)
if TYPE_CHECKING:
assert isinstance(elem, (Markdown, Markup))
message += MessageSegment(type=elem.__class__.__name__.lower(), data=asdict(elem)) # noqa
self._adapter.post_event(
MessageEvent(
time=event.time,
Expand Down
8 changes: 2 additions & 6 deletions nonebot/adapters/console/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ async def send(
full_message = Message()
full_message += message

return await self.send_msg(
user_id=event.user.nickname, message=full_message, **kwargs
)
return await self.send_msg(user_id=event.user.nickname, message=full_message, **kwargs)

async def send_msg(self, *, user_id: str, message: Message, **kwargs: Any) -> None:
elements = []
Expand All @@ -63,9 +61,7 @@ async def send_msg(self, *, user_id: str, message: Message, **kwargs: Any) -> No
elements.append(Markdown(**seg.data))
elif seg.type == "markup":
elements.append(Markup(**seg.data))
return await self.call_api(
"send_msg", user_id=user_id, message=ConsoleMessage(elements), **kwargs
)
return await self.call_api("send_msg", user_id=user_id, message=ConsoleMessage(elements), **kwargs)

async def handle_event(self, event: Event) -> None:
"""处理收到的事件"""
Expand Down
10 changes: 4 additions & 6 deletions nonebot/adapters/console/event.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import List, Literal
from typing import Literal
from typing_extensions import override

from nonechat.info import User
Expand Down Expand Up @@ -68,15 +68,13 @@ def is_tome(self) -> bool:

@override
def get_event_description(self) -> str:
texts: List[str] = []
msg_string: List[str] = []
texts: list[str] = []
msg_string: list[str] = []
for seg in self.message:
if seg.is_text():
texts.append(str(seg))
else:
msg_string.extend(
(escape_tag("".join(texts)), f"<le>{escape_tag(str(seg))}</le>")
)
msg_string.extend((escape_tag("".join(texts)), f"<le>{escape_tag(str(seg))}</le>"))
texts.clear()
msg_string.append(escape_tag("".join(texts)))
return f"Message from {self.user.nickname} {''.join(msg_string)!r}"
Expand Down
51 changes: 15 additions & 36 deletions nonebot/adapters/console/message.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing_extensions import Self, override
from typing import Type, Union, Iterable, Optional
from typing import Union, Optional
from collections.abc import Iterable

from rich.style import Style
from rich.emoji import EmojiVariant
Expand All @@ -14,32 +15,22 @@
class MessageSegment(BaseMessageSegment["Message"]):
@classmethod
@override
def get_message_class(cls) -> Type["Message"]:
def get_message_class(cls) -> type["Message"]:
return Message

@override
def __add__(
self, other: Union[str, "MessageSegment", Iterable["MessageSegment"]]
) -> "Message":
return Message(self) + (
MessageSegment.text(other) if isinstance(other, str) else other
)
def __add__(self, other: Union[str, "MessageSegment", Iterable["MessageSegment"]]) -> "Message":
return Message(self) + (MessageSegment.text(other) if isinstance(other, str) else other)

@override
def __radd__(
self, other: Union[str, "MessageSegment", Iterable["MessageSegment"]]
) -> "Message":
return (
MessageSegment.text(other) if isinstance(other, str) else Message(other)
) + self
def __radd__(self, other: Union[str, "MessageSegment", Iterable["MessageSegment"]]) -> "Message":
return (MessageSegment.text(other) if isinstance(other, str) else Message(other)) + self

@override
def __str__(self) -> str:
if self.type == "text":
return self.data["text"]
params = ", ".join(
[f"{k}={truncate(str(v))}" for k, v in self.data.items() if v is not None]
)
params = ", ".join([f"{k}={truncate(str(v))}" for k, v in self.data.items() if v is not None])
return f"[{self.type}{':' if params else ''}{params}]"

@override
Expand Down Expand Up @@ -100,32 +91,20 @@ class Message(BaseMessage[MessageSegment]):

@classmethod
@override
def get_segment_class(cls) -> Type[MessageSegment]:
def get_segment_class(cls) -> type[MessageSegment]:
return MessageSegment

@override
def __add__(
self, other: Union[str, MessageSegment, Iterable[MessageSegment]]
) -> Self:
return super().__add__(
MessageSegment.text(other) if isinstance(other, str) else other
)
def __add__(self, other: Union[str, MessageSegment, Iterable[MessageSegment]]) -> Self:
return super().__add__(MessageSegment.text(other) if isinstance(other, str) else other)

@override
def __radd__(
self, other: Union[str, MessageSegment, Iterable[MessageSegment]]
) -> Self:
return super().__radd__(
MessageSegment.text(other) if isinstance(other, str) else other
)
def __radd__(self, other: Union[str, MessageSegment, Iterable[MessageSegment]]) -> Self:
return super().__radd__(MessageSegment.text(other) if isinstance(other, str) else other)

@override
def __iadd__(
self, other: Union[str, MessageSegment, Iterable[MessageSegment]]
) -> Self:
return super().__iadd__(
MessageSegment.text(other) if isinstance(other, str) else other
)
def __iadd__(self, other: Union[str, MessageSegment, Iterable[MessageSegment]]) -> Self:
return super().__iadd__(MessageSegment.text(other) if isinstance(other, str) else other)

@staticmethod
@override
Expand Down
4 changes: 1 addition & 3 deletions nonebot/adapters/console/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
log = logger_wrapper("Console")


def truncate(
s: str, length: int = 70, kill_words: bool = True, end: str = "..."
) -> str:
def truncate(s: str, length: int = 70, kill_words: bool = True, end: str = "...") -> str:
if len(s) <= length:
return s

Expand Down
Loading

0 comments on commit 959c1b1

Please sign in to comment.