Skip to content

Conversation

@KokeroO
Copy link
Contributor

@KokeroO KokeroO commented Oct 19, 2025

  • corrige cache de números PN, LIDs e g.us para enviar o número correto
  • atualiza para os últimos commits da baileys
  • corrige envio de áudio e documentos via chatwoot no canal baileys
  • diversas correções na integração com chatwoot
  • corrige mensagens ignoradas no recebimento de leads

Summary by Sourcery

Upgrade Baileys integration, refine number caching and media handling in Chatwoot and Baileys services, and fix attachment and contact processing

New Features:

  • Upgrade Baileys dependency to the latest master and adapt code to its new API
  • Integrate on-whatsapp-cache for unified handling of LID and standard JIDs
  • Introduce randomized delays for outgoing WhatsApp messages

Bug Fixes:

  • Correct number cache for phone (PN), LID, and group JIDs to maintain proper sender identities
  • Fix sending of audio and document attachments via Chatwoot’s WhatsApp channel
  • Prevent ignored duplicate messages and restore lead reception flows

Enhancements:

  • Remove custom media download and retry logic, forwarding URLs directly for attachments
  • Simplify conversation creation and contact update logic in ChatwootService
  • Improve logging verbosity and streamline webhook processing by removing background deletion

Chores:

  • Update package.json to pin Baileys to the GitHub master branch

…na baileys e chatwoot

* corrige cache de números PN, LIDs e g.us para enviar o número correto
* atualiza para os últimos commits da baileys
* corrige envio de áudio e documentos via chatwoot no canal baileys
* diversas correções na integração com chatwoot
* corrige mensagens ignoradas no recebimento de leads
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 19, 2025

Reviewer's Guide

Refactors ChatwootService to unify conversation and media handling (including randomized delays), streamlines webhook processing by removing background deletion logic, enhances BaileysStartupService with improved caching and duplicate suppression, introduces contextInfo support in sendMessage, overhauls onWhatsappCache persistence strategy, updates message processor types, and upgrades the Baileys dependency to the latest master.

Sequence diagram for improved WhatsApp number cache verification and persistence

sequenceDiagram
  participant BaileysStartupService
  participant onWhatsappCache
  participant BaileysClient
  participant Database
  BaileysStartupService->>onWhatsappCache: getOnWhatsappCache(numbers)
  onWhatsappCache-->>BaileysStartupService: cachedNumbers
  alt Numbers not in cache
    BaileysStartupService->>BaileysClient: onWhatsApp(numbersNotInCache)
    BaileysClient-->>BaileysStartupService: verificationResults
  end
  BaileysStartupService->>onWhatsappCache: saveOnWhatsappCache(numbersToCache)
  onWhatsappCache->>Database: upsert isOnWhatsapp records
  Database-->>onWhatsappCache: confirmation
  onWhatsappCache-->>BaileysStartupService: done
Loading

Sequence diagram for ChatwootService media sending (audio/document) refactor

sequenceDiagram
  participant ChatwootService
  participant Axios
  participant BaileysService
  ChatwootService->>Axios: GET media URL
  Axios-->>ChatwootService: media response
  alt Audio type
    ChatwootService->>BaileysService: sendAudio(number, media, delay, quoted)
    BaileysService-->>ChatwootService: messageSent
  else Document/Image type
    ChatwootService->>BaileysService: sendDocument(number, media, fileName, delay, quoted)
    BaileysService-->>ChatwootService: messageSent
  end
Loading

Class diagram for updated onWhatsappCache persistence and data model

classDiagram
  class OnWhatsappCache {
    +saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[])
    +getAvailableNumbers(remoteJid: string): string[]
  }
  class ISaveOnWhatsappCacheParams {
    +remoteJid: string
    +remoteJidAlt: string
    +lid: "lid" | undefined
  }
  class isOnWhatsapp {
    +id: number
    +remoteJid: string
    +jidOptions: string
    +lid: string
  }
  OnWhatsappCache --> isOnWhatsapp : persists
  ISaveOnWhatsappCacheParams --> OnWhatsappCache : parameter
Loading

Class diagram for BaileysStartupService message sending with contextInfo

classDiagram
  class BaileysStartupService {
    +sendMessage(sender, message, mentions, linkPreview, quoted, messageId, ephemeralExpiration, contextInfo)
    +sendText(sender, message, ...)
    +onWhatsApp(...numbers)
  }
  class WAMessage {
    +key
    +message
    +messageTimestamp
    +contextInfo
  }
  BaileysStartupService --> WAMessage : creates/sends
Loading

Class diagram for ChatwootService conversation and media handling refactor

classDiagram
  class ChatwootService {
    +createConversation(instance, body)
    +sendAttachment(waInstance, number, media, caption, options)
    +receiveWebhook(instance, body)
    -cache
    -logger
  }
  class InstanceDto {
    +instanceName
    +instanceId
  }
  ChatwootService --> InstanceDto : uses
Loading

File-Level Changes

Change Details Files
Refactor conversation creation and contact updates
  • Introduce phoneNumber and isGroup flags to choose remoteJid
  • Replace legacy addressingMode logic for LID and group scenarios
  • Update cacheKey and verbose logs to reference phoneNumber
  • Simplify chatId derivation using phoneNumber and isGroup
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Simplify attachment download and sending logic
  • Remove custom S3/MinIO retry and HTTP timeout constants
  • Parse media URL for mimeType and fileName instead of buffered download
  • Use direct media URL for audio and document sends, removing base64 conversion
  • Replace fixed 1200ms delay with randomized delay
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Streamline webhook receive and attachment processing
  • Remove deletion lock and background deletion logic
  • Replace WEBHOOK_INITIAL_DELAY_MS constant with a simple 500ms delay
  • Inline attachment loop instead of setImmediate background execution
  • Randomize text message delay instead of fixed interval
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Enhance contact caching and duplicate filtering in BaileysStartupService
  • Add debug logging in contacts.update handler
  • Invoke saveOnWhatsappCache for '@s.whatsapp' and '@lid' contacts
  • Filter duplicate messages by requestId in messages.upsert
  • Change logger.log to verbose for consistency
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Introduce contextInfo support in sendMessage
  • Remove automatic messageId generation fallback
  • Add optional contextInfo parameter to sendMessage signature
  • Propagate contextInfo when sending and forwarding messages
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Overhaul onWhatsappCache persistence logic
  • Extend getAvailableNumbers to respect '@lid' and 'g.us' domains
  • Load existing records and merge jidOptions to preserve historical JIDs
  • Support remoteJidAlt for LID, enforce unique JID list
  • Add verbose logging around cache upsert operations
src/utils/onWhatsappCache.ts
Update message processor types
  • Replace proto.IWebMessageInfo with WAMessage in messages.upsert
  • Adjust import to use WAMessage from 'baileys'
src/api/integrations/channel/whatsapp/baileysMessage.processor.ts
Upgrade Baileys dependency to latest master
  • Change 'baileys' version in package.json to GitHub master branch
package.json

Possibly linked issues

  • #issue: The PR's Baileys update and refactoring of message and contact caching directly address the reported Baileys error and the failure to pass webhookURL in messages.

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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:1147-1148` </location>
<code_context>
-      let mimeType: string;
-      let fileName: string;
+      const parsedMedia = path.parse(decodeURIComponent(media));
+      let mimeType = mimeTypes.lookup(parsedMedia?.ext) || '';
+      let fileName = parsedMedia?.name + parsedMedia?.ext;

-      try {
</code_context>

<issue_to_address>
**issue:** Mime type fallback may be unreliable for unknown extensions.

If neither mimeTypes.lookup nor response.headers['content-type'] returns a value, mimeType may be empty, which could cause issues later. Please add a default value to ensure mimeType is always set.
</issue_to_address>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1382-1383` </location>
<code_context>
             continue;
           }

