attenpy 0.2.0__tar.gz → 0.3.0__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.
Files changed (39) hide show
  1. {attenpy-0.2.0 → attenpy-0.3.0}/PKG-INFO +1 -1
  2. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/__init__.py +3 -3
  3. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/client.py +12 -4
  4. attenpy-0.3.0/attenpy/endpoints/__init__.py +6 -0
  5. attenpy-0.3.0/attenpy/endpoints/explores.py +73 -0
  6. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/endpoints/notices.py +10 -11
  7. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/endpoints/posts.py +38 -27
  8. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/endpoints/users.py +17 -9
  9. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/http.py +22 -30
  10. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/models/__init__.py +6 -3
  11. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/models/attachment.py +10 -4
  12. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/models/base.py +3 -3
  13. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/models/notice.py +28 -14
  14. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/models/post.py +9 -1
  15. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/models/user.py +3 -1
  16. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/pagination.py +2 -2
  17. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/payloads/__init__.py +6 -5
  18. attenpy-0.3.0/attenpy/payloads/explore.py +22 -0
  19. attenpy-0.3.0/attenpy/payloads/user.py +13 -0
  20. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/payloads/ws.py +0 -5
  21. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/ref.py +6 -6
  22. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/snowflake.py +6 -10
  23. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/utils.py +4 -0
  24. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/ws.py +5 -9
  25. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy.egg-info/PKG-INFO +1 -1
  26. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy.egg-info/SOURCES.txt +3 -0
  27. attenpy-0.3.0/pyproject.toml +72 -0
  28. attenpy-0.2.0/attenpy/endpoints/__init__.py +0 -5
  29. attenpy-0.2.0/pyproject.toml +0 -31
  30. {attenpy-0.2.0 → attenpy-0.3.0}/LICENSE +0 -0
  31. {attenpy-0.2.0 → attenpy-0.3.0}/README.md +0 -0
  32. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/exceptions.py +0 -0
  33. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/payloads/notice.py +0 -0
  34. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/payloads/post.py +0 -0
  35. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy/types.py +0 -0
  36. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy.egg-info/dependency_links.txt +0 -0
  37. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy.egg-info/requires.txt +0 -0
  38. {attenpy-0.2.0 → attenpy-0.3.0}/attenpy.egg-info/top_level.txt +0 -0
  39. {attenpy-0.2.0 → attenpy-0.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: attenpy
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: SDK for AttenAPI
5
5
  Author: AttenTeam
6
6
  License: MIT
@@ -2,6 +2,7 @@ from .client import Client
2
2
  from .exceptions import AttenpyException, HTTPException, InvalidResponseError
3
3
  from .models import (
4
4
  Attachment,
5
+ AttachmentCategory,
5
6
  Notice,
6
7
  NoticeKind,
7
8
  NoticeTarget,
@@ -13,18 +14,17 @@ from .models import (
13
14
  User,
14
15
  )
15
16
  from .payloads import (
16
- BotReadyPayload,
17
17
  NoticeUnreadCountPayload,
18
18
  ParentsPostPayload,
19
19
  )
20
20
  from .ref import UserRef
21
21
  from .snowflake import Snowflake
22
22
 
23
- __version__ = "0.2.0"
23
+ __version__ = "0.2.1"
24
24
  __all__ = [
25
25
  "AttenpyException",
26
26
  "Attachment",
27
- "BotReadyPayload",
27
+ "AttachmentCategory",
28
28
  "Client",
29
29
  "HTTPException",
30
30
  "InvalidResponseError",
@@ -1,6 +1,8 @@
1
1
  import asyncio
2
+ from collections.abc import Callable
3
+ from types import TracebackType
2
4
 
3
- from .endpoints import NoticeEndpoint, PostEndpoint, UserEndpoint
5
+ from .endpoints import ExploreEndpoint, NoticeEndpoint, PostEndpoint, UserEndpoint
4
6
  from .http import HTTPClient
5
7
  from .ws import EventHandler, WSClient
6
8
 
@@ -29,18 +31,19 @@ class Client:
29
31
  self.users = UserEndpoint(self)
30
32
  self.posts = PostEndpoint(self)
31
33
  self.notices = NoticeEndpoint(self)
34
+ self.explores = ExploreEndpoint(self)
32
35
 
33
36
  self._closed_event = asyncio.Event()
34
37
 
35
38
  # websocket
36
39
 
37
- def add_handler(self, event_name: str, func):
40
+ def add_handler(self, event_name: str, func: EventHandler):
38
41
  self.ws.add_handler(event_name, func)
39
42
 
40
43
  def remove_handler(self, event_name: str):
41
44
  self.ws.remove_handler(event_name)
42
45
 
43
- def on(self, event_name: str):
46
+ def on[T: EventHandler](self, event_name: str) -> Callable[[T], T]:
44
47
  return _EventHandlerRegister(self.ws, event_name)
45
48
 
46
49
  async def connect_ws(self, *, reconnect: bool = False) -> None:
@@ -74,5 +77,10 @@ class Client:
74
77
  async def __aenter__(self):
75
78
  return self
76
79
 
77
- async def __aexit__(self, exc_type, exc, tb):
80
+ async def __aexit__(
81
+ self,
82
+ exc_type: type[BaseException] | None,
83
+ exc: BaseException | None,
84
+ tb: TracebackType | None,
85
+ ) -> None:
78
86
  await self.close()
@@ -0,0 +1,6 @@
1
+ from .explores import ExploreEndpoint
2
+ from .notices import NoticeEndpoint
3
+ from .posts import PostEndpoint
4
+ from .users import UserEndpoint
5
+
6
+ __all__ = ["UserEndpoint", "PostEndpoint", "NoticeEndpoint", "ExploreEndpoint"]
@@ -0,0 +1,73 @@
1
+ from collections.abc import AsyncGenerator, Sequence
2
+ from datetime import datetime
3
+ from typing import TYPE_CHECKING, Unpack
4
+
5
+ from pydantic import TypeAdapter
6
+
7
+ from ..models import Post, PostVisibility
8
+ from ..pagination import (
9
+ PaginateOptions,
10
+ paginate,
11
+ )
12
+ from ..payloads import StatPayload, TrendPayload
13
+ from ..ref import UserRef
14
+ from ..utils import api_bool
15
+
16
+ if TYPE_CHECKING:
17
+ from ..client import Client
18
+
19
+ TREND_DATA_TA = TypeAdapter[list[TrendPayload]](list[TrendPayload])
20
+ STAT_DATA_TA = TypeAdapter[list[StatPayload]](list[StatPayload])
21
+ MIX_DATA_TA = TypeAdapter[list[Post]](list[Post])
22
+
23
+
24
+ class ExploreEndpoint:
25
+ def __init__(self, client: "Client"):
26
+ self.client = client
27
+
28
+ async def get_recent(self, **kw: Unpack[PaginateOptions]) -> AsyncGenerator[Post]:
29
+ async for data in paginate(self.client.http, "/explore/recent", **kw):
30
+ yield Post.model_validate(data)
31
+
32
+ async def get_following_post(self, **kw: Unpack[PaginateOptions]) -> AsyncGenerator[Post]:
33
+ async for data in paginate(self.client.http, "/explore/following", **kw):
34
+ yield Post.model_validate(data)
35
+
36
+ async def get_mix_post(self) -> AsyncGenerator[Post]:
37
+ for data in MIX_DATA_TA.validate_python((await self.client.http.get("/explore/mix")).data):
38
+ yield data
39
+
40
+ async def get_trend(self) -> AsyncGenerator[TrendPayload]:
41
+ for data in TREND_DATA_TA.validate_python(
42
+ (await self.client.http.get("/explore/trend")).data
43
+ ):
44
+ yield data
45
+
46
+ async def search_post(
47
+ self,
48
+ q: str,
49
+ *,
50
+ user: Sequence[UserRef | str] | None = None,
51
+ visibility: PostVisibility | None = None,
52
+ is_reply: bool | None = None,
53
+ before: datetime | str | None = None,
54
+ after: datetime | str | None = None,
55
+ **kw: Unpack[PaginateOptions],
56
+ ) -> AsyncGenerator[Post]:
57
+ params = dict[str, str | list[str]](q=q)
58
+ if user:
59
+ params["user"] = list(map(str, user))
60
+ if visibility:
61
+ params["visibility"] = str(visibility)
62
+ if is_reply is not None:
63
+ params["is_reply"] = api_bool(is_reply)
64
+ if before:
65
+ params["before"] = before.isoformat() if isinstance(before, datetime) else str(before)
66
+ if after:
67
+ params["after"] = after.isoformat() if isinstance(after, datetime) else str(after)
68
+ async for data in paginate(self.client.http, "/explore/search", params=params, **kw):
69
+ yield Post.model_validate(data)
70
+
71
+ async def get_stats(self) -> AsyncGenerator[StatPayload]:
72
+ for data in STAT_DATA_TA.validate_python((await self.client.http.get("/stats")).data):
73
+ yield data
@@ -1,7 +1,7 @@
1
- from collections.abc import AsyncIterator, Sequence
1
+ from collections.abc import AsyncGenerator, Sequence
2
2
  from typing import TYPE_CHECKING, Unpack
3
3
 
4
- from ..models import Notice
4
+ from ..models import Notice, Warn
5
5
  from ..models.notice import NoticeType
6
6
  from ..pagination import PaginateOptions, paginate
7
7
  from ..payloads import NoticeUnreadCountPayload
@@ -15,23 +15,22 @@ class NoticeEndpoint:
15
15
  self.client = client
16
16
 
17
17
  async def list(
18
- self,
19
- *,
20
- types: Sequence[NoticeType] | None = None,
21
- **kw: Unpack[PaginateOptions],
22
- ) -> AsyncIterator[Notice]:
18
+ self, *, types: Sequence[NoticeType] | None = None, **kw: Unpack[PaginateOptions]
19
+ ) -> AsyncGenerator[Notice]:
23
20
  params = None
24
21
  if types:
25
- params = {"type": list(dict.fromkeys(types))}
22
+ params = {"type": [i.value for i in set(types)]}
26
23
  async for data in paginate(self.client.http, "/notices", params=params, **kw):
27
24
  yield Notice.model_validate(data)
28
25
 
29
26
  async def read_up_to(self, notice: int | Notice):
30
- await self.client.http.put(
31
- "/notices/read-up-to", json={"notice_id": int(notice)}
32
- )
27
+ await self.client.http.put("/notices/read-up-to", json={"notice_id": int(notice)})
33
28
 
34
29
  async def get_unread_count(self) -> NoticeUnreadCountPayload:
35
30
  return NoticeUnreadCountPayload.model_validate(
36
31
  (await self.client.http.get("/notices/unread-count")).data
37
32
  )
33
+
34
+ async def list_warns(self, **kw: Unpack[PaginateOptions]) -> AsyncGenerator[Warn]:
35
+ async for data in paginate(self.client.http, "/warns", **kw):
36
+ yield Warn.model_validate(data)
@@ -1,6 +1,9 @@
1
- from typing import TYPE_CHECKING, AsyncIterator, Unpack
1
+ from collections.abc import AsyncGenerator
2
+ from typing import TYPE_CHECKING, Unpack
2
3
 
3
- from ..models import PartialPost, PartialUser, Post
4
+ from pydantic import TypeAdapter
5
+
6
+ from ..models import PartialPost, PartialUser, Post, PostVisibility
4
7
  from ..pagination import (
5
8
  PaginateOptions,
6
9
  paginate,
@@ -11,6 +14,8 @@ from ..utils import int_or_none
11
14
  if TYPE_CHECKING:
12
15
  from ..client import Client
13
16
 
17
+ HISTORY_DATA_TA = TypeAdapter[list[Post]](list[Post])
18
+
14
19
 
15
20
  class PostEndpoint:
16
21
  def __init__(self, client: "Client"):
@@ -20,18 +25,28 @@ class PostEndpoint:
20
25
  self,
21
26
  content: str,
22
27
  quote: int | PartialPost | None = None,
28
+ *,
29
+ visibility: PostVisibility,
23
30
  ) -> Post:
24
31
  return Post.model_validate(
25
32
  (
26
33
  await self.client.http.post(
27
- "/posts", json={"content": content, "quote": int_or_none(quote)}
34
+ "/posts",
35
+ json={
36
+ "content": content,
37
+ "quote_id": int_or_none(quote),
38
+ "visibility": visibility,
39
+ },
28
40
  )
29
41
  ).data
30
42
  )
31
43
 
32
44
  async def get(self, post: int | PartialPost) -> Post:
45
+ return Post.model_validate((await self.client.http.get(f"/posts/{int(post)}")).data)
46
+
47
+ async def edit(self, post: int | PartialPost, content: str) -> Post:
33
48
  return Post.model_validate(
34
- (await self.client.http.get(f"/posts/{int(post)}")).data
49
+ (await self.client.http.patch(f"/posts/{int(post)}", json={"content": content})).data
35
50
  )
36
51
 
37
52
  async def reply(
@@ -39,12 +54,18 @@ class PostEndpoint:
39
54
  parent: int | PartialPost,
40
55
  content: str,
41
56
  quote: int | PartialPost | None = None,
57
+ *,
58
+ visibility: PostVisibility,
42
59
  ) -> Post:
43
60
  return Post.model_validate(
44
61
  (
45
62
  await self.client.http.post(
46
63
  f"/posts/{int(parent)}/reply",
47
- json={"content": content, "quote": int_or_none(quote)},
64
+ json={
65
+ "content": content,
66
+ "quote_id": int_or_none(quote),
67
+ "visibility": visibility,
68
+ },
48
69
  )
49
70
  ).data
50
71
  )
@@ -65,49 +86,39 @@ class PostEndpoint:
65
86
  await self.client.http.delete(f"/posts/{int(post)}/bookmark")
66
87
 
67
88
  async def repost(self, post: int | PartialPost) -> Post:
68
- return Post.model_validate(
69
- (await self.client.http.post(f"/posts/{int(post)}/repost")).data
70
- )
89
+ return Post.model_validate((await self.client.http.post(f"/posts/{int(post)}/repost")).data)
71
90
 
72
91
  async def unrepost(self, post: int | PartialPost):
73
92
  await self.client.http.delete(f"/posts/{int(post)}/repost")
74
93
 
75
94
  async def get_loves(
76
95
  self, post: int | PartialPost, **kw: Unpack[PaginateOptions]
77
- ) -> AsyncIterator[PartialUser]:
96
+ ) -> AsyncGenerator[PartialUser]:
78
97
  async for data in paginate(self.client.http, f"/posts/{int(post)}/loves", **kw):
79
98
  yield PartialUser.model_validate(data)
80
99
 
81
- async def get_history(
82
- self, post: int | PartialPost, **kw: Unpack[PaginateOptions]
83
- ) -> AsyncIterator[Post]:
84
- async for data in paginate(
85
- self.client.http, f"/posts/{int(post)}/history", **kw
100
+ async def get_history(self, post: int | PartialPost) -> AsyncGenerator[Post]:
101
+ for data in HISTORY_DATA_TA.validate_python(
102
+ (await self.client.http.get(f"/posts/{int(post)}/history")).data
86
103
  ):
87
- yield Post.model_validate(data)
104
+ yield data
88
105
 
89
106
  async def get_quotes(
90
107
  self, post: int | PartialPost, **kw: Unpack[PaginateOptions]
91
- ) -> AsyncIterator[Post]:
92
- async for data in paginate(
93
- self.client.http, f"/posts/{int(post)}/quotes", **kw
94
- ):
108
+ ) -> AsyncGenerator[Post]:
109
+ async for data in paginate(self.client.http, f"/posts/{int(post)}/quotes", **kw):
95
110
  yield Post.model_validate(data)
96
111
 
97
112
  async def get_replies(
98
113
  self, post: int | PartialPost, **kw: Unpack[PaginateOptions]
99
- ) -> AsyncIterator[Post]:
100
- async for data in paginate(
101
- self.client.http, f"/posts/{int(post)}/replies", **kw
102
- ):
114
+ ) -> AsyncGenerator[Post]:
115
+ async for data in paginate(self.client.http, f"/posts/{int(post)}/replies", **kw):
103
116
  yield Post.model_validate(data)
