Skip to content

Commit

Permalink
🔖 fix version 0.5.1
Browse files Browse the repository at this point in the history
fxxk ruff
  • Loading branch information
RF-Tar-Railt committed Oct 15, 2023
1 parent b3ad769 commit 42b8f79
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 114 deletions.
37 changes: 8 additions & 29 deletions nonebot/adapters/satori/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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,
Expand Down Expand Up @@ -91,19 +78,15 @@ 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())
if isinstance(payload, EventPayload):
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(
{
Expand All @@ -120,8 +103,7 @@ async def _authenticate(
except Exception as e:
log(
"ERROR",
"<r><bg #f8bbd0>Error while sending "
+ "Identify event</bg #f8bbd0></r>",
"<r><bg #f8bbd0>Error while sending " + "Identify event</bg #f8bbd0></r>",
e,
)
return
Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
34 changes: 8 additions & 26 deletions nonebot/adapters/satori/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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 配置信息
Expand All @@ -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:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down
9 changes: 2 additions & 7 deletions nonebot/adapters/satori/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down
40 changes: 8 additions & 32 deletions nonebot/adapters/satori/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand All @@ -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")
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions nonebot/adapters/satori/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}

Expand Down
18 changes: 3 additions & 15 deletions nonebot/adapters/satori/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,11 @@


def escape(text: str) -> str:
return (
text.replace('"', "&quot;")
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
)
return text.replace('"', "&quot;").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def unescape(text: str) -> str:
return (
text.replace("&quot;", '"')
.replace("&amp;", "&")
.replace("&lt;", "<")
.replace("&gt;", ">")
)
return text.replace("&quot;", '"').replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")


class Element(BaseModel):
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]
Expand Down

0 comments on commit 42b8f79

Please sign in to comment.