+          if (contactRaw.remoteJid.includes('@s.whatsapp') || contactRaw.remoteJid.includes('@lid')) {
+            await saveOnWhatsappCache([
+              {
+                remoteJid:
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Cache update logic for contacts may result in duplicate entries.

Review the handling of remoteJid and remoteJidAlt to prevent duplicate or inconsistent cache entries when updating with both contact types.

Suggested implementation:

```typescript
          if (contactRaw.remoteJid.includes('@s.whatsapp') || contactRaw.remoteJid.includes('@lid')) {
            const cacheRemoteJid = messageRaw.key.addressingMode === 'lid' ? messageRaw.key.remoteJidAlt : messageRaw.key.remoteJid;
            const cacheRemoteJidAlt = messageRaw.key.remoteJidAlt;

            // Check for existing cache entry for either remoteJid or remoteJidAlt
            const existingCacheEntry = await getWhatsappCacheEntry(cacheRemoteJid) || (cacheRemoteJidAlt ? await getWhatsappCacheEntry(cacheRemoteJidAlt) : null);

            if (existingCacheEntry) {
              // Merge or update the cache entry to ensure consistency
              await updateWhatsappCacheEntry({
                ...existingCacheEntry,
                remoteJid: cacheRemoteJid,
                remoteJidAlt: cacheRemoteJidAlt,
                lid: messageRaw.key.addressingMode === 'lid' ? 'lid' : null,
              });
            } else {
              // Add new cache entry if neither exists
              await saveOnWhatsappCache([
                {
                  remoteJid: cacheRemoteJid,
                  remoteJidAlt: cacheRemoteJidAlt,
                  lid: messageRaw.key.addressingMode === 'lid' ? 'lid' : null,
                },
              ]);
            }
          }

```

You will need to implement or ensure the existence of the following helper functions:
- `getWhatsappCacheEntry(remoteJid: string)` to retrieve a cache entry by remoteJid.
- `updateWhatsappCacheEntry(entry: object)` to update an existing cache entry.

If these functions do not exist, you should add them to your cache management module or service.
</issue_to_address>

### Comment 3
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:3385-3394` </location>
<code_context>
+    // TODO: Unificar verificação de cache para todos os números (normais e LID)
</code_context>

<issue_to_address>
**issue:** Multiple TODOs indicate incomplete refactoring and potential for missed edge cases.

The presence of TODOs for cache handling, particularly for LID numbers, suggests incomplete logic. Please address these to avoid missing edge cases.
</issue_to_address>

### Comment 4
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:576` </location>
<code_context>
    const remoteJid = body.key.remoteJid;

</code_context>

<issue_to_address>
**suggestion (code-quality):** Prefer object destructuring when accessing and using properties. ([`use-object-destructuring`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/use-object-destructuring))

```suggestion
    const {remoteJid} = body.key;
```

<br/><details><summary>Explanation</summary>Object destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the [Airbnb Javascript Style Guide](https://airbnb.io/javascript/#destructuring--object)
</details>
</issue_to_address>

### Comment 5
<location> `src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts:2054` </location>
<code_context>
              content = bodyMessage ? bodyMessage : '';

</code_context>

<issue_to_address>
**suggestion (code-quality):** Avoid unneeded ternary statements ([`simplify-ternary`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/simplify-ternary))

```suggestion
              content = bodyMessage || '';
```

<br/><details><summary>Explanation</summary>It is possible to simplify certain ternary statements into either use of an `||` or `!`.
This makes the code easier to read, since there is no conditional logic.
</details>
</issue_to_address>

### Comment 6
<location> `src/utils/onWhatsappCache.ts:110-114` </location>
<code_context>
      if (altJid) {
        if (!finalJidOptions.includes(altJid)) {
          finalJidOptions.push(altJid);
        }
      }

</code_context>

<issue_to_address>
**suggestion (code-quality):** Merge nested if conditions ([`merge-nested-ifs`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/merge-nested-ifs))

```suggestion
      if (altJid && !finalJidOptions.includes(altJid)) {
            finalJidOptions.push(altJid);
      }

```

<br/><details><summary>Explanation</summary>Reading deeply nested conditional code is confusing, since you have to keep track of which
conditions relate to which levels. We therefore strive to reduce nesting where
possible, and the situation where two `if` conditions can be combined using
`and` is an easy win.
</details>
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

KokeroO and others added 5 commits October 19, 2025 02:26
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…e.ts

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…e.ts

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@DavidsonGomes DavidsonGomes merged commit cd71ff5 into EvolutionAPI:develop Oct 19, 2025
5 checks passed
milesibastos added a commit to chatwoot-br/evolution-api that referenced this pull request Oct 20, 2025
commit 48bda1b
Merge: e83a7e2 dd21a29
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Sun Oct 19 17:59:26 2025 -0300

    Merge pull request EvolutionAPI#2107 from KokeroO/develop

    fix( baileys.service ): Corrige ao salvar no DB valores Uint8Array

commit dd21a29
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 18:53:16 2025 +0000

    fix(baileys): salvar corretamente buffer no db

commit e83a7e2
Merge: cd71ff5 d58d0b8
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Sun Oct 19 06:41:28 2025 -0300

    Merge pull request EvolutionAPI#2105 from KokeroO/develop

    fix: Simplify logging of messageSent object

commit d58d0b8
Merge: 4efc9b6 cd71ff5
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 06:34:58 2025 -0300

    Merge branch 'EvolutionAPI:develop' into develop

commit 4efc9b6
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 06:34:45 2025 -0300

    Simplify logging of messageSent object

    Evita o erro de this.isZero not is function

commit cd71ff5
Merge: cdf0666 582166e
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Sun Oct 19 06:23:39 2025 -0300

    Merge pull request EvolutionAPI#2103 from KokeroO/develop

    feat(baileys,chatwoot,on-whatsapp-cache): implementações e correções na baileys e chatwoot

commit 582166e
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 05:41:55 2025 +0000

    fix(lint): lint

commit e1ae03c
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 05:37:22 2025 +0000

    fix(comments): comments fix

commit 0737c45
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 02:29:04 2025 -0300

    Update src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

    Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>

commit adbe107
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 02:28:45 2025 -0300

    Update src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

    Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>

commit 423f629
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 02:26:52 2025 -0300

    Update src/utils/onWhatsappCache.ts

    Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>

commit 946dcae
Author: Willian Coqueiro <wil_kokero@hotmail.com>
Date:   Sun Oct 19 03:05:11 2025 +0000

    feat(baileys,chatwoot,on-whatsapp-cache): implementações e correções na baileys e chatwoot

    * corrige cache de números PN, LIDs e g.us para enviar o número correto
    * atualiza para os últimos commits da baileys
    * corrige envio de áudio e documentos via chatwoot no canal baileys
    * diversas correções na integração com chatwoot
    * corrige mensagens ignoradas no recebimento de leads
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