evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

fix(chatwoot): deliver bot QR when conversation is resolved

Open cesar-carlos opened this issue 5 months ago • 3 comments

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 createBotMessage and createBotQr
  • Match init commands exactly (init, init:<number>, iniciar) instead of includes('init')
  • Guard receiveWebhook when 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)

  1. Enable CHATWOOT_BOT_CONTACT=true
  2. Create/connect instance with Chatwoot integration
  3. Send init in bot conversation (+123456)
  4. Let Chatwoot automation resolve the conversation
  5. Baileys generates QR → Evolution logs WARN conversation not found → user never receives QR in Chatwoot

Test plan

  • [ ] Send init in bot conversation with a resolved thread → conversation reopens and QR image arrives
  • [ ] Send init when no bot conversation exists → conversation is created and QR arrives
  • [ ] Commands init:5511999999999 and iniciar still trigger connection
  • [ ] Commands like definition no longer trigger connection
  • [ ] QR limit message is delivered when QRCODE_LIMIT is 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.

cesar-carlos avatar Jun 11 '26 15:06 cesar-carlos

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
  • Add getOrOpenBotConversation to reuse, reopen, or create the bot inbox conversation before sending messages
  • Reuse contact ID resolution logic and guard when contact or Chatwoot client is missing
  • Use the new helper in bot message/QR creation instead of relying solely on open conversations
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Tighten bot init command detection and protect webhook processing when WA instance is missing
  • Introduce isBotInitCommand to match exact init-style commands rather than substring matches
  • Guard receiveWebhook early when the WhatsApp instance is not loaded in memory
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
Send QR image and instructions in a single bot message
  • Remove separate bot QR notification before the text message
  • Change createBotMessage call to createBotQr so QR image and instructions are sent together, avoiding duplicate QR posts
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 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

  • 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.

sourcery-ai[bot] avatar Jun 11 '26 15:06 sourcery-ai[bot]

Related issue: #2580

cesar-carlos avatar Jun 11 '26 15:06 cesar-carlos

please, do not send to main, you need to send to develop

dpaes avatar Jun 12 '26 03:06 dpaes

🔴 👎

O fix do Chatwoot (entregar o QR do bot quando a conversa é resolvida) é pertinente, mas o PR aponta para main. Reabre contra develop.

@dpaes

NeritonDias avatar Jun 26 '26 02:06 NeritonDias