Skip to main content

Production-ready Python SDK for ITD API

Project description

ITDpy

PyPI version Downloads License

Python SDK для социальной сети итд.com.

⚠️ Неофициальный API-клиент.
SDK предназначен для разработки клиентских приложений и тестирования API в рамках действующих правил платформы.

🔒 Безопасность и использование

ITDpy использует собственный User-Agent, в котором указывается версия SDK, а также может быть указано имя сервиса.

Это сделано для:

  • повышения безопасности
  • предотвращения злоупотреблений
  • более корректного и легального использования API платформы

Это стандартная практика для SDK и не влияет на обычное использование библиотеки.

Установка

pip install itdpy

Через git

git clone https://github.com/Gam5510/ITDpy
cd itdpy
pip install -r requirements.txt
pip install -e .

Документация

Docs

Быстрый старт

Получение токена Как получить токен

from itdpy.client import ITDClient

client = ITDClient(refresh_token="Ваш refresh token")

me = client.users.me()
print(me.id)
print(me.username)

Новые функции 1.x версии библиотеки

Модели как объект, dict и JSON сразу

post = client.posts.get("POST_ID")

print(post.id)
print(post["createdAt"])
print(post.get("created_at"))
print(post.to_dict())
print(post.to_json())

Списки как list-like объекты

posts = client.posts.list(limit=10)

print(len(posts))
print(posts[0].id)
print(posts.first())
print(posts.to_json())

Вложенные списки тоже умеют to_json()

result = client.search.all("python")

print(result.users.to_json())
print(result.hashtags.to_json())

PollBuilder

from itdpy.models import PollBuilder

poll = PollBuilder("Как подавать котлеты?").add("С пюрешкой").add("Без пюрешки").multiple_choice(True).build()

post = client.posts.create(
    content="Голосуем",
    poll=poll,
)

Poll можно сериализовать и как модель, и как payload

print(poll.to_dict())
print(poll.to_json())
print(poll.to_request_dict())

Markdown и HTML парсинг

client.posts.create(
    content="**Жирный** текст",
    parse_md=True,
)

client.posts.create(
    content="<b>Жирный</b> текст",
    parse_html=True,
)

Sync SSE streaming

stream = client.notifications.stream()

@stream.on("notification")
def on_notification(event):
    print(event.data)

stream.run()

Фильтрация событий по типу

from itdpy.models import NotificationType

@stream.on("notification", type=NotificationType.LIKE)
def on_like(event):
    print(event.data)

keep_online

client.keep_online(
    on_event=lambda event_type, data: print(event_type, data),
    background=True,
)

Enums вместо строк

from itdpy import PostsTab, UserPostSorting, AccessType

posts = client.posts.list(tab=PostsTab.POPULAR)
user_posts = client.posts.get_user_posts("username", sort=UserPostSorting.NEW)
client.users.update_privacy(wall_access=AccessType.FOLLOWERS)

Ошибки разделены по типам

from itdpy import NotFoundError, ValidationError, RateLimitError, APIError

try:
    client.posts.get("invalid")
except NotFoundError:
    print("Не найдено")
except ValidationError as e:
    print(e.message)
except RateLimitError as e:
    print(e.retry_after)
except APIError as e:
    print(e.message)

Пагинация батчами

all_posts = client.posts.list_all(limit=100)
all_comments = client.comments.list_all("POST_ID", limit=100)
all_notifications = client.notifications.list_all(limit=100)

Пост на чужую стену

post = client.posts.post_to_wall(
    username="username",
    content="Привет на стену",
)

После close() запросы больше не идут

client.close()
client.posts.list()# -> RuntimeError

Config библиотеки

from itdpy import ITDClient, Config

config = Config(
    timeout=30,
    upload_timeout=180,
    max_retries=5,
    backoff_factor=2.0,
)

client = ITDClient(
    refresh_token="Ваш refresh token",
    config=config,
)

Имя сервиса

Можно указать имя вашего приложения или сервиса через Config.service:

from itdpy import ITDClient, Config

config = Config(service="my_app")
client = ITDClient(
    refresh_token="Ваш refresh token",
    config=config,
)

SDK автоматически добавит это значение в User-Agent.

Прочее

Проект активно развивается. Если у вас есть идеи или предложения, создавайте issue или pull request. Мой телеграм @gam5510 для обратной связи.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

itdpy-1.0.2.tar.gz (26.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

itdpy-1.0.2-py3-none-any.whl (35.8 kB view details)

Uploaded Python 3

File details

Details for the file itdpy-1.0.2.tar.gz.

File metadata

  • Download URL: itdpy-1.0.2.tar.gz
  • Upload date:
  • Size: 26.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for itdpy-1.0.2.tar.gz
Algorithm Hash digest
SHA256 09330f9545c4e5dc5e543e8cd385b9a57b7ac8773862efe3efa74883b596ee18
MD5 ee4d14d764c24f2e40394ca63ff67a7b
BLAKE2b-256 a7b9c8da22b19170d291b20dd647e99511b6142639cf44c7537ae4a2831cec37

See more details on using hashes here.

File details

Details for the file itdpy-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: itdpy-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 35.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.25

File hashes

Hashes for itdpy-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 39aa5cbe4733717dd782c968b567e6016a9f20d68513b38398de8ae23f9cca23
MD5 31b3e5811eb7d4d599e1ec9a6409969c
BLAKE2b-256 c91d4befa770ebc65ba37ba485d4dd4366c504bc375a76cad8621cd0353213b8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page