Skip to content

Adicionando um novo webhook no endpoint de updateMessage #1343

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

Conversation

pedro-php
Copy link
Contributor

@pedro-php pedro-php commented Mar 27, 2025

Feature

Problema

Ao se editar uma mensagem, utilizando o endpoint de updateMessage, nenhum webhook de confirmação de sucesso é enviado pela API. Webhooks são apenas enviados quando uma mensagem é editada no dispositivo conectado.

O que foi alterado

Foi adicionado o evento send.message.update, que é disparado pelo webhook SEND_MESSAGE_UPDATE, no endpoint /chat/updateMessage/. Este evento e este webhook foram também adicionados às integrações com o RabbitMQ, CHATWOOT e no evento de criação e edição de instância.

Resolução

O usuário pode agora, ao criar ou editar uma instância, adicionar o webhook SEND_MESSAGE_UPDATE à ela. Este webhook é disparado ao se realizar à chamada ao endpoint /chat/updateMessage/ em caso de sucesso. Esta alteração melhora a consistência da API, padronizando o comportamento dos endpoints, já que um webhook já é disparado ao enviar uma mensagem.

Summary by Sourcery

Add a new webhook for message update events in the API

New Features:

  • Introduce a new webhook event SEND_MESSAGE_UPDATE for successful message updates in the API

Enhancements:

  • Improve API consistency by adding a webhook for message update events, similar to message send events

Chores:

  • Update configuration schemas and environment variables to support the new message update webhook

Copy link
Contributor

sourcery-ai bot commented Mar 27, 2025

Reviewer's Guide by Sourcery

This pull request introduces the SEND_MESSAGE_UPDATE webhook event, triggered when a message is successfully updated via the /chat/updateMessage/ endpoint. This change ensures consistency by providing webhook feedback for message updates, similar to the existing functionality for new messages. The implementation includes modifications to the Baileys service, configuration files, instance schema, Chatwoot integration, and event controller to support the new event.

Sequence diagram for updateMessage endpoint with SEND_MESSAGE_UPDATE webhook

sequenceDiagram
    participant Client
    participant BaileysService
    participant WhatsApp
    participant WebhookService

    Client->>BaileysService: /chat/updateMessage/
    BaileysService->>WhatsApp: sendMessage (edit)
    activate WhatsApp
    WhatsApp-->>BaileysService: messageSent
    deactivate WhatsApp
    BaileysService->>WebhookService: sendDataWebhook(SEND_MESSAGE_UPDATE, updatedMessage)
    activate WebhookService
    WebhookService-->>BaileysService: Success
    deactivate WebhookService
    BaileysService-->>Client: messageSent
Loading

Updated class diagram for ConfigService

classDiagram
    class ConfigService {
        +EventsRabbitmq: object
        +EventsWebhook: object
        +EventsPusher: object
        +constructor()
        +get<T>(propertyPath: string): T
    }
    class EventsRabbitmq {
        +MESSAGES_UPDATE: boolean
        +MESSAGES_DELETE: boolean
        +SEND_MESSAGE: boolean
        +SEND_MESSAGE_UPDATE: boolean
        +CONTACTS_SET: boolean
        +CONTACTS_UPDATE: boolean
        +CONTACTS_UPSERT: boolean
    }
    class EventsWebhook {
        +MESSAGES_UPDATE: boolean
        +MESSAGES_DELETE: boolean
        +SEND_MESSAGE: boolean
        +SEND_MESSAGE_UPDATE: boolean
        +CONTACTS_SET: boolean
        +CONTACTS_UPDATE: boolean
        +CONTACTS_UPSERT: boolean
    }
    class EventsPusher {
        +MESSAGES_UPDATE: boolean
        +MESSAGES_DELETE: boolean
        +SEND_MESSAGE: boolean
        +SEND_MESSAGE_UPDATE: boolean
        +CONTACTS_SET: boolean
        +CONTACTS_UPDATE: boolean
        +CONTACTS_UPSERT: boolean
    }

    ConfigService -- EventsRabbitmq : has
    ConfigService -- EventsWebhook : has
    ConfigService -- EventsPusher : has
