Skip to content

Develop debug #1861

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

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from

Conversation

saulommartins
Copy link

@saulommartins saulommartins commented Aug 21, 2025

Summary by Sourcery

Add comprehensive debug logging throughout the chatbot integration pipeline to trace message handling, bot resolution, and error flows.

Enhancements:

  • Instrument BaseChatbotController.emit with detailed logs for startup, settings lookup, ignore checks, session retrieval, content extraction, bot finding (including fallback logic), debounce processing, and processBot success or failure.
  • Wrap ChatbotController.emit in a try-catch and log each sub-controller.emit invocation and overall completion or error.
  • Log incoming message batches and individual messages in BaileysStartupService and BaileysMessageProcessor to trace receipt and forwarding to the chatbotController.
  • Enhance OpenaiService.process to log process start, bot metadata, message content, and session state.
  • Add debug console logs in the findBotByTrigger utility to report search criteria and matched triggers.

Copy link
Contributor

sourcery-ai bot commented Aug 21, 2025

Reviewer's Guide

This PR adds extensive debug logging across chatbot integration layers, wrapping key operations in log statements and try/catch blocks to trace execution flow and errors without altering business logic.

Sequence diagram for enhanced logging in chatbot message processing

sequenceDiagram
    participant WhatsAppService as BaileysStartupService
    participant ChatbotController
    participant BotController as BaseChatbotController
    participant BotService as OpenaiService
    actor User

    User->>WhatsAppService: Sends message
    WhatsAppService->>WhatsAppService: Log MESSAGES.UPSERT STARTED
    WhatsAppService->>WhatsAppService: Log Processing message details
    WhatsAppService->>ChatbotController: emit({instance, remoteJid, msg, ...})
    ChatbotController->>ChatbotController: Log EMIT STARTED
    ChatbotController->>BotController: emit(emitData)
    BotController->>BotController: Log EMIT STARTED
    BotController->>BotController: Log Looking for settings
    BotController->>BotController: Log Settings found
    BotController->>BotController: Log Looking for session
    BotController->>BotController: Log Session found
    BotController->>BotController: Log Content
    BotController->>BotController: Log Looking for bot trigger
    BotController->>BotController: Log Bot found
    BotController->>BotController: Log fallback if needed
    BotController->>BotController: Log Fallback bot found or not
    BotController->>BotController: Log Processing with/without debounce
    BotController->>BotService: processBot(...)
    BotService->>BotService: Log PROCESS STARTED
    BotService->>BotService: Log Bot ID, enabled, Content, Session
    BotService-->>BotController: processBot result
    BotController-->>ChatbotController: emit result
    ChatbotController-->>WhatsAppService: emit result
    WhatsAppService->>WhatsAppService: Log chatbotController.emit completed
    WhatsAppService->>User: Message processed
Loading

Class diagram for updated logging in chatbot integration classes

classDiagram
    class BaileysStartupService {
        +logger
        +emit()
        +sendDataWebhook()
        +process message with logging
    }
    class ChatbotController {
        +logger
        +emit()
        +processDebounce()
        +logging for each bot emit
    }
    class BaseChatbotController {
        +logger
        +emit()
        +findBotTrigger()
        +getSession()
        +processBot()
        +logging at each step
    }
    class OpenaiService {
        +logger
        +processBot()
        +logging for processBot
    }
    BaileysStartupService --> ChatbotController : calls emit
    ChatbotController --> BaseChatbotController : calls emit
    BaseChatbotController --> OpenaiService : calls processBot
Loading

Flow diagram for debug logging in bot trigger search

flowchart TD
    A[findBotByTrigger called] --> B[Log: Searching for bot]
    B --> C[Check for triggerType 'all' or 'none']
    C --> D[Log: All/None trigger found]
    D --> E{Trigger found?}
    E -- Yes --> F[Log: Returning bot]
    E -- No --> G[Continue with advancedOperatorsSearch]
Loading

File-Level Changes

Change Details Files
Instrument BaseChatbotController.emit with detailed logs and error handling
  • Log start of emit and integration status
  • Log settings lookup and ignoreJids check
  • Log session retrieval and content extraction
  • Log bot trigger search, fallback logic and results
  • Wrap processBot calls with debounce/non-debounce logs, success and error handling
src/api/integrations/chatbot/base-chatbot.controller.ts
Wrap ChatbotController.emit calls in logging and error handling
  • Log start of emit and each controller.emit invocation
  • Log completion of each emit call
  • Catch and log errors during the emit sequence
src/api/integrations/chatbot/chatbot.controller.ts
Add debug logs in BaileysStartupService for message upsert
  • Log start of MESSAGES_UPSERT and message details
  • Log before calling chatbotController.emit
  • Wrap emit call in try/catch with success/error logs
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Enhance BaileysMessageProcessor logs
  • Log processing of a batch with count
  • Log details for each message in the batch
src/api/integrations/channel/whatsapp/baileysMessage.processor.ts
Extend OpenaiService with start-up debug logs
  • Log process start with remoteJid and bot type
  • Log bot ID, enabled status, content and session state
src/api/integrations/chatbot/openai/services/openai.service.ts
Add console logging in findBotByTrigger util
  • Log search parameters and intermediate results
  • Log final bot trigger selection or absence
