: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(conversations): track support slack bot channel joins (#68156)
Alex Va27f68ff059a
diff --git a/products/conversations/backend/api/tests/test_slack_message_routing.py b/products/conversations/backend/api/tests/test_slack_message_routing.pyindex 323f9ee4f7ce..c61b86518d06 100644--- a/products/conversations/backend/api/tests/test_slack_message_routing.py+++ b/products/conversations/backend/api/tests/test_slack_message_routing.py@@ -358,14 +358,15 @@ class TestSlackMemberAlerts(BaseTest):mock_get_client.return_value.chat_postMessage.assert_not_called()+ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")@patch(f"{MODULE}.get_slack_client")- def test_member_event_no_op_without_alert_channel(self, mock_get_client):+ def test_member_event_no_alert_without_alert_channel(self, mock_get_client, _mock_bot_id):self.team.conversations_settings["slack_alert_channel_id"] = Noneself.team.save()handle_member_joined_channel({"user": "U123", "channel": "C_SUPPORT"}, self.team, "T123")- mock_get_client.assert_not_called()+ mock_get_client.return_value.chat_postMessage.assert_not_called()@patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")@patch(f"{MODULE}.get_slack_client")@@ -409,3 +410,36 @@ class TestSlackMemberAlerts(BaseTest):mock_get_client.return_value.chat_postMessage.assert_called_once()kwargs = mock_get_client.return_value.chat_postMessage.call_args.kwargsassert kwargs["text"] == "<@U123> joined <#C_SUPPORT>"++ @parameterized.expand(+ [+ ("unconfigured_channel", [], False),+ ("configured_channel", ["C_SUPPORT"], True),+ ]+ )+ @patch(f"{MODULE}.report_team_action")+ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.get_slack_client")+ def test_bot_join_fires_posthog_event(+ self, _name, channel_ids, expected_is_configured, mock_get_client, _mock_bot_id, mock_report+ ):+ self.team.conversations_settings["slack_channel_ids"] = channel_ids+ self.team.save()++ handle_member_joined_channel({"user": "U_OWN_BOT", "channel": "C_SUPPORT"}, self.team, "T123")++ mock_report.assert_called_once_with(+ self.team,+ "support slack bot joined channel",+ {"slack_team_id": "T123", "slack_channel_id": "C_SUPPORT", "is_configured_channel": expected_is_configured},+ )+ # It's analytics only — no Slack alert for the bot's own join.+ mock_get_client.return_value.chat_postMessage.assert_not_called()++ @patch(f"{MODULE}.report_team_action")+ @patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")+ @patch(f"{MODULE}.get_slack_client")+ def test_non_bot_join_does_not_fire_posthog_event(self, _mock_get_client, _mock_bot_id, mock_report):+ handle_member_joined_channel({"user": "U123", "channel": "C_SUPPORT"}, self.team, "T123")++ mock_report.assert_not_called()diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex a4be2edb8567..1393707d58ea 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -20,6 +20,7 @@ from django.db.models import Fimport structlogfrom slack_sdk import WebClient+from posthog.event_usage import report_team_actionfrom posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team@@ -995,13 +996,56 @@ def handle_support_reaction(event: dict, team: Team, slack_team_id: str) -> None_backfill_thread_replies(client, team, ticket, channel, root_ts, after_ts=message_ts)-def _handle_member_event(event: dict, team: Team, *, joined: bool) -> None:+def _track_bot_joined_channel(event: dict, team: Team, slack_team_id: str, *, own_bot_user_id: str | None) -> None:+ """Fire an internal PostHog event when our own bot is added to a channel.++ Unlike the human join/leave alerts, this isn't gated on any team setting — it's usage+ analytics for PostHog, not a customer-facing Slack message. Only the bot's own join is+ tracked; every other user's join is ignored here.++ There's deliberately no matching "bot left channel" event: Slack delivers+ ``member_left_channel`` only to remaining channel members, so the bot doesn't reliably+ receive its own removal.+ """+ user = event.get("user")+ channel = event.get("channel")+ if not user or not channel:+ return+ if not _SLACK_USER_ID_RE.match(user) or not _SLACK_CHANNEL_ID_RE.match(channel):+ return+ if not own_bot_user_id or user != own_bot_user_id:+ return++ settings_dict = team.conversations_settings or {}+ report_team_action(+ team,+ "support slack bot joined channel",+ {+ "slack_team_id": slack_team_id,+ "slack_channel_id": channel,+ "is_configured_channel": channel in _configured_support_channels(settings_dict),+ },+ )+++def _handle_member_event(+ event: dict,+ team: Team,+ *,+ joined: bool,+ client: WebClient | None = None,+ own_bot_user_id: str | None = None,+) -> None:"""Post a join/leave alert to the configured alert channel.Fires for any channel the bot is in (Slack only delivers member_joined_channel /member_left_channel for channels the bot belongs to). Gated per-direction by theteam's settings. Members of the team's own organization are skipped — the alert ismeant to surface external participants, not internal teammates.++ ``client``/``own_bot_user_id`` may be supplied by the caller so the join path resolves+ the bot identity once for both tracking and alerting; when omitted (leave path) they're+ resolved lazily here, after the gates, so a leave with alerts off does no Slack API work."""settings_dict = team.conversations_settings or {}@@ -1021,12 +1065,13 @@ def _handle_member_event(event: dict, team: Team, *, joined: bool) -> None:logger.warning("slack_member_event_malformed_ids", user=user, channel=channel)return- client = get_slack_client(team)+ if client is None:+ client = get_slack_client(team)+ own_bot_user_id = get_bot_user_id_cached(team, client)# If we can't resolve the bot's own ID (auth.test failed), bail — without it we can't tell# the bot's own join apart from a real user's, and posting a self-referential alert is worse# than skipping one alert during a transient auth outage.- own_bot_user_id = get_bot_user_id_cached(team, client)if not own_bot_user_id:logger.warning("slack_member_event_bot_id_unresolved", team_id=_get_team_id(team))return@@ -1066,7 +1111,12 @@ def _handle_member_event(event: dict, team: Team, *, joined: bool) -> None:def handle_member_joined_channel(event: dict, team: Team, slack_team_id: str) -> None:"""Handle a Slack 'member_joined_channel' event by alerting the configured channel."""- _handle_member_event(event, team, joined=True)+ # Resolve the bot identity once and share it with both the analytics event and the alert,+ # since a bot join always needs it for tracking regardless of the alert toggle.+ client = get_slack_client(team)+ own_bot_user_id = get_bot_user_id_cached(team, client)+ _track_bot_joined_channel(event, team, slack_team_id, own_bot_user_id=own_bot_user_id)+ _handle_member_event(event, team, joined=True, client=client, own_bot_user_id=own_bot_user_id)def handle_member_left_channel(event: dict, team: Team, slack_team_id: str) -> None: