feat(baileys,chatwoot,on-whatsapp-cache): implementações e correções na baileys e chatwoot by KokeroO · Pull Request #2103 · EvolutionAPI/evolution-api · GitHub
Skip to content

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

Merged
DavidsonGomes merged 6 commits intoEvolutionAPI:developfrom
KokeroO:develop
Oct 19, 2025
Merged

feat(baileys,chatwoot,on-whatsapp-cache): implementações e correções na baileys e chatwoot#2103
DavidsonGomes merged 6 commits intoEvolutionAPI:developfrom
KokeroO:develop

Conversation

@KokeroO
Copy link
Copy Markdown
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
Copy Markdown
Contributor

sourcery-ai Bot commented Oct 19, 2025

Copy link
Copy Markdown
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.

Comment thread src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Comment thread src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts Outdated
Comment thread src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts Outdated
Comment thread src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts Outdated
Comment thread src/utils/onWhatsappCache.ts Outdated
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