Skip to content

Замена времени на DateTimeUnion. - #84

Closed
AlexeyRF wants to merge 1 commit into
MaxApiTeam:dev/2.4.1from
AlexeyRF:dev/2.4.1
Closed

Замена времени на DateTimeUnion.#84
AlexeyRF wants to merge 1 commit into
MaxApiTeam:dev/2.4.1from
AlexeyRF:dev/2.4.1

Conversation

@AlexeyRF

Copy link
Copy Markdown

Рефакторинг. Замена формата работы времени на DateTimeUnion. Пример кода для проверки, где при работе задействуется DTU:


import asyncio
from datetime import datetime, timedelta, timezone
from pymax import Client
from pymax.auth import ConsolePasswordProvider

async def demo_datetime_union():
    phone = input("Введите номер телефона").strip()
    client = Client(phone=phone,password_provider=ConsolePasswordProvider())
    await client.connect()
    chat_id = 0
    
    # 1. Использование datetime 
    target_date = datetime(2025, 12, 22, 12, 0, tzinfo=timezone.utc)
    print(f"\n1. Скачиваем 100 сообщений вперёд начиная с {target_date}")
    chunk_dt = await client.fetch_history(chat_id=chat_id,from_time=target_date, forward=100,backward=0)
    print(f"Получено сообщений: {len(chunk_dt)}")

    # 2. Использование timedelta
    time_offset = timedelta(days=-3)
    print("\n2. Скачиваем сообщения за последние 3 дня")
    chunk_td = await client.fetch_history(chat_id=chat_id,from_time=time_offset, forward=100, backward=0)
    print(f"Получено сообщений: {len(chunk_td)}")

    # 3. Использование int
    timestamp_ms = int(target_date.timestamp() * 1000) - 1
    print(f"\n3. Скачиваем сообщения используя Unix Time {timestamp_ms} мс")
    chunk_int = await client.fetch_history(chat_id=chat_id,from_time=timestamp_ms,forward=100, backward=0)
    print(f"Получено сообщений: {len(chunk_int)}")

    # 4. Использование DateTimeUnion для чатов
    print(f"\n4. Скачиваем список чатов до {target_date}")
    chats_dt = await client.fetch_chats(marker=target_date)
    print(f"Получено чатов: {len(chats_dt)}")
    await client.close()

if __name__ == "__main__": asyncio.run(demo_datetime_union())

Затронуты pymax/api/chats/service.py pymax/api/messenger/service.py pymax/infra/chat.py pymax/infra/message.py pymax/types/domain/chat.py
@coderabbitai

coderabbitai Bot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0087f8fb-9dec-4c58-866f-fa0020fde878

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ink-developer

Copy link
Copy Markdown
Collaborator

Мне здесь не нравятся несколько вещей.

Не стоит дублировать _convert_time в MessageService и ChatService. Лучше вынести DateTimeUnion и конвертацию времени в общий модуль (Например, common).

При этом нужно явно определить семантику int: сейчас _convert_time в MessageService считает int секундами и умножает его на 1000, тогда как marker и from_time исторически уже передаются в миллисекундах. Просто переиспользовать текущую функцию для всех случаев нельзя.

Ещё в новом ChatService._convert_time() отсутствует return для int, хотя сигнатура это допускает.

DateTimeUnion имеет смысл использовать только на пользовательской границе API. После нормализации внутренние payload'ы должны по-прежнему получать int.
Для marker/from_time не нужно использовать truthiness:

marker if marker is not None else int(time.time() * 1000)

Тогда 0 не будет ошибочно заменяться текущим временем.

@AlexeyRF

Copy link
Copy Markdown
Author

Оке, вечером сяду поправлю

@AlexeyRF

Copy link
Copy Markdown
Author

Закрою, доделаю для 2.5.0

@AlexeyRF AlexeyRF closed this Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants