-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Desabilitar confirmações de leitura no Chatwoot + Fix "Falha ao enviar" (v2.3.7 - [Baileys]) / CHATWOOT_MESSAGE_READ=false has no effect + webhook receiveWebhook causes timeout #2494
Description
Bem-vido!
- Sim, pesquisei problemas semelhantes no GitHub e não encontrei nenhum.
O que você fez?
Solução: Desabilitar confirmações de leitura no Chatwoot + Fix "Falha ao enviar" (v2.3.7 - [Baileys])
Compartilhando a solução para dois problemas relacionados que afetam fluxos com alto volume de mensagens na integração Evolution API + Chatwoot.
Problema 1: Confirmações de leitura inundam o Chatwoot
Em fluxos com muitas mensagens, as confirmações de leitura (read receipts) enviadas ao Chatwoot geram uma enxurrada de eventos que sobrecarrega o processamento — conversas ficam lentas e webhooks acumulam fila.
O que NÃO funciona
-
CHATWOOT_MESSAGE_READ=falsena stack: a variável é carregada corretamente no container (confirmado viaenv | grep CHATWOOT), mas o comportamento não muda. Conforme relatado nesta issue, as descrições das variáveisMESSAGE_READeMESSAGE_DELETEestão trocadas no.env.example, mas mesmo invertendo, o problema persiste. -
readMessages: falseereadStatus: falsevia settings da instância (/settings/find/{instance}): controla apenas o lado do WhatsApp (se marca como lido ao processar), não impede o envio de eventos ao Chatwoot. -
Re-set do Chatwoot via
/chatwoot/set/{instance}: não tem efeito permanente.
Causa raiz
No código compilado (dist/main.js), existe o seguinte trecho no handler de messages.update do Baileys service:
ie[n.status]==="READ" && i.fromMe && this.configService.get("CHATWOOT").ENABLED
&& this.localChatwoot?.enabled
&& this.chatwootService.eventWhatsapp("messages.read", ...)
Quando o status de uma mensagem muda para READ no WhatsApp, o evento messages.read é disparado ao ChatwootService. Dentro do ChatwootService, o handler desse evento atualiza o status da mensagem no Chatwoot.
A variável CHATWOOT_MESSAGE_READ não controla esse fluxo — ela controla apenas se a Evolution marca mensagens como lidas no WhatsApp quando o agente envia pelo Chatwoot (fluxo inverso).
Problema 2: "Falha ao enviar" no Chatwoot
Quando o Chatwoot envia uma mensagem via webhook para a Evolution API, o controller espera todo o processamento (envio ao WhatsApp + confirmação) antes de responder ao Chatwoot:
return this.chatwootService.receiveWebhook(s, e)
Além disso, o receiveWebhook tem um delay de 500ms embutido. Em fluxos com várias mensagens simultâneas, o Chatwoot atinge o timeout e marca como "Falha ao enviar", mesmo que a mensagem tenha sido enviada com sucesso.
Solução: Patches via entrypoint no Docker
A solução aplica dois sed no dist/main.js antes de iniciar a API, via entrypoint na stack Docker. Os patches sobrevivem a qualquer restart/redeploy.
Patch 1: Desabilitar confirmações de leitura
Faz o handler de messages.read no ChatwootService retornar imediatamente sem processar:
sed -i 's|if(s==="messages.read"){|if(s==="messages.read"){return;|g' /evolution/dist/main.jsPatch 2: Resposta imediata no webhook
Faz o controller responder instantaneamente ao Chatwoot e processar o envio ao WhatsApp em background (fire-and-forget):
sed -i 's|return this.chatwootService.receiveWebhook(s,e)|this.chatwootService.receiveWebhook(s,e).catch(err=>this.logger.error(err));return{message:"bot"}|g' /evolution/dist/main.jsImplementação na stack Docker (Swarm/Compose)
Adicionar o entrypoint no serviço da Evolution API:
services:
evolution:
image: evoapicloud/evolution-api:v2.3.7
entrypoint:
- sh
- -c
- |
echo "[PATCH 1/2] Desabilitando confirmacao de leitura no Chatwoot..."
sed -i 's|if(s==="messages.read"){|if(s==="messages.read"){return;|g' /evolution/dist/main.js
echo "[PATCH 2/2] Resposta imediata no webhook do Chatwoot..."
sed -i 's|return this.chatwootService.receiveWebhook(s,e)|this.chatwootService.receiveWebhook(s,e).catch(err=>this.logger.error(err));return{message:"bot"}|g' /evolution/dist/main.js
echo "[PATCH] Todos os patches aplicados."
npm run start:prod
# ... restante da configuraçãoVerificação
Nos logs do container, as linhas de PATCH devem aparecer antes do boot da API:
[PATCH 1/2] Desabilitando confirmacao de leitura no Chatwoot...
[PATCH 2/2] Resposta imediata no webhook do Chatwoot...
[PATCH] Todos os patches aplicados.
Resultado
- Confirmações de leitura não são mais enviadas ao Chatwoot
- Mensagens enviadas pelo Chatwoot não exibem mais "Falha ao enviar"
- Recebimento e envio de mensagens funcionam normalmente
- Os patches são reaplicados automaticamente a cada restart do container
Ambiente
- Evolution API: v2.3.7 (
evoapicloud/evolution-api:v2.3.7) - Chatwoot: v4.12.1
- Deploy: Docker Swarm
- Banco: PostgreSQL 16
- Cache: Redis 7
Sugestão aos mantenedores
Seria útil implementar no código-fonte:
- Uma variável de ambiente dedicada (ex:
CHATWOOT_DISABLE_READ_EVENTS=true) que de fato bloqueie o envio demessages.readao Chatwoot - Tornar o
receiveWebhookdo controller assíncrono por padrão, respondendo imediatamente ao Chatwoot - Corrigir as descrições invertidas de
CHATWOOT_MESSAGE_READeCHATWOOT_MESSAGE_DELETEno.env.example
What did you do?
Configured CHATWOOT_MESSAGE_READ=false in the Docker stack environment variables to disable read receipts from being sent to Chatwoot. Also experienced "Falha ao enviar" (Failed to send) errors in Chatwoot when sending multiple messages in sequence.
What did you expect?
- Setting
CHATWOOT_MESSAGE_READ=falseshould prevent read receipt events (messages.read) from being forwarded to Chatwoot - Messages sent from Chatwoot should be acknowledged immediately, without waiting for WhatsApp delivery confirmation
What did you observe instead?
Bug 1: CHATWOOT_MESSAGE_READ has no effect
The variable is correctly loaded in the container (confirmed via env | grep CHATWOOT), but read receipts continue flooding Chatwoot. The variable only controls whether Evolution marks messages as read on WhatsApp when an agent sends via Chatwoot — it does not control the messages.read event being sent to Chatwoot.
The actual code responsible (in dist/main.js, Baileys service messages.update handler):
ie[n.status]==="READ" && i.fromMe
&& this.configService.get("CHATWOOT").ENABLED
&& this.localChatwoot?.enabled
&& this.chatwootService.eventWhatsapp("messages.read", ...)This fires regardless of CHATWOOT_MESSAGE_READ being true or false.
Additionally, as reported in #1616, the descriptions of CHATWOOT_MESSAGE_READ and CHATWOOT_MESSAGE_DELETE are swapped in .env.example. Even inverting them does not fix the issue.
Bug 2: receiveWebhook is synchronous, causing Chatwoot timeout
The controller waits for the entire processing before responding:
async receiveWebhook(s, e) {
if (!this.configService.get("CHATWOOT").ENABLED) throw new Error("Chatwoot is disabled");
return this.chatwootService.receiveWebhook(s, e); // blocks until WhatsApp confirms
}The chatwootService.receiveWebhook also has a 500ms built-in delay. When multiple messages are sent, Chatwoot times out and shows "Falha ao enviar" even though messages are actually delivered.
Workaround
Two sed patches applied via entrypoint in the Docker stack:
services:
evolution:
image: evoapicloud/evolution-api:v2.3.7
entrypoint:
- sh
- -c
- |
# Patch 1: Disable read receipts to Chatwoot
sed -i 's|if(s==="messages.read"){|if(s==="messages.read"){return;|g' /evolution/dist/main.js
# Patch 2: Async webhook response (fire-and-forget)
sed -i 's|return this.chatwootService.receiveWebhook(s,e)|this.chatwootService.receiveWebhook(s,e).catch(err=>this.logger.error(err));return{message:"bot"}|g' /evolution/dist/main.js
npm run start:prodSuggested fix in source code
- Add a dedicated env variable (e.g.
CHATWOOT_DISABLE_READ_EVENTS=true) that actually blocksmessages.readevents from being sent to Chatwoot - Make the
receiveWebhookcontroller respond immediately with{message: "bot"}and process async in background - Fix the swapped descriptions of
CHATWOOT_MESSAGE_READandCHATWOOT_MESSAGE_DELETEin.env.example(reported in Erro de digitação no arquivo .env.example #1616)
Environment
- Evolution API: v2.3.7 (
evoapicloud/evolution-api:v2.3.7) - Chatwoot: v4.12.1
- Deploy: Docker Swarm
- Database: PostgreSQL 16
- Cache: Redis 7
- OS: Ubuntu (Docker Swarm mode)
O que você esperava?
n/a
O que vc observou ao invés do que esperava?
n/a
Capturas de Tela/Vídeos
No response
Qual versão da API você está usando?
v2.3.7
Qual é o seu ambiente?
Windows
Outras expecificações do ambiente
n/a
Se aplicável, cole a saída do log
No response
Notas Adicionais
No response