-
Notifications
You must be signed in to change notification settings - Fork 3
DEVEXP-795: Conversation Webhooks #122
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
matsk-sinch
wants to merge
3
commits into
v2.0
Choose a base branch
from
DEVEXP-795_Conversation-Webhooks
base: v2.0
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import re | ||
| from flask import request, Response | ||
| from webhooks.conversation_api.server_business_logic import handle_conversation_event | ||
|
|
||
|
|
||
| def _charset_from_content_type(content_type): | ||
| """Extract charset from Content-Type header; default to utf-8 if missing.""" | ||
| if not content_type: | ||
| return "utf-8" | ||
| match = re.search(r"charset\s*=\s*([^\s;]+)", content_type, re.I) | ||
| return match.group(1).strip("'\"").lower() if match else "utf-8" | ||
|
|
||
|
|
||
| def _decode_body(raw_body, content_type): | ||
| """Decode request body using Content-Type charset, fallback to utf-8.""" | ||
| if not raw_body: | ||
| return "" | ||
| charset = _charset_from_content_type(content_type) | ||
| try: | ||
| return raw_body.decode(charset) | ||
| except (LookupError, UnicodeDecodeError): | ||
| return raw_body.decode("utf-8") | ||
|
|
||
|
|
||
| class ConversationController: | ||
| def __init__(self, sinch_client, webhooks_secret): | ||
| self.sinch_client = sinch_client | ||
| self.webhooks_secret = webhooks_secret | ||
| self.logger = self.sinch_client.configuration.logger | ||
|
|
||
| def conversation_event(self): | ||
| headers = dict(request.headers) | ||
| raw_body = request.raw_body if request.raw_body else b"" | ||
| content_type = headers.get("Content-Type") or headers.get("content-type") or "" | ||
| body_str = _decode_body(raw_body, content_type) | ||
|
|
||
| webhooks_service = self.sinch_client.conversation.webhooks(self.webhooks_secret) | ||
|
|
||
| # Set to True to enforce signature validation (recommended in production) | ||
| ensure_valid_signature = False | ||
| if ensure_valid_signature: | ||
| valid = webhooks_service.validate_authentication_header( | ||
| headers=headers, | ||
| json_payload=body_str, | ||
| ) | ||
| if not valid: | ||
| return Response(status=401) | ||
|
|
||
| event = webhooks_service.parse_event(body_str) | ||
| handle_conversation_event(event=event, logger=self.logger) | ||
|
|
||
| return Response(status=200) |
81 changes: 81 additions & 0 deletions
81
examples/webhooks/conversation_api/server_business_logic.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| from sinch.domains.conversation.models.v1.webhooks import ( | ||
| ConversationWebhookEventBase, | ||
| MessageDeliveryReceiptEvent, | ||
| MessageInboundEvent, | ||
| MessageSubmitEvent, | ||
| ) | ||
|
|
||
|
|
||
| def handle_conversation_event(event: ConversationWebhookEventBase, logger): | ||
| """ | ||
| Dispatch a Conversation webhook event to the appropriate handler by trigger type. | ||
|
|
||
| :param event: Parsed webhook event (MessageDeliveryReceiptEvent, MessageInboundEvent, etc.). | ||
| :param logger: Logger instance for output. | ||
| """ | ||
| if isinstance(event, MessageInboundEvent): | ||
| _handle_message_inbound(event, logger) | ||
| elif isinstance(event, MessageDeliveryReceiptEvent): | ||
| _handle_message_delivery(event, logger) | ||
| elif isinstance(event, MessageSubmitEvent): | ||
| _handle_message_submit(event, logger) | ||
| else: | ||
| logger.debug("Event: %s", event.model_dump_json(indent=2) if hasattr(event, "model_dump_json") else event) | ||
|
|
||
|
|
||
| def _handle_message_inbound(event: MessageInboundEvent, logger): | ||
| """Handle MESSAGE_INBOUND: log inbound message.""" | ||
| logger.info("## MESSAGE_INBOUND") | ||
| msg = event.message | ||
| contact_msg = msg.contact_message | ||
| channel_identity = msg.channel_identity | ||
| contact_id = msg.contact_id | ||
| channel = channel_identity.channel if channel_identity else "?" | ||
| identity = channel_identity.identity if channel_identity else "?" | ||
| logger.info( | ||
| "A new message has been received on the channel '%s' (identity: %s) from the contact ID '%s'", | ||
| channel, | ||
| identity, | ||
| contact_id, | ||
| ) | ||
| if contact_msg: | ||
| if hasattr(contact_msg, "text_message") and contact_msg.text_message: | ||
| logger.info("Text: %s", contact_msg.text_message.text) | ||
| elif hasattr(contact_msg, "media_message") and contact_msg.media_message: | ||
| logger.info("Media: %s", getattr(contact_msg.media_message, "url", contact_msg.media_message)) | ||
| elif hasattr(contact_msg, "fallback_message") and contact_msg.fallback_message: | ||
| logger.info("Fallback: %s", contact_msg.fallback_message) | ||
| else: | ||
| logger.info("Contact message: %s", contact_msg) | ||
|
|
||
|
|
||
| def _handle_message_delivery(event: MessageDeliveryReceiptEvent, logger): | ||
| """Handle MESSAGE_DELIVERY: log delivery status and failure reason if failed.""" | ||
| logger.info("## MESSAGE_DELIVERY") | ||
| report = event.message_delivery_report | ||
| status = report.status | ||
| logger.info("Message delivery status: '%s'", status) | ||
| if status == "FAILED" and report.reason: | ||
| logger.info( | ||
| "Reason: %s (%s) - %s", | ||
| report.reason.code, | ||
| getattr(report.reason, "sub_code", ""), | ||
| report.reason.description, | ||
| ) | ||
|
|
||
|
|
||
| def _handle_message_submit(event: MessageSubmitEvent, logger): | ||
| """Handle MESSAGE_SUBMIT: log that the message was submitted to the channel.""" | ||
| logger.info("## MESSAGE_SUBMIT") | ||
| submit_notification = event.message_submit_notification | ||
| channel_identity = submit_notification.channel_identity | ||
| channel = channel_identity.channel if channel_identity else "?" | ||
| identity = channel_identity.identity if channel_identity else "?" | ||
| logger.info( | ||
| "The following message has been submitted on the channel '%s' (identity: %s) to the contact ID '%s'", | ||
| channel, | ||
| identity, | ||
| submit_notification.contact_id, | ||
| ) | ||
| if submit_notification.submitted_message: | ||
| logger.debug("Submitted message: %s", submit_notification.submitted_message) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| from sinch.domains.conversation.models.v1.webhooks.events import ( | ||
| ConversationWebhookEvent, | ||
| ConversationWebhookEventBase, | ||
| InboundMessage, | ||
| MessageDeliveryReceiptEvent, | ||
| MessageDeliveryReport, | ||
| MessageDeliveryStatusType, | ||
| MessageInboundEvent, | ||
| MessageSubmitEvent, | ||
| MessageSubmitNotification, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "ConversationWebhookEvent", | ||
| "ConversationWebhookEventBase", | ||
| "InboundMessage", | ||
| "MessageDeliveryReceiptEvent", | ||
| "MessageDeliveryReport", | ||
| "MessageDeliveryStatusType", | ||
| "MessageInboundEvent", | ||
| "MessageSubmitEvent", | ||
| "MessageSubmitNotification", | ||
| ] |
39 changes: 39 additions & 0 deletions
39
sinch/domains/conversation/models/v1/webhooks/events/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| from sinch.domains.conversation.models.v1.webhooks.events.conversation_webhook_event import ( | ||
| ConversationWebhookEvent, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.conversation_webhook_event_base import ( | ||
| ConversationWebhookEventBase, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.inbound_message import ( | ||
| InboundMessage, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_delivery_receipt_event import ( | ||
| MessageDeliveryReceiptEvent, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_delivery_report import ( | ||
| MessageDeliveryReport, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_delivery_status_type import ( | ||
| MessageDeliveryStatusType, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_inbound_event import ( | ||
| MessageInboundEvent, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_submit_event import ( | ||
| MessageSubmitEvent, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_submit_notification import ( | ||
| MessageSubmitNotification, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "ConversationWebhookEvent", | ||
| "ConversationWebhookEventBase", | ||
| "InboundMessage", | ||
| "MessageDeliveryReceiptEvent", | ||
| "MessageDeliveryReport", | ||
| "MessageDeliveryStatusType", | ||
| "MessageInboundEvent", | ||
| "MessageSubmitEvent", | ||
| "MessageSubmitNotification", | ||
| ] |
22 changes: 22 additions & 0 deletions
22
sinch/domains/conversation/models/v1/webhooks/events/conversation_webhook_event.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| from typing import Union | ||
|
|
||
| from sinch.domains.conversation.models.v1.webhooks.events.conversation_webhook_event_base import ( | ||
| ConversationWebhookEventBase, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_delivery_receipt_event import ( | ||
| MessageDeliveryReceiptEvent, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_inbound_event import ( | ||
| MessageInboundEvent, | ||
| ) | ||
| from sinch.domains.conversation.models.v1.webhooks.events.message_submit_event import ( | ||
| MessageSubmitEvent, | ||
| ) | ||
|
|
||
|
|
||
| ConversationWebhookEvent = Union[ | ||
| MessageDeliveryReceiptEvent, | ||
| MessageInboundEvent, | ||
| MessageSubmitEvent, | ||
| ConversationWebhookEventBase, | ||
| ] |
35 changes: 35 additions & 0 deletions
35
sinch/domains/conversation/models/v1/webhooks/events/conversation_webhook_event_base.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| from datetime import datetime | ||
| from typing import Optional | ||
|
|
||
| from pydantic import Field, StrictStr | ||
|
|
||
| from sinch.domains.conversation.webhooks.v1.internal import WebhookEvent | ||
|
|
||
|
|
||
| class ConversationWebhookEventBase(WebhookEvent): | ||
| """Base fields present on every Conversation API webhook payload.""" | ||
|
|
||
| app_id: Optional[StrictStr] = Field( | ||
| default=None, | ||
| description="Id of the subscribed app.", | ||
| ) | ||
| project_id: Optional[StrictStr] = Field( | ||
| default=None, | ||
| description="The project ID of the app which has subscribed for the callback.", | ||
| ) | ||
| accepted_time: Optional[datetime] = Field( | ||
| default=None, | ||
| description="Timestamp when the channel callback was accepted by the Conversation API.", | ||
| ) | ||
| event_time: Optional[datetime] = Field( | ||
| default=None, | ||
| description="Timestamp of the event as provided by the underlying channels.", | ||
| ) | ||
| message_metadata: Optional[StrictStr] = Field( | ||
| default=None, | ||
| description="Context-dependent metadata.", | ||
| ) | ||
| correlation_id: Optional[StrictStr] = Field( | ||
| default=None, | ||
| description="Value from correlation_id of the send message request.", | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What conduce the choice to have models for webhooks not under
modelsdirectory like other models related to V1 ? (e.g. https://github.com/sinch/sinch-sdk-java/tree/feat/V2.0-next/openapi-contracts/src/main/com/sinch/sdk/domains/conversation/models/v1/webhooks/events and https://github.com/sinch/sinch-sdk-node/tree/main/packages/conversation/src/models/v1/mod-callback-events)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As discussed, moved under
models/