satori-python-core 1.3.2__tar.gz → 1.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: satori-python-core
3
- Version: 1.3.2
3
+ Version: 1.3.4
4
4
  Summary: Satori Protocol SDK for python, specify common part
5
5
  Home-page: https://github.com/RF-Tar-Railt/satori-python
6
6
  Author-Email: RF-Tar-Railt <rf_tar_railt@qq.com>
@@ -27,11 +27,11 @@ Description-Content-Type: text/markdown
27
27
  [![PyPI](https://img.shields.io/pypi/v/satori-python)](https://pypi.org/project/satori-python)
28
28
  [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/satori-python)](https://www.python.org/)
29
29
 
30
- 基于 [Satori](https://satori.chat/zh-CN/) 协议的 Python 开发工具包
30
+ 基于 [Satori](https://satori.chat/zh-CN/protocol) 协议的 Python 开发工具包
31
31
 
32
32
  ## 协议介绍
33
33
 
34
- [Satori Protocol](https://satori.chat/zh-CN/)
34
+ [Satori Protocol](https://satori.chat/zh-CN/protocol)
35
35
 
36
36
  ### 协议端
37
37
 
@@ -5,11 +5,11 @@
5
5
  [![PyPI](https://img.shields.io/pypi/v/satori-python)](https://pypi.org/project/satori-python)
6
6
  [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/satori-python)](https://www.python.org/)
7
7
 
8
- 基于 [Satori](https://satori.chat/zh-CN/) 协议的 Python 开发工具包
8
+ 基于 [Satori](https://satori.chat/zh-CN/protocol) 协议的 Python 开发工具包
9
9
 
10
10
  ## 协议介绍
11
11
 
12
- [Satori Protocol](https://satori.chat/zh-CN/)
12
+ [Satori Protocol](https://satori.chat/zh-CN/protocol)
13
13
 
14
14
  ### 协议端
15
15
 
@@ -21,7 +21,7 @@ classifiers = [
21
21
  "Programming Language :: Python :: 3.14",
22
22
  "Operating System :: OS Independent",
23
23
  ]
24
- version = "1.3.2"
24
+ version = "1.3.4"
25
25
 
26
26
  [project.license]
27
27
  text = "MIT"
@@ -39,15 +39,14 @@ build-backend = "mina.backend"
39
39
 
40
40
  [dependency-groups]
41
41
  dev = [
42
- "isort>=5.13.2",
43
- "black>=24.4.0",
44
- "ruff>=0.4.1",
42
+ "black>=26.3.0",
43
+ "ruff>=0.15.1",
45
44
  "pre-commit>=3.7.0",
46
- "fix-future-annotations>=0.5.0",
47
45
  "mina-build<0.6,>=0.5.1",
48
46
  "pdm-mina>=0.3.2",
49
47
  "nonechat<0.7.0,>=0.6.0",
50
48
  "uvicorn[standard]>=0.37.0",
49
+ "pydantic>=2.13.1",
51
50
  ]
52
51
 
53
52
  [tool.pdm.build]
@@ -63,7 +62,7 @@ excludes = [
63
62
 
64
63
  [tool.pdm.scripts.format]
65
64
  composite = [
66
- "isort ./src/ ./example/",
65
+ "ruff check --select I --fix ./src/ ./example/",
67
66
  "black ./src/ ./example/",
68
67
  "ruff check",
69
68
  ]
@@ -77,14 +76,6 @@ line-length = 120
77
76
  include = "\\.pyi?$"
78
77
  extend-exclude = ""
79
78
 
80
- [tool.isort]
81
- profile = "black"
82
- line_length = 120
83
- skip_gitignore = true
84
- extra_standard_library = [
85
- "typing_extensions",
86
- ]
87
-
88
79
  [tool.ruff]
89
80
  line-length = 120
90
81
  target-version = "py310"
@@ -94,6 +85,7 @@ exclude = [
94
85
  "exam2.py",
95
86
  "src/satori/_vendor/*",
96
87
  ]
88
+ respect-gitignore = true
97
89
 
98
90
  [tool.ruff.lint]
99
91
  select = [
@@ -113,6 +105,12 @@ ignore = [
113
105
  "T201",
114
106
  ]
115
107
 
108
+ [tool.ruff.lint.isort]
109
+ extra-standard-library = [
110
+ "typing_extensions",
111
+ ]
112
+ force-sort-within-sections = false
113
+
116
114
  [tool.pyright]
117
115
  pythonPlatform = "All"
118
116
  pythonVersion = "3.10"
@@ -45,7 +45,7 @@ from .model import Role as Role
45
45
  from .model import Upload as Upload
46
46
  from .model import User as User
47
47
 
48
- __version__ = "1.3.2"
48
+ __version__ = "1.3.4"
49
49
 
50
50
 
51
51
  MessageReceipt = MessageObject
@@ -4,7 +4,7 @@ from dataclasses import InitVar, dataclass, field
4
4
  from io import BytesIO
5
5
  from pathlib import Path
6
6
  from types import UnionType
7
- from typing import Any, ClassVar, Final, TypeVar, Union, final, get_args, get_origin, overload
7
+ from typing import Any, ClassVar, Final, Literal, TypeVar, Union, final, get_args, get_origin, overload
8
8
  from typing_extensions import Self, override
9
9
 
10
10
  from ._vendor.fleep import get
@@ -17,7 +17,7 @@ TE = TypeVar("TE", bound="Element")
17
17
 
18
18
 
19
19
  def conv_bool(v: str) -> bool:
20
- if v.lower() not in ("true", "false"):
20
+ if v.lower() not in {"true", "false"}:
21
21
  raise ValueError(v)
22
22
  return v.lower() == "true"
23
23
 
@@ -28,13 +28,17 @@ class Element:
28
28
  _children: list["Element"] = field(init=False, default_factory=list)
29
29
 
30
30
  __names__: ClassVar[tuple[str, ...]]
31
- __convert_fields__: ClassVar[dict[str, Callable[[str], Any]]]
31
+ __convert_fields__: ClassVar[dict[str, Literal[True] | Callable[[str], Any]]]
32
+ __unpack_names__: ClassVar[frozenset[str]]
32
33
 
33
34
  def __init_subclass__(cls, **kwargs):
34
- cls.__convert_fields__ = {}
35
+ convert_fields = {}
36
+ for base in cls.__mro__:
37
+ if hasattr(base, "__convert_fields__"):
38
+ convert_fields.update(base.__convert_fields__)
35
39
  annotations = cls.__annotations__
36
40
  for name, typ in annotations.items():
37
- if name.startswith("_"):
41
+ if name.startswith("_") or isinstance(typ, InitVar):
38
42
  continue
39
43
  # _type = get_args(typ)[0] if hasattr(typ, "__origin__") else typ
40
44
  orig = get_origin(typ)
@@ -46,39 +50,49 @@ class Element:
46
50
  _type = args[0]
47
51
  else:
48
52
  _type = typ
49
- if _type is not str:
50
- if _type is bool:
51
- cls.__convert_fields__[name] = conv_bool
52
- elif _type in (list, dict):
53
- cls.__convert_fields__[name] = decode
53
+ if _type is bool:
54
+ convert_fields[name] = conv_bool
55
+ elif _type in (list, dict):
56
+ convert_fields[name] = decode
57
+ else:
58
+ convert_fields[name] = True if _type is str else _type
59
+ cls.__convert_fields__ = convert_fields
60
+ names = getattr(cls, "__names__", None)
61
+ for base in cls.__mro__:
62
+ if parent_names := getattr(base, "__names__", None):
63
+ if names is None:
64
+ names = parent_names
54
65
  else:
55
- cls.__convert_fields__[name] = _type
56
-
57
- @property
58
- def children(self) -> list["Element"]:
59
- return self._children
60
-
61
- @property
62
- def tag(self) -> str:
63
- return self.__class__.__name__.lower()
66
+ names = names + parent_names
67
+ cls.__unpack_names__ = frozenset(names if names is not None else annotations.keys())
64
68
 
65
69
  @classmethod
66
70
  def unpack(cls, attrs: dict[str, Any]):
67
71
  data = {}
68
- names = getattr(cls, "__names__", None)
69
- for name in cls.__dataclass_fields__.keys():
72
+ args = {}
73
+ convert_fields = cls.__convert_fields__
74
+ names = cls.__unpack_names__
75
+ for name in convert_fields:
70
76
  if name not in attrs:
71
77
  continue
72
- if name in cls.__convert_fields__:
73
- data[name] = cls.__convert_fields__[name](attrs[name])
74
- else:
78
+ convert = convert_fields[name]
79
+ if convert is True:
75
80
  data[name] = attrs[name]
76
- obj = cls(**{k: v for k, v in data.items() if names is None or k in names}) # type: ignore
81
+ else:
82
+ data[name] = convert(attrs[name])
83
+ if name in names:
84
+ args[name] = data[name]
85
+ obj = cls(**args) # type: ignore
77
86
  obj._attrs.update(data)
78
87
  return obj
79
88
 
80
- def __post_init__(self):
81
- self._attrs = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
89
+ @property
90
+ def children(self) -> list["Element"]:
91
+ return self._children
92
+
93
+ @property
94
+ def tag(self) -> str:
95
+ return self.__class__.__name__.lower()
82
96
 
83
97
  def attributes(self) -> str:
84
98
  def _attr(key: str, value: Any):
@@ -94,6 +108,8 @@ class Element:
94
108
  return "".join(_attr(k, v) for k, v in self._attrs.items())
95
109
 
96
110
  def dumps(self, strip: bool = False) -> str:
111
+ if not self._attrs:
112
+ self._attrs = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
97
113
  if self.tag == "text" and "text" in self._attrs:
98
114
  return self._attrs["text"] if strip else escape(self._attrs["text"])
99
115
  inner = "".join(c.dumps(strip) for c in self._children)
@@ -124,6 +140,9 @@ class Element:
124
140
  def __getitem__(self, key: str) -> Any:
125
141
  return self._attrs[key]
126
142
 
143
+ def raw(self) -> RawElement:
144
+ return RawElement(self.tag, self._attrs, [c.raw() for c in self._children])
145
+
127
146
 
128
147
  @dataclass(repr=False)
129
148
  class Text(Element):
@@ -131,6 +150,13 @@ class Text(Element):
131
150
 
132
151
  text: str
133
152
 
153
+ @override
154
+ @classmethod
155
+ def unpack(cls, attrs: dict[str, Any]):
156
+ obj = cls(attrs["text"])
157
+ obj._attrs["text"] = attrs["text"]
158
+ return obj
159
+
134
160
  @override
135
161
  def dumps(self, strip: bool = False) -> str:
136
162
  return self.text if strip else escape(self.text)
@@ -145,6 +171,12 @@ class At(Element):
145
171
  role: str | None = None
146
172
  type: str | None = None
147
173
 
174
+ @classmethod
175
+ def unpack(cls, attrs: dict[str, Any]):
176
+ obj = cls(attrs.get("id"), attrs.get("name"), attrs.get("role"), attrs.get("type"))
177
+ obj._attrs.update(attrs)
178
+ return obj
179
+
148
180
  @staticmethod
149
181
  def role_(
150
182
  role: str,
@@ -164,6 +196,12 @@ class Emoji(Element):
164
196
  id: str
165
197
  name: str | None = None
166
198
 
199
+ @classmethod
200
+ def unpack(cls, attrs: dict[str, Any]):
201
+ obj = cls(attrs["id"], attrs.get("name"))
202
+ obj._attrs.update(attrs)
203
+ return obj
204
+
167
205
  def to_model(self):
168
206
  from .model import EmojiObject
169
207
 
@@ -177,6 +215,12 @@ class Sharp(Element):
177
215
  id: str
178
216
  name: str | None = None
179
217
 
218
+ @classmethod
219
+ def unpack(cls, attrs: dict[str, Any]):
220
+ obj = cls(attrs["id"], attrs.get("name"))
221
+ obj._attrs.update(attrs)
222
+ return obj
223
+
180
224
 
181
225
  @dataclass(repr=False)
182
226
  class Link(Element):
@@ -184,6 +228,12 @@ class Link(Element):
184
228
 
185
229
  href: str
186
230
 
231
+ @classmethod
232
+ def unpack(cls, attrs: dict[str, Any]):
233
+ obj = cls(attrs["href"])
234
+ obj._attrs.update(attrs)
235
+ return obj
236
+
187
237
  def __post_call__(self):
188
238
  if not self._children:
189
239
  return
@@ -255,7 +305,6 @@ class Resource(Element):
255
305
  return cls(**data)
256
306
 
257
307
  def __post_init__(self, extra: dict[str, Any] | None = None):
258
- super().__post_init__()
259
308
  if extra:
260
309
  self._attrs.update(extra)
261
310
 
@@ -267,7 +316,7 @@ class Image(Resource):
267
316
  width: int | None = None
268
317
  height: int | None = None
269
318
 
270
- __names__ = ("src", "title", "width", "height")
319
+ __names__ = ("width", "height")
271
320
 
272
321
  @property
273
322
  @override
@@ -282,7 +331,7 @@ class Audio(Resource):
282
331
  duration: float | None = None
283
332
  poster: str | None = None
284
333
 
285
- __names__ = ("src", "title", "duration", "poster")
334
+ __names__ = ("duration", "poster")
286
335
 
287
336
 
288
337
  @dataclass(repr=False)
@@ -294,7 +343,7 @@ class Video(Resource):
294
343
  duration: float | None = None
295
344
  poster: str | None = None
296
345
 
297
- __names__ = ("src", "title", "width", "height", "duration", "poster")
346
+ __names__ = ("width", "height", "duration", "poster")
298
347
 
299
348
 
300
349
  @dataclass(repr=False)
@@ -303,7 +352,7 @@ class File(Resource):
303
352
 
304
353
  poster: str | None = None
305
354
 
306
- __names__ = ("src", "title", "poster")
355
+ __names__ = ("poster",)
307
356
 
308
357
 
309
358
  @dataclass(init=False, repr=False)
@@ -312,6 +361,12 @@ class Style(Element):
312
361
 
313
362
  __names__ = ()
314
363
 
364
+ @classmethod
365
+ def unpack(cls, attrs: dict[str, Any]):
366
+ obj = cls()
367
+ obj._attrs.update(attrs)
368
+ return obj
369
+
315
370
  def __init__(self, *text: "str | Text | Style"):
316
371
  super().__init__()
317
372
  self.__call__(*text)
@@ -422,6 +477,12 @@ class Message(Element):
422
477
  id: str | None
423
478
  forward: bool | None
424
479
 
480
+ @classmethod
481
+ def unpack(cls, attrs: dict[str, Any]):
482
+ obj = cls(attrs.get("id"), conv_bool(attrs["forward"]) if "forward" in attrs else None)
483
+ obj._attrs.update(attrs)
484
+ return obj
485
+
425
486
  def __init__(
426
487
  self,
427
488
  id: str | None = None,
@@ -451,6 +512,12 @@ class Author(Element):
451
512
  name: str | None = None
452
513
  avatar: str | None = None
453
514
 
515
+ @classmethod
516
+ def unpack(cls, attrs: dict[str, Any]):
517
+ obj = cls(attrs["id"], attrs.get("name"), attrs.get("avatar"))
518
+ obj._attrs.update(attrs)
519
+ return obj
520
+
454
521
 
455
522
  @dataclass(repr=False)
456
523
  class Button(Element):
@@ -462,6 +529,12 @@ class Button(Element):
462
529
  text: str | None = None
463
530
  theme: str | None = None
464
531
 
532
+ @classmethod
533
+ def unpack(cls, attrs: dict[str, Any]):
534
+ obj = cls(attrs["type"], attrs.get("id"), attrs.get("href"), attrs.get("text"), attrs.get("theme"))
535
+ obj._attrs.update(attrs)
536
+ return obj
537
+
465
538
  @classmethod
466
539
  def action(cls, button_id: str, theme: str | None = None):
467
540
  return Button("action", id=button_id, theme=theme)
@@ -533,7 +606,7 @@ class Raw(Element):
533
606
 
534
607
  @override
535
608
  def dumps(self, strip: bool = False):
536
- return self.content if strip else escape(self.content)
609
+ return self.content
537
610
 
538
611
 
539
612
  def register_element(cls: type[TE], tag: str | None = None) -> type[TE]:
@@ -547,7 +620,7 @@ def register_element(cls: type[TE], tag: str | None = None) -> type[TE]:
547
620
  return cls
548
621
 
549
622
 
550
- ELEMENT_TYPE_MAP = {
623
+ COMMON_TYPE_MAP = {
551
624
  "text": Text,
552
625
  "at": At,
553
626
  "emoji": Emoji,
@@ -558,6 +631,9 @@ ELEMENT_TYPE_MAP = {
558
631
  "video": Video,
559
632
  "file": File,
560
633
  "author": Author,
634
+ "button": Button,
635
+ "a": Link,
636
+ "link": Link,
561
637
  }
562
638
 
563
639
  STYLE_TYPE_MAP = {
@@ -586,35 +662,32 @@ STYLE_TYPE_MAP = {
586
662
  "br": Br,
587
663
  }
588
664
 
665
+ ELEMENT_TYPE_MAP = {**COMMON_TYPE_MAP, **STYLE_TYPE_MAP}
666
+
589
667
 
590
668
  def transform(elements: list[RawElement]) -> list[Element]:
591
669
  msg = []
592
670
  for elem in elements:
593
671
  tag = elem.tag()
594
672
  if tag in ELEMENT_TYPE_MAP:
595
- seg_cls = ELEMENT_TYPE_MAP[tag]
596
- msg.append(seg_cls.unpack(elem.attrs)(*transform(elem.children)))
597
- elif tag in ("a", "link"):
598
- link = Link.unpack(elem.attrs)
599
- if elem.children:
600
- link(*transform(elem.children))
601
- msg.append(link)
602
- elif tag == "button":
603
- button = Button.unpack(elem.attrs)
673
+ seg = ELEMENT_TYPE_MAP[tag].unpack(elem.attrs)
604
674
  if elem.children:
605
- button(*transform(elem.children))
606
- msg.append(button)
607
- elif tag in STYLE_TYPE_MAP:
608
- seg_cls = STYLE_TYPE_MAP[tag]
609
- msg.append(seg_cls.unpack(elem.attrs)(*transform(elem.children)))
610
- elif tag in ("br", "newline"):
611
- msg.append(Br())
675
+ seg(*transform(elem.children))
676
+ msg.append(seg)
612
677
  elif tag == "message":
613
678
  msg.append(Message.unpack(elem.attrs)(*transform(elem.children)))
614
679
  elif tag == "quote":
615
- msg.append(Quote.unpack(elem.attrs)(*transform(elem.children)))
680
+ quot = Quote.unpack(elem.attrs)
681
+ if elem.children:
682
+ quot(*transform(elem.children))
683
+ msg.append(quot)
684
+ elif tag in ("br", "newline"):
685
+ msg.append(Br())
616
686
  else:
617
- msg.append(Custom(elem.type, elem.attrs)(*transform(elem.children)))
687
+ custom = Custom(tag, elem.attrs)
688
+ if elem.children:
689
+ custom(*transform(elem.children))
690
+ msg.append(custom)
618
691
  return msg
619
692
 
620
693
 
@@ -1,6 +1,8 @@
1
1
  import mimetypes
2
+ import sys
3
+ import typing
2
4
  from collections.abc import AsyncIterable, Awaitable, Callable
3
- from dataclasses import Field, dataclass, field
5
+ from dataclasses import dataclass, field
4
6
  from datetime import datetime
5
7
  from enum import IntEnum
6
8
  from os import PathLike
@@ -12,17 +14,26 @@ from .element import Element, Emoji, transform
12
14
  from .parser import Element as RawElement
13
15
  from .parser import parse
14
16
 
17
+ if sys.version_info >= (3, 12):
18
+ _generic_init_subclass = typing._generic_init_subclass
19
+ else:
20
+ _generic_init_subclass = Generic.__init_subclass__.__func__
15
21
 
16
- @dataclass
22
+
23
+ @dataclass(slots=True)
17
24
  class ModelBase:
18
25
  __converter__: ClassVar[dict[str, Callable[[Any], Any]]] = {}
19
26
  _raw_data: dict[str, Any] = field(init=False, default_factory=dict, repr=False, compare=False, hash=False)
20
27
 
28
+ @classmethod
29
+ def before_parse(cls, raw: dict):
30
+ pass
31
+
21
32
  @classmethod
22
33
  def parse(cls: type[Self], raw: dict) -> Self:
23
- fs: dict[str, Field] = cls.__dataclass_fields__
24
34
  data = {}
25
- for name in fs.keys():
35
+ cls.before_parse(data)
36
+ for name in cls.__dataclass_fields__:
26
37
  if name in raw:
27
38
  if name in cls.__converter__:
28
39
  data[name] = cls.__converter__[name](raw[name])
@@ -32,6 +43,42 @@ class ModelBase:
32
43
  obj._raw_data = raw
33
44
  return obj
34
45
 
46
+ def __init_subclass__(cls, **kwargs):
47
+ has_converter = False
48
+ keys = set()
49
+ for c in cls.__mro__:
50
+ if c is Generic:
51
+ _generic_init_subclass(cls, **kwargs)
52
+ if getattr(c, "__converter__", None):
53
+ has_converter = True
54
+ keys.update(getattr(c, "__annotations__", {}).keys())
55
+ keys = frozenset(k for k in keys if not k.startswith("_"))
56
+
57
+ def parse1(cls_: type[Self], raw: dict, _keys=keys) -> Self:
58
+ data = {k: v for k, v in raw.items() if k in _keys}
59
+ obj = cls_(**data) # type: ignore
60
+ obj._raw_data = raw
61
+ return obj
62
+
63
+ def parse2(cls_: type[Self], raw: dict, _keys=keys) -> Self:
64
+ data = {}
65
+ cls_.before_parse(data)
66
+ for name in _keys:
67
+ if name in raw:
68
+ if name in cls_.__converter__:
69
+ data[name] = cls_.__converter__[name](raw[name])
70
+ else:
71
+ data[name] = raw[name]
72
+ obj = cls_(**data) # type: ignore
73
+ obj._raw_data = raw
74
+ return obj
75
+
76
+ if "parse" not in cls.__dict__:
77
+ if has_converter:
78
+ cls.parse = classmethod(parse2) # type: ignore
79
+ else:
80
+ cls.parse = classmethod(parse1) # type: ignore
81
+
35
82
  def dump(self) -> dict:
36
83
  raise NotImplementedError
37
84
 
@@ -43,7 +90,7 @@ class ChannelType(IntEnum):
43
90
  VOICE = 3
44
91
 
45
92
 
46
- @dataclass
93
+ @dataclass(slots=True)
47
94
  class Channel(ModelBase):
48
95
  id: str
49
96
  type: ChannelType = ChannelType.TEXT
@@ -61,7 +108,7 @@ class Channel(ModelBase):
61
108
  return res
62
109
 
63
110
 
64
- @dataclass
111
+ @dataclass(slots=True)
65
112
  class Guild(ModelBase):
66
113
  id: str
67
114
  name: str | None = None
@@ -76,7 +123,7 @@ class Guild(ModelBase):
76
123
  return res
77
124
 
78
125
 
79
- @dataclass
126
+ @dataclass(slots=True)
80
127
  class User(ModelBase):
81
128
  id: str
82
129
  name: str | None = None
@@ -97,7 +144,7 @@ class User(ModelBase):
97
144
  return res
98
145
 
99
146
 
100
- @dataclass
147
+ @dataclass(slots=True)
101
148
  class Friend(ModelBase):
102
149
  user: User | None = None
103
150
  nick: str | None = None
@@ -117,7 +164,7 @@ class Friend(ModelBase):
117
164
  return res
118
165
 
119
166
 
120
- @dataclass
167
+ @dataclass(slots=True)
121
168
  class Role(ModelBase):
122
169
  id: str
123
170
  name: str | None = None
@@ -126,7 +173,7 @@ class Role(ModelBase):
126
173
  def parse(cls, raw: str | dict):
127
174
  if isinstance(raw, str):
128
175
  return cls(id=raw)
129
- return super().parse(raw)
176
+ return cls(raw["id"], raw.get("name"))
130
177
 
131
178
  def dump(self):
132
179
  res = {"id": self.id}
@@ -135,7 +182,7 @@ class Role(ModelBase):
135
182
  return res
136
183
 
137
184
 
138
- @dataclass
185
+ @dataclass(slots=True)
139
186
  class Member(ModelBase):
140
187
  user: User | None = None
141
188
  nick: str | None = None
@@ -177,11 +224,11 @@ class LoginStatus(IntEnum):
177
224
  """正在重新连接"""
178
225
 
179
226
 
180
- @dataclass
227
+ @dataclass(slots=True, kw_only=True)
181
228
  class Login(ModelBase):
182
- sn: int
183
- status: LoginStatus
184
- adapter: str
229
+ sn: int = 0
230
+ status: LoginStatus = LoginStatus.ONLINE
231
+ adapter: str = "satori"
185
232
  platform: str
186
233
  user: User
187
234
  features: list[str] = field(default_factory=list)
@@ -203,29 +250,22 @@ class Login(ModelBase):
203
250
  return res
204
251
 
205
252
  @classmethod
206
- def parse(cls, raw: dict):
253
+ def before_parse(cls, raw: dict):
207
254
  if "self_id" in raw and "user" not in raw:
208
255
  raw["user"] = {"id": raw["self_id"]}
209
- if "sn" not in raw:
210
- raw["sn"] = 0
211
- if "adapter" not in raw:
212
- raw["adapter"] = "satori"
213
- if "status" not in raw:
214
- raw["status"] = LoginStatus.ONLINE
215
- return super().parse(raw)
216
256
 
217
257
  @property
218
258
  def id(self) -> str:
219
259
  return self.user.id
220
260
 
221
261
 
222
- @dataclass
262
+ @dataclass(slots=True)
223
263
  class LoginPartial(Login):
224
264
  platform: str | None = None
225
265
  user: User | None = None
226
266
 
227
267
 
228
- @dataclass
268
+ @dataclass(slots=True)
229
269
  class ArgvInteraction(ModelBase):
230
270
  name: str
231
271
  arguments: list
@@ -235,7 +275,7 @@ class ArgvInteraction(ModelBase):
235
275
  return {"name": self.name, "arguments": self.arguments, "options": self.options}
236
276
 
237
277
 
238
- @dataclass
278
+ @dataclass(slots=True)
239
279
  class ButtonInteraction(ModelBase):
240
280
  id: str
241
281
  data: str | None = None
@@ -262,7 +302,7 @@ class Opcode(IntEnum):
262
302
  """元信息更新 (接收)"""
263
303
 
264
304
 
265
- @dataclass
305
+ @dataclass(slots=True)
266
306
  class Identify(ModelBase):
267
307
  token: str | None = None
268
308
  sn: int | None = None
@@ -271,7 +311,7 @@ class Identify(ModelBase):
271
311
  def parse(cls, raw: dict):
272
312
  if "sequence" in raw and "sn" not in raw:
273
313
  raw["sn"] = raw["sequence"]
274
- return super().parse(raw)
314
+ return cls(token=raw.get("token"), sn=raw.get("sn"))
275
315
 
276
316
  @property
277
317
  def sequence(self) -> int | None:
@@ -281,7 +321,7 @@ class Identify(ModelBase):
281
321
  return {k: v for k, v in (("token", self.token), ("sn", self.sn)) if v is not None}
282
322
 
283
323
 
284
- @dataclass
324
+ @dataclass(slots=True)
285
325
  class Ready(ModelBase):
286
326
  logins: list[LoginPartial]
287
327
  proxy_urls: list[str] = field(default_factory=list)
@@ -292,7 +332,7 @@ class Ready(ModelBase):
292
332
  return {"logins": [login.dump() for login in self.logins], "proxy_urls": self.proxy_urls}
293
333
 
294
334
 
295
- @dataclass
335
+ @dataclass(slots=True)
296
336
  class MetaPayload(ModelBase):
297
337
  """Meta 信令"""
298
338
 
@@ -302,7 +342,7 @@ class MetaPayload(ModelBase):
302
342
  return {"proxy_urls": self.proxy_urls}
303
343
 
304
344
 
305
- @dataclass
345
+ @dataclass(slots=True)
306
346
  class Meta(ModelBase):
307
347
  """Meta 数据"""
308
348
 
@@ -315,7 +355,7 @@ class Meta(ModelBase):
315
355
  return {"logins": [login.dump() for login in self.logins], "proxy_urls": self.proxy_urls}
316
356
 
317
357
 
318
- @dataclass
358
+ @dataclass(slots=True)
319
359
  class EmojiObject(ModelBase):
320
360
  id: str
321
361
  name: str | None = None
@@ -330,7 +370,7 @@ class EmojiObject(ModelBase):
330
370
  return Emoji(self.id, self.name)
331
371
 
332
372
 
333
- @dataclass
373
+ @dataclass(slots=True)
334
374
  class MessageObject(ModelBase):
335
375
  id: str
336
376
  content: str = ""
@@ -342,6 +382,8 @@ class MessageObject(ModelBase):
342
382
  updated_at: datetime | None = None
343
383
  referrer: dict | None = None
344
384
 
385
+ _parsed_message: list[Element] | None = field(init=False, default=None, repr=False, compare=False, hash=False)
386
+
345
387
  @classmethod
346
388
  def from_elements(
347
389
  cls,
@@ -361,10 +403,10 @@ class MessageObject(ModelBase):
361
403
 
362
404
  @property
363
405
  def message(self) -> list[Element]:
364
- if hasattr(self, "_parsed_message"):
406
+ if self._parsed_message is not None:
365
407
  return self._parsed_message
366
- self._parsed_message = transform(parse(self.content))
367
- return self._parsed_message
408
+ self._parsed_message = msg = transform(parse(self.content))
409
+ return msg
368
410
 
369
411
  @message.setter
370
412
  def message(self, value: list[Element]):
@@ -372,11 +414,10 @@ class MessageObject(ModelBase):
372
414
  self.content = "".join(str(i) for i in value)
373
415
 
374
416
  @classmethod
375
- def parse(cls, raw: dict):
417
+ def before_parse(cls, raw: dict):
376
418
  if "elements" in raw and "content" not in raw:
377
419
  content = [RawElement(*item.values()) for item in raw["elements"]]
378
420
  raw["content"] = "".join(str(i) for i in content)
379
- return super().parse(raw)
380
421
 
381
422
  __converter__ = {
382
423
  "channel": Channel.parse,
@@ -406,7 +447,7 @@ class MessageObject(ModelBase):
406
447
  return res
407
448
 
408
449
 
409
- @dataclass
450
+ @dataclass(slots=True)
410
451
  class Event(ModelBase):
411
452
  type: str
412
453
  timestamp: datetime
@@ -444,7 +485,7 @@ class Event(ModelBase):
444
485
  }
445
486
 
446
487
  @classmethod
447
- def parse(cls, raw: dict):
488
+ def before_parse(cls, raw: dict):
448
489
  if "id" in raw and "sn" not in raw:
449
490
  raw["sn"] = raw["id"]
450
491
  if "platform" in raw and "self_id" in raw and "login" not in raw:
@@ -458,7 +499,6 @@ class Event(ModelBase):
458
499
  if "login" not in raw:
459
500
  raw["login"] = {"sn": 0, "status": LoginStatus.ONLINE, "platform": raw.get("platform", "unknown")}
460
501
  raw["login"]["user"] = {"id": raw["self_id"]}
461
- return super().parse(raw)
462
502
 
463
503
  @property
464
504
  def platform(self):
@@ -509,7 +549,7 @@ class Event(ModelBase):
509
549
  T = TypeVar("T", bound=ModelBase)
510
550
 
511
551
 
512
- @dataclass
552
+ @dataclass(slots=True)
513
553
  class PageResult(ModelBase, Generic[T]):
514
554
  data: list[T]
515
555
  next: str | None = None
@@ -526,7 +566,7 @@ class PageResult(ModelBase, Generic[T]):
526
566
  return res
527
567
 
528
568
 
529
- @dataclass
569
+ @dataclass(slots=True)
530
570
  class PageDequeResult(PageResult[T]):
531
571
  prev: str | None = None
532
572
 
@@ -569,7 +609,7 @@ Direction: TypeAlias = Literal["before", "after", "around"]
569
609
  Order: TypeAlias = Literal["asc", "desc"]
570
610
 
571
611
 
572
- @dataclass
612
+ @dataclass(slots=True)
573
613
  class Upload:
574
614
  file: bytes | IO[bytes] | PathLike
575
615
  mimetype: str = "image/png"
@@ -12,27 +12,37 @@ def escape(text: str, inline: bool = False) -> str:
12
12
  return result.replace('"', "&quot;") if inline else result
13
13
 
14
14
 
15
+ uc_escape_pat1 = re.compile(r"&#(\d+);")
16
+ uc_escape_pat2 = re.compile(r"&#x([0-9a-f]+);")
17
+ uc_escape_pat3 = re.compile(r"&(amp|#38|#x26);")
18
+
19
+
15
20
  def unescape(text: str) -> str:
16
21
  result = text.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
17
- result = re.sub(r"&#(\d+);", lambda m: m[0] if m[1] == "38" else chr(int(m[1])), result)
18
- result = re.sub(r"&#x([0-9a-f]+);", lambda m: m[0] if m[1] == "26" else chr(int(m[1], 16)), result)
19
- return re.sub("&(amp|#38|#x26);", "&", result)
22
+ result = uc_escape_pat1.sub(lambda m: m[0] if m[1] == "38" else chr(int(m[1])), result)
23
+ result = uc_escape_pat2.sub(lambda m: m[0] if m[1] == "26" else chr(int(m[1], 16)), result)
24
+ return uc_escape_pat3.sub("&", result)
20
25
 
21
26
 
22
27
  def uncapitalize(source: str) -> str:
23
- return source[0].lower() + source[1:]
28
+ return source[:1].lower() + source[1:]
29
+
30
+
31
+ camel_pat = re.compile(r"[_-][a-z]")
32
+ param_pat = re.compile(r".[A-Z]+")
33
+ snake_pat = re.compile(r".[A-Z]")
24
34
 
25
35
 
26
36
  def camel_case(source: str) -> str:
27
- return re.sub("[_-][a-z]", lambda mat: mat[0][1:].upper(), source)
37
+ return camel_pat.sub(lambda mat: mat[0][1:].upper(), source)
28
38
 
29
39
 
30
40
  def param_case(source: str) -> str:
31
- return re.sub(".[A-Z]+", lambda mat: mat[0][0] + "-" + mat[0][1:].lower(), uncapitalize(source).replace("_", "-"))
41
+ return param_pat.sub(lambda mat: mat[0][0] + "-" + mat[0][1:].lower(), uncapitalize(source).replace("_", "-"))
32
42
 
33
43
 
34
44
  def snake_case(source: str) -> str:
35
- return re.sub(".[A-Z]", lambda mat: mat[0][0] + "_" + mat[0][1:].lower(), uncapitalize(source).replace("-", "_"))
45
+ return snake_pat.sub(lambda mat: mat[0][0] + "_" + mat[0][1:].lower(), uncapitalize(source).replace("-", "_"))
36
46
 
37
47
 
38
48
  def ensure_list(value: T | list[T] | None) -> list[T]:
@@ -49,9 +59,9 @@ def make_element(content: Union[str, bool, int, float, "Element"]) -> Optional["
49
59
  if isinstance(content, Element):
50
60
  return content
51
61
  if isinstance(content, (bool, int, float)):
52
- return Element(type="text", attrs={"text": str(content)})
62
+ return Element.parse(type="text", attrs={"text": str(content)})
53
63
  if isinstance(content, str) and content:
54
- return Element(type="text", attrs={"text": content})
64
+ return Element.parse(type="text", attrs={"text": content})
55
65
  if content is not None:
56
66
  raise ValueError(f"Invalid content: {content!r}")
57
67
 
@@ -68,7 +78,9 @@ class Element:
68
78
  type: str
69
79
  attrs: dict[str, Any]
70
80
  children: list["Element"]
71
- source: str | None = None
81
+ source: str | None
82
+
83
+ __slots__ = ("type", "attrs", "children", "source")
72
84
 
73
85
  def __init__(
74
86
  self,
@@ -99,6 +111,31 @@ class Element:
99
111
  elif not self.attrs:
100
112
  self.attrs["text"] = ""
101
113
 
114
+ @classmethod
115
+ def parse(
116
+ cls, type: str, attrs: dict[str, Any], children: list["Element"] | None = None, source: str | None = None
117
+ ) -> "Element":
118
+ elem = cls.__new__(cls)
119
+ elem.type = type
120
+ elem.attrs = {}
121
+ elem.children = []
122
+ elem.source = source
123
+ for k, v in attrs.items():
124
+ if v is None:
125
+ continue
126
+ if k == "children":
127
+ elem.children.extend(ensure_list(v))
128
+ else:
129
+ elem.attrs[camel_case(k)] = v
130
+ if children:
131
+ elem.children.extend(children)
132
+ if type == "text":
133
+ if "content" in elem.attrs:
134
+ elem.attrs["text"] = elem.attrs.pop("content")
135
+ elif not elem.attrs:
136
+ elem.attrs["text"] = ""
137
+ return elem
138
+
102
139
  def tag(self):
103
140
  if self.type == "component":
104
141
  if is_ := self.attrs.get("is"):
@@ -234,6 +271,9 @@ tag_pat2 = re.compile(
234
271
  attr_pat1 = re.compile(r"([^\s=]+)(?:=\"(?P<value1>[^\"]*)\"|='(?P<value2>[^']*)')?", re.S)
235
272
  attr_pat2 = re.compile(r"([^\s=]+)(?:=\"(?P<value1>[^\"]*)\"|='(?P<value2>[^']*)'|=\{(?P<curly>[^\}]+)\})?", re.S)
236
273
 
274
+ space_pat1 = re.compile(r"^\s*\n\s*", re.MULTILINE)
275
+ space_pat2 = re.compile(r"\s*\n\s*$", re.MULTILINE)
276
+
237
277
 
238
278
  class Position(IntEnum):
239
279
  OPEN = 0
@@ -242,7 +282,7 @@ class Position(IntEnum):
242
282
  CONTINUE = 3
243
283
 
244
284
 
245
- @dataclass
285
+ @dataclass(slots=True)
246
286
  class Token:
247
287
  type: Literal["angle", "curly"]
248
288
  name: str
@@ -299,7 +339,7 @@ def parse_tokens(tokens: list[str | Token], context: dict | None = None) -> list
299
339
  result: list[Element] = []
300
340
  for token in tokens:
301
341
  if isinstance(token, str):
302
- result.append(Element(type="text", attrs={"text": token}))
342
+ result.append(Element.parse(type="text", attrs={"text": token}))
303
343
  elif token.type == "angle":
304
344
  attrs = {}
305
345
  attr_pat = attr_pat2 if context is not None else attr_pat1
@@ -318,10 +358,10 @@ def parse_tokens(tokens: list[str | Token], context: dict | None = None) -> list
318
358
  attrs[key] = True
319
359
  token.extra = token.extra[mat.end() :]
320
360
  result.append(
321
- Element(
361
+ Element.parse(
322
362
  token.name,
323
363
  attrs,
324
- *parse_tokens(token.children["default"], context) if token.children else [],
364
+ parse_tokens(token.children["default"], context) if token.children else [],
325
365
  )
326
366
  )
327
367
  elif not token.name:
@@ -351,9 +391,9 @@ def parse(src: str, context: dict | None = None):
351
391
  def parse_content(source: str, _start: bool, _end: bool):
352
392
  source = unescape(source)
353
393
  if _start:
354
- source = re.sub(r"^\s*\n\s*", "", source, flags=re.MULTILINE)
394
+ source = space_pat1.sub("", source)
355
395
  if _end:
356
- source = re.sub(r"\s*\n\s*$", "", source, flags=re.MULTILINE)
396
+ source = space_pat2.sub("", source)
357
397
  push_text(source)
358
398
 
359
399
  tag_pat = tag_pat2 if context is not None else tag_pat1
File without changes
@@ -24,10 +24,16 @@ try:
24
24
  def encode(obj):
25
25
  return encoder.encode(obj).decode()
26
26
 
27
+ def encode_bytes(obj):
28
+ return encoder.encode(obj)
29
+
27
30
  except ImportError:
28
31
  import json
29
32
 
30
33
  def encode(obj):
31
34
  return json.dumps(obj, separators=(",", ":"), ensure_ascii=False)
32
35
 
36
+ def encode_bytes(obj):
37
+ return json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
38
+
33
39
  decode = json.loads