104
117
 
105
118
  async def get_reposts(
106
119
  self, post: int | PartialPost, **kw: Unpack[PaginateOptions]
107
- ) -> AsyncIterator[Post]:
108
- async for data in paginate(
109
- self.client.http, f"/posts/{int(post)}/reposts", **kw
110
- ):
120
+ ) -> AsyncGenerator[Post]:
121
+ async for data in paginate(self.client.http, f"/posts/{int(post)}/reposts", **kw):
111
122
  yield Post.model_validate(data)
112
123
 
113
124
  async def get_parents(self, post: int | PartialPost) -> ParentsPostPayload:
@@ -1,5 +1,8 @@
1
+ from collections.abc import AsyncGenerator
1
2
  from types import EllipsisType
2
- from typing import TYPE_CHECKING, AsyncIterator, Unpack
3
+ from typing import TYPE_CHECKING, Unpack
4
+
5
+ from attenpy.payloads import BanStatusPayload
3
6
 
4
7
  from ..models import Attachment, PartialPost, PartialUser, Post, User
5
8
  from ..pagination import (
@@ -59,48 +62,53 @@ class UserEndpoint:
59
62
 
60
63
  async def get_followers(
61
64
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
62
- ) -> AsyncIterator[PartialUser]:
65
+ ) -> AsyncGenerator[PartialUser]:
63
66
  async for data in paginate(self.client.http, f"/users/{user}/followers", **kw):