Loading

Updated class diagram for Events enum

classDiagram
    class Events {
        <<enumeration>>
        MESSAGES_UPDATE
        MESSAGES_DELETE
        SEND_MESSAGE
        SEND_MESSAGE_UPDATE
        CONTACTS_SET
        CONTACTS_UPSERT
        CONTACTS_UPDATE
    }
Loading

File-Level Changes

Change Details Files
Implemented the SEND_MESSAGE_UPDATE event and webhook to trigger upon successful message updates via the /chat/updateMessage/ endpoint.
  • Added SEND_MESSAGE_UPDATE to the Events enum.
  • Modified the updateMessage function to trigger the SEND_MESSAGE_UPDATE event after a successful message update.
  • Added configurations for the SEND_MESSAGE_UPDATE event for RabbitMQ, webhooks, and Pusher.
  • Updated the instance schema to include SEND_MESSAGE_UPDATE as a valid event.
  • Updated the Chatwoot service to handle the send.message.update event.
  • Added SEND_MESSAGE_UPDATE to the event controller.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/config/env.config.ts
src/validate/instance.schema.ts
Docker/swarm/evolution_api_v2.yaml
src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts
src/api/integrations/event/event.controller.ts
src/api/types/wa.types.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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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 @pedro-php - I've reviewed your changes - here's some feedback:

Overall Comments:

  • It's great to see the addition of the SEND_MESSAGE_UPDATE event to maintain consistency across the API.
  • Ensure that the new SEND_MESSAGE_UPDATE event is handled gracefully when it fails, and that the user is notified.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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 March 27, 2025 18:04
@DavidsonGomes
Copy link
Collaborator

A branch correta é a develop, temos alguns conflitos, por favor ajuste para ser aprovado

@pedro-php
Copy link
Contributor Author

pedro-php commented Mar 28, 2025

Fix

Problema

A aplicação estava gerando erros ao realizar a build a partir da branch develop.

O que foi alterado

Foi ajustada a conversão do timestamp, que pode ser do tipo long ou number, garantindo a conversão correta para inserção no Prisma.

Resolução

Agora é possível realizar a build da branch develop sem erros.


Merge

O que foi alterado

A branch develop já continha um trecho de código com duas ações em relação à main:

  1. Modificar a mensagem atualizada no endpoint /chat/updateMessage/, realizando um update no banco de dados via Prisma.
  2. Modificar o webhook, adicionando a mensagem antiga que foi alterada à partir do prisma.

A primeira ação foi mantida. Já na segunda, foram feitas alterações para tornar o webhook consistente com o evento MESSAGE_EDITED, que já é disparado quando uma mensagem é alterada pelo dispositivo. Dessa forma, ambos os webhooks têm agora o mesmo formato, assim como os webhooks de enviar e receber mensagem.

Além disso, o novo webhook SEND_MESSAGE_UPDATE foi mantido, garantindo consistência com os endpoints de mensagem, que já possuem eventos distintos para mensagens enviadas pela API e mensagens enviadas pelo dispositivo.

Resolução

Agora, ao criar ou editar uma instância, o usuário pode adicionar o webhook SEND_MESSAGE_UPDATE. Esse webhook será disparado ao chamar o endpoint /chat/updateMessage/ com sucesso. As mensagens continuam a ser atualizadas no banco de dados quando este endpoint é chamado.

Essa alteração melhora a consistência da API, padronizando o comportamento dos endpoints, já que um webhook já é disparado ao enviar uma mensagem.

Sugestão

Removi o envio da mensagem antiga no endpoint de atualização (UPDATE). Caso seja necessário readicioná-la, sugiro que isso seja feito em ambos os webhooks para manter a padronização e a consistência da API.

@DavidsonGomes

@DavidsonGomes DavidsonGomes merged commit 0d2a7ad into EvolutionAPI:develop Mar 30, 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