Skip to content

Push Linear updates to Discord channel #345

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 18 commits into
base: main
Choose a base branch
from
Open

Push Linear updates to Discord channel #345

wants to merge 18 commits into from

Conversation

zuuring
Copy link
Member

@zuuring zuuring commented Apr 24, 2025

Notes

This adds two new commands which will create a new webhook connection between Linear & Discord in order to send project updates directly to Discord from linear via a custom embed.

  • /linear-updates connect team-name
  • /linear-updates disconnect team-name

Once a channel is connected, Linear will send all Project updates from that specific team to the channel via the webhook call using a secure header with linear-signature that we set during the initial creation. This connection can also be built on to support additional notifications from Linear -> Discord

Adds two new environment variables which need to be defined for the script to load on start

  • VALKYRIE_WEBHOOK_URL=
  • LINEAR_API_TOKEN=

Summary by CodeRabbit

  • New Features

    • Introduced integration between Discord and Linear, allowing users to connect or disconnect Linear project updates to Discord channels via slash commands.
    • Project updates from Linear are now automatically posted as embedded messages in designated Discord channels.
    • Secure connection management and validation for webhook events, ensuring only authorized updates are delivered.
    • Dynamic command options for selecting Linear teams when connecting channels.
  • Bug Fixes

    • Improved error handling for invalid channels, missing tokens, and signature mismatches during webhook processing.

@zuuring zuuring added the enhancement New feature or request label Apr 24, 2025
@zuuring zuuring self-assigned this Apr 24, 2025
@zuuring zuuring requested a review from Shadowfiend April 24, 2025 14:36
Copy link
Contributor

Did we get you the ability to set these variables in kube?

@Shadowfiend Shadowfiend requested a review from Copilot May 16, 2025 13:20
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds functionality to connect and disconnect Linear teams with Discord channels, enabling automated delivery of Linear project updates as custom embeds via webhooks.

  • Introduces two new slash commands: "/linear-updates connect team-name" and "/linear-updates disconnect team-name".
  • Implements webhook creation and deletion logic with secure header verification.
  • Utilizes two new environment variables for configuration.


const teams = await fetchLinearTeams()

await application.commands.set([])
Copy link
Preview

Copilot AI May 16, 2025

Choose a reason for hiding this comment

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

Clearing all commands here may unintentionally remove commands from other integrations; consider updating or adding only the specific Linear command instead of resetting the entire command list.

Copilot uses AI. Check for mistakes.

Copy link
Contributor

@Shadowfiend Shadowfiend left a comment

Choose a reason for hiding this comment

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

Left a few notes.

}
if (existingConnections[teamId]) {
await interaction.reply({
content: "⚠️ This Linear team is already connected to a channel.",
Copy link
Contributor

Choose a reason for hiding this comment

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

Unless there's a technical limitation, I think it's fine to connect the same team to multiple channels—we just shouldn't connect the same team to the same channel more than once. Wdyt?

Copy link
Member Author

Choose a reason for hiding this comment

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

Did some refactoring here so that you can set updates across several channels but still fires the message if you try connecting updates to one that has that specific team + channel already linked ✨

return
}
await interaction.reply({
content: "Linked this channel",
Copy link
Contributor

Choose a reason for hiding this comment

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

Any chance we can be explicit here? e.g. Now streaming <team name> project updates to this channel?

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually is this redundant to the message after succeeding?

})

await interaction.editReply({
content: `Connected Linear team **${team.name}** to this channel and added webhook to Linear`,
Copy link
Contributor

Choose a reason for hiding this comment

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

This seems a little too technical tbh.

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed and added these to debug only!

}
})
robot.router.post(
/^\/linear-([a-z0-9-]+)-(\d{6})$/,
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's use /linear/ and subpath below that? Maybe even /linear/webhook/team/...?

Copy link
Member Author

Choose a reason for hiding this comment

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

Changed this around but kept the id pattern at the end so it's /linear/webhook/channel-name-randomId

@Shadowfiend
Copy link
Contributor

@coderabbitai full review

Copy link

coderabbitai bot commented May 16, 2025

✅ Actions performed

Full review triggered.

Copy link

coderabbitai bot commented May 16, 2025

Walkthrough

A new module was added to integrate Linear project management updates with Discord via a bot. It introduces slash commands for connecting or disconnecting a Linear team to a Discord channel, manages webhook registration and deletion, verifies incoming webhook signatures, and posts formatted project update messages to Discord channels. Persistent storage is used for connection data.

Changes

File(s) Change Summary
discord-scripts/linear-integration.ts New module implementing Discord–Linear integration: slash commands for connect/disconnect, webhook management, signature verification, event handling, and message posting to Discord. Exports an async function for setup.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Discord
    participant Bot
    participant Linear API
    participant Brain

    User->>Discord: Issues /linear-updates connect/disconnect command
    Discord->>Bot: Sends interaction event
    Bot->>Linear API: (On connect) Register webhook for team
    Bot->>Brain: Store connection details (team, channel, secret)
    Bot->>Linear API: (On disconnect) Delete webhook
    Bot->>Brain: Remove connection details
    Bot-->>Discord: Ephemeral reply to user
Loading
sequenceDiagram
    participant Linear API
    participant Bot
    participant Brain
    participant Discord Channel

    Linear API->>Bot: POST webhook event (with signature)
    Bot->>Brain: Retrieve connection by team/channel
    Bot->>Bot: Verify HMAC signature
    alt Valid signature & ProjectUpdate event
        Bot->>Discord Channel: Post formatted project update embed
    else Invalid signature or unknown event
        Bot->>Bot: Log error, respond with error status
    end
Loading

Poem

A hop, a skip, a webhook ping,
Linear and Discord now in sync!
With secrets safe and channels bright,
Project updates take their flight.
Slash commands leap, connections grow—
This bunny built a status flow!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

discord-scripts/linear-integration.ts

Oops! Something went wrong! :(

ESLint: 8.35.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'prettier' imported from /node_modules/eslint-plugin-prettier/worker.js
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at onImport.tracePromise.proto (node:internal/modules/esm/loader:657:36)
at TracingChannel.tracePromise (node:diagnostics_channel:344:14)

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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: 3

♻️ Duplicate comments (3)
discord-scripts/linear-integration.ts (3)

45-48: URL concatenation is still fragile – trailing-slash bug remains

Past feedback pointed this out and the code remains unchanged. If VALKYRIE_ROOT_URL lacks a trailing “/”, the final URL becomes invalid (https://example.comlinear-foo). Use the URL constructor or normalise the root first.
(See previous suggestion at line 47.)


97-98: Resetting all application commands wipes unrelated slash commands

application.commands.set([]) removes every global command before recreating ours. That can break other integrations running in the same bot. Please update only the specific command instead of flushing the entire list.


281-282: Variable is mis-named (channelId actually holds a Team ID)

The value extracted from teamsInfo[0].id is the Linear team identifier, not a Discord channel identifier. The misleading name caused confusion later (see existingConnections[channelId]).

🧹 Nitpick comments (2)
discord-scripts/linear-integration.ts (2)

40-52: Replace console.* with the project logger

console.error/log bypasses our structured logging and also trips the ESLint rule already shown in the pipeline.
Switch to robot.logger (or whichever logger abstraction we standardise on). Example:

-      console.error("Webhook creation failed: Channel is not a TextChannel.")
+      robot.logger.error("Webhook creation failed: Channel is not a TextChannel.")
...
-    console.log("Generated custom webhook URL:", customWebhookUrl)
+    robot.logger.info(`Generated custom webhook URL: ${customWebhookUrl}`)
...
-    console.error("Error generating custom webhook URL:", error)
+    robot.logger.error("Error generating custom webhook URL:", error)
🧰 Tools
🪛 GitHub Check: lint

[warning] 41-41:
Unexpected console statement


[warning] 49-49:
Unexpected console statement


[warning] 52-52:
Unexpected console statement


159-177: One-channel-per-team restriction is hard-coded

existingConnections[teamId] keys the persistence by team only, so the same Linear team cannot be streamed to multiple Discord channels (earlier review discussed this). If multi-channel support is acceptable, consider keying by teamId + channelId or storing an array of channels per team to avoid this limitation while still preventing duplicate entries in a single channel.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 691922a and 048f421.

📒 Files selected for processing (1)
  • discord-scripts/linear-integration.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
discord-scripts/linear-integration.ts

[warning] 41-41:
Unexpected console statement


[warning] 49-49:
Unexpected console statement


[warning] 52-52:
Unexpected console statement


[warning] 62-62:
Unexpected console statement

zuuring added 2 commits June 2, 2025 12:31
Add autocomplete to command for loading team names dynamically.
Fix for a bug when sometimes the channel name isn't properly found on webhook
@zuuring zuuring requested a review from Shadowfiend June 2, 2025 12:44
@zuuring
Copy link
Member Author

zuuring commented Jun 2, 2025

@Shadowfiend Made some large refactoring here as well as fixing the issues like verbiage on messages, channel mapping, and being able to add the connection to several channels. If it looks good, approve but don't merge as I can get the vars added to our instance 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants