feat: add spans in client

This commit is contained in:
firedotguy
2026-02-28 23:48:26 +03:00
parent ec58bae1e8
commit 86a378b613
5 changed files with 23 additions and 5 deletions

View File

@@ -82,6 +82,17 @@ c.create_post('тест1') # создание постов
# итд
```
### Стилизация постов ("спаны")
С обновления 1.3.0 добавлена функция "спанов". Для парсинга пока поддерживается только html, но в будущем будет добавлен markdown.
```python
from itd import ITDClient
from itd.utils import parse_html
с = ITDClient(cookies='refresh_token=123')
print(с.create_post(*parse_html('значит, я это щас отправил со своего клиента, <b>воот</b>. И еще тут спаны написаны через html, по типу < i > <i>11</i>')))
```
<!-- ### SSE - прослушивание уведомлений в реальном времени
```python

View File

@@ -23,7 +23,7 @@ from itd.routes.pins import get_pins, remove_pin, set_pin
from itd.models.comment import Comment
from itd.models.notification import Notification
from itd.models.post import Post, NewPost, PollData, Poll
from itd.models.post import Post, NewPost, PollData, Poll, Span
from itd.models.clan import Clan
from itd.models.hashtag import Hashtag
from itd.models.user import User, UserProfileUpdate, UserPrivacy, UserFollower, UserWhoToFollow, UserPrivacyData
@@ -644,11 +644,12 @@ class Client:
@refresh_on_error
def create_post(self, content: str | None = None, wall_recipient_id: UUID | None = None, attachment_ids: list[UUID] = [], poll: PollData | None = None) -> NewPost:
def create_post(self, content: str | None = None, spans: list[Span] = [], wall_recipient_id: UUID | None = None, attachment_ids: list[UUID] = [], poll: PollData | None = None) -> NewPost:
"""Создать пост
Args:
content (str | None, optional): Содержимое. Defaults to None.
spans (lsit[Span], optional): Стилизация содержимого. Defaults to [].
wall_recipient_id (UUID | None, optional): UUID пользователя (чтобы создать пост ему на стене). Defaults to None.
attachment_ids (list[UUID], optional): UUID вложений. Defaults to [].
poll (PollData | None, optional): Опрос. Defaults to None.
@@ -660,7 +661,7 @@ class Client:
Returns:
NewPost: Новый пост
"""
res = create_post(self.token, content, wall_recipient_id, attachment_ids, poll.poll if poll else None)
res = create_post(self.token, content, [span.model_dump(mode="json") for span in spans], wall_recipient_id, attachment_ids, poll.poll if poll else None)
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFound('Wall recipient')

View File

@@ -49,3 +49,5 @@ class SpanType(Enum):
SPOILER = 'spoiler' # спойлер
UNDERLINE = 'underline' # подчеркнутый
HASHTAG = 'hashtag' # хэштэг ? (появляется только при получении постов, при создании нету)
LINK = 'link' # ссылка
QUOTE = 'quote' # цитата

View File

@@ -5,8 +5,10 @@ from itd.request import fetch
from itd.enums import PostsTab
from itd.models.post import NewPoll
def create_post(token: str, content: str | None = None, wall_recipient_id: UUID | None = None, attachment_ids: list[UUID] = [], poll: NewPoll | None = None):
def create_post(token: str, content: str | None = None, spans: list[dict] = [], wall_recipient_id: UUID | None = None, attachment_ids: list[UUID] = [], poll: NewPoll | None = None):
data: dict = {'content': content or ''}
if spans:
data['spans'] = spans
if wall_recipient_id:
data['wallRecipientId'] = str(wall_recipient_id)
if attachment_ids:

View File

@@ -1,13 +1,15 @@
# новая версия от чат гпт. у меня самого не получилось сделать
import re
from itd.models.post import Span
from itd.enums import SpanType
class Tag:
def __init__(self, open: str, close: str, type: SpanType):
def __init__(self, open: str, close: str, type: SpanType, url: str | None = None):
self.open = open
self.close = close
self.type = type
self.url = url
def _parse_spans(text: str, tags: list[Tag]) -> tuple[str, list[Span]]: