feat: add get replies and get_user_posts

This commit is contained in:
firedotguy
2026-02-07 23:20:00 +03:00
parent 6236c5981b
commit 5ebcdb1ad5
7 changed files with 69 additions and 6 deletions

View File

@@ -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]:
"""Получить список лайкнутых постов пользователя

View File

@@ -28,6 +28,7 @@ class AttachType(Enum):
AUDIO = 'audio'
IMAGE = 'image'
VIDEO = 'video'
FILE = 'file'
class PostsTab(Enum):
FOLLOWING = 'following'

View File

@@ -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'
return f'You do not own "{self.pin}" pin'
class NoContent(Exception):
def __str__(self) -> str:
return 'Content or attachments required'

View File

@@ -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})

View File

@@ -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",)

View File

@@ -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 = [

View File

@@ -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'