Skip to content

fix(whatsapp-baileys): Verifica eventos com falhas e fallback para erro ao baixar mídias #1660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 27, 2025

Conversation

KokeroO
Copy link
Contributor

@KokeroO KokeroO commented Jun 27, 2025

Descrição

  1. Em alguns momentos raros, temos os erros 400 e 403 ao receber eventos da Baileys. Esses erros são por diversos motivos como token invalido de descriptografia, sessão expirada, etc.
  2. Outros momentos também raros ao tentar baixar uma mídia utilizando getBase64FromMediaMessage recebemos um erro de download.
  3. A implementação anterior de evitar os eventos message.upsert foi super positiva, mas nos momentos em que recebo os erros 400 e 403 com a descrição de No matching sessions found for message, Bad MAC, failed to decrypt message ou SessionError, impede o re-processamento de do evento no retry da Baileys. Isso causa em certas situações o impedimento do processamento das primeiras mensagens até que a sessão e tokens de descriptografia estejam validos.

Solução

  1. Implementado a verificação de erros conhecidos provenientes dos erros 400 e 403 da Baileys antes do restante do bloco de processamento try dos eventos message.upsert.
  2. Implementação de fallback com o método da Baileys downloadContentFromMessage após erro ao tentar baixar com o método getBase64FromMediaMessage. (Por algum motivo downloadContentFromMessage funciona melhor.)
  3. Com a primeira implementação se corrigiu este problema.

Summary by Sourcery

Handle transient Baileys decryption errors by filtering specific message stub parameters before processing and improve media download reliability with a retry fallback using downloadContentFromMessage.

Enhancements:

  • Skip processing and log warnings for message.upsert events containing known decryption or session errors (e.g., Bad MAC, No matching sessions found, SessionError).
  • Implement a fallback strategy for media downloads by retrying after a delay and using Baileys' downloadContentFromMessage when downloadMediaMessage fails.
  • Add a mapMediaType helper to translate message types for the downloadContentFromMessage fallback.

- Implement broken event checking before duplicate message checking. (Do not process failed events).
- Implement error handling when downloading media with a fallback mechanism.
Copy link
Contributor

sourcery-ai bot commented Jun 27, 2025

Reviewer's Guide

Adds pre-processing filters for known Baileys 400/403 errors on incoming message events and introduces a robust fallback path for downloading media when the primary method fails.

Sequence diagram for robust media download with fallback in WhatsApp Baileys service

sequenceDiagram
    participant Service as BaileysStartupService
    participant Baileys as Baileys Library
    participant Logger as Logger
    Service->>Baileys: downloadMediaMessage()
    alt Success
        Baileys-->>Service: Buffer
    else Failure
        Service->>Logger: Log error (Download Media failed)
        Service->>Service: Wait 5 seconds
        Service->>Baileys: downloadContentFromMessage()
        alt Fallback Success
            Baileys-->>Service: Media Stream
            Service->>Service: Concatenate chunks to Buffer
            Service->>Logger: Log info (Download successful)
        else Fallback Failure
            Service->>Logger: Log error (Fallback also failed)
        end
    end
Loading

Sequence diagram for pre-processing Baileys message events with error filtering

sequenceDiagram
    participant Service as BaileysStartupService
    participant Logger as Logger
    participant Baileys as Baileys Library
    Baileys-->>Service: message.upsert(messages)
    loop For each received message
        alt messageStubParameters contains known error
            Service->>Logger: Log warning (Message ignored)
            Service-->>Service: continue (skip processing)
        else
            Service->>Service: Process message as usual
        end
    end
Loading

File-Level Changes

Change Details Files
Filter out message.upsert events with known Baileys error codes before main processing
  • Inspect messageStubParameters for specific error substrings
  • Log a warning and continue to next message when matched
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Add a fallback download path for media messages on primary download failure
  • Add mapMediaType helper to map message types for downloadContentFromMessage
  • Wrap downloadMediaMessage in try/catch with a 5-second retry pause
  • On catch, stream content via downloadContentFromMessage, assemble chunks into a buffer, and log success or failure
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@KokeroO
Copy link
Contributor Author

KokeroO commented Jun 27, 2025

@DavidsonGomes Estou na segunda semana testando essa solução em diversos clientes em produção. Aqui já validei a solução antes de subir o PR.

@DavidsonGomes DavidsonGomes merged commit 3c917af into EvolutionAPI:develop Jun 27, 2025
1 check passed
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