:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): deliver platform alerts to discord natively (#112141)
Jimmy Zhud68cb14c983b
diff --git a/products/alerts_platform/backend/delivery/discord.py b/products/alerts_platform/backend/delivery/discord.pynew file mode 100644index 000000000000..f26a46591788--- /dev/null+++ b/products/alerts_platform/backend/delivery/discord.py@@ -0,0 +1,85 @@+"""Discord delivery, as a plain markdown message posted to a channel webhook.++Plain content rather than an embed, because that is what the HogFunction template sends, so a+Discord channel sees the same kind of message from either path.+"""++import re+from typing import Any, Final+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit++from posthog.security.url_validation import has_authority_bypass_chars+from posthog.slack.channels import clip_text++from products.alerts_platform.backend.delivery.message import AlertMessage+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.delivery.webhook_url import WebhookUrlTransport++PROVIDER: Final = "discord"++MAX_CONTENT_CHARS: Final = 2000++# Stops a URL in a query error from unfurling into a preview of a page the alert never chose.+SUPPRESS_EMBEDS: Final = 1 << 2++# Discord honors a backslash before any of these, so escaped text renders as typed. `#` and `-`+# are here because a query error can span lines, and either one starts a heading or a list.+_MARKDOWN_SPECIALS: Final = re.compile(r"([\\*_~`|\[\]<>#-])")+++def escape_markdown(text: str) -> str:+ return _MARKDOWN_SPECIALS.sub(r"\\\1", text)+++def content_for(message: AlertMessage) -> str:+ headline = f"**{escape_markdown(message.headline)}**"+ lines = [f"**{detail.label}:** {escape_markdown(detail.value)}" for detail in message.details]+ if not lines:+ return headline+ content = f"{headline}\n\n" + "\n".join(lines)+ if len(content) <= MAX_CONTENT_CHARS:+ return content+ # An error message can carry a whole query, so it is a detail that overflows. Each detail gets+ # an equal share, so clipping the error cannot drop the failure count after it.+ share = (MAX_CONTENT_CHARS - len(headline) - 2 - (len(lines) - 1)) // len(lines)+ return f"{headline}\n\n" + "\n".join(clip_text(line, share) for line in lines)+++class DiscordTransport(WebhookUrlTransport):+ provider = PROVIDER+ display_name = "Discord"++ def check_url(self, url: str) -> None:+ # The URL shape the HogFunction template accepts, so no destination that works today is refused.+ refused = DeliveryError("This Discord destination's URL is not a Discord webhook URL.")+ if has_authority_bypass_chars(url):+ raise refused+ try:+ parts = urlsplit(url)+ port = parts.port+ except ValueError:+ raise refused from None+ if (+ parts.scheme != "https"+ or parts.hostname != "discord.com"+ or port not in (None, 443)+ or parts.username is not None+ or not parts.path.startswith("/api/webhooks/")+ ):+ raise refused++ def send_url(self, url: str) -> str:+ # Without `wait=true` Discord answers before it saves the message, and a message it then+ # fails to save returns no error, so the send would be recorded as delivered.+ parts = urlsplit(url)+ query = [(key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True) if key != "wait"]+ return urlunsplit(parts._replace(query=urlencode([*query, ("wait", "true")])))++ def body_for(self, message: AlertMessage) -> dict[str, Any]:+ return {+ "content": content_for(message),+ # An alert name or a query error can contain `@everyone` or a role mention. Nobody is+ # pinged by an alert, which matches the template's default.+ "allowed_mentions": {"parse": []},+ "flags": SUPPRESS_EMBEDS,+ }diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex d117975cf5e7..bce7d05903a5 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -14,6 +14,7 @@ from posthog.dataclasses import frozenfrom posthog.models import Teamfrom products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups+from products.alerts_platform.backend.delivery.discord import DiscordTransportfrom products.alerts_platform.backend.delivery.dispatch import deliverfrom products.alerts_platform.backend.delivery.slack import SlackTransportfrom products.alerts_platform.backend.delivery.teams import TeamsTransport@@ -39,12 +40,13 @@ LIVE_DELIVERY_FLAG: Final = "alert-platform-live-delivery"# A destination type with no entry here has no native transport, and delivery skips it. Make a# team live only when its alerts use no such type. Nothing checks this in code, and one alert-# delivering natively to Slack and through a HogFunction to Discord would send two differently-# worded messages for one event.+# delivering natively to one destination and through a HogFunction to another would send two+# differently worded messages for one event._TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {DestinationType.SLACK: SlackTransport,DestinationType.WEBHOOK: WebhookTransport,DestinationType.TEAMS: TeamsTransport,+ DestinationType.DISCORD: DiscordTransport,}diff --git a/products/alerts_platform/backend/delivery/webhook_url.py b/products/alerts_platform/backend/delivery/webhook_url.pyindex 770f62a6c42f..f386ed0cab75 100644--- a/products/alerts_platform/backend/delivery/webhook_url.py+++ b/products/alerts_platform/backend/delivery/webhook_url.py@@ -52,13 +52,17 @@ class WebhookUrlTransport(ABC):if not url:raise DeliveryError(f"This {self.display_name} destination has no webhook URL.")self.check_url(url)- self._post(url, self.body_for(message))+ self._post(self.send_url(url), self.body_for(message))return Nonedef check_url(self, url: str) -> None:"""Refuses a URL this provider never issues. The SSRF check runs on every send regardless."""return None+ def send_url(self, url: str) -> str:+ """The URL to post to, which a provider can extend with its own query parameters."""+ return url+@abstractmethoddef body_for(self, message: AlertMessage) -> dict[str, Any]: ...diff --git a/products/alerts_platform/backend/tests/test_delivery_discord.py b/products/alerts_platform/backend/tests/test_delivery_discord.pynew file mode 100644index 000000000000..32b3be522946--- /dev/null+++ b/products/alerts_platform/backend/tests/test_delivery_discord.py@@ -0,0 +1,75 @@+from typing import cast++import pytest++from django.test import SimpleTestCase++from parameterized import parameterized++from products.alerts_platform.backend.delivery.discord import MAX_CONTENT_CHARS, DiscordTransport, content_for+from products.alerts_platform.backend.delivery.message import MessageDetail+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.facade.contracts import AlertDestinationData+from products.alerts_platform.backend.tests.delivery_messages import alert_message, pinned_post+++class TestDiscordMessage(SimpleTestCase):+ def test_user_text_can_neither_ping_nor_disguise_a_link(self) -> None:+ message = alert_message(+ headline="@everyone [Checkout](https://evil.example) is firing",+ details=(+ MessageDetail(label="Threshold", value="> 300"),+ MessageDetail(label="Error", value="bad query\n# not a heading"),+ ),+ )++ body = DiscordTransport().body_for(message)++ assert body == {+ "content": "**@everyone \\[Checkout\\](https://evil.example) is firing**\n\n"+ "**Threshold:** \\> 300\n**Error:** bad query\n\\# not a heading",+ "allowed_mentions": {"parse": []},+ "flags": 4,+ }++ def test_a_long_error_keeps_the_message_inside_what_discord_accepts(self) -> None:+ message = alert_message(+ headline="API errors could not be checked",+ details=(MessageDetail(label="Error", value="x" * 5000), MessageDetail(label="Failed checks", value="3")),+ )++ content = content_for(message)++ assert len(content) <= MAX_CONTENT_CHARS+ assert content.endswith("**Failed checks:** 3")+++class TestDiscordTransport(SimpleTestCase):+ @parameterized.expand(+ [+ ("discord", "https://discord.com/api/webhooks/123/not-a-real-token", True),+ ("elsewhere", "https://example.com/api/webhooks/123/token", False),+ ("lookalike", "https://discord.com.evil.example/api/webhooks/123/token", False),+ ("userinfo", "https://[email protected]/api/webhooks/123/token", False),+ ]+ )+ def test_only_a_url_discord_issues_is_posted_to(self, _name: str, url: str, posted: bool) -> None:+ target = cast(AlertDestinationData, {"type": "discord", "webhook_url": url})++ with pinned_post(204) as adapter:+ if posted:+ DiscordTransport().deliver(team_id=2, target=target, message=alert_message())+ else:+ with pytest.raises(DeliveryError):+ DiscordTransport().deliver(team_id=2, target=target, message=alert_message())++ assert bool(adapter.sent) is posted++ def test_a_send_waits_for_discord_to_save_the_message(self) -> None:+ url = "https://discord.com/api/webhooks/123/not-a-real-token?thread_id=456"+ target = cast(AlertDestinationData, {"type": "discord", "webhook_url": url})++ with pinned_post(200) as adapter:+ DiscordTransport().deliver(team_id=2, target=target, message=alert_message())++ assert adapter.sent[-1].url == f"{url}&wait=true"