64
67
  yield PartialUser.model_validate(data)
65
68
 
66
69
  async def get_following(
67
70
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
68
- ) -> AsyncIterator[PartialUser]:
71
+ ) -> AsyncGenerator[PartialUser]:
69
72
  async for data in paginate(self.client.http, f"/users/{user}/following", **kw):
70
73
  yield PartialUser.model_validate(data)
71
74
 
72
75
  async def get_mutes(
73
76
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
74
- ) -> AsyncIterator[PartialUser]:
77
+ ) -> AsyncGenerator[PartialUser]:
75
78
  async for data in paginate(self.client.http, f"/users/{user}/mutes", **kw):
76
79
  yield PartialUser.model_validate(data)
77
80
 
78
81
  async def get_posts(
79
82
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
80
- ) -> AsyncIterator[Post]:
83
+ ) -> AsyncGenerator[Post]:
81
84
  async for data in paginate(self.client.http, f"/users/{user}/posts", **kw):
82
85
  yield Post.model_validate(data)
83
86
 
84
87
  async def get_medias(
85
88
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
86
- ) -> AsyncIterator[Post]:
89
+ ) -> AsyncGenerator[Post]:
87
90
  async for data in paginate(self.client.http, f"/users/{user}/medias", **kw):
88
91
  yield Post.model_validate(data)
89
92
 
90
93
  async def get_loves(
91
94
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
92
- ) -> AsyncIterator[Post]:
95
+ ) -> AsyncGenerator[Post]:
93
96
  async for data in paginate(self.client.http, f"/users/{user}/loves", **kw):
94
97
  yield Post.model_validate(data)
95
98
 
96
99
  async def get_bookmarks(
97
100
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
98
- ) -> AsyncIterator[Post]:
101
+ ) -> AsyncGenerator[Post]:
99
102
  async for data in paginate(self.client.http, f"/users/{user}/bookmarks", **kw):
100
103
  yield Post.model_validate(data)
101
104
 
102
105
  async def get_reposts(
103
106
  self, user: UserRef | str, **kw: Unpack[PaginateOptions]
104
- ) -> AsyncIterator[Post]:
107
+ ) -> AsyncGenerator[Post]:
105
108
  async for data in paginate(self.client.http, f"/users/{user}/reposts", **kw):
106
109
  yield Post.model_validate(data)
110
+
111
+ async def ban_status(self, user: UserRef | str) -> BanStatusPayload:
112
+ return BanStatusPayload.model_validate(
113
+ (await self.client.http.get(f"/users/{user}/ban")).data
114
+ )
@@ -1,5 +1,6 @@
1
1
  import asyncio
2
- from typing import Any, Optional, TypedDict, Unpack
2
+ from types import TracebackType
3
+ from typing import Any, TypedDict, Unpack, cast
3
4
 
4
5
  import aiohttp
5
6
  from pydantic import ValidationError
@@ -17,14 +18,14 @@ class HTTPClient:
17
18
  def __init__(self, base_url: str, token: str | None):
18
19
  self.base_url = base_url.rstrip("/")
19
20
  self.token = token
20
- self._session: Optional[aiohttp.ClientSession] = None
21
+ self._session: aiohttp.ClientSession | None = None
21
22
  self._closed: bool = False
22
23
 
23
24
  async def _get_session(self) -> aiohttp.ClientSession:
24
25
  if self.closed:
25
26
  raise RuntimeError("Session is closed")
26
27
  if self._session is None or self._session.closed:
27
- headers = {}
28
+ headers = dict[str, str]()
28
29
  if self.token:
29
30
  headers["Authorization"] = "Bearer " + self.token
30
31
  self._session = aiohttp.ClientSession(headers=headers)
@@ -40,8 +41,8 @@ class HTTPClient:
40
41
  if payload["ok"] is False:
41
42
  return ErrorResponse.model_validate(payload)
42
43
  if "page" in payload:
43
- return ListResponse.model_validate(payload)
44
- return SuccessResponse.model_validate(payload)
44
+ return ListResponse[Any].model_validate(payload)
45
+ return SuccessResponse[Any].model_validate(payload)
45
46
  except ValidationError as exc:
46
47
  raise InvalidResponseError(payload) from exc
47
48
 
@@ -64,42 +65,28 @@ class HTTPClient:
64
65
  if isinstance(retry_after, int | float) and retry_after >= 0:
65
66
  await asyncio.sleep(retry_after)
66
67
  continue
67
- raise HTTPException(
68
- resp.status, data
69
- ) # TODO statusごとにクラス分ける
68
+ raise HTTPException(resp.status, data) # TODO statusごとにクラス分ける
70
69
  return data
71
70
 
72
- async def get(
73
- self, path: str, **kw: Unpack[RequestOptions]
74
- ) -> SuccessResponse[Any]:
71
+ async def get(self, path: str, **kw: Unpack[RequestOptions]) -> SuccessResponse[Any]:
75
72
  return await self._request("GET", path, **kw)
76
73
 
77
- async def get_list(
78
- self, path: str, **kw: Unpack[RequestOptions]
79
- ) -> ListResponse[Any]:
74
+ async def get_list(self, path: str, **kw: Unpack[RequestOptions]) -> ListResponse[Any]:
80
75
  data = await self._request("GET", path, **kw)
81
- if isinstance(data, SuccessResponse):
82
- raise InvalidResponseError(data.model_dump(mode="python"))
83
- return data
76
+ if isinstance(data, ListResponse):
77
+ return cast(ListResponse[Any], data)
78
+ raise InvalidResponseError(data.model_dump(mode="python"))
84
79
 
85
- async def post(
86
- self, path: str, **kw: Unpack[RequestOptions]
87
- ) -> SuccessResponse[Any]:
80
+ async def post(self, path: str, **kw: Unpack[RequestOptions]) -> SuccessResponse[Any]:
88
81
  return await self._request("POST", path, **kw)
89
82
 
90
- async def put(
91
- self, path: str, **kw: Unpack[RequestOptions]
92
- ) -> SuccessResponse[Any]:
83
+ async def put(self, path: str, **kw: Unpack[RequestOptions]) -> SuccessResponse[Any]:
93
84
  return await self._request("PUT", path, **kw)
94
85
 
95
- async def patch(
96
- self, path: str, **kw: Unpack[RequestOptions]
97
- ) -> SuccessResponse[Any]:
86
+ async def patch(self, path: str, **kw: Unpack[RequestOptions]) -> SuccessResponse[Any]:
98
87
  return await self._request("PATCH", path, **kw)
99
88
 
100
- async def delete(
101
- self, path: str, **kw: Unpack[RequestOptions]
102
- ) -> SuccessResponse[Any]:
89
+ async def delete(self, path: str, **kw: Unpack[RequestOptions]) -> SuccessResponse[Any]:
103
90
  return await self._request("DELETE", path, **kw)
104
91
 
105
92
  @property
@@ -114,5 +101,10 @@ class HTTPClient:
114
101
  async def __aenter__(self):
115
102
  return self
116
103
 
117
- async def __aexit__(self, exc_type, exc, tb):
104
+ async def __aexit__(
105
+ self,
106
+ exc_type: type[BaseException] | None,
107
+ exc: BaseException | None,
108
+ tb: TracebackType | None,
109
+ ) -> None:
118
110
  await self.close()
@@ -1,7 +1,7 @@
1
- from .attachment import Attachment, PartialAttachment
1
+ from .attachment import Attachment, AttachmentCategory, PartialAttachment
2
2
  from .base import CursorPage, ErrorResponse, ListResponse, SuccessResponse
3
- from .notice import Notice, NoticeKind, NoticeTarget, NoticeType
4
- from .post import PartialPost, Post
3
+ from .notice import Notice, NoticeKind, NoticeTarget, NoticeType, Warn
4
+ from .post import PartialPost, Post, PostVisibility
5
5
  from .user import PartialUser, User
6
6
 
7
7
  Notice.model_rebuild()
@@ -12,6 +12,7 @@ User.model_rebuild()
12
12
 
