From 5ebcdb1ad581264b0bd23cf6baa5dbdd72388dca Mon Sep 17 00:00:00 2001 From: firedotguy Date: Sat, 7 Feb 2026 23:20:00 +0300 Subject: [PATCH] feat: add get replies and get_user_posts --- itd/client.py | 58 +++++++++++++++++++++++++++++++++++++++--- itd/enums.py | 1 + itd/exceptions.py | 6 ++++- itd/routes/comments.py | 3 +++ itd/routes/posts.py | 3 +++ pyproject.toml | 2 +- setup.py | 2 +- 7 files changed, 69 insertions(+), 6 deletions(-) diff --git a/itd/client.py b/itd/client.py index 2b5deaa..8f1f4f4 100644 --- a/itd/client.py +++ b/itd/client.py @@ -8,10 +8,10 @@ from requests.exceptions import ConnectionError, HTTPError from itd.routes.users import get_user, update_profile, follow, unfollow, get_followers, get_following, update_privacy from itd.routes.etc import get_top_clans, get_who_to_follow, get_platform_status -from itd.routes.comments import get_comments, add_comment, delete_comment, like_comment, unlike_comment, add_reply_comment +from itd.routes.comments import get_comments, add_comment, delete_comment, like_comment, unlike_comment, add_reply_comment, get_replies from itd.routes.hashtags import get_hashtags, get_posts_by_hashtag from itd.routes.notifications import get_notifications, mark_as_read, mark_all_as_read, get_unread_notifications_count -from itd.routes.posts import create_post, get_posts, get_post, edit_post, delete_post, pin_post, repost, view_post, get_liked_posts, restore_post, like_post, unlike_post +from itd.routes.posts import create_post, get_posts, get_post, edit_post, delete_post, pin_post, repost, view_post, get_liked_posts, restore_post, like_post, unlike_post, get_user_posts from itd.routes.reports import report from itd.routes.search import search from itd.routes.files import upload_file @@ -36,7 +36,7 @@ from itd.request import set_cookies from itd.exceptions import ( NoCookie, NoAuthData, SamePassword, InvalidOldPassword, NotFound, ValidationError, UserBanned, PendingRequestExists, Forbidden, UsernameTaken, CantFollowYourself, Unauthorized, - CantRepostYourPost, AlreadyReposted, AlreadyReported, TooLarge, PinNotOwned + CantRepostYourPost, AlreadyReposted, AlreadyReported, TooLarge, PinNotOwned, NoContent ) @@ -426,6 +426,8 @@ class Client: raise NotFound('User') if res.status_code == 422 and 'found' in res.json(): raise ValidationError(*list(res.json()['found'].items())[0]) + if res.json().get('error', {}).get('code') == 'VALIDATION_ERROR': + raise NoContent() if res.json().get('error', {}).get('code') == 'NOT_FOUND': raise NotFound('Comment') res.raise_for_status() @@ -458,6 +460,32 @@ class Client: return [Comment.model_validate(comment) for comment in data['comments']], Pagination(page=(cursor // limit) or 1, limit=limit, total=data['total'], hasMore=data['hasMore'], nextCursor=None) + @refresh_on_error + def get_replies(self, comment_id: UUID, limit: int = 50, page: int = 1, sort: str = 'oldest') -> tuple[list[Comment], Pagination]: + """Получить список комментариев + + Args: + comment_id (UUID): UUID поста + limit (int, optional): Лимит. Defaults to 50. + page (int, optional): Курсор (сколько пропустить). Defaults to 1. + sort (str, optional): Сортировка. Defaults to 'oldesr'. + + Raises: + NotFound: Пост не найден + + Returns: + list[Comment]: Список комментариев + Pagination: Пагинация + """ + res = get_replies(self.token, comment_id, page, limit, sort) + if res.json().get('error', {}).get('code') == 'NOT_FOUND': + raise NotFound('Comment') + res.raise_for_status() + data = res.json()['data'] + + return [Comment.model_validate(comment) for comment in data['replies']], Pagination.model_validate(data['pagination']) + + @refresh_on_error def like_comment(self, id: UUID) -> int: """Лайкнуть комментарий @@ -801,6 +829,30 @@ class Client: raise NotFound('Post') res.raise_for_status() + @refresh_on_error + def get_user_posts(self, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None) -> tuple[list[Post], LikedPostsPagintaion]: + """Получить список постов пользователя + + Args: + username_or_id (str | UUID): UUID или username пользователя + limit (int, optional): Лимит. Defaults to 20. + cursor (datetime | None, optional): Сдвиг (next_cursor). Defaults to None. + + Raises: + NotFound: Пользователь не найден + + Returns: + list[Post]: Список постов + LikedPostsPagintaion: Пагинация + """ + res = get_user_posts(self.token, username_or_id, limit, cursor) + if res.json().get('error', {}).get('code') == 'NOT_FOUND': + raise NotFound('User') + res.raise_for_status() + data = res.json()['data'] + + return [Post.model_validate(post) for post in data['posts']], LikedPostsPagintaion.model_validate(data['pagination']) + @refresh_on_error def get_liked_posts(self, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None) -> tuple[list[Post], LikedPostsPagintaion]: """Получить список лайкнутых постов пользователя diff --git a/itd/enums.py b/itd/enums.py index acf2d13..a4255aa 100644 --- a/itd/enums.py +++ b/itd/enums.py @@ -28,6 +28,7 @@ class AttachType(Enum): AUDIO = 'audio' IMAGE = 'image' VIDEO = 'video' + FILE = 'file' class PostsTab(Enum): FOLLOWING = 'following' diff --git a/itd/exceptions.py b/itd/exceptions.py index 121929a..1d4b894 100644 --- a/itd/exceptions.py +++ b/itd/exceptions.py @@ -98,4 +98,8 @@ class PinNotOwned(Exception): def __init__(self, pin: str) -> None: self.pin = pin def __str__(self): - return f'You do not own "{self.pin}" pin' \ No newline at end of file + return f'You do not own "{self.pin}" pin' + +class NoContent(Exception): + def __str__(self) -> str: + return 'Content or attachments required' \ No newline at end of file diff --git a/itd/routes/comments.py b/itd/routes/comments.py index c211b17..9d10795 100644 --- a/itd/routes/comments.py +++ b/itd/routes/comments.py @@ -19,3 +19,6 @@ def unlike_comment(token: str, comment_id: UUID): def delete_comment(token: str, comment_id: UUID): return fetch(token, 'delete', f'comments/{comment_id}') + +def get_replies(token: str, comment_id: UUID, page: int = 1, limit: int = 50, sort: str = 'oldest'): + return fetch(token, 'get', f'comments/{comment_id}/replies', {'page': page, 'limit': limit, 'sort': sort}) diff --git a/itd/routes/posts.py b/itd/routes/posts.py index 0cd1290..30eb802 100644 --- a/itd/routes/posts.py +++ b/itd/routes/posts.py @@ -40,6 +40,9 @@ def view_post(token: str, id: UUID): def get_liked_posts(token: str, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None): return fetch(token, 'get', f'posts/user/{username_or_id}/liked', {'limit': limit, 'cursor': cursor}) +def get_user_posts(token: str, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None): + return fetch(token, 'get', f'posts/user/{username_or_id}', {'limit': limit, 'cursor': cursor}) + def restore_post(token: str, post_id: UUID): return fetch(token, "post", f"posts/{post_id}/restore",) diff --git a/pyproject.toml b/pyproject.toml index c39335f..d5390c8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "itd-sdk" -version = "1.0.1" +version = "1.1.0" description = "ITD client for python" readme = "README.md" authors = [ diff --git a/setup.py b/setup.py index 36eaeb8..8f007b7 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name='itd-sdk', - version='1.0.1', + version='1.1.0', packages=find_packages(), install_requires=[ 'requests', 'pydantic'