Skip to content

: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.

feat(slack_app): capture analytics event on @PostHog mention (#61338)

Oliver Browne00e0a876930d
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 28023d9f03cb..840f7fb75e98 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -17,10 +17,12 @@ from django.views.decorators.csrf import csrf_exempt
import requests
import structlog
+import posthoganalytics
from slack_sdk.errors import SlackApiError
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
+from posthog.event_usage import groups
from posthog.llm.gateway_client import get_llm_client
from posthog.models.integration import (
SLACK_INTEGRATION_KINDS,
@@ -1625,7 +1627,96 @@ def _start_command_workflow(
return ROUTE_HANDLED_LOCALLY
+def _count_session_thread_messages(integration: Integration, channel: str | None, thread_ts: str | None) -> int | None:
+ """Best-effort count of messages in a Slack thread (the session). None if unavailable.
+
+ Runs in the Slack webhook request path, so the client timeout is bounded: a slow or
+ rate-limited Slack response must not eat into Slack's retry window before we return.
+ """
+ if not channel or not thread_ts:
+ return None
+ try:
+ client = SlackIntegration(integration).client
+ client.timeout = 3
+ response = client.conversations_replies(channel=channel, ts=thread_ts, limit=200)
+ return len(response.get("messages", []))
+ except Exception:
+ logger.warning(
+ "posthog_code_mention_count_failed",
+ integration_id=integration.id,
+ channel=channel,
+ thread_ts=thread_ts,
+ exc_info=True,
+ )
+ return None
+
+
+def _report_slack_mention_received(event: dict, integration: Integration, slack_team_id: str) -> None:
+ """Capture a product-analytics event each time the @PostHog bot is mentioned.
+
+ A Slack thread is treated as the session: ``thread_ts`` identifies it, and a mention whose
+ ``thread_ts`` is absent or equal to its own ``ts`` is the session's first message. The acting
+ Slack user is resolved to a PostHog ``User`` so the event is attributed to a real person where
+ one exists; otherwise it falls back to a stable Slack-derived distinct id.
+ """
+ try:
+ channel = event.get("channel") if isinstance(event.get("channel"), str) else None
+ message_ts = event.get("ts") if isinstance(event.get("ts"), str) else None
+ raw_thread_ts = event.get("thread_ts") if isinstance(event.get("thread_ts"), str) else None
+ thread_ts = raw_thread_ts or message_ts
+ is_first_message_in_session = raw_thread_ts is None or raw_thread_ts == message_ts
+
+ slack_user_id = event.get("user") if isinstance(event.get("user"), str) and event.get("user") else None
+ posthog_user = (
+ _resolve_posthog_user_from_event(
+ slack_user_id=slack_user_id,
+ probe_integration=integration,
+ candidate_integrations=[integration],
+ )
+ if slack_user_id
+ else None
+ )
+ # Prefer the resolved PostHog user's distinct id so the event attributes to a real person;
+ # fall back to a stable Slack-derived id so anonymous-but-valid mentions are still captured.
+ identified_distinct_id = posthog_user.distinct_id if posthog_user else None
+ distinct_id = identified_distinct_id or f"slack:{slack_team_id}:{slack_user_id or 'unknown'}"
+
+ if is_first_message_in_session:
+ session_message_count: int | None = 1
+ else:
+ session_message_count = _count_session_thread_messages(integration, channel, thread_ts)
+
+ properties: dict[str, Any] = {
+ "is_first_message_in_session": is_first_message_in_session,
+ "session_message_count": session_message_count,
+ "slack_session_id": f"{slack_team_id}:{channel}:{thread_ts}" if channel and thread_ts else None,
+ "slack_team_id": slack_team_id,
+ "slack_channel": channel,
+ "slack_thread_ts": thread_ts,
+ "slack_user_id": slack_user_id,
+ "posthog_user_identified": identified_distinct_id is not None,
+ }
+ if posthog_user is not None and identified_distinct_id is not None:
+ properties["$set"] = posthog_user.get_analytics_metadata()
+
+ posthoganalytics.capture(
+ distinct_id=distinct_id,
+ event="posthog code slack mention received",
+ properties=properties,
+ groups=groups(team=integration.team),
+ send_feature_flags=True,
+ )
+ except Exception:
+ logger.warning(
+ "posthog_code_mention_analytics_failed",
+ slack_team_id=slack_team_id,
+ integration_id=integration.id,
+ exc_info=True,
+ )
+
+
def _start_mention_workflow(event: dict, integration: Integration, slack_team_id: str, event_id: str | None) -> str:
+ _report_slack_mention_received(event, integration, slack_team_id)
if _resolve_pending_repo_picker_from_followup(event, integration):
return ROUTE_HANDLED_LOCALLY
workflow_inputs = PostHogCodeSlackMentionWorkflowInputs(
diff --git a/products/slack_app/backend/tests/test_mention_analytics.py b/products/slack_app/backend/tests/test_mention_analytics.py
new file mode 100644
index 000000000000..d00611bdd8a8
--- /dev/null
+++ b/products/slack_app/backend/tests/test_mention_analytics.py
@@ -0,0 +1,124 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.slack_app.backend.api import _report_slack_mention_received
+
+
+class TestReportSlackMentionReceived:
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ cache.clear()
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="user-distinct-1")
+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ @parameterized.expand(
+ [
+ # name, event, user_resolved, thread_reply_count, exp_first, exp_count, exp_identified
+ (
+ "first_message_resolved",
+ {"channel": "C001", "ts": "1700.0001", "user": "U123"},
+ True,
+ None,
+ True,
+ 1,
+ True,
+ ),
+ (
+ "thread_root_is_the_mention_itself",
+ {"channel": "C001", "ts": "1700.0001", "thread_ts": "1700.0001", "user": "U123"},
+ True,
+ None,
+ True,
+ 1,
+ True,
+ ),
+ (
+ "followup_counts_thread_messages",
+ {"channel": "C001", "ts": "1700.0009", "thread_ts": "1700.0001", "user": "U123"},
+ True,
+ 3,
+ False,
+ 3,
+ True,
+ ),
+ (
+ "first_message_unresolved_user",
+ {"channel": "C001", "ts": "1700.0001", "user": "U999"},
+ False,
+ None,
+ True,
+ 1,
+ False,
+ ),
+ ]
+ )
+ @patch("products.slack_app.backend.api.SlackIntegration")
+ @patch("products.slack_app.backend.api.posthoganalytics.capture")
+ @patch("products.slack_app.backend.api._resolve_posthog_user_from_event")
+ def test_capture_properties(
+ self,
+ _name,
+ event,
+ user_resolved,
+ thread_reply_count,
+ exp_first,
+ exp_count,
+ exp_identified,
+ mock_resolve,
+ mock_capture,
+ mock_slack_integration,
+ ):
+ mock_resolve.return_value = self.user if user_resolved else None
+ if thread_reply_count is not None:
+ mock_client = MagicMock()
+ mock_client.conversations_replies.return_value = {"messages": [{}] * thread_reply_count}
+ mock_slack_integration.return_value.client = mock_client
+
+ _report_slack_mention_received(event, self.integration, "T12345")
+
+ assert mock_capture.call_count == 1
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["event"] == "posthog code slack mention received"
+ assert kwargs["send_feature_flags"] is True
+ assert kwargs["groups"]["project"] == str(self.team.uuid)
+
+ thread_ts = event.get("thread_ts") or event["ts"]
+ expected_distinct_id = "user-distinct-1" if exp_identified else f"slack:T12345:{event['user']}"
+ assert kwargs["distinct_id"] == expected_distinct_id
+
+ props = kwargs["properties"]
+ assert props["is_first_message_in_session"] is exp_first
+ assert props["session_message_count"] == exp_count
+ assert props["slack_session_id"] == f"T12345:{event['channel']}:{thread_ts}"
+ assert props["slack_thread_ts"] == thread_ts
+ assert props["slack_user_id"] == event["user"]
+ assert props["posthog_user_identified"] is exp_identified
+ assert ("$set" in props) is exp_identified
+
+ @patch("products.slack_app.backend.api.posthoganalytics.capture")
+ @patch("products.slack_app.backend.api._resolve_posthog_user_from_event")
+ def test_capture_failure_is_swallowed(self, mock_resolve, mock_capture):
+ mock_resolve.side_effect = Exception("boom")
+ event = {"channel": "C001", "ts": "1700.0001", "user": "U123"}
+
+ # Must not raise: analytics is best-effort and cannot break Slack event handling.
+ _report_slack_mention_received(event, self.integration, "T12345")
+
+ assert mock_capture.call_count == 0