Skip to content

fix: melhora consistência e formatação dos chatbots (N8N e Evolution Bot) #1484

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

Merged
merged 4 commits into from
May 22, 2025

Conversation

oriondesign2015
Copy link
Contributor

@oriondesign2015 oriondesign2015 commented May 22, 2025

Descrição

Esta PR implementa várias correções para melhorar a consistência e formatação dos chatbots, padronizando comportamentos e melhorando a experiência do usuário.

Mudanças

N8n

  1. Formatação de Mensagens

    • Adicionado .trim() nas variáveis beforeText e remainingText
    • Remove quebras de linha extras antes e depois de mídias (imagens, vídeos, etc)
    • Mantém apenas as quebras de linha intencionais na mensagem
  2. Gerenciamento de Sessão

    • Removida a atualização automática de status para 'opened' quando a sessão está pausada
    • Agora ignora completamente mensagens recebidas durante sessão pausada
    • Sessão só é reativada através do endpoint de mudança de status

Evolution Bot

  1. Processamento de Mensagens

    • Corrigido o processamento de mensagens subsequentes
    • Ajustado o fluxo para manter a sessão ativa após enviar resposta
    • Melhorada a consistência no tratamento de mensagens
  2. Comportamento de Sessão

    • Padronizado o comportamento de sessão pausada com o N8n
    • Sessão pausada não reativa automaticamente ao receber mensagens
    • Mantém consistência no gerenciamento de estado entre diferentes tipos de chatbot

Observação

Devido à refatoração em andamento do sistema de chatbots, é possível que outras integrações (como OpenAI, Dify, Flowise, EvoAI, etc) apresentem problemas semelhantes de gerenciamento de sessão que podem ser corrigidas em PRs subsequentes.

Summary by Sourcery

Improve consistency and formatting for N8N and Evolution Bot chatbots by trimming message whitespace, removing unintended newlines, and standardizing session pause behavior across integrations.

Bug Fixes:

  • Trim whitespace and strip extra line breaks around media links in N8N messages.
  • Prevent paused sessions from automatically reopening by ignoring incoming messages in N8N and the base service.
  • Add missing "msg" parameter in Evolution Bot controller to correct message processing signature.
  • Return null in ChatbotController when a session conflict is detected instead of void.

Enhancements:

  • Keep Evolution Bot sessions active after sending responses to maintain conversation flow.
  • Unify paused session handling across N8N and Evolution Bot for consistent state management.

Corrige o problema de formatação nas mensagens do N8n onde quebras de linha extras estavam sendo adicionadas antes e depois das mídias (imagens, vídeos, etc). Agora o texto é enviado mantendo apenas as quebras de linha intencionais.
Corrige o problema onde o Evolution Bot não processava mensagens subsequentes após a primeira resposta. A correção permite que o bot continue respondendo a todas as mensagens enquanto a sessão estiver ativa, melhorando a continuidade da conversa.
Corrige o problema onde o Evolution Bot reativava automaticamente por qualquer mensagem do usuario quando a sessão estava pausada. Agora, quando uma sessão está pausada, o bot ignora completamente as mensagens recebidas até que a sessão seja explicitamente reativada.
Corrige o problema onde o N8N reativava automaticamente a sessão após receber uma mensagem quando estava pausado. Agora, quando uma sessão está pausada, o bot ignora completamente as mensagens recebidas até que a sessão seja explicitamente reativada através do endpoint de mudança de status.
Copy link
Contributor

sourcery-ai bot commented May 22, 2025

Reviewer's Guide

This PR applies whitespace trimming to chatbot messages in N8n, overhauls session pause handling (disabling auto-reopen and ignoring messages during pause) across the BaseChatbotService, and harmonizes controller behaviors—standardizing skip logic, return values, and forwarding the raw message in the EvolutionBotController.

Sequence Diagram: Message Processing with Paused Session in BaseChatbotService

sequenceDiagram
    participant ClientCode as Specific Chatbot Logic
    participant BaseChatbotService

    ClientCode->>BaseChatbotService: processMessage(..., session, content, ...)
    BaseChatbotService->>BaseChatbotService: Check if session object exists
    alt session is null (new conversation)
        BaseChatbotService->>BaseChatbotService: initNewSession(...)
    end
    BaseChatbotService->>BaseChatbotService: Get session.status
    alt session.status is "paused"
        BaseChatbotService-->>ClientCode: Return immediately (message ignored)
    else session.status is not "paused" (e.g., "opened", "awaitingInput")
        BaseChatbotService->>BaseChatbotService: Proceed with normal message processing (e.g., check keywords, interact with bot logic)
        BaseChatbotService-->>ClientCode: Return (processing complete / potential response)
    end
Loading

Class Diagram: Updates to Chatbot System Classes

classDiagram
    class BaseChatbotService~BotType, SettingsType~ {
        #processMessage(instance, remoteJid, bot, settings, session, content, pushName, msg): Promise~void~
    }
    class N8nService {
        % Method where message formatting (e.g., .trim()) was updated %
        -_parseMessageContent(message: string): string
        % Method handling incoming N8N webhooks, session logic updated for paused state %
        +handleWebhook(payload: any): void
    }
    N8nService --|> BaseChatbotService

    class BaseChatbotController~BotType, BotData~ {
        % Method handling incoming messages, logic for skipping already closed sessions updated %
        #_onMessageReceived(event: any, session: Session, ...): void
    }
    class EvolutionBotController {
        % Method signature updated to include 'msg' parameter %
        #processMessage(instance, remoteJid, bot, session, settings, content: string, pushName?: string, msg?: any): void
    }
    EvolutionBotController --|> BaseChatbotController

    class EvolutionBotService {
        % Method signature updated to include 'msg' parameter, called by EvolutionBotController %
        #process(instance, remoteJid, bot, session, settings, content: string, pushName?: string, msg?: any): void
    }
    EvolutionBotService --|> BaseChatbotService

    class ChatbotController {
        % Method for assigning bot to session, return behavior changed for specific conditions %
        #_ensureBotAssignedToSession(integrationId: string, remoteJid: string, botId?: string, session?: Session, ...): Session | null
    }
Loading

File-Level Changes

Change Details Files
Enhanced message formatting by trimming and preserving intentional line breaks
  • Added .trim() to beforeText
  • Added .trim() to remainingText
src/api/integrations/chatbot/n8n/services/n8n.service.ts
Revamped session pause handling to ignore incoming messages and stop automatic reopening
  • Removed automatic status update on paused sessions
  • Added early return for paused sessions in BaseChatbotService
  • Adjusted new-session initialization to distinguish paused from missing sessions
src/api/integrations/chatbot/n8n/services/n8n.service.ts
src/api/integrations/chatbot/base-chatbot.service.ts
Standardized session skip logic across controllers and adjusted return behavior
  • Changed skip condition to check status 'closed' instead of awaitUser
  • Updated return to null when session is already opened
  • Extended EvolutionBotController to forward the raw msg argument
src/api/integrations/chatbot/base-chatbot.controller.ts
src/api/integrations/chatbot/chatbot.controller.ts
src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts

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

@DavidsonGomes DavidsonGomes merged commit edde059 into EvolutionAPI:develop May 22, 2025
1 check passed
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