13
13
  __all__ = [
14
14
  "Attachment",
15
+ "AttachmentCategory",
15
16
  "CursorPage",
16
17
  "ErrorResponse",
17
18
  "PartialAttachment",
@@ -25,4 +26,6 @@ __all__ = [
25
26
  "Post",
26
27
  "SuccessResponse",
27
28
  "User",
29
+ "PostVisibility",
30
+ "Warn",
28
31
  ]
@@ -1,11 +1,19 @@
1
1
  from datetime import datetime
2
- from typing import Literal
2
+ from enum import StrEnum, auto
3
3
 
4
4
  from pydantic import BaseModel
5
5
 
6
6
  from ..snowflake import Snowflake
7
7
 
8
8
 
9
+ class AttachmentCategory(StrEnum):
10
+ ICON = auto()
11
+ BANNER = auto()
12
+ POST_ATTACHMENT = auto()
13
+ GROUP_ICON = auto()
14
+ CHAT_ATTACHMENT = auto()
15
+
16
+
9
17
  class PartialAttachment(BaseModel):
10
18
  url: str
11
19
 
@@ -13,9 +21,7 @@ class PartialAttachment(BaseModel):
13
21
  class Attachment(BaseModel):
14
22
  id: int
15
23
  url: str
16
- category: Literal[
17
- "icon", "banner", "post_attachment", "group_icon", "chat_attachment"
18
- ]
24
+ category: AttachmentCategory
19
25
  mime: str
20
26
  deleted: bool
21
27
 
@@ -1,4 +1,4 @@
1
- from typing import Any, Generic, Literal, TypeVar
1
+ from typing import Any, Literal, TypeVar
2
2
 
3
3
  from pydantic import BaseModel, field_validator
4
4
 
@@ -22,7 +22,7 @@ class RequestMeta(BaseModel):
22
22
  return _normalize_optional_snowflake(value)
23
23
 
24
24
 
25
- class SuccessResponse(BaseModel, Generic[T]):
25
+ class SuccessResponse[T](BaseModel):
26
26
  ok: Literal[True]
27
27
  meta: RequestMeta
28
28
  data: T
@@ -42,7 +42,7 @@ class CursorPage(BaseModel):
42
42
  return _normalize_optional_snowflake(value)
43
43
 
44
44
 
45
- class ListResponse(SuccessResponse[list[T]], Generic[T]):
45
+ class ListResponse[T](SuccessResponse[list[T]]):
46
46
  page: CursorPage
47
47
 
48
48
 
@@ -1,5 +1,6 @@
1
1
  from datetime import datetime
2
- from typing import TYPE_CHECKING, Literal, TypeAlias
2
+ from enum import StrEnum, auto
3
+ from typing import TYPE_CHECKING
3
4
 
4
5
  from pydantic import BaseModel
5
6
 
@@ -8,20 +9,26 @@ from ..snowflake import Snowflake
8
9
  if TYPE_CHECKING:
9
10
  from .user import PartialUser
10
11
 
11
- NoticeType: TypeAlias = Literal[
12
- "welcome",
13
- "login",
14
- "warn",
15
- "follow",
16
- "mention",
17
- "reply",
18
- "quote",
19
- "repost",
20
- "love",
21
- "invite_chat",
22
- ]
23
12
 
24
- NoticeKind: TypeAlias = Literal["session", "post", "chat", "warn"]
13
+ class NoticeType(StrEnum):
14
+ WELCOME = auto()
15
+ LOGIN = auto()
16
+ WARN = auto()
17
+ FOLLOW = auto()
18
+ MENTION = auto()
19
+ REPLY = auto()
20
+ QUOTE = auto()
21
+ REPOST = auto()
22
+ LOVE = auto()
23
+ INVITE_CHAT = auto()
24
+ ACCESS_REQUEST = auto()
25
+
26
+
27
+ class NoticeKind(StrEnum):
28
+ SESSION = auto()
29
+ POST = auto()
30
+ CHAT = auto()
31
+ WARN = auto()
25
32
 
26
33
 
27
34
  class NoticeTarget(BaseModel):
@@ -48,3 +55,10 @@ class Notice(BaseModel):
48
55
  @property
49
56
  def created_at(self) -> datetime:
50
57
  return Snowflake(self.id).datetime
58
+
59
+
60
+ class Warn(BaseModel):
61
+ id: int
62
+ user_id: int
63
+ kind: int
64
+ content: str
@@ -1,4 +1,5 @@
1
1
  from datetime import datetime
2
+ from enum import StrEnum, auto
2
3
  from typing import TYPE_CHECKING
3
4
 
4
5
  from pydantic import BaseModel
@@ -10,6 +11,11 @@ if TYPE_CHECKING:
10
11
  from .user import PartialUser
11
12
 
12
13
 
14
+ class PostVisibility(StrEnum):
15
+ PUBLIC = auto()
16
+ LOCKED = auto()
17
+
18
+
13
19
  class PartialPost(BaseModel):
14
20
  id: int
15
21
  author_id: int
@@ -17,11 +23,13 @@ class PartialPost(BaseModel):
17
23
  content_md: str
18
24
  parent_id: int | None
19
25
  target_history_id: int | None
20
- current_history_id: int
26
+ current_history_id: int | None
21
27
  quote_id: int | None
22
28
  root_id: int | None
23
29
  is_repost: bool
24
30
  is_edited: bool
31
+ visibility: PostVisibility
32
+ is_hidden: bool
25
33
  deleted: bool
26
34
  attachments: list["Attachment"]
27
35
 
@@ -21,6 +21,7 @@ class PartialUser(BaseModel):
21
21
  is_muted: bool | None
22
22
  is_following: bool | None = None
23
23
  is_followed: bool | None = None
24
+ has_post_access: bool | None = None
24
25
 
25
26
  def __int__(self) -> int:
26
27
  return self.id
@@ -35,8 +36,9 @@ class PartialUser(BaseModel):
35
36
 
36
37
 
37
38
  class User(PartialUser):
38
- scratch_id: int
39
+ scratch_id: int | None
39
40
  bio: str
41
+ banner: "Attachment | None"
40
42
  pinned: "Post | None"
41
43
  followers_count: int
42
44
  following_count: int
@@ -1,4 +1,4 @@
1
- from collections.abc import AsyncIterator
1
+ from collections.abc import AsyncGenerator
2
2
  from typing import Any, Literal, TypedDict, TypeVar, Unpack
3
3
 
4
4
  from .http import HTTPClient
@@ -24,7 +24,7 @@ async def paginate(
24
24
  *,
25
25
  params: dict[str, Any] | None = None,
26
26
  **kw: Unpack[PaginateOptions],
27
- ) -> AsyncIterator:
27
+ ) -> AsyncGenerator[Any]:
28
28
  params = (params and params.copy()) or {}
29
29
  params["order"] = kw.get("order", PAGINATE_ORDER_DEFAULT)
