fix(chatwoot): deliver bot QR when conversation is resolved
Summary
Fixes a production issue where WhatsApp QR codes are generated by Baileys but never reach the Chatwoot bot conversation after users send init.
Root cause: createBotMessage and createBotQr only post to conversations with status === 'open'. Chatwoot automations frequently resolve the bot thread (+123456) right after init, so Evolution logs conversation not found and silently drops the QR. Instances can remain stuck in connecting until QRCODE_LIMIT is reached.
Changes
- Add
getOrOpenBotConversation()to reopen the latest bot inbox conversation or create a new one before sending bot messages - Use the helper in
createBotMessageandcreateBotQr - Match
initcommands exactly (init,init:<number>,iniciar) instead ofincludes('init') - Guard
receiveWebhookwhen the WA instance is not loaded in memory - Send QR image + scan instructions in a single bot message (avoid duplicate QR posts per refresh)
Reproduction (before fix)
- Enable
CHATWOOT_BOT_CONTACT=true - Create/connect instance with Chatwoot integration
- Send
initin bot conversation (+123456) - Let Chatwoot automation resolve the conversation
- Baileys generates QR → Evolution logs
WARN conversation not found→ user never receives QR in Chatwoot
Test plan
- [ ] Send
initin bot conversation with a resolved thread → conversation reopens and QR image arrives - [ ] Send
initwhen no bot conversation exists → conversation is created and QR arrives - [ ] Commands
init:5511999999999andiniciarstill trigger connection - [ ] Commands like
definitionno longer trigger connection - [ ] QR limit message is delivered when
QRCODE_LIMITis reached - [ ] Normal Chatwoot ↔ WhatsApp customer conversations are unaffected
Made with Cursor
Summary by Sourcery
Ensure Chatwoot bot conversations are reopened or created before delivering QR and status messages, and tighten handling of bot init commands and WhatsApp instance availability.
Bug Fixes:
- Prevent WhatsApp QR codes from being dropped when the bot conversation has been auto-resolved by reopening or creating the bot inbox conversation before sending messages.
- Avoid failures when Chatwoot contact payloads lack a top-level ID by safely deriving the contact ID from nested payload data.
- Stop triggering bot initialization on messages that merely contain the substring 'init' by matching specific init-style commands only.
- Prevent processing of bot webhooks when the corresponding WhatsApp instance is not loaded in memory.
Enhancements:
- Send WhatsApp QR images and scan instructions in a single bot message to avoid duplicate QR posts per refresh and improve user experience.
Reviewer's Guide
Reopens or creates a dedicated Chatwoot bot conversation before sending WhatsApp QR/status messages, hardens command parsing and webhook handling, and consolidates QR delivery into a single bot message.
Sequence diagram for reopening or creating bot conversation before QR delivery
sequenceDiagram
actor User
participant Chatwoot
participant ChatwootService
participant ChatwootClient
User->>Chatwoot: send /init
Chatwoot->>ChatwootService: receiveWebhook(body)
ChatwootService->>ChatwootService: isBotInitCommand(command)
alt [command is init]
ChatwootService->>ChatwootService: getOrOpenBotConversation(instance, inbox, contact)
alt [open conversation exists]
ChatwootService-->>ChatwootService: return openConversation
else [no open conversation]
ChatwootService->>ChatwootClient: contacts.listConversations(accountId, contactId)
ChatwootClient-->>ChatwootService: conversations
alt [latest inbox conversation is resolved]
ChatwootService->>ChatwootClient: conversations.toggleStatus(accountId, conversationId, status)
ChatwootClient-->>ChatwootService: updatedConversation
else [no conversation]
ChatwootService->>ChatwootClient: conversations.create(accountId, contact_id, inbox_id)
ChatwootClient-->>ChatwootService: createdConversation
end
end
ChatwootService->>ChatwootService: createBotQr(instance, msgQrCode, messageType, fileStream, filename)
end
File-Level Changes
| Change | Details | Files |
|---|---|---|
| Ensure bot QR/status messages always target an open bot conversation |
|
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts |
| Tighten bot init command detection and protect webhook processing when WA instance is missing |
|
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts |
| Send QR image and instructions in a single bot message |
|
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts |
Possibly linked issues
- #META Chatwoot umbrella: PR fixes missing bot QR delivery to Chatwoot, one of the QR/connection problems tracked in this meta-issue.
Tips and commands
Interacting with Sourcery
- Trigger a new review: Comment
@sourcery-ai reviewon 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 issueto create an issue from it. - Generate a pull request title: Write
@sourcery-aianywhere in the pull request title to generate a title at any time. You can also comment@sourcery-ai titleon the pull request to (re-)generate the title at any time. - Generate a pull request summary: Write
@sourcery-ai summaryanywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment@sourcery-ai summaryon the pull request to (re-)generate the summary at any time. - Generate reviewer's guide: Comment
@sourcery-ai guideon the pull request to (re-)generate the reviewer's guide at any time. - Resolve all Sourcery comments: Comment
@sourcery-ai resolveon 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 dismisson 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 reviewto 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
- Contact our support team for questions or feedback.
- Visit our documentation for detailed guides and information.
- Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.
Related issue: #2580
please, do not send to main, you need to send to develop
🔴 👎
O fix do Chatwoot (entregar o QR do bot quando a conversa é resolvida) é pertinente, mas o PR aponta para main. Reabre contra develop.
@dpaes