From aad83b55d5cdac6858db0f4b046f2f1a73b5acf0 Mon Sep 17 00:00:00 2001 From: firedotguy Date: Tue, 10 Feb 2026 18:28:16 +0300 Subject: [PATCH] chore: update version; move scripts into examples folder --- README.md | 19 ++++++- examples/README.md | 56 ------------------- {scripts => examples/kilyabin}/README.md | 0 .../kilyabin}/itd-change-banner.py | 0 .../kilyabin}/itd-create-post.py | 0 examples/stream/basic_stream.py | 12 ++-- examples/stream/filter_notifications.py | 25 ++++----- examples/stream/notification_logger.py | 16 +++--- examples/stream/stop_stream.py | 21 +++---- pyproject.toml | 2 +- setup.py | 2 +- 11 files changed, 54 insertions(+), 99 deletions(-) rename {scripts => examples/kilyabin}/README.md (100%) rename {scripts => examples/kilyabin}/itd-change-banner.py (100%) rename {scripts => examples/kilyabin}/itd-create-post.py (100%) diff --git a/README.md b/README.md index 2106185..85607e3 100644 --- a/README.md +++ b/README.md @@ -18,10 +18,25 @@ c = ITDClient('TOKEN', 'refresh_token=...; __ddg1_=...; __ddgid_=...; is_auth=1; print(c.get_me()) ``` - + + +## Получение cookies + +Для получения access_token требуются cookies с `refresh_token`. Как их получить: + +1. Откройте [итд.com](https://xn--d1ah4a.com) в браузере +2. Откройте DevTools (F12) +3. Перейдите на вкладку **Network** +4. Обновите страницу +5. Найдите запрос к `/auth/refresh` +6. Скопируйте значение **Cookie** из Request Headers +> Пример: `refresh_token=123123A67BCdEfGG; is_auth=1` +> В cookies также могут присутствовать значения типа `__ddgX__` (DDoS-Guard cookies) или `_ym_XXXX` (`X` - любое число или буква). Они необязательные и их наличие не влияет на результат + +![cookie](cookie-screen.png) --- ### Скрипт на обновление имени diff --git a/examples/README.md b/examples/README.md index 870e87e..055735c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -2,62 +2,6 @@ Эта папка содержит примеры использования ITD SDK для различных сценариев. -## Структура - -``` -examples/ -├── README.md # Этот файл -└── stream/ # Примеры работы с SSE потоком уведомлений - ├── basic_stream.py - ├── stop_stream.py - ├── filter_notifications.py - └── notification_logger.py -``` - -## Подготовка - -Перед запуском примеров установите зависимости: - -```bash -pip install -r ../requirements.txt -``` - -## Получение cookies - -Все примеры требуют cookies с `refresh_token`. Как их получить: - -1. Откройте [итд.com](https://xn--d1ah4a.com) в браузере -2. Откройте DevTools (F12) -3. Перейдите на вкладку **Network** -4. Найдите запрос к `/auth/refresh` -5. Скопируйте значение **Cookie** из Request Headers -6. Формат: `refresh_token=...; __ddg1_=...; is_auth=1` - -См. `cookie-screen.png` в корне проекта для примера. - ---- - -## Stream - Прослушивание уведомлений - -Примеры работы с SSE потоком уведомлений в реальном времени. - -📁 **Папка:** `stream/` -📖 **Документация:** [stream/README.md](stream/README.md) - -**Примеры:** -- `basic_stream.py` - Базовое прослушивание всех уведомлений -- `stop_stream.py` - Программная остановка потока -- `filter_notifications.py` - Фильтрация по типу уведомлений -- `notification_logger.py` - Логирование в JSON файл - -**Быстрый старт:** -```bash -cd stream -python basic_stream.py -``` - ---- - ## Дополнительная информация - [Основной README](../README.md) - Документация по всему SDK diff --git a/scripts/README.md b/examples/kilyabin/README.md similarity index 100% rename from scripts/README.md rename to examples/kilyabin/README.md diff --git a/scripts/itd-change-banner.py b/examples/kilyabin/itd-change-banner.py similarity index 100% rename from scripts/itd-change-banner.py rename to examples/kilyabin/itd-change-banner.py diff --git a/scripts/itd-create-post.py b/examples/kilyabin/itd-create-post.py similarity index 100% rename from scripts/itd-create-post.py rename to examples/kilyabin/itd-create-post.py diff --git a/examples/stream/basic_stream.py b/examples/stream/basic_stream.py index 6928ea1..cbffb0d 100644 --- a/examples/stream/basic_stream.py +++ b/examples/stream/basic_stream.py @@ -5,20 +5,20 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) -from itd import ITDClient, StreamConnect, StreamNotification +from itd import ITDClient, StreamConnect def main(): cookies = 'YOUR_COOKIES_HERE' - + if cookies == 'YOUR_COOKIES_HERE': print('! Укажите cookies в переменной cookies') print(' См. examples/README.md для инструкций') return - + client = ITDClient(cookies=cookies) - + print('-- Подключение к SSE...') - + try: for event in client.stream_notifications(): if isinstance(event, StreamConnect): @@ -29,7 +29,7 @@ def main(): if event.preview: preview = event.preview[:50] + '...' if len(event.preview) > 50 else event.preview print(f' {preview}') - + except KeyboardInterrupt: print(f'\n! Отключение...') diff --git a/examples/stream/filter_notifications.py b/examples/stream/filter_notifications.py index f26063e..10f844a 100644 --- a/examples/stream/filter_notifications.py +++ b/examples/stream/filter_notifications.py @@ -5,48 +5,47 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) -from itd import ITDClient, StreamConnect, StreamNotification +from itd import ITDClient, StreamConnect from itd.enums import NotificationType def main(): cookies = 'YOUR_COOKIES_HERE' - + if cookies == 'YOUR_COOKIES_HERE': print('! Укажите cookies в переменной cookies') print(' См. examples/README.md для инструкций') return - + client = ITDClient(cookies=cookies) - - # Настройка: какие типы уведомлений показывать + SHOW_TYPES = { NotificationType.LIKE, NotificationType.FOLLOW, - NotificationType.COMMENT, + NotificationType.COMMENT } - + print('-- Подключение к SSE...') print(f'-- Фильтр: {", ".join(t.value for t in SHOW_TYPES)}\n') - + try: for event in client.stream_notifications(): if isinstance(event, StreamConnect): print(f'✅ Подключено! User ID: {event.user_id}\n') continue - + if event.type not in SHOW_TYPES: continue - + # Обработка разных типов if event.type == NotificationType.LIKE: print(f'❤️ {event.actor.display_name} лайкнул ваш пост') - + elif event.type == NotificationType.FOLLOW: print(f'👤 {event.actor.display_name} подписался на вас') - + elif event.type == NotificationType.COMMENT: print(f'💬 {event.actor.display_name}: {event.preview}') - + except KeyboardInterrupt: print(f'\n! Отключение...') diff --git a/examples/stream/notification_logger.py b/examples/stream/notification_logger.py index fb758b0..9e0bd0b 100644 --- a/examples/stream/notification_logger.py +++ b/examples/stream/notification_logger.py @@ -5,29 +5,29 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) -from itd import ITDClient, StreamConnect, StreamNotification +from itd import ITDClient, StreamConnect from datetime import datetime import json def main(): cookies = 'YOUR_COOKIES_HERE' - + if cookies == 'YOUR_COOKIES_HERE': print('! Укажите cookies в переменной cookies') print(' См. examples/README.md для инструкций') return - + client = ITDClient(cookies=cookies) log_file = f'notifications_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log' - + print(f'-- Подключение к SSE...') print(f'-- Логирование в: {log_file}\n') - + try: with open(log_file, 'w', encoding='utf-8') as f: for event in client.stream_notifications(): timestamp = datetime.now().isoformat() - + if isinstance(event, StreamConnect): log_entry = { 'timestamp': timestamp, @@ -49,10 +49,10 @@ def main(): 'target_id': str(event.target_id) if event.target_id else None } print(f'* {event.type.value}: {event.actor.username}') - + f.write(json.dumps(log_entry, ensure_ascii=False) + '\n') f.flush() - + except KeyboardInterrupt: print(f'\n! Отключение... Лог сохранен в {log_file}') diff --git a/examples/stream/stop_stream.py b/examples/stream/stop_stream.py index ef46cf2..91c29b9 100644 --- a/examples/stream/stop_stream.py +++ b/examples/stream/stop_stream.py @@ -6,19 +6,17 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) import threading -import time -from itd import ITDClient, StreamConnect, StreamNotification +from itd import ITDClient, StreamConnect def main(): - cookies = 'YOUR_COOKIES_HERE' - + cookies = 'YOUR_COOKIES_HERE' + if cookies == 'YOUR_COOKIES_HERE': print('! Укажите cookies в переменной cookies') return - + client = ITDClient(cookies=cookies) - - # Функция для прослушивания в отдельном потоке + def listen(): print('! Начинаем прослушивание...') try: @@ -29,17 +27,16 @@ def main(): print(f'🔔 {event.type.value}: {event.actor.username}') except Exception as e: print(f'! Ошибка: {e}') - - # В отдельном потоке + thread = threading.Thread(target=listen, daemon=True) thread.start() - + print('Прослушивание запущено. Нажмите Enter для остановки...') input() - + print('!! Останавливаем прослушивание...') client.stop_stream() - + thread.join(timeout=5) print('! Остановлено') diff --git a/pyproject.toml b/pyproject.toml index 49e7d79..1d718a8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "itd-sdk" -version = "1.1.0" +version = "1.2.0" description = "ITD client for python" readme = "README.md" authors = [ diff --git a/setup.py b/setup.py index 6b0f401..b04f3fe 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name='itd-sdk', - version='1.1.0', + version='1.2.0', packages=find_packages(), install_requires=[ 'requests', 'pydantic', 'sseclient-py'