Skip to content

fix: добавлен retry при edit для ошибки attachment.file.not.processed - #192

Open
2-3savage wants to merge 2 commits into
love-apples:mainfrom
2-3savage:fix/attachment-file-not-processed
Open

fix: добавлен retry при edit для ошибки attachment.file.not.processed#192
2-3savage wants to merge 2 commits into
love-apples:mainfrom
2-3savage:fix/attachment-file-not-processed

Conversation

@2-3savage

Copy link
Copy Markdown

Проблема

При использовании EditMessage с предварительно загруженным через upload_media файлом (AttachmentUpload), API MAX иногда возвращает HTTP 200 с телом:

{
  "success": false,
  "message": "Key: errors.process.attachment.file.not.processed"
}

Ожидаемое поведение — возврат HTTP 400 с кодом attachment.not.ready, который должен быть перехвачен MaxApiError и отправлен в retry-механизм с задержкой 2 секунды.

Однако фактически:

  • Retry-механизм не срабатывает, так как отсутствует ожидаемый код ошибки
  • raw не содержит поле code с attachment.not.ready, только сообщение Key: errors.process.attachment.file.not.processed

Важно отметить, что данная проблема воспроизводится только в EditMessage. В SendMessage API корректно возвращает HTTP 400 с правильным кодом ошибки.

Фикс

Добавлена обработка ошибки attachment.file.not.processed в BaseConnection.request()

Теперь:

Ответ с success=False перехватывается

Сообщение attachment.file.not.processed маппится в код attachment.not.ready

Выбрасывается MaxApiError с корректным кодом

Retry-механизм в EditMessage.fetch() перехватывает ошибку и делает повторную попытку через 2 секунды и т.д.

TODO

Удалить костыль, когда MAX API начнёт возвращать корректный HTTP-статус для этой ошибки

- Добавлен маппинг ошибки 'attachment.file.not.processed' в 'attachment.not.ready'
- Добавлена обработка ответов API с success=False при HTTP 200
- TODO: убрать когда MAX API начнёт возвращать корректный HTTP статус"
@2-3savage

2-3savage commented Aug 19, 2026

Copy link
Copy Markdown
Author

Всем привет!

Хотелось бы побыстрее увидеть в проде, т.к. буквально сегодня с этим столкнулся и очень нужен фикс 😊

Либо можно написать разрабам апишки и показать им, что выдает 200 при ошибке.

Comment thread maxapi/connection/base.py

if "attachment.file.not.processed" in error_message or "attachment.not.ready" in error_message:
if bot.dispatcher:
asyncio.create_task(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Висячие таски не надо делать, посмотри как в других местах реализован сбор

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Привет! Спасибо за ревью.

Я посмотрел, как это реализовано в других местах проекта, например, при обработке ошибок if not response.ok. Там используется точно такой же паттерн с asyncio.create_task.

if not response.ok:
    raw = await response.json()
    if bot.dispatcher:
        asyncio.create_task(
            bot.dispatcher.handle_raw_response(
                UpdateType.RAW_API_RESPONSE, raw
            )
        )
    raise MaxApiError(code=response.status, raw=raw)

Мне удалить asyncio.create_task и сделать асинхронный вызов await bot.dispatcher.handle_raw_response(...), или я что-то упускаю?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Normalizes a malformed HTTP 200 attachment error so EditMessage can trigger its existing retry mechanism.

Changes:

  • Detects unsuccessful attachment-processing responses.
  • Maps them to attachment.not.ready.
  • Raises MaxApiError and dispatches the raw response.
Suppressed comments (1)

maxapi/connection/base.py:235

  • MaxApiError.raw normally contains the complete API response (see the HTTP-error path above), but this replacement drops success, message, and any future diagnostic fields. Preserve the original body while adding the normalized code so callers and logs can still inspect the actual server error.
                raise MaxApiError(code=400, raw={"code": "attachment.not.ready"})

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread maxapi/connection/base.py Outdated
Comment on lines +224 to +227
if raw.get('success') is False:
error_message = raw.get('message', '')

if "attachment.file.not.processed" in error_message or "attachment.not.ready" in error_message:
Comment thread maxapi/connection/base.py Outdated
Comment on lines +224 to +227
if raw.get('success') is False:
error_message = raw.get('message', '')

if "attachment.file.not.processed" in error_message or "attachment.not.ready" in error_message:
@Olegt0rr Olegt0rr added the upstream MAX API issue label Aug 19, 2026
Comment thread maxapi/connection/base.py Outdated
)
)

raise MaxApiError(code=400, raw={"code": "attachment.not.ready"})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Сработать могло на "attachment.file.not.processed", а ты в ошибку пишешь "attachment.not.ready". Лучше сохранять оригинальное сообщение - иначе это может ввести в заблуждение

@2-3savage
2-3savage force-pushed the fix/attachment-file-not-processed branch from 2a6970e to 501e650 Compare August 20, 2026 02:57
@2-3savage
2-3savage requested a review from Olegt0rr August 24, 2026 08:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

upstream MAX API issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants