Skip to content

Commit

Permalink
✨ version 0.7.0
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Nov 10, 2023
1 parent e6453e8 commit 2052f60
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 13 deletions.
16 changes: 16 additions & 0 deletions nonebot/adapters/satori/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class EventType(str, Enum):
MESSAGE_UPDATED = "message-updated"
REACTION_ADDED = "reaction-added"
REACTION_REMOVED = "reaction-removed"
INTERNAL = "internal"


class Event(BaseEvent, SatoriEvent):
Expand All @@ -61,10 +62,16 @@ def get_message(self) -> Message:

@override
def get_user_id(self) -> str:
if self.user:
return self.user.id
raise ValueError("Event has no context!")

@override
def get_session_id(self) -> str:
if self.channel:
if self.guild:
return f"{self.guild.id}/{self.channel.id}"
return self.channel.id
raise ValueError("Event has no context!")

@override
Expand Down Expand Up @@ -407,3 +414,12 @@ class ReactionRemovedEvent(ReactionEvent):
@override
def get_event_description(self) -> str:
return escape_tag(f"Reaction removed from {self.msg_id}")


@register_event_class
class InternalEvent(Event):
__type__ = EventType.INTERNAL

@override
def get_event_name(self) -> str:
return getattr(self, "_type", "internal")
57 changes: 48 additions & 9 deletions nonebot/adapters/satori/message.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from io import BytesIO
from pathlib import Path
from base64 import b64encode
from dataclasses import field, dataclass
from dataclasses import InitVar, field, dataclass
from typing_extensions import NotRequired, override
from typing import Any, List, Type, Union, Iterable, Optional, TypedDict

Expand All @@ -28,7 +28,8 @@ def _attr(key: str, value: Any):
return f'{key}="{escape(str(value))}"'

attrs = " ".join(_attr(k, v) for k, v in self.data.items())
return f"<{self.type} {attrs} />"
attrs = f" {attrs}" if attrs else ""
return f"<{self.type}{attrs}/>"

@classmethod
@override
Expand Down Expand Up @@ -71,14 +72,17 @@ def sharp(channel_id: str, name: Optional[str] = None) -> "Sharp":
return Sharp("sharp", data)

@staticmethod
def link(href: str) -> "Link":
def link(href: str, display: Optional[str] = None) -> "Link":
if display:
return Link("link", {"text": href, "display": display})
return Link("link", {"text": href})

@staticmethod
def image(
url: Optional[str] = None,
path: Optional[Union[str, Path]] = None,
raw: Optional[RawData] = None,
extra: Optional[dict] = None,
cache: Optional[bool] = None,
timeout: Optional[str] = None,
) -> "Image":
Expand All @@ -95,13 +99,14 @@ def image(
data["cache"] = cache
if timeout is not None:
data["timeout"] = timeout
return Image("img", data)
return Image("img", data, extra=extra)

@staticmethod
def audio(
url: Optional[str] = None,
path: Optional[Union[str, Path]] = None,
raw: Optional[RawData] = None,
extra: Optional[dict] = None,
cache: Optional[bool] = None,
timeout: Optional[str] = None,
) -> "Audio":
Expand All @@ -118,13 +123,14 @@ def audio(
data["cache"] = cache
if timeout is not None:
data["timeout"] = timeout
return Audio("audio", data)
return Audio("audio", data, extra=extra)

@staticmethod
def video(
url: Optional[str] = None,
path: Optional[Union[str, Path]] = None,
raw: Optional[RawData] = None,
extra: Optional[dict] = None,
cache: Optional[bool] = None,
timeout: Optional[str] = None,
) -> "Video":
Expand All @@ -141,13 +147,14 @@ def video(
data["cache"] = cache
if timeout is not None:
data["timeout"] = timeout
return Video("video", data)
return Video("video", data, extra=extra)

@staticmethod
def file(
url: Optional[str] = None,
path: Optional[Union[str, Path]] = None,
raw: Optional[RawData] = None,
extra: Optional[dict] = None,
cache: Optional[bool] = None,
timeout: Optional[str] = None,
) -> "File":
Expand All @@ -164,7 +171,7 @@ def file(
data["cache"] = cache
if timeout is not None:
data["timeout"] = timeout
return File("file", data)
return File("file", data, extra=extra)

@staticmethod
def bold(text: str) -> "Bold":
Expand Down Expand Up @@ -291,12 +298,19 @@ class Sharp(MessageSegment):
data: SharpData = field(default_factory=dict)


class LinkData(TypedDict):
text: str
display: NotRequired[str]


@dataclass
class Link(MessageSegment):
data: TextData = field(default_factory=dict)
data: LinkData = field(default_factory=dict)

@override
def __str__(self):
if "display" in self.data:
return f'<a href="{escape(self.data["text"])}">{escape(self.data["display"])}</a>'
return f'<a href="{escape(self.data["text"])}"/>'

@override
Expand All @@ -315,6 +329,11 @@ class ImageData(TypedDict):
@dataclass
class Image(MessageSegment):
data: ImageData = field(default_factory=dict)
extra: InitVar[Optional[dict]] = None

def __post_init__(self, extra: Optional[dict]):
if extra:
self.data.update(extra)


class AudioData(TypedDict):
Expand All @@ -326,6 +345,11 @@ class AudioData(TypedDict):
@dataclass
class Audio(MessageSegment):
data: AudioData = field(default_factory=dict)
extra: InitVar[Optional[dict]] = None

def __post_init__(self, extra: Optional[dict]):
if extra:
self.data.update(extra)


class VideoData(TypedDict):
Expand All @@ -337,6 +361,11 @@ class VideoData(TypedDict):
@dataclass
class Video(MessageSegment):
data: VideoData = field(default_factory=dict)
extra: InitVar[Optional[dict]] = None

def __post_init__(self, extra: Optional[dict]):
if extra:
self.data.update(extra)


class FileData(TypedDict):
Expand All @@ -348,6 +377,11 @@ class FileData(TypedDict):
@dataclass
class File(MessageSegment):
data: FileData = field(default_factory=dict)
extra: InitVar[Optional[dict]] = None

def __post_init__(self, extra: Optional[dict]):
if extra:
self.data.update(extra)


@dataclass
Expand Down Expand Up @@ -570,7 +604,12 @@ def from_satori_element(cls, elements: List[Element]) -> "Message":
seg_cls, seg_type = ELEMENT_TYPE_MAP[elem.type]
msg.append(seg_cls(seg_type, elem.attrs.copy()))
elif elem.type in ("a", "link"):
msg.append(Link("link", {"text": elem.attrs["href"]}))
if elem.children:
msg.append(
Link("link", {"text": elem.attrs["href"], "display": elem.children[0].attrs["text"]})
)
else:
msg.append(Link("link", {"text": elem.attrs["href"]}))
elif elem.type in STYLE_TYPE_MAP:
seg_cls, seg_type = STYLE_TYPE_MAP[elem.type]
msg.append(seg_cls(seg_type, {"text": elem.children[0].attrs["text"]}))
Expand Down
3 changes: 0 additions & 3 deletions nonebot/adapters/satori/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,7 @@ def parse_updated_at(cls, v):
class OuterMessage(InnerMessage):
channel: Channel
guild: Guild
member: InnerMember
user: User
created_at: datetime
updated_at: datetime


class Event(BaseModel, extra=Extra.allow):
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.6.3"
version = "0.7.0"
description = "Satori Protocol Adapter for Nonebot2"
authors = [
{name = "RF-Tar-Railt",email = "[email protected]"},
Expand Down

0 comments on commit 2052f60

Please sign in to comment.