30
30
  if "cursor" in kw:
@@ -1,13 +1,14 @@
1
+ from .explore import StatPayload, TrendPayload
1
2
  from .notice import NoticeUnreadCountPayload
2
3
  from .post import ParentsPostPayload
3
- from .ws import (
4
- BotReadyPayload,
5
- WsTokenPayload,
6
- )
4
+ from .user import BanStatusPayload
5
+ from .ws import WsTokenPayload
7
6
 
8
7
  __all__ = [
9
8
  "ParentsPostPayload",
10
9
  "NoticeUnreadCountPayload",
11
10
  "WsTokenPayload",
12
- "BotReadyPayload",
11
+ "TrendPayload",
12
+ "StatPayload",
13
+ "BanStatusPayload",
13
14
  ]
@@ -0,0 +1,22 @@
1
+ from datetime import date
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class TrendPayload(BaseModel):
7
+ tag: str
8
+ user_count: int
9
+ post_count: int
10
+
11
+
12
+ class StatPayload(BaseModel):
13
+ date: date
14
+ total_posts: int
15
+ total_replies: int
16
+ total_loves: int
17
+ total_reposts: int
18
+ total_users: int
19
+ total_notices: int
20
+ total_chat_channels: int
21
+ total_chat_messages: int
22
+ total_requests: int
@@ -0,0 +1,13 @@
1
+ from datetime import datetime
2
+
3
+ from pydantic import BaseModel
4
+
5
+ from attenpy.models import Warn
6
+
7
+
8
+ class BanStatusPayload(BaseModel):
9
+ is_banned: bool
10
+ banned_at: datetime | None
11
+ unbanned_at: datetime | None
12
+ ban_warn: Warn | None
13
+ recent_warns: list[Warn]
@@ -5,8 +5,3 @@ from pydantic import BaseModel
5
5
 
6
6
  class WsTokenPayload(BaseModel):
7
7
  token: str
8
-
9
-
10
- class BotReadyPayload(BaseModel):
11
- bot_id: int
12
- owner_user_id: int
@@ -1,5 +1,5 @@
1
1
  from dataclasses import dataclass
2
- from typing import ClassVar, Literal, Union
2
+ from typing import ClassVar, Literal
3
3
 
4
4
 
5
5
  @dataclass(frozen=True, kw_only=True)
@@ -27,11 +27,11 @@ class UserRef:
27
27
  @property
28
28
  def value(
29
29
  self,
30
- ) -> Union[
31
- tuple[Literal["username"], str],
32
- tuple[Literal["user_id"], int],
33
- tuple[Literal["me"], Literal[True]],
34
- ]:
30
+ ) -> (
31
+ tuple[Literal["username"], str]
32
+ | tuple[Literal["user_id"], int]
33
+ | tuple[Literal["me"], Literal[True]]
34
+ ):
35
35
  if self.username is not None:
36
36
  return "username", self.username
37
37
  elif self.user_id is not None:
@@ -22,16 +22,14 @@ class Snowflake:
22
22
  self.value: Final[int] = value
23
23
 
24
24
  @classmethod
25
- def parse(cls, value: int | str | "Snowflake") -> Self:
25
+ def parse(cls, value: int | str | Snowflake) -> Self:
26
26
  if isinstance(value, Snowflake):
27
27
  return cls(value.value)
28
-
29
- if isinstance(value, int):
28
+ elif isinstance(value, int):
30
29
  if 0 <= value <= MAX_SNOWFLAKE:
31
30
  return cls(value)
32
31
  raise ValueError(f"snowflake must be between 0 and {MAX_SNOWFLAKE}")
33
-
34
- if isinstance(value, str):
32
+ elif isinstance(value, str):
35
33
  text = value.strip()
36
34
  if not text.isdecimal():
37
35
  raise ValueError("snowflake must be a decimal string")
@@ -39,8 +37,8 @@ class Snowflake:
39
37
  if 0 <= parsed <= MAX_SNOWFLAKE:
40
38
  return cls(parsed)
41
39
  raise ValueError(f"snowflake must be between 0 and {MAX_SNOWFLAKE}")
42
-
43
- raise TypeError("snowflake must be an integer or decimal string")
40
+ else:
41
+ raise TypeError("snowflake must be an integer or decimal string")
44
42
 
45
43
  @classmethod
46
44
  def from_datetime(cls, dt: datetime, *, is_max: bool = False) -> Self:
@@ -49,9 +47,7 @@ class Snowflake:
49
47
 
50
48
  if is_max:
51
49
  return cls(
52
- (offset_ms << TIMESTAMP_SHIFT)
53
- | (MAX_WORKER_ID << WORKER_ID_SHIFT)
54
- | MAX_SEQUENCE
50
+ (offset_ms << TIMESTAMP_SHIFT) | (MAX_WORKER_ID << WORKER_ID_SHIFT) | MAX_SEQUENCE
55
51
  )
56
52
  return cls(offset_ms << TIMESTAMP_SHIFT)
57
53
 
@@ -3,3 +3,7 @@ from typing import Any
3
3
 
4
4
  def int_or_none(obj: Any) -> int | None:
5
5
  return None if obj is None else int(obj)
6
+
7
+
8
+ def api_bool(val: bool) -> str:
9
+ return "1" if val else "0"
@@ -1,20 +1,17 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import asyncio
4
- from collections.abc import Callable
4
+ from collections.abc import Callable, Coroutine
5
5
  from contextlib import suppress
