Skip to content

Conversation

matheusmpupo
Copy link

@matheusmpupo matheusmpupo commented Mar 28, 2025

The Teams provider was previously using the webhook API from the Connectors method, which was deprecated in July 2024 and officially reached end-of-service in January 2025.

Reference: Microsoft 365 Dev Blog: Retirement of Office 365 Connectors within Microsoft Teams

To maintain Teams notification functionality, it must migrate to the new Power Automate method. This approach involves sending an HTML-based message to Power Automate, which then processes the notification via its Workflows mechanism.

Implementation Reference:
Teams Incoming Webhook Deprecated – Use Power Automate Instead

This pull request updates the implementation to align with new recommended approach, ensuring continued support for Teams notifications, while also maintaining the old method in case of anyone that still uses it.

Summary by CodeRabbit

  • New Features
    • Expanded Microsoft Teams notifications with support for an additional workflow provider featuring enhanced message formatting and error handling.
    • Continued to support the existing notification method, ensuring smooth user experience during the transition.

Copy link

coderabbitai bot commented Mar 28, 2025

Walkthrough

The changes introduce a new conditional branch in the Teams notification logic to handle two providers. The "webhookb2" branch behavior is maintained while a new branch for the "workflows" provider has been added. For the "workflows" provider, messages are formatted as HTML and sent as a JSON payload via an HTTP POST request, with error handling for both the sending process and response status. Additional packages (bytes and net/http) have been imported to support this new flow.

Changes

File Change Summary
pkg/providers/teams/teams.go Added a new conditional branch for the "workflows" provider that formats messages as HTML, constructs a JSON payload, and sends an HTTP POST request. Retained the existing logic for "webhookb2" along with updated error handling and logging.

Sequence Diagram(s)

sequenceDiagram
    participant Sender as Notification Sender
    participant Teams as Teams Provider
    participant HTTP as HTTP Endpoint

    Sender->>Teams: Call Send() with provider info
    alt Provider is webhookb2
        Teams->>Teams: Parse webhook URL and construct shoutrrr URL
        Teams-->>Sender: Send notification using shoutrrr
    else Provider is workflows
        Teams->>Teams: Format message as HTML and build JSON payload
        Teams->>HTTP: Send HTTP POST request with payload
        HTTP-->>Teams: Return response status
        Teams-->>Sender: Return notification result and handle errors
    end
Loading

Poem

I'm a little rabbit, hopping with glee,
Code paths diverge for Teams, you see.
Webhookb2 and workflows now play,
Sending alerts in their own unique way.
Hoppin’ into changes — oh what fun! 🐰🎉
May every push shine brighter than the sun!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/providers/teams/teams.go (1)

48-49: Provider extraction logic may be brittle.

The method to determine provider type relies on a fixed position in the URL path. This approach could be fragile if the URL structure changes.

Consider using a more robust approach, such as:

- provider := strings.Split(pr.TeamsWebHookURL, "/")[3]
+ urlParts := strings.Split(pr.TeamsWebHookURL, "/")
+ provider := ""
+ if len(urlParts) > 3 {
+     provider = urlParts[3]
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 36f061c and ff92af6.

📒 Files selected for processing (1)
  • pkg/providers/teams/teams.go (2 hunks)
🔇 Additional comments (4)
pkg/providers/teams/teams.go (4)

4-6: Appropriate imports for the new HTTP functionality.

The added imports for bytes and net/http packages are necessary for the new HTTP POST implementation used with the Power Automate method.


50-66: Good preservation of backward compatibility.

The implementation maintains support for the deprecated webhookb2 method while properly documenting it as deprecated, ensuring users can migrate at their own pace.


71-77: Good HTTP request implementation and resource management.

The HTTP request implementation correctly handles the response body with a deferred close operation, which prevents resource leaks.


78-82:

✅ Verification successful

Verify the expected status code for Power Automate.

The code checks for http.StatusAccepted (202), which should be confirmed against Microsoft's documentation for Power Automate workflows.


🌐 Web query:

What status code does Microsoft Power Automate return for successful webhook requests?

💡 Result:

By default, Microsoft Power Automate returns HTTP 202 Accepted for successful webhook requests, indicating asynchronous processing[1][4][8]. This means the request has been accepted but processing may not yet be completed.

Key Details:

  • Asynchronous Execution: Power Automate processes webhook-triggered flows asynchronously, immediately returning 202 after accepting the payload[1][6].
  • Customization Option: You can override the default behavior by adding an HTTP Response action at the end of your flow to return different status codes (e.g., 200 OK)[1][5].
  • Error Handling: Even if subsequent steps fail (e.g., large payloads or JSON errors), the initial response remains 202 Accepted[8]. Errors appear in flow runs but aren’t reflected in the HTTP response code[8].

Example Use Case:

Webhook Trigger → Flow Processing → HTTP 202 (Default)
                          ↳ Add "HTTP Response" action → Returns 200 OK (Custom)

For integrations requiring immediate 200 OK responses (e.g., third-party plugins), explicit use of the HTTP Response action is necessary[1][10].

Citations:


Status Code Verification: Microsoft Power Automate Behavior Confirmed

After reviewing the documentation, Microsoft Power Automate returns HTTP 202 Accepted by default for successful webhook requests. The current implementation in pkg/providers/teams/teams.go that checks for http.StatusAccepted is correct for default flows. If you later decide to implement a custom HTTP Response action that returns a different status code (such as 200 OK), you'll need to update this logic accordingly.

Comment on lines +67 to +70
// New Power Automate method
} else if provider == "workflows" {
htmlMessage := strings.ReplaceAll(msg, "\n", "<br>")
payload := fmt.Sprintf(`{"text": "%s"}`, htmlMessage)
Copy link

@coderabbitai coderabbitai bot Mar 28, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve JSON payload creation for better security.

The current implementation has two potential issues:

  1. Simple replacement of newlines with HTML breaks might not handle other HTML special characters
  2. Using string formatting to construct JSON can lead to malformed JSON if the message contains quotes or special characters
- htmlMessage := strings.ReplaceAll(msg, "\n", "<br>")
- payload := fmt.Sprintf(`{"text": "%s"}`, htmlMessage)
+ import "encoding/json"
+ import "html"
+
+ // HTML encode message to escape special characters
+ htmlMessage := html.EscapeString(strings.ReplaceAll(msg, "\n", "<br>"))
+ 
+ // Create payload using proper JSON marshaling
+ type teamsPayload struct {
+     Text string `json:"text"`
+ }
+ payloadObj := teamsPayload{Text: htmlMessage}
+ payloadBytes, err := json.Marshal(payloadObj)
+ if err != nil {
+     err = errors.Wrap(err, fmt.Sprintf("failed to create JSON payload for teams notification id: %s", pr.ID))
+     TeamsErr = multierr.Append(TeamsErr, err)
+     continue
+ }

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Member

Choose a reason for hiding this comment

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

+1

Copy link

Choose a reason for hiding this comment

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

@dogancanbakir Thanks for confirming! I'm glad you found the suggestion helpful. Let me know if you need any further assistance with the implementation!

(_/)
(^.^)
/>🎯 Bullseye!

@ehsandeep ehsandeep requested a review from dogancanbakir March 31, 2025 09:47
Comment on lines +67 to +70
// New Power Automate method
} else if provider == "workflows" {
htmlMessage := strings.ReplaceAll(msg, "\n", "<br>")
payload := fmt.Sprintf(`{"text": "%s"}`, htmlMessage)
Copy link
Member

Choose a reason for hiding this comment

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

+1

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