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: two-way support for MS Teams shared channels (#64790)

Alex V70248664eece
diff --git a/products/conversations/backend/api/teams_oauth.py b/products/conversations/backend/api/teams_oauth.py
index 11dfdc4536c2..7600ac5d6140 100644
--- a/products/conversations/backend/api/teams_oauth.py
+++ b/products/conversations/backend/api/teams_oauth.py
@@ -38,8 +38,11 @@ TEAMS_OAUTH_SCOPES = (
"User.ReadBasic.All "
# ChannelMessage.Read.All (delegated) lets the shared-channel poller read
# channel messages via Graph's messages/delta as the connecting admin.
- # Must stay in sync with support_teams.GRAPH_REFRESH_SCOPES.
- "ChannelMessage.Read.All offline_access openid profile"
+ # ChannelMessage.Send (delegated) lets us post confirmation cards and agent
+ # replies back into shared channels via Graph — the bot connector can't write
+ # to shared channels (the bot isn't a member). Must stay in sync with
+ # support_teams.GRAPH_REFRESH_SCOPES.
+ "ChannelMessage.Read.All ChannelMessage.Send offline_access openid profile"
)
AZURE_AD_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
AZURE_AD_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
diff --git a/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py b/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
index ecf5c0fdadbe..0f7f212fa378 100644
--- a/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
+++ b/products/conversations/backend/api/tests/test_teams_shared_channel_polling.py
@@ -10,9 +10,19 @@ from products.conversations.backend.models import (
TeamConversationsTeamsConfig,
Ticket,
)
-from products.conversations.backend.support_teams import store_teams_service_url
+from products.conversations.backend.support_teams import (
+ GRAPH_REFRESH_SCOPES,
+ GRAPH_REFRESH_SCOPES_READONLY,
+ refresh_graph_token,
+ store_teams_service_url,
+)
from products.conversations.backend.tasks import poll_team_shared_channels, poll_teams_shared_channels
-from products.conversations.backend.teams import graph_message_to_activity
+from products.conversations.backend.teams import (
+ graph_message_to_activity,
+ parse_teams_root_message_id,
+ post_teams_channel_message_via_graph,
+ resolve_shared_channel_team_id,
+)
TRUSTED_SERVICE_URL = "https://smba.trafficmanager.net/teams"
@@ -81,6 +91,7 @@ class TestGraphMessageToActivity(BaseTest):
self.assertEqual(activity["channelData"]["channel"]["id"], CHANNEL_ID)
+@patch("products.conversations.backend.teams.requests.post", return_value=_resp(status_code=201))
@patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "Alice", "email": None})
@patch("products.conversations.backend.tasks.get_graph_token", return_value="graph-token")
class TestPollSharedChannel(BaseTest):
@@ -237,6 +248,26 @@ class TestPollSharedChannel(BaseTest):
TeamConversationsTeamsChannelSync.objects.for_team(self.team.id).filter(channel_id=CHANNEL_ID).exists()
)
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_confirmation_card_posted_via_graph_for_polled_ticket(
+ self, mock_get: MagicMock, _token: MagicMock, _resolve: MagicMock, mock_post: MagicMock
+ ) -> None:
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+ mock_post.reset_mock()
+
+ mock_get.side_effect = None
+ mock_get.return_value = _resp(json_data={"value": [_graph_message(msg_id="m2")], "@odata.deltaLink": "DELTA2"})
+ poll_team_shared_channels(self.team.id)
+
+ self.assertEqual(Ticket.objects.filter(team=self.team).count(), 1)
+ mock_post.assert_called_once()
+ url = mock_post.call_args.args[0] if mock_post.call_args.args else mock_post.call_args.kwargs["url"]
+ self.assertIn(f"/teams/{TEAMS_TEAM_ID}/channels/{CHANNEL_ID}/messages/m2/replies", url)
+
class TestStoreTeamsServiceUrl(BaseTest):
def setUp(self) -> None:
@@ -264,6 +295,115 @@ class TestStoreTeamsServiceUrl(BaseTest):
self.assertIsNone(self.config.teams_service_url)
+@patch("products.conversations.backend.support_teams.get_teams_instance_settings")
+@patch("products.conversations.backend.support_teams.requests.post")
+class TestRefreshGraphTokenScopeFallback(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.config, _ = TeamConversationsTeamsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"teams_tenant_id": "tenant-abc", "teams_graph_refresh_token": "ref-1"},
+ )
+
+ def _ok(self) -> MagicMock:
+ return _resp(json_data={"access_token": "fresh", "refresh_token": "ref-2", "expires_in": 3600})
+
+ def test_falls_back_to_readonly_scopes_when_send_not_consented(
+ self, mock_post: MagicMock, mock_settings: MagicMock
+ ) -> None:
+ mock_settings.return_value = {"SUPPORT_TEAMS_APP_ID": "app", "SUPPORT_TEAMS_APP_SECRET": "secret"}
+ # First (full scopes) rejected as if Send isn't consented; readonly retry succeeds.
+ mock_post.side_effect = [_resp(status_code=400), self._ok()]
+
+ token = refresh_graph_token(self.config)
+
+ self.assertEqual(token, "fresh")
+ self.assertEqual(mock_post.call_count, 2)
+ self.assertEqual(mock_post.call_args_list[0].kwargs["data"]["scope"], GRAPH_REFRESH_SCOPES)
+ self.assertEqual(mock_post.call_args_list[1].kwargs["data"]["scope"], GRAPH_REFRESH_SCOPES_READONLY)
+
+ def test_no_fallback_when_full_scopes_succeed(self, mock_post: MagicMock, mock_settings: MagicMock) -> None:
+ mock_settings.return_value = {"SUPPORT_TEAMS_APP_ID": "app", "SUPPORT_TEAMS_APP_SECRET": "secret"}
+ mock_post.return_value = self._ok()
+
+ token = refresh_graph_token(self.config)
+
+ self.assertEqual(token, "fresh")
+ self.assertEqual(mock_post.call_count, 1)
+
+ def test_no_readonly_downgrade_on_transient_error(self, mock_post: MagicMock, mock_settings: MagicMock) -> None:
+ mock_settings.return_value = {"SUPPORT_TEAMS_APP_ID": "app", "SUPPORT_TEAMS_APP_SECRET": "secret"}
+ # Transient failures (429/5xx) must NOT retry read-only — that would downgrade
+ # a recoverable full-scope token. Only 400 (consent denied) falls back.
+ for status_code in (429, 503):
+ mock_post.reset_mock()
+ mock_post.return_value = _resp(status_code=status_code)
+
+ with self.assertRaises(ValueError):
+ refresh_graph_token(self.config)
+
+ self.assertEqual(mock_post.call_count, 1)
+ self.assertEqual(mock_post.call_args_list[0].kwargs["data"]["scope"], GRAPH_REFRESH_SCOPES)
+
+
+class TestSharedChannelGraphSend(BaseTest):
+ @parameterized.expand(
+ [
+ ("no_marker", "19:[email protected]", None),
+ ("with_marker", f"{CHANNEL_ID};messageid=root-9", "root-9"),
+ ("empty_id", f"{CHANNEL_ID};messageid=", None),
+ ("none", None, None),
+ ]
+ )
+ def test_parse_root_message_id(self, _name: str, conversation_id: str | None, expected: str | None) -> None:
+ self.assertEqual(parse_teams_root_message_id(conversation_id), expected)
+
+ @parameterized.expand(
+ [
+ ("shared", "shared", TEAMS_TEAM_ID),
+ ("unknown_future_value", "unknownFutureValue", TEAMS_TEAM_ID),
+ ("standard", "standard", None),
+ ("private", "private", None),
+ ]
+ )
+ def test_resolve_shared_channel_team_id(self, _name: str, membership_type: str, expected: str | None) -> None:
+ self.team.conversations_settings = {
+ "teams_channels": [
+ {"channel_id": CHANNEL_ID, "team_id": TEAMS_TEAM_ID, "membership_type": membership_type}
+ ],
+ }
+ self.assertEqual(resolve_shared_channel_team_id(self.team, CHANNEL_ID), expected)
+
+ def test_resolve_returns_none_for_unconfigured_channel(self) -> None:
+ self.team.conversations_settings = {"teams_channels": []}
+ self.assertIsNone(resolve_shared_channel_team_id(self.team, CHANNEL_ID))
+
+ @patch("products.conversations.backend.teams.requests.post", return_value=_resp(status_code=201))
+ def test_graph_send_posts_reply_to_thread(self, mock_post: MagicMock) -> None:
+ status = post_teams_channel_message_via_graph(
+ team=self.team,
+ teams_team_id=TEAMS_TEAM_ID,
+ channel_id=CHANNEL_ID,
+ html="<p>reply</p>",
+ reply_to_message_id="root-1",
+ token="tok",
+ )
+ self.assertEqual(status, 201)
+ url = mock_post.call_args.args[0] if mock_post.call_args.args else mock_post.call_args.kwargs["url"]
+ self.assertIn(f"/teams/{TEAMS_TEAM_ID}/channels/{CHANNEL_ID}/messages/root-1/replies", url)
+
+ @patch("products.conversations.backend.teams.requests.post", return_value=_resp(status_code=403))
+ def test_graph_send_returns_status_on_error(self, _mock_post: MagicMock) -> None:
+ status = post_teams_channel_message_via_graph(
+ team=self.team,
+ teams_team_id=TEAMS_TEAM_ID,
+ channel_id=CHANNEL_ID,
+ html="<p>reply</p>",
+ token="tok",
+ )
+ self.assertEqual(status, 403)
+
+
class TestPollFanout(BaseTest):
# Graph returns "unknownFutureValue" for shared channels in some tenants, so both
# it and the literal "shared" must fan out; standard/private must not.
diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.py
index 0a7a77da342c..0c664ad97c4f 100644
--- a/products/conversations/backend/signals.py
+++ b/products/conversations/backend/signals.py
@@ -19,7 +19,14 @@ from .cache import invalidate_messages_cache, invalidate_tickets_cache
from .events import capture_message_received, capture_message_sent, capture_ticket_created
from .models import EmailOutboxMessage, Ticket
from .models.constants import Channel
-from .tasks import post_reply_to_github, post_reply_to_slack, post_reply_to_teams, send_email_reply
+from .tasks import (
+ post_reply_to_github,
+ post_reply_to_slack,
+ post_reply_to_teams,
+ post_reply_to_teams_via_graph,
+ send_email_reply,
+)
+from .teams import parse_teams_root_message_id, resolve_shared_channel_team_id
logger = structlog.get_logger(__name__)
@@ -456,7 +463,7 @@ def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, *
channel_source=Channel.TEAMS,
).first()
- if not ticket or not ticket.teams_conversation_id or not ticket.teams_service_url:
+ if not ticket or not ticket.teams_conversation_id:
return
team = ticket.team
@@ -468,15 +475,33 @@ def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, *
if created_by:
author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email
- cast(Any, post_reply_to_teams).delay(
- ticket_id=str(ticket.id),
- team_id=team_id,
- content=content,
- rich_content=rich_content,
- author_name=author_name,
- teams_service_url=ticket.teams_service_url,
- teams_conversation_id=ticket.teams_conversation_id,
- )
+ # Shared channels are written to via Graph (the bot connector can't post
+ # there); standard channels keep using the bot connector reply path.
+ shared_team_id = resolve_shared_channel_team_id(team, ticket.teams_channel_id)
+ if shared_team_id:
+ root_message_id = parse_teams_root_message_id(ticket.teams_conversation_id)
+ if not root_message_id:
+ return
+ cast(Any, post_reply_to_teams_via_graph).delay(
+ ticket_id=str(ticket.id),
+ team_id=team_id,
+ teams_team_id=shared_team_id,
+ channel_id=ticket.teams_channel_id,
+ root_message_id=root_message_id,
+ content=content,
+ rich_content=rich_content,
+ author_name=author_name,
+ )
+ elif ticket.teams_service_url:
+ cast(Any, post_reply_to_teams).delay(
+ ticket_id=str(ticket.id),
+ team_id=team_id,
+ content=content,
+ rich_content=rich_content,
+ author_name=author_name,
+ teams_service_url=ticket.teams_service_url,
+ teams_conversation_id=ticket.teams_conversation_id,
+ )
except Exception:
logger.exception("teams_reply_signal_failed", item_id=item_id)
diff --git a/products/conversations/backend/support_teams.py b/products/conversations/backend/support_teams.py
index ed7cf5f2be50..5da1306a1dbe 100644
--- a/products/conversations/backend/support_teams.py
+++ b/products/conversations/backend/support_teams.py
@@ -74,7 +74,18 @@ JWT_CLOCK_TOLERANCE_SECONDS = 5 * 60
# ChannelMessage.Read.All (delegated) powers the shared-channel message poller:
# shared/private channels never push ambient messages over the bot webhook, so we
# pull them from Graph's per-channel messages/delta as the connecting admin.
+# ChannelMessage.Send (delegated) lets us post confirmation cards and agent replies
+# back into shared channels via Graph, since the bot connector can't write there.
GRAPH_REFRESH_SCOPES = (
+ "Team.ReadBasic.All Channel.ReadBasic.All User.ReadBasic.All "
+ "ChannelMessage.Read.All ChannelMessage.Send offline_access openid profile"
+)
+
+# Tenants that authorized before ChannelMessage.Send was added never consented to it,
+# and Azure AD rejects a refresh-token grant that requests an unconsented scope
+# (AADSTS65001). We fall back to this read-only set so the poller keeps working for
+# those tenants — sending will 403 until an admin reconnects and grants Send.
+GRAPH_REFRESH_SCOPES_READONLY = (
"Team.ReadBasic.All Channel.ReadBasic.All User.ReadBasic.All ChannelMessage.Read.All offline_access openid profile"
)
@@ -337,17 +348,32 @@ def refresh_graph_token(config: TeamConversationsTeamsConfig) -> str:
if not app_id or not app_secret:
raise ValueError("Teams bot credentials not configured")
- resp = requests.post(
- GRAPH_TOKEN_URL,
- data={
- "client_id": app_id,
- "client_secret": app_secret,
- "refresh_token": config.teams_graph_refresh_token,
- "grant_type": "refresh_token",
- "scope": GRAPH_REFRESH_SCOPES,
- },
- timeout=15,
- )
+ def _post_refresh(scope: str) -> requests.Response:
+ return requests.post(
+ GRAPH_TOKEN_URL,
+ data={
+ "client_id": app_id,
+ "client_secret": app_secret,
+ "refresh_token": config.teams_graph_refresh_token,
+ "grant_type": "refresh_token",
+ "scope": scope,
+ },
+ timeout=15,
+ )
+
+ resp = _post_refresh(GRAPH_REFRESH_SCOPES)
+ # Azure AD returns 400 (AADSTS65001 / invalid_scope) when a requested scope was
+ # never consented — e.g. a tenant that connected before ChannelMessage.Send
+ # existed. Retry read-only so polling survives (send stays 403 until reconnect).
+ # Only 400 means scope denial; 429/5xx are transient and must NOT downgrade the
+ # token to read-only, so they fall through to the failure path below.
+ if resp.status_code == 400:
+ logger.warning(
+ "teams_graph_token_refresh_retry_readonly",
+ team_id=config.team_id,
+ status=resp.status_code,
+ )
+ resp = _post_refresh(GRAPH_REFRESH_SCOPES_READONLY)
if resp.status_code != 200:
logger.warning(
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index 4bf7ee8f779a..adf0c4935497 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -72,7 +72,9 @@ from products.conversations.backend.teams import (
graph_message_to_activity,
handle_teams_mention,
handle_teams_message,
+ is_shared_membership_type,
post_help_card,
+ post_teams_channel_message_via_graph,
)
from products.conversations.backend.teams_formatting import rich_content_to_teams_html
@@ -828,17 +830,52 @@ def post_reply_to_teams(
raise cast(Any, post_reply_to_teams).retry(exc=e)
-# Graph's channel membershipType is an evolvable enum: the v1.0
-# /teams/{id}/channels endpoint emits "unknownFutureValue" for shared channels in
-# some tenants instead of the literal "shared". So we treat anything that isn't an
-# explicit standard/private channel as pollable (shared), rather than matching
-# "shared" exactly — and the Graph re-verification below rejects only the explicit
-# standard/private cases.
-TEAMS_NON_POLLED_MEMBERSHIP_TYPES = {"standard", "private"}
+@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)
+@skip_team_scope_audit
+def post_reply_to_teams_via_graph(
+ ticket_id: str,
+ team_id: int,
+ teams_team_id: str,
+ channel_id: str,
+ root_message_id: str,
+ content: str,
+ rich_content: dict | None,
+ author_name: str,
+) -> None:
+ """Post a support agent's reply into a shared Teams channel thread via Graph.
+ Shared channels can't be written to over the bot connector, so replies go through
+ Graph with the delegated admin token (same path the poller reads with).
+ """
+ team = Team.objects.filter(id=team_id).first()
+ if not team:
+ logger.warning("teams_graph_reply_team_not_found", team_id=team_id)
+ return
+
+ reply_html = rich_content_to_teams_html(rich_content, content)
+ if author_name:
+ reply_html = f"<p><b>{html_mod.escape(author_name)}</b></p>{reply_html}"
-def _is_shared_membership_type(membership_type: str | None) -> bool:
- return membership_type not in TEAMS_NON_POLLED_MEMBERSHIP_TYPES
+ status = post_teams_channel_message_via_graph(
+ team=team,
+ teams_team_id=teams_team_id,
+ channel_id=channel_id,
+ html=reply_html,
+ reply_to_message_id=root_message_id,
+ log_context={"ticket_id": ticket_id},
+ )
+ if status in (200, 201):
+ logger.info("teams_graph_reply_posted", ticket_id=ticket_id, channel_id=channel_id)
+ return
+
+ # Retry only transient failures (network/no-token=0, throttling, 5xx). Permanent
+ # ones — 401/403 (token/consent), 404 (thread gone), 400 — won't self-heal and
+ # would just burn the retry budget, so log and drop.
+ if status == 0 or status == 429 or status >= 500:
+ raise cast(Any, post_reply_to_teams_via_graph).retry(
+ exc=Exception(f"Teams Graph reply transient failure (status {status})")
+ )
+ logger.warning("teams_graph_reply_permanent_failure", ticket_id=ticket_id, status=status)
def _shared_channel_entries(support_settings: dict) -> list[dict]:
@@ -846,7 +883,7 @@ def _shared_channel_entries(support_settings: dict) -> list[dict]:
entries = support_settings.get("teams_channels")
if not isinstance(entries, list):
return []
- return [e for e in entries if isinstance(e, dict) and _is_shared_membership_type(e.get("membership_type"))]
+ return [e for e in entries if isinstance(e, dict) and is_shared_membership_type(e.get("membership_type"))]
def _parse_graph_datetime(value: str | None) -> datetime | None:
@@ -897,7 +934,7 @@ def _poll_one_shared_channel(
headers={"Authorization": f"Bearer {token}"},
timeout=TEAMS_DELTA_REQUEST_TIMEOUT_SECONDS,
)
- if ch_resp.status_code != 200 or not _is_shared_membership_type(ch_resp.json().get("membershipType")):
+ if ch_resp.status_code != 200 or not is_shared_membership_type(ch_resp.json().get("membershipType")):
logger.warning(
"poll_teams_shared_channel_not_shared",
team_id=team.id,
@@ -968,6 +1005,9 @@ def _poll_one_shared_channel(
tenant_id=tenant_id,
is_thread_reply=False,
channel_detail=ChannelDetail.TEAMS_CHANNEL_MESSAGE,
+ # Shared channel: confirm via Graph (bot connector can't post here),
+ # reusing the token we already hold for the delta read.
+ graph_post_context={"teams_team_id": teams_team_id, "token": token},
)
except Exception:
logger.exception(
diff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.py
index 932956edc62d..9a0ba1d0ea1e 100644
--- a/products/conversations/backend/teams.py
+++ b/products/conversations/backend/teams.py
@@ -420,6 +420,95 @@ def _send_confirmation_card(
logger.warning("teams_confirmation_post_error", ticket_id=str(ticket.id))
+# Graph's channel membershipType is an evolvable enum: the v1.0
+# /teams/{id}/channels endpoint emits "unknownFutureValue" for shared channels in
+# some tenants instead of the literal "shared". We treat anything that isn't an
+# explicit standard/private channel as shared (poll + Graph-post), and Graph
+# re-verification elsewhere rejects only the explicit standard/private cases.
+TEAMS_NON_POLLED_MEMBERSHIP_TYPES = {"standard", "private"}
+
+
+def is_shared_membership_type(membership_type: str | None) -> bool:
+ return membership_type not in TEAMS_NON_POLLED_MEMBERSHIP_TYPES
+
+
+def parse_teams_root_message_id(conversation_id: str | None) -> str | None:
+ """Extract the Graph root message id from a ``<channel>;messageid=<id>`` conversation id."""
+ if not conversation_id:
+ return None
+ marker = ";messageid="
+ if marker not in conversation_id:
+ return None
+ return conversation_id.split(marker, 1)[1] or None
+
+
+def resolve_shared_channel_team_id(team: Team, channel_id: str | None) -> str | None:
+ """Return the Graph teamId (group id) for a configured *shared* channel, else ``None``.
+
+ Shared/private channels are written to via Graph (delegated admin token), not the
+ bot connector, so this both selects the transport and supplies the teamId the Graph
+ messages endpoint needs (the ticket itself doesn't store the group id).
+ """
+ if not channel_id:
+ return None
+ settings_dict = team.conversations_settings or {}
+ entries = settings_dict.get("teams_channels")
+ if not isinstance(entries, list):
+ return None
+ for entry in entries:
+ if not isinstance(entry, dict) or entry.get("channel_id") != channel_id:
+ continue
+ if not is_shared_membership_type(entry.get("membership_type")):
+ return None
+ team_group_id = entry.get("team_id")
+ return str(team_group_id) if team_group_id else None
+ return None
+
+
+def post_teams_channel_message_via_graph(
+ *,
+ team: Team,
+ teams_team_id: str,
+ channel_id: str,
+ html: str,
+ reply_to_message_id: str | None = None,
+ token: str | None = None,
+ log_context: dict | None = None,
+) -> int:
+ """Post an HTML channel message (or thread reply) via Graph as the connecting admin.
+
+ The bot connector can't write to shared channels (the bot isn't a member), so
+ confirmation cards and agent replies for shared-channel tickets go through Graph
+ with the same delegated token the poller uses to read. Returns the HTTP status
+ code (``0`` for a missing token or network error) so callers can distinguish
+ transient failures from permanent ones (e.g. 403 when Send isn't consented yet).
+ """
+ ctx = log_context or {}
+ if token is None:
+ try:
+ token = get_graph_token(team)
+ except ValueError:
+ logger.warning("teams_graph_post_no_token", **ctx)
+ return 0
+
+ base = f"{GRAPH_API_BASE}/teams/{teams_team_id}/channels/{channel_id}/messages"
+ url = f"{base}/{reply_to_message_id}/replies" if reply_to_message_id else base
+ try:
+ resp = requests.post(
+ url,
+ json={"body": {"contentType": "html", "content": html}},
+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
+ timeout=15,
+ )
+ except requests.RequestException:
+ logger.warning("teams_graph_post_error", url=url, **ctx)
+ return 0
+
+ if resp.status_code not in (200, 201):
+ logger.warning("teams_graph_post_failed", status=resp.status_code, body=resp.text[:500], url=url, **ctx)
+ return resp.status_code
+
+
def create_or_update_teams_ticket(
*,
team: Team,
@@ -427,6 +516,7 @@ def create_or_update_teams_ticket(
tenant_id: str,
is_thread_reply: bool = False,
channel_detail: ChannelDetail | None = None,
+ graph_post_context: dict | None = None,
) -> Ticket | None:
"""
Core function: create a new ticket or add a message to an existing one from a Teams Activity.
@@ -573,14 +663,27 @@ def create_or_update_teams_ticket(
},
)
- # Post confirmation card in the Teams thread
- _send_confirmation_card(
- service_url=service_url,
- conversation_id=conversation_id,
- reply_to_id=activity_id,
- ticket=ticket,
- team=team,
- )
+ # Post confirmation card in the Teams thread. Shared-channel tickets (polled)
+ # can't be confirmed over the bot connector, so go through Graph instead.
+ if graph_post_context:
+ ticket_url = f"{settings.SITE_URL}/project/{team_id}/support/tickets/{ticket.id}"
+ post_teams_channel_message_via_graph(
+ team=team,
+ teams_team_id=graph_post_context["teams_team_id"],
+ channel_id=channel_id,
+ html=f'\U0001f3ab Ticket #{ticket.ticket_number} created. <a href="{ticket_url}">View in PostHog</a>',
+ reply_to_message_id=activity_id,
+ token=graph_post_context.get("token"),
+ log_context={"ticket_id": str(ticket.id)},
+ )
+ else:
+ _send_confirmation_card(
+ service_url=service_url,
+ conversation_id=conversation_id,
+ reply_to_id=activity_id,
+ ticket=ticket,
+ team=team,
+ )
return ticket
diff --git a/products/conversations/frontend/scenes/settings/TeamsSection.tsx b/products/conversations/frontend/scenes/settings/TeamsSection.tsx
index 5aff9a4c80a6..785fe20ed6e4 100644
--- a/products/conversations/frontend/scenes/settings/TeamsSection.tsx
+++ b/products/conversations/frontend/scenes/settings/TeamsSection.tsx
@@ -21,6 +21,12 @@ import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { supportSettingsLogic } from './supportSettingsLogic'
+// Graph reports shared channels as "shared" or, in some tenants, "unknownFutureValue".
+// Anything that isn't an explicit standard/private channel is polled (shared).
+function isSharedMembershipType(membershipType: string | null | undefined): boolean {
+ return membershipType != null && !['standard', 'private'].includes(membershipType)
+}
+
export function TeamsSection(): JSX.Element {
return (
<SceneSection
@@ -56,7 +62,7 @@ interface TeamsChannelRowProps {
}
function TeamsChannelRow({ pair, onRemove, isLoading, adminRestrictionReason }: TeamsChannelRowProps): JSX.Element {
- const isShared = pair.membership_type === 'shared'
+ const isShared = isSharedMembershipType(pair.membership_type)
return (
<div className="flex items-center justify-between gap-2 py-2 px-3 border rounded">
<div className="flex-1 min-w-0">
@@ -204,10 +210,13 @@ function AddTeamsChannelRow({ adminRestrictionReason }: AddTeamsChannelRowProps)
options={[
{ value: null, label: 'Select channel...' },
...selectedTeamChannels.map(
- (c: { id: string; name: string; membership_type?: string | null }) => ({
- value: c.id,
- label: c.membership_type === 'shared' ? `#${c.name} (shared)` : `#${c.name}`,
- })
+ (c: { id: string; name: string; membership_type?: string | null }) => {
+ const isShared = isSharedMembershipType(c.membership_type)
+ return {
+ value: c.id,
+ label: isShared ? `#${c.name} (shared)` : `#${c.name}`,
+ }
+ }
),
]}
onChange={handleChannelSelect}