Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,6 @@ if __name__ == "__main__":

Спасибо всем за помощь в разработке!

<a href="https://github.com/ink-developer/PyMax/graphs/contributors">
<a href="https://github.com/MaxApiTeam/PyMax/graphs/contributors">
<img src="https://contrib.rocks/image?repo=ink-developer/PyMax" />
Comment on lines +168 to 169
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Inconsistent repository URL migration in contributors section.

Line 168 was updated to reference MaxApiTeam/PyMax, but the image source on Line 169 still points to the old organization (ink-developer/PyMax). This mismatch will cause the contributors badge to render stale data.

Additionally, Line 157 (Star History badge) also contains references to the old repository (ink-developer/PyMax appears twice in the URL) and may need similar updates for consistency.

🔎 Proposed fix to complete the repository migration
- <a href="https://github.com/MaxApiTeam/PyMax/graphs/contributors">
-   <img src="https://contrib.rocks/image?repo=ink-developer/PyMax" />
+ <a href="https://github.com/MaxApiTeam/PyMax/graphs/contributors">
+   <img src="https://contrib.rocks/image?repo=MaxApiTeam/PyMax" />

Also update Line 157:

-[![Star History Chart](https://api.star-history.com/svg?repos=ink-developer/PyMax&type=date&legend=top-left)](https://www.star-history.com/#ink-developer/PyMax&type=date&legend=top-left)
+[![Star History Chart](https://api.star-history.com/svg?repos=MaxApiTeam/PyMax&type=date&legend=top-left)](https://www.star-history.com/#MaxApiTeam/PyMax&type=date&legend=top-left)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<a href="https://github.com/MaxApiTeam/PyMax/graphs/contributors">
<img src="https://contrib.rocks/image?repo=ink-developer/PyMax" />
<a href="https://github.com/MaxApiTeam/PyMax/graphs/contributors">
<img src="https://contrib.rocks/image?repo=MaxApiTeam/PyMax" />
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

169-169: Images should have alternate text (alt text)

(MD045, no-alt-text)

🤖 Prompt for AI Agents
In README.md around lines 157 and 168-169, the contributors image and the Star
History badge still reference the old repository path ink-developer/PyMax while
other links use MaxApiTeam/PyMax; update the badge and image URLs to
consistently use MaxApiTeam/PyMax (replace all occurrences of
ink-developer/PyMax in those lines/URLs with MaxApiTeam/PyMax) so the
contributors image and star history reflect the migrated repository.

</a>
123 changes: 0 additions & 123 deletions mkdocs.yml

This file was deleted.

9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "maxapi-python"
version = "1.2.3"
version = "1.2.4"
description = "Python wrapper для API мессенджера Max"
readme = "README.md"
requires-python = ">=3.10"
Expand All @@ -19,12 +19,13 @@ dependencies = [
"aiohttp>=3.12.15",
"aiofiles>=24.1.0",
"qrcode>=8.2",
"ua-generator>=2.0.19",
]

[project.urls]
Homepage = "https://github.com/ink-developer/PyMax"
Repository = "https://github.com/ink-developer/PyMax"
Issues = "https://github.com/ink-developer/PyMax/issues"
Homepage = "https://github.com/MaxApiTeam/PyMax"
Repository = "https://github.com/MaxApiTeam/PyMax"
Issues = "https://github.com/MaxApiTeam/PyMax/issues"

[build-system]
requires = ["hatchling"]
Expand Down
150 changes: 127 additions & 23 deletions redocs/source/clients.rst
Original file line number Diff line number Diff line change
@@ -1,11 +1,44 @@
Clients
=======

Выбор между MaxClient и SocketMaxClient
----------------------------------------

PyMax предоставляет два клиента с разной функциональностью в зависимости от выбранного протокола подключения:

.. list-table:: Сравнение клиентов
:widths: 30 35 35
:header-rows: 1

* - Функция
- MaxClient (WebSocket)
- SocketMaxClient (Socket)
* - Протокол подключения
- WebSocket
- TCP Socket
* - Способ авторизации
- Вход по QR-коду
- Вход/регистрация по номеру телефона
* - Регистрация новых пользователей
- ❌ Не поддерживается
- ✅ Поддерживается
* - Скорость подключения
- Быстрое
- Медленнее
* - Рекомендуемое использование
- Базовые боты и приложения
- Массовая регистрация, системная авторизация

MaxClient
---------

Основной асинхронный WebSocket клиент для взаимодействия с Max API.

**Поддерживаемые методы авторизации:**
- ✅ Вход по QR-коду (WEB device_type)
- ❌ Вход по номеру телефона (больше не поддерживается)
- ❌ Регистрация по номеру телефона

Инициализация:

.. code-block:: python
Expand All @@ -20,27 +53,10 @@ MaxClient
logger=None, # Пользовательский логгер
)

.. warning::

Параметр ``device_type`` в ``UserAgentPayload`` **критически важен** для выбора способа авторизации:

**DESKTOP** — вход по номеру телефона:

.. code-block:: python

from pymax.payloads import UserAgentPayload

ua = UserAgentPayload(device_type="DESKTOP", app_version="25.12.13")
client = MaxClient(phone="+79111111111", headers=ua)

**WEB** — вход через QR-код; токен совместим с веб-версией Max:

.. code-block:: python

from pymax.payloads import UserAgentPayload
.. note::

ua = UserAgentPayload(device_type="WEB", app_version="25.12.13")
client = MaxClient(phone="+79111111111", headers=ua)
MaxClient по умолчанию использует **WEB** device_type и поддерживает только вход по QR-коду.
Это является рекомендуемым способом авторизации для большинства приложений.

Основные методы:

Expand Down Expand Up @@ -84,6 +100,19 @@ MaxClient
limit=50
)

# Изменить профиль с загрузкой фото
result = await client.change_profile(
first_name="Иван",
last_name="Петров",
description="Привет!",
photo=Photo(...) # Новая фотография профиля
)

# Разрешить группу по ссылке
group = await client.resolve_group_by_link(
link="https://max.app/g/ABC123"
)

Свойства:

.. code-block:: python
Expand All @@ -95,6 +124,7 @@ MaxClient
client.channels # Список каналов (list[Channel])
client.phone # Номер телефона (str)
client.token # Токен сессии (str | None)
client.contacts # Список контактов (list[User])

Обработчики событий:

Expand Down Expand Up @@ -140,9 +170,83 @@ MaxClient
SocketMaxClient
---------------

Низкоуровневый WebSocket клиент для прямого взаимодействия с API.
Обычно не требуется использовать напрямую - используйте MaxClient вместо этого.
Асинхронный TCP Socket клиент для взаимодействия с Max API. Используется для входа и регистрации по номеру телефона.

**Поддерживаемые методы авторизации:**
- ✅ Вход по номеру телефона (DESKTOP, ANDROID, IOS device_types)
- ✅ Регистрация нового пользователя по номеру телефона

**Когда использовать SocketMaxClient:**
- Необходимо зарегистрировать новых пользователей
- Требуется вход по номеру телефона (без QR-кода)
- Необходимо использовать DESKTOP, ANDROID или IOS device_types
- Разрабатываете системы массовой регистрации или авторизации
- Нужна автоматизация входа (вход по номеру телефона удобнее для автоматизации, чем сканирование QR-кода)

.. note::

**SocketMaxClient — это полноценный и рекомендуемый способ авторизации!**

Не воспринимайте Socket клиент как что-то вспомогательное или альтернативное.
Вход по номеру телефона — это основной способ авторизации в Max, и ``SocketMaxClient`` обеспечивает надежный доступ к этому функционалу.

Для многих сценариев (особенно для автоматизации и интеграции) вход по номеру телефона **удобнее и практичнее**, чем сканирование QR-кода.

Инициализация и вход:

.. code-block:: python

from pymax import SocketMaxClient
from pymax.payloads import UserAgentPayload

# Для входа по номеру телефона
client = SocketMaxClient(
phone="+79001234567",
work_dir="./cache",
headers=UserAgentPayload(device_type="DESKTOP"),
)

await client.start() # Потребуется ввести код подтверждения

Регистрация нового пользователя:

.. code-block:: python

from pymax import SocketMaxClient
from pymax.payloads import UserAgentPayload

client = SocketMaxClient(
phone="+79001234567",
registration=True, # Флаг регистрации
first_name="Иван",
last_name="Петров",
headers=UserAgentPayload(device_type="DESKTOP"),
)

await client.start() # Потребуется ввести код подтверждения

.. important::

SocketMaxClient должен использоваться для:

1. **Регистрации новых пользователей** — MaxClient не поддерживает регистрацию
2. **Входа по номеру телефона** — требуется phone verification код
3. **Системной авторизации** — когда QR-код недоступен или неудобен
4. **Автоматизации** — вход по номеру телефона легче автоматизировать

.. note::

Если вам нужны низкоуровневые детали, смотрите исходный код библиотеки.
После успешной авторизации через SocketMaxClient вы можете сохранить токен и использовать его с MaxClient для более быстрого подключения к WebSocket API.

.. code-block:: python

# Первый раз: получаем токен через Socket
socket_client = SocketMaxClient(phone="+79001234567")
await socket_client.start()
token = socket_client.token

# Сохраняем токен

# Следующие разы: используем токен с WebSocket клиентом
ws_client = MaxClient(phone="+79001234567", token=token)
await ws_client.start()
2 changes: 1 addition & 1 deletion redocs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
project = "PyMax"
author = "ink-developer"
copyright = "2025, ink-developer"
release = "1.1.21"
release = "1.2.4"

# -- Path setup ---------------------------------------------------------------
sys.path.insert(0, os.path.abspath("../../src"))
Expand Down
11 changes: 3 additions & 8 deletions redocs/source/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Greeter Bot

client = MaxClient(phone="+79001234567")

@client.on_message(Filters.private())
@client.on_message(Filters.chat(123))
async def greet(message):
user = await client.get_user(message.sender)
if user and user.names:
Expand Down Expand Up @@ -150,13 +150,8 @@ File Manager
for attach in message.attaches:
if attach.type == AttachType.PHOTO:
print("Получено фото!")
file_info = await client.get_file_by_id(
chat_id=message.chat_id,
message_id=message.id,
file_id=attach.file_id
)
if file_info:
print(f"URL: {file_info.url}")

print(f"URL: {attach.base_url}")

@client.on_message(Filters.text("файл"))
async def send_file(message):
Expand Down
5 changes: 0 additions & 5 deletions redocs/source/guides.rst
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,6 @@ Guides
async def greeting(message: Message) -> None:
pass

# Только личные
@client.on_message(Filters.dialog())
async def private(message: Message) -> None:
pass

# Только группы
@client.on_message(Filters.chat())
async def in_group(message: Message) -> None:
Expand Down
Loading