Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support Media.name in telegram adapter #55

Merged
merged 3 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,13 @@ async def media(self, seg: Union[Image, Voice, Video, Audio, File], bot: Bot) ->
}[name]
if seg.id or seg.url:
return method(seg.id or seg.url)
elif seg.path:
return method(Path(seg.path).read_bytes())
if seg.path:
raw = Path(seg.path).read_bytes()
elif seg.raw:
return method(seg.raw_bytes)
raw = seg.raw_bytes
else:
raise SerializeFailed(lang.require("nbp-uniseg", "invalid_segment").format(type=name, seg=seg))
return method((seg.name, raw) if seg.name else raw)

@export
async def reply(self, seg: Reply, bot: Bot) -> "MessageSegment":
Expand Down
19 changes: 12 additions & 7 deletions src/nonebot_plugin_alconna/uniseg/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,11 @@ class Media(Segment):
__default_name__ = "media"
to_url: ClassVar[Optional[MediaToUrl]] = None

def __is_default_name(self) -> bool:
return self.name == self.__default_name__

def __post_init__(self):
if self.path:
if self.path and self.__is_default_name():
self.name = Path(self.path).name
if self.url and not urlparse(self.url).hostname:
self.url = f"https://{self.url}"
Expand All @@ -391,12 +394,14 @@ def __post_init__(self):
def raw_bytes(self) -> bytes:
if not self.raw:
raise ValueError(f"{self} has no raw data")
raw = self.raw.getvalue() if isinstance(self.raw, BytesIO) else self.raw
header = raw[:128]
info = fleep.get(header)
self.mimetype = info.mimes[0] if info.mimes else self.mimetype
if info.types and info.extensions:
self.name = f"{info.types[0]}.{info.extensions[0]}"
if (not self.mimetype) or self.__is_default_name():
raw = self.raw.getvalue() if isinstance(self.raw, BytesIO) else self.raw
header = raw[:128]
info = fleep.get(header)
if not self.mimetype:
self.mimetype = info.mimes[0] if info.mimes else self.mimetype
if self.__is_default_name() and info.types and info.extensions:
self.name = f"{info.types[0]}.{info.extensions[0]}"
return raw


Expand Down