6
6
  from json import JSONDecodeError
7
- from typing import TYPE_CHECKING, Any, Coroutine
7
+ from typing import TYPE_CHECKING, Any, cast
8
8
  from urllib.parse import urlencode, urlsplit, urlunsplit
9
9
 
10
10
  import aiohttp
11
11
  from pydantic import BaseModel
12
12
 
13
13
  from .models import Notice
14
- from .payloads import (
15
- BotReadyPayload,
16
- WsTokenPayload,
17
- )
14
+ from .payloads import WsTokenPayload
18
15
  from .ref import UserRef
19
16
 
20
17
  if TYPE_CHECKING:
@@ -23,13 +20,12 @@ if TYPE_CHECKING:
23
20
  EventHandler = Callable[[Any], Coroutine[Any, Any, Any]]
24
21
 
25
22
  EVENT_PAYLOAD_MODELS: dict[str, type[BaseModel]] = {
26
- "bot.ready": BotReadyPayload,
27
23
  "notice.created": Notice,
28
24
  }
29
25
 
30
26
 
31
27
  class WSClient:
32
- def __init__(self, client: "Client"):
28
+ def __init__(self, client: Client):
33
29
  self.client = client
34
30
  self._handlers: dict[str, EventHandler] = {}
35
31
  self._task: asyncio.Task[None] | None = None
@@ -124,7 +120,7 @@ class WSClient:
124
120
  continue
125
121
 
126
122
  try:
127
- payload = message.json()
123
+ payload = cast(dict[str, str], message.json())
128
124
  except (TypeError, JSONDecodeError):
129
125
  continue
130
126
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: attenpy
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: SDK for AttenAPI
5
5
  Author: AttenTeam
6
6
  License: MIT
@@ -17,6 +17,7 @@ attenpy.egg-info/dependency_links.txt
17
17
  attenpy.egg-info/requires.txt
18
18
  attenpy.egg-info/top_level.txt
19
19
  attenpy/endpoints/__init__.py
20
+ attenpy/endpoints/explores.py
20
21
  attenpy/endpoints/notices.py
21
22
  attenpy/endpoints/posts.py
22
23
  attenpy/endpoints/users.py
@@ -27,6 +28,8 @@ attenpy/models/notice.py
27
28
  attenpy/models/post.py
28
29
  attenpy/models/user.py
29
30
  attenpy/payloads/__init__.py
31
+ attenpy/payloads/explore.py
30
32
  attenpy/payloads/notice.py
31
33
  attenpy/payloads/post.py
34
+ attenpy/payloads/user.py
32
35
  attenpy/payloads/ws.py
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "attenpy"
7
+ version = "0.3.0"
8
+ description = "SDK for AttenAPI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ dependencies = [
12
+ "aiohttp>=3.9.0",
13
+ "pydantic>=2.0.0",
14
+ ]
15
+ license = { text = "MIT" }
16
+ authors = [
17
+ { name = "AttenTeam" }
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://atten.win/"
22
+ Repository = "https://github.com/attensns/attenpy"
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "pytest>=7.0.0",
27
+ "pytest-asyncio>=0.21.0",
28
+ ]
29
+
30
+ [tool.setuptools.packages.find]
31
+ include = ["attenpy*"]
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "basedpyright>=1.40.1",
36
+ "ruff>=0.16.8",
37
+ ]
38
+
39
+ [tool.ruff]
40
+ target-version = "py313"
41
+ line-length = 100
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E","F","W","I","UP","B","SIM"]
45
+ preview = true
46
+
47
+ [tool.ruff.format]
48
+ quote-style = "double"
49
+ indent-style = "space"
50
+
51
+
52
+ [tool.basedpyright]
53
+ pythonVersion = "3.13"
54
+ venvPath = "."
55
+ venv = ".venv"
56
+
57
+ include = ["attenpy"]
58
+ exclude = [
59
+ "**/__pycache__",
60
+ ".venv",
61
+ "build",
62
+ "dist",
63
+ ]
64
+
65
+ typeCheckingMode = "strict"
66
+
67
+ reportUnusedCallResult = false
68
+ reportMissingTypeStubs = false
69
+ reportImplicitOverride = false
70
+ reportPrivateUsage = false
71
+ reportUnnecessaryCast = false
72
+ reportUnnecessaryIsInstance = false
@@ -1,5 +0,0 @@
1
- from .notices import NoticeEndpoint
2
- from .posts import PostEndpoint
3
- from .users import UserEndpoint
4
-
5
- __all__ = ["UserEndpoint", "PostEndpoint", "NoticeEndpoint"]
@@ -1,31 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools>=61.0"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "attenpy"
7
- version = "0.2.0"
8
- description = "SDK for AttenAPI"
9
- readme = "README.md"
10
- requires-python = ">=3.12"
11
- dependencies = [
12
- "aiohttp>=3.9.0",
13
- "pydantic>=2.0.0",
14
- ]
15
- license = { text = "MIT" }
16
- authors = [
17
- { name = "AttenTeam" }
18
- ]
19
-
20
- [project.urls]
21
- Homepage = "https://atten.win/"
22
- Repository = "https://github.com/attensns/attenpy"
23
-
24
- [project.optional-dependencies]
25
- dev = [
26
- "pytest>=7.0.0",
27
- "pytest-asyncio>=0.21.0",
28
- ]
29
-
30
- [tool.setuptools.packages.find]
31
- include = ["attenpy*"]
File without changes
File without changes
File without changes
File without changes
File without changes