src/utils/findBotByTrigger.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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a 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 - here's some feedback:

  • You’re adding many inline debug logs with emojis which could clutter production output—consider using structured logging with configurable levels and verbosity instead of raw console messages.
  • There’s a lot of repeated logger.log calls for entry/exit and status checks—extracting a reusable logging decorator or helper would cut down boilerplate and improve maintainability.
  • In findBotByTrigger you’re using console.log directly; please switch to the project’s logger instance for consistency and better control over log output.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- You’re adding many inline debug logs with emojis which could clutter production output—consider using structured logging with configurable levels and verbosity instead of raw console messages.
- There’s a lot of repeated logger.log calls for entry/exit and status checks—extracting a reusable logging decorator or helper would cut down boilerplate and improve maintainability.
- In findBotByTrigger you’re using console.log directly; please switch to the project’s logger instance for consistency and better control over log output.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1049` </location>
<code_context>
       settings: any,
     ) => {
       try {
+        this.logger.log(`🚀 [Baileys] MESSAGES.UPSERT STARTED - type: ${type}, messages: ${messages.length}`);
+        
</code_context>

<issue_to_address>
Error logging may omit stack trace information.

Log the full error object or stack trace to improve error reporting and facilitate debugging.
</issue_to_address>

### Comment 2
<location> `src/utils/findBotByTrigger.ts:4` </location>
<code_context>
 import { advancedOperatorsSearch } from './advancedOperatorsSearch';

 export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => {
+  console.log(`🔍 [findBotByTrigger] Searching for bot - content: "${content}", instanceId: ${instanceId}`);
+  
   // Check for triggerType 'all' or 'none' (both should match any message)
</code_context>

<issue_to_address>
Use of console.log for logging may be inconsistent with other logger usage.

Replace console.log with the project's structured logger to ensure consistent logging and log level management.

Suggested implementation:

```typescript
import { advancedOperatorsSearch } from './advancedOperatorsSearch';
import { logger } from '../logger';

export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => {
  logger.info(`🔍 [findBotByTrigger] Searching for bot - content: "${content}", instanceId: ${instanceId}`);

  // Check for triggerType 'all' or 'none' (both should match any message)
  const findTriggerAllOrNone = await botRepository.findFirst({
    where: {
    },
  });

  logger.info(`🤖 [findBotByTrigger] All/None trigger found: ${findTriggerAllOrNone ? 'YES' : 'NO'} - ID: ${findTriggerAllOrNone?.id || 'NONE'}`);

  if (findTriggerAllOrNone) {
    logger.info(`✅ [findBotByTrigger] Returning bot with triggerType: ${findTriggerAllOrNone.triggerType}`);
    return findTriggerAllOrNone;

```

If your logger uses a different import path or method (e.g., `import logger from ...` or `logger.log('info', ...)`), adjust the import and usage accordingly.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 1339 to +1348

this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);

await chatbotController.emit({
instance: { instanceName: this.instance.name, instanceId: this.instanceId },
remoteJid: messageRaw.key.remoteJid,
msg: messageRaw,
pushName: messageRaw.pushName,
});
this.logger.log(`🤖 [Baileys] Calling chatbotController.emit for remoteJid: ${messageRaw.key.remoteJid}`);

try {
await chatbotController.emit({
instance: { instanceName: this.instance.name, instanceId: this.instanceId },
remoteJid: messageRaw.key.remoteJid,
msg: messageRaw,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Error logging may omit stack trace information.

Log the full error object or stack trace to improve error reporting and facilitate debugging.

Comment on lines 14 to +20
},
});

console.log(`🤖 [findBotByTrigger] All/None trigger found: ${findTriggerAllOrNone ? 'YES' : 'NO'} - ID: ${findTriggerAllOrNone?.id || 'NONE'}`);

if (findTriggerAllOrNone) {
console.log(`✅ [findBotByTrigger] Returning bot with triggerType: ${findTriggerAllOrNone.triggerType}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Use of console.log for logging may be inconsistent with other logger usage.

Replace console.log with the project's structured logger to ensure consistent logging and log level management.

Suggested implementation:

import { advancedOperatorsSearch } from './advancedOperatorsSearch';
import { logger } from '../logger';

export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => {
  logger.info(`🔍 [findBotByTrigger] Searching for bot - content: "${content}", instanceId: ${instanceId}`);

  // Check for triggerType 'all' or 'none' (both should match any message)
  const findTriggerAllOrNone = await botRepository.findFirst({
    where: {
    },
  });

  logger.info(`🤖 [findBotByTrigger] All/None trigger found: ${findTriggerAllOrNone ? 'YES' : 'NO'} - ID: ${findTriggerAllOrNone?.id || 'NONE'}`);

  if (findTriggerAllOrNone) {
    logger.info(`✅ [findBotByTrigger] Returning bot with triggerType: ${findTriggerAllOrNone.triggerType}`);
    return findTriggerAllOrNone;

If your logger uses a different import path or method (e.g., import logger from ... or logger.log('info', ...)), adjust the import and usage accordingly.

@DavidsonGomes DavidsonGomes changed the base branch from main to develop August 22, 2025 01:19
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.

1 participant