-
Notifications
You must be signed in to change notification settings - Fork 4.6k
feat(baileys,chatwoot,on-whatsapp-cache): implementações e correções na baileys e chatwoot #2103
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
Conversation
…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
Reviewer's GuideRefactors 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 persistencesequenceDiagram
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
Sequence diagram for ChatwootService media sending (audio/document) refactorsequenceDiagram
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
Class diagram for updated onWhatsappCache persistence and data modelclassDiagram
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
Class diagram for BaileysStartupService message sending with contextInfoclassDiagram
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
Class diagram for ChatwootService conversation and media handling refactorclassDiagram
class ChatwootService {
+createConversation(instance, body)
+sendAttachment(waInstance, number, media, caption, options)
+receiveWebhook(instance, body)
-cache
-logger
}
class InstanceDto {
+instanceName
+instanceId
}
ChatwootService --> InstanceDto : uses
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this 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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Outdated
Show resolved
Hide resolved
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Outdated
Show resolved
Hide resolved
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Outdated
Show resolved
Hide resolved
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>
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
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:
Bug Fixes:
Enhancements:
Chores: