Skip to content

Commit

Permalink
🐛 version 0.10.4
Browse files Browse the repository at this point in the history
fit custom element
  • Loading branch information
RF-Tar-Railt committed Apr 7, 2024
1 parent 75d53e4 commit b4e0f35
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 11 deletions.
23 changes: 15 additions & 8 deletions nonebot/adapters/satori/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from nonebot.adapters import Bot as BaseBot

from .element import parse
from .utils import API, log
from .config import ClientInfo
from .event import Event, MessageEvent
Expand All @@ -30,7 +31,7 @@
from .adapter import Adapter


def _check_reply(
async def _check_reply(
bot: "Bot",
event: MessageEvent,
) -> None:
Expand All @@ -47,24 +48,30 @@ def _check_reply(
return

msg_seg = message[index]
del message[index]
if TYPE_CHECKING:
assert isinstance(msg_seg, RenderMessage)
event.reply = msg_seg # type: ignore
if "content" not in msg_seg.data:
return
author_msg = msg_seg.data["content"].get("author")
if author_msg:
if "content" in msg_seg.data and (author_msg := msg_seg.data["content"].get("author")):
author_seg = author_msg[0]
if TYPE_CHECKING:
assert isinstance(author_seg, Author)
event.to_me = author_seg.data.get("id") == bot.self_id

del message[index]
elif "id" not in event.reply.data or not event.channel:
return
else:
msg = await bot.message_get(channel_id=event.channel.id, message_id=event.reply.data["id"])
event.reply.data["content"] = Message.from_satori_element(parse(msg.content))
if msg.user and msg.user.id == bot.self_id:
event.to_me = True
else:
return
if (
len(message) > index
and message[index].type == "at"
and message[index].data.get("id") == str(bot.self_info.id)
):
event.to_me = True
del message[index]
if len(message) > index and message[index].type == "text":
message[index].data["text"] = message[index].data["text"].lstrip()
Expand Down Expand Up @@ -183,7 +190,7 @@ def get_authorization_header(self) -> Dict[str, str]:

async def handle_event(self, event: Event) -> None:
if isinstance(event, MessageEvent):
_check_reply(self, event)
await _check_reply(self, event)
_check_at_me(self, event)
_check_nickname(self, event)
await handle_event(self, event)
Expand Down
35 changes: 33 additions & 2 deletions nonebot/adapters/satori/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pathlib import Path
from base64 import b64encode
from dataclasses import InitVar, field, dataclass
from typing_extensions import Self, NotRequired, override
from typing_extensions import Self, Required, NotRequired, override
from typing import Any, Dict, List, Type, Tuple, Union, Iterable, Optional, TypedDict

from nonebot.adapters import Message as BaseMessage
Expand Down Expand Up @@ -630,6 +630,34 @@ def __str__(self):
return f'<button {" ".join(attr)} />'


class CustomData(TypedDict, total=False):
_children: Required[List["MessageSegment"]]


@dataclass
class Custom(MessageSegment):
data: CustomData = field(default_factory=dict) # type: ignore

def __str__(self) -> str:
def _attr(key: str, value: Any):
if value is None:
return ""
key = param_case(key)
if value is True:
return f" {key}"
if value is False:
return f" no-{key}"
return f' {key}="{escape(str(value), True)}"'

attrs = "".join(_attr(k, v) for k, v in self.data.items() if k != "_children")
if self.type == "text" and "text" in self.data:
return escape(self.data["text"])
inner = "".join(str(c) for c in self.data["_children"])
if not inner:
return f"<{self.type}{attrs}/>"
return f"<{self.type}{attrs}>{inner}</{self.type}>"


ELEMENT_TYPE_MAP = {
"text": (Text, "text"),
"at": (At, "at"),
Expand Down Expand Up @@ -705,7 +733,10 @@ def handle(element: Element, upper_styles: Optional[List[str]] = None):
data["content"] = Message.from_satori_element(element.children)
yield RenderMessage(tag, data) # type: ignore
else:
yield Raw("raw", {"raw": str(element)})
custom = Custom(element.tag(), {**element.attrs, "_children": []}) # type: ignore
for child in element.children:
custom.data["_children"].extend(handle(child))
yield custom


class Message(BaseMessage[MessageSegment]):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "nonebot-adapter-satori"
version = "0.10.3"
version = "0.10.4"
description = "Satori Protocol Adapter for Nonebot2"
authors = [
{name = "RF-Tar-Railt",email = "rf_tar_railt@qq.com"},
Expand Down
3 changes: 3 additions & 0 deletions tests/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ def test_message():
Message.from_satori_element(parse("<img src='url' test:bbb='foo' width='123'/>"))[0].data["test:bbb"]
== "foo"
)
assert Message.from_satori_element(
parse("<chronocat:face id='265' name='[辣眼睛]' platform='chronocat'/>")
)[0].data == {"id": "265", "name": "[辣眼睛]", "platform": "chronocat", "_children": []}


@pytest.mark.asyncio
Expand Down

0 comments on commit b4e0f35

Please sign in to comment.