Skip to content

Conversation

guispiller
Copy link

@guispiller guispiller commented Sep 30, 2025

📋 Description

Summary

This PR enhances the GROUP_PARTICIPANTS_UPDATE -> add - webhook to properly
convert LID (Local Identifier) values to real phone numbers, ensuring
consistency with the existing /group/participants endpoint
behavior.

Problem

Currently, when the GROUP_PARTICIPANTS_UPDATE webhook is triggered,
participants with LID identifiers return the raw LID value instead
of the actual phone number:

Before:
json
{
"jid": "131159895875721@lid",
"phoneNumber": "131159895875721@lid"
}

Solution

The webhook now uses the same logic as the /group/participants
endpoint to resolve LID values to actual phone numbers:

After:
{
"jid": "131159895875721@lid",
"phoneNumber": "[email protected]"
}

Changes Made

  • Enhanced GROUP_PARTICIPANTS_UPDATE webhook handler to call
    findParticipants() method
  • Added proper LID to phone number conversion using existing group
    metadata
  • Maintained backward compatibility for normal JID formats
  • Added fallback mechanism in case of conversion errors

Testing

  • Webhook correctly handles normal JID participants
  • Webhook properly converts LID participants to real phone numbers
  • Existing /group/participants endpoint remains unaffected
  • Error handling works correctly with fallback to original data

PS: This solves my biggest problem around here on group entrances, but i don't know if it's the best approach.

🧪 Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🔧 Refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧹 Code cleanup
  • 🔒 Security fix

🧪 Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced
  • Tested with different connection types (if applicable)

📸 Screenshots (if applicable)

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios
  • Any dependent changes have been merged and published

📝 Additional Notes

PS: This solves my biggest problem around here on group entrances, but i don't know if it's the best approach.

Summary by Sourcery

Enhance the GROUP_PARTICIPANTS_UPDATE webhook handler to fetch full participant metadata, convert LID identifiers to real phone numbers, and include name and image URL fields, while preserving backward compatibility and adding an error fallback.

New Features:

  • Resolve local participant identifiers (LIDs) to actual phone numbers in GROUP_PARTICIPANTS_UPDATE webhook payloads
  • Populate participant name and image URL in the GROUP_PARTICIPANTS_UPDATE webhook

Bug Fixes:

  • Fix phoneNumber field returning raw LID instead of real number

Enhancements:

  • Maintain backward compatibility for non-LID JIDs
  • Add fallback to original payload on lookup errors

Copy link
Contributor

sourcery-ai bot commented Sep 30, 2025

Reviewer's Guide

Refactor the GROUP_PARTICIPANTS_UPDATE webhook handler to asynchronously fetch group metadata for LID-to-phoneNumber resolution, enrich participant records (phoneNumber, name, imgUrl), and provide a fallback path on errors.

Sequence diagram for GROUP_PARTICIPANTS_UPDATE webhook with LID to phoneNumber conversion

sequenceDiagram
    participant "Webhook Handler"
    participant "Group Metadata Service (findParticipants)"
    participant "Webhook Consumer"
    participant "Logger"

    "Webhook Handler"->>"Group Metadata Service (findParticipants)": Fetch group participants metadata
    "Group Metadata Service (findParticipants)"-->>"Webhook Handler": Return enriched participant data
    "Webhook Handler"->>"Webhook Consumer": Send GROUP_PARTICIPANTS_UPDATE with resolved phoneNumbers
    Note over "Webhook Handler","Logger": On error, fallback to sending raw participant data
    "Webhook Handler"->>"Logger": Log error
    "Webhook Handler"->>"Webhook Consumer": Send GROUP_PARTICIPANTS_UPDATE with original data
Loading

Class diagram for enhanced participant data structure in webhook

classDiagram
    class ParticipantUpdate {
        +id: string
        +participants: Participant[]
        +action: ParticipantAction
    }
    class Participant {
        +jid: string
        +phoneNumber: string
        +name: string
        +imgUrl: string
    }
    ParticipantUpdate "1" *-- "*" Participant: contains
    class ParticipantAction {
        <<enum>>
    }
Loading

File-Level Changes

Change Details Files
Async resolution and enrichment of group participants in the webhook
  • Convert handler to async and invoke findParticipants for full participant data
  • Map each participantId to an object with resolved phoneNumber, name, imgUrl
  • Wrap resolution logic in try-catch and log errors with fallback to original payload
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.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:

  • This change alters the payload shape for GROUP_PARTICIPANTS_UPDATE (participants array now contains objects instead of strings), which could break existing webhook consumers—consider versioning the event or clearly documenting this schema change.
  • Calling findParticipants on every update may add latency under load; consider caching resolved participant data or batching these lookups to reduce overhead.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- This change alters the payload shape for GROUP_PARTICIPANTS_UPDATE (participants array now contains objects instead of strings), which could break existing webhook consumers—consider versioning the event or clearly documenting this schema change.
- Calling findParticipants on every update may add latency under load; consider caching resolved participant data or batching these lookups to reduce overhead.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1594-1599` </location>
<code_context>
     },

-    'group-participants.update': (participantsUpdate: {
+    'group-participants.update': async (participantsUpdate: {
       id: string;
       participants: string[];
       action: ParticipantAction;
     }) => {
-      this.sendDataWebhook(Events.GROUP_PARTICIPANTS_UPDATE, participantsUpdate);
+      try {
+        // Usa o mesmo método que o endpoint /group/participants 
+        const groupParticipants = await this.findParticipants({ groupJid: participantsUpdate.id });
</code_context>

<issue_to_address>
**issue:** Consider handling cases where findParticipants returns undefined or an unexpected structure.

Add validation to ensure groupParticipants and its participants property exist before mapping, to avoid undefined values or runtime errors.
</issue_to_address>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1622` </location>
<code_context>
+        
+        this.sendDataWebhook(Events.GROUP_PARTICIPANTS_UPDATE, enhancedParticipantsUpdate);
+      } catch (error) {
+        console.log('Erro ao buscar dados dos participantes para webhook:', error);
+        // Fallback - envia sem conversão
+        this.sendDataWebhook(Events.GROUP_PARTICIPANTS_UPDATE, participantsUpdate);
</code_context>

<issue_to_address>
**suggestion:** Using console.log for error reporting may not be ideal for production environments.

Recommend implementing a structured logging or error tracking solution to improve error visibility and monitoring in production.

Suggested implementation:

```typescript
        this.logger.error('Erro ao buscar dados dos participantes para webhook', error);

```

If `this.logger` is not already defined in the class, you will need to:

1. Import a logger (e.g., `import { Logger } from '@nestjs/common';`).
2. Add `private readonly logger = new Logger(WhatsappBaileysService.name);` to the class constructor or as a class property.

If you use a different logging library, adjust the import and instantiation accordingly.
</issue_to_address>

### Comment 3
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1604-1613` </location>
<code_context>
+          
+          return {
+            jid: participantId,
+            phoneNumber: participantData?.phoneNumber || participantId,
+            name: participantData?.name,
+            imgUrl: participantData?.imgUrl,
</code_context>

<issue_to_address>
**suggestion:** Defaulting phoneNumber to participantId may cause confusion if formats differ.

Validate or normalize participantId before using it as a fallback for phoneNumber to prevent format inconsistencies.

```suggestion
        // Helper to normalize participantId as phone number
        function normalizePhoneNumber(id: string): string {
          // Example normalization: remove non-digit characters and leading plus
          // Adjust this logic to match your application's phone number format requirements
          return id.replace(/[^\d]/g, '');
        }

        const resolvedParticipants = participantsUpdate.participants.map((participantId) => {
          const participantData = groupParticipants.participants.find(p => p.id === participantId);

          let phoneNumber: string;
          if (participantData?.phoneNumber) {
            phoneNumber = participantData.phoneNumber;
          } else {
            phoneNumber = normalizePhoneNumber(participantId);
          }

          return {
            jid: participantId,
            phoneNumber,
            name: participantData?.name,
            imgUrl: participantData?.imgUrl,
          };
        });
```
</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.

@DavidsonGomes DavidsonGomes changed the base branch from main to develop September 30, 2025 00:18
  compatibility

  - Keep original participants array (string[]) for backward
  compatibility
  - Add new participantsData field with resolved phone numbers and
  metadata
  - Consumers can migrate gradually from participants to
  participantsData
  - No breaking changes to existing webhook integrations

  Payload structure:
  - participants: string[] (original JID strings)
  - participantsData: object[] (enhanced with phoneNumber, name,
  imgUrl)
@guispiller
Copy link
Author

guispiller commented Sep 30, 2025

I've resolved to NOT break the payload shape, thanks for the feedback.

@DavidsonGomes
Copy link
Collaborator

Fix the lint please

@Vitordotpy
Copy link

that fix will save me, thank you 😭

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.

3 participants