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: sync shared-channel Teams thread replies via Graph (#64833)

Alex V511fdea89755
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 0f7f212fa378..083413975159 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
@@ -19,6 +19,7 @@ from products.conversations.backend.support_teams import (
from products.conversations.backend.tasks import poll_team_shared_channels, poll_teams_shared_channels
from products.conversations.backend.teams import (
graph_message_to_activity,
+ graph_reply_to_activity,
parse_teams_root_message_id,
post_teams_channel_message_via_graph,
resolve_shared_channel_team_id,
@@ -38,11 +39,12 @@ def _graph_message(
user_id: str | None = "aad-user-1",
deleted: bool = False,
reply_to_id: str | None = None,
+ created_at: str = "2024-01-01T12:00:00Z",
) -> dict[str, Any]:
msg: dict[str, Any] = {
"id": msg_id,
"messageType": message_type,
- "createdDateTime": "2024-01-01T12:00:00Z",
+ "createdDateTime": created_at,
"body": {"contentType": "html", "content": content},
}
if deleted:
@@ -91,6 +93,27 @@ class TestGraphMessageToActivity(BaseTest):
self.assertEqual(activity["channelData"]["channel"]["id"], CHANNEL_ID)
+class TestGraphReplyToActivity(BaseTest):
+ @parameterized.expand(
+ [
+ ("normal_reply", _graph_message(reply_to_id="root-1"), True),
+ ("deleted_reply", _graph_message(reply_to_id="root-1", deleted=True), False),
+ ("app_authored", _graph_message(reply_to_id="root-1", user_id=None), False),
+ ("wrong_root", _graph_message(reply_to_id="other-root"), False),
+ ("empty_body", _graph_message(reply_to_id="root-1", content=" "), False),
+ ]
+ )
+ def test_mapping(self, _name: str, msg: dict, should_map: bool) -> None:
+ activity = graph_reply_to_activity(msg, CHANNEL_ID, "root-1", TRUSTED_SERVICE_URL)
+ if not should_map:
+ self.assertIsNone(activity)
+ return
+ assert activity is not None
+ self.assertEqual(activity["id"], msg["id"])
+ self.assertEqual(activity["conversation"]["id"], f"{CHANNEL_ID};messageid=root-1")
+
+
+@patch("products.conversations.backend.tasks._sync_shared_channel_thread_replies")
@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")
@@ -250,7 +273,7 @@ class TestPollSharedChannel(BaseTest):
@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
+ self, mock_get: MagicMock, _token: MagicMock, _resolve: MagicMock, mock_post: MagicMock, *_: Any
) -> None:
mock_get.side_effect = [
_channel_verify_resp(),
@@ -269,6 +292,82 @@ class TestPollSharedChannel(BaseTest):
self.assertIn(f"/teams/{TEAMS_TEAM_ID}/channels/{CHANNEL_ID}/messages/m2/replies", url)
+@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 TestPollSharedChannelThreadReplies(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team.conversations_settings = {
+ "teams_enabled": True,
+ "teams_channels": [
+ {
+ "team_id": TEAMS_TEAM_ID,
+ "team_name": "Group",
+ "channel_id": CHANNEL_ID,
+ "channel_name": "shared",
+ "membership_type": "shared",
+ },
+ ],
+ }
+ self.team.save()
+ TeamConversationsTeamsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={
+ "teams_tenant_id": "tenant-abc",
+ "teams_graph_access_token": "graph-tok",
+ "teams_graph_refresh_token": "graph-ref",
+ },
+ )
+
+ @patch("products.conversations.backend.tasks.requests.get")
+ def test_thread_reply_ingested_from_graph_replies(self, mock_get: MagicMock, *_: Any) -> None:
+ from datetime import UTC, datetime
+
+ mock_get.side_effect = [
+ _channel_verify_resp(),
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA1"}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ mock_get.side_effect = [
+ _resp(json_data={"value": [_graph_message(msg_id="root-1")], "@odata.deltaLink": "DELTA2"}),
+ _resp(json_data={"value": []}),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ ticket = Ticket.objects.filter(team=self.team).get()
+ self.assertEqual(ticket.teams_conversation_id, f"{CHANNEL_ID};messageid=root-1")
+ ticket.teams_thread_replies_synced_at = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)
+ ticket.save(update_fields=["teams_thread_replies_synced_at"])
+
+ mock_get.side_effect = [
+ _resp(json_data={"value": [], "@odata.deltaLink": "DELTA3"}),
+ _resp(
+ json_data={
+ "value": [
+ _graph_message(
+ msg_id="reply-1",
+ reply_to_id="root-1",
+ content="<p>follow up question</p>",
+ created_at="2024-06-01T12:00:00Z",
+ )
+ ]
+ }
+ ),
+ ]
+ poll_team_shared_channels(self.team.id)
+
+ from posthog.models.comment import Comment
+
+ self.assertEqual(Comment.objects.filter(team=self.team, item_id=str(ticket.id)).count(), 2)
+ reply_comment = Comment.objects.filter(team=self.team, item_id=str(ticket.id)).order_by("created_at").last()
+ assert isinstance(reply_comment.item_context, dict)
+ self.assertEqual(reply_comment.item_context.get("teams_graph_message_id"), "reply-1")
+ ticket.refresh_from_db()
+ self.assertIsNotNone(ticket.teams_thread_replies_synced_at)
+
+
class TestStoreTeamsServiceUrl(BaseTest):
def setUp(self) -> None:
super().setUp()
@@ -380,7 +479,7 @@ class TestSharedChannelGraphSend(BaseTest):
@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(
+ status, _message_id = post_teams_channel_message_via_graph(
team=self.team,
teams_team_id=TEAMS_TEAM_ID,
channel_id=CHANNEL_ID,
@@ -394,7 +493,7 @@ class TestSharedChannelGraphSend(BaseTest):
@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(
+ status, message_id = post_teams_channel_message_via_graph(
team=self.team,
teams_team_id=TEAMS_TEAM_ID,
channel_id=CHANNEL_ID,
@@ -402,6 +501,7 @@ class TestSharedChannelGraphSend(BaseTest):
token="tok",
)
self.assertEqual(status, 403)
+ self.assertIsNone(message_id)
class TestPollFanout(BaseTest):
diff --git a/products/conversations/backend/migrations/0039_ticket_teams_thread_replies_synced_at.py b/products/conversations/backend/migrations/0039_ticket_teams_thread_replies_synced_at.py
new file mode 100644
index 000000000000..2a16821b68d6
--- /dev/null
+++ b/products/conversations/backend/migrations/0039_ticket_teams_thread_replies_synced_at.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-06-19 00:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("conversations", "0038_teamconversationsteamsconfig_teams_service_url_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="ticket",
+ name="teams_thread_replies_synced_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index aa32bf37cec9..110bb2a77d5d 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0038_teamconversationsteamsconfig_teams_service_url_and_more
+0039_ticket_teams_thread_replies_synced_at
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index 822ada23246b..73ca1ad84c2c 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -68,6 +68,8 @@ class Ticket(UUIDTModel):
teams_conversation_id = models.CharField(max_length=256, null=True, blank=True) # Reply chain / thread ID
teams_service_url = models.URLField(max_length=512, null=True, blank=True) # Bot Connector endpoint for replies
teams_tenant_id = models.CharField(max_length=64, null=True, blank=True)
+ # Shared-channel thread reply poller watermark (Graph createdDateTime of last ingested reply).
+ teams_thread_replies_synced_at = models.DateTimeField(null=True, blank=True)
# GitHub channel fields (only set for channel_source="github")
github_repo = models.CharField(max_length=256, null=True, blank=True) # owner/repo
diff --git a/products/conversations/backend/support_teams.py b/products/conversations/backend/support_teams.py
index 5da1306a1dbe..3d307738bad6 100644
--- a/products/conversations/backend/support_teams.py
+++ b/products/conversations/backend/support_teams.py
@@ -89,6 +89,35 @@ GRAPH_REFRESH_SCOPES_READONLY = (
"Team.ReadBasic.All Channel.ReadBasic.All User.ReadBasic.All ChannelMessage.Read.All offline_access openid profile"
)
+SUPPORTHOG_TEAMS_GRAPH_MESSAGE_KEY_PREFIX = "supporthog:teams:graph-msg:"
+# Long TTL: polled thread replies and outbound Graph posts must stay deduped across
+# the every-minute sweep (and Bot Framework-style retries on transient failures).
+SUPPORTHOG_TEAMS_GRAPH_MESSAGE_TTL_SECONDS = 30 * 24 * 60 * 60
+
+
+def _teams_graph_message_key(team_id: int, channel_id: str, message_id: str) -> str:
+ # Graph chatMessage ids are tick-based and only unique within a channel, so the
+ # dedup key must be scoped by team + channel to avoid cross-tenant collisions.
+ return f"{SUPPORTHOG_TEAMS_GRAPH_MESSAGE_KEY_PREFIX}{team_id}:{channel_id}:{message_id}"
+
+
+def mark_teams_graph_message_seen(team_id: int, channel_id: str, message_id: str) -> None:
+ """Record a Graph chatMessage id so the shared-channel reply poller won't re-ingest it."""
+ if not message_id or not channel_id:
+ return
+ cache.set(
+ _teams_graph_message_key(team_id, channel_id, message_id),
+ True,
+ timeout=SUPPORTHOG_TEAMS_GRAPH_MESSAGE_TTL_SECONDS,
+ )
+
+
+def is_teams_graph_message_seen(team_id: int, channel_id: str, message_id: str) -> bool:
+ """Return True if this Graph message id was already processed (read-only check)."""
+ if not message_id or not channel_id:
+ return False
+ return cache.get(_teams_graph_message_key(team_id, channel_id, message_id)) is not None
+
def get_teams_instance_settings() -> dict:
return get_instance_settings(
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index adf0c4935497..2c7a0cfd24ea 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -10,6 +10,7 @@ from uuid import UUID
from django.core import mail
from django.core.cache import cache
from django.db import IntegrityError, models, transaction
+from django.db.models import F
from django.db.models.fields.json import JSONField
from django.db.models.functions import Coalesce
from django.utils import timezone
@@ -46,7 +47,7 @@ from products.conversations.backend.models import (
TeamConversationsTeamsChannelSync,
TeamConversationsTeamsConfig,
)
-from products.conversations.backend.models.constants import ChannelDetail, Status
+from products.conversations.backend.models.constants import Channel, ChannelDetail, Status
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.slack import (
get_slack_client,
@@ -70,9 +71,11 @@ from products.conversations.backend.teams import (
_is_bot_mention,
create_or_update_teams_ticket,
graph_message_to_activity,
+ graph_reply_to_activity,
handle_teams_mention,
handle_teams_message,
is_shared_membership_type,
+ parse_teams_root_message_id,
post_help_card,
post_teams_channel_message_via_graph,
)
@@ -856,7 +859,7 @@ def post_reply_to_teams_via_graph(
if author_name:
reply_html = f"<p><b>{html_mod.escape(author_name)}</b></p>{reply_html}"
- status = post_teams_channel_message_via_graph(
+ status, _message_id = post_teams_channel_message_via_graph(
team=team,
teams_team_id=teams_team_id,
channel_id=channel_id,
@@ -900,6 +903,158 @@ def _parse_graph_datetime(value: str | None) -> datetime | None:
# in a single run. Remaining pages resume on subsequent every-minute runs.
TEAMS_DELTA_MAX_PAGES_PER_RUN = 20
TEAMS_DELTA_REQUEST_TIMEOUT_SECONDS = 30
+TEAMS_REPLIES_MAX_PAGES_PER_TICKET = 5
+# Cap the number of tickets whose threads we poll per channel per run.
+# Oldest-synced tickets are polled first so the sweep round-robins through
+# the backlog across successive every-minute runs.
+TEAMS_REPLIES_MAX_TICKETS_PER_CHANNEL = 20
+# Only poll threads on tickets created within this window.
+TEAMS_REPLIES_TICKET_AGE_DAYS = 30
+
+
+def _sync_one_ticket_thread_replies(
+ *,
+ team: Team,
+ tenant_id: str,
+ token: str,
+ teams_team_id: str,
+ channel_id: str,
+ service_url: str,
+ ticket: Ticket,
+) -> None:
+ """Ingest new thread replies for one shared-channel ticket via Graph."""
+ root_message_id = parse_teams_root_message_id(ticket.teams_conversation_id)
+ if not root_message_id:
+ return
+
+ watermark = ticket.teams_thread_replies_synced_at or ticket.created_at
+ latest_synced_at = ticket.teams_thread_replies_synced_at
+
+ url: str | None = (
+ f"{GRAPH_API_BASE}/teams/{teams_team_id}/channels/{channel_id}/messages/{root_message_id}/replies?$top=200"
+ )
+ headers = {"Authorization": f"Bearer {token}"}
+ pages = 0
+
+ while url and pages < TEAMS_REPLIES_MAX_PAGES_PER_TICKET:
+ pages += 1
+ resp = requests.get(url, headers=headers, timeout=TEAMS_DELTA_REQUEST_TIMEOUT_SECONDS)
+
+ if resp.status_code in (401, 402, 403, 404, 429):
+ logger.warning(
+ "poll_teams_shared_channel_replies_denied",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ status=resp.status_code,
+ )
+ return
+ if resp.status_code != 200:
+ logger.warning(
+ "poll_teams_shared_channel_replies_error",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ status=resp.status_code,
+ )
+ return
+
+ data = resp.json()
+ replies = data.get("value") or []
+
+ page_had_failure = False
+ for reply in replies:
+ msg_created = _parse_graph_datetime(reply.get("createdDateTime"))
+ if msg_created and msg_created < watermark:
+ continue
+
+ activity = graph_reply_to_activity(reply, channel_id, root_message_id, service_url)
+ if activity is None:
+ continue
+
+ try:
+ result = create_or_update_teams_ticket(
+ team=team,
+ activity=activity,
+ tenant_id=tenant_id,
+ is_thread_reply=True,
+ )
+ except Exception:
+ logger.exception(
+ "poll_teams_shared_channel_reply_ingest_failed",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ )
+ page_had_failure = True
+ continue
+
+ if result and msg_created and (latest_synced_at is None or msg_created > latest_synced_at):
+ latest_synced_at = msg_created
+
+ if page_had_failure:
+ break
+
+ url = data.get("@odata.nextLink")
+
+ new_watermark = latest_synced_at or timezone.now()
+ if new_watermark != ticket.teams_thread_replies_synced_at:
+ Ticket.objects.filter(id=ticket.id, team=team).update(teams_thread_replies_synced_at=new_watermark)
+
+
+def _sync_shared_channel_thread_replies(
+ *,
+ team: Team,
+ tenant_id: str,
+ token: str,
+ teams_team_id: str,
+ channel_id: str,
+ service_url: str,
+) -> None:
+ """Pull new thread replies for every Teams ticket in a shared channel."""
+ sync = TeamConversationsTeamsChannelSync.objects.for_team(team.id).filter(channel_id=channel_id).first()
+ if not sync or not sync.primed:
+ return
+
+ age_cutoff = timezone.now() - timedelta(days=TEAMS_REPLIES_TICKET_AGE_DAYS)
+ tickets = (
+ Ticket.objects.filter(
+ team=team,
+ channel_source=Channel.TEAMS,
+ teams_channel_id=channel_id,
+ created_at__gte=age_cutoff,
+ )
+ .exclude(teams_conversation_id__isnull=True)
+ .exclude(teams_conversation_id="")
+ .exclude(status=Status.RESOLVED)
+ .order_by(F("teams_thread_replies_synced_at").asc(nulls_first=True))[:TEAMS_REPLIES_MAX_TICKETS_PER_CHANNEL]
+ )
+
+ for ticket in tickets:
+ try:
+ _sync_one_ticket_thread_replies(
+ team=team,
+ tenant_id=tenant_id,
+ token=token,
+ teams_team_id=teams_team_id,
+ channel_id=channel_id,
+ service_url=service_url,
+ ticket=ticket,
+ )
+ except requests.RequestException:
+ logger.warning(
+ "poll_teams_shared_channel_replies_network_error",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ )
+ except Exception:
+ logger.exception(
+ "poll_teams_shared_channel_replies_unexpected",
+ team_id=team.id,
+ channel_id=channel_id,
+ ticket_id=str(ticket.id),
+ )
def _poll_one_shared_channel(
@@ -1092,6 +1247,14 @@ def poll_team_shared_channels(team_id: int) -> None:
channel_id=channel_id,
service_url=service_url,
)
+ _sync_shared_channel_thread_replies(
+ team=team,
+ tenant_id=tenant_id,
+ token=token,
+ teams_team_id=teams_team_id,
+ channel_id=channel_id,
+ service_url=service_url,
+ )
except requests.RequestException:
logger.warning("poll_teams_shared_channel_network_error", team_id=team_id, channel_id=channel_id)
except Exception:
diff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.py
index 9a0ba1d0ea1e..5fbc8482b74f 100644
--- a/products/conversations/backend/teams.py
+++ b/products/conversations/backend/teams.py
@@ -32,7 +32,9 @@ from .support_teams import (
get_bot_from_id,
get_graph_token,
invalidate_bot_framework_token,
+ is_teams_graph_message_seen,
is_trusted_teams_service_url,
+ mark_teams_graph_message_seen,
)
from .teams_formatting import teams_html_to_content_and_rich_content
@@ -474,14 +476,14 @@ def post_teams_channel_message_via_graph(
reply_to_message_id: str | None = None,
token: str | None = None,
log_context: dict | None = None,
-) -> int:
+) -> tuple[int, str | None]:
"""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).
+ with the same delegated token the poller uses to read. Returns ``(status, message_id)``
+ where status is the HTTP status code (``0`` for a missing token or network error)
+ and ``message_id`` is the created chatMessage id on success.
"""
ctx = log_context or {}
if token is None:
@@ -489,7 +491,7 @@ def post_teams_channel_message_via_graph(
token = get_graph_token(team)
except ValueError:
logger.warning("teams_graph_post_no_token", **ctx)
- return 0
+ return 0, None
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
@@ -502,11 +504,20 @@ def post_teams_channel_message_via_graph(
)
except requests.RequestException:
logger.warning("teams_graph_post_error", url=url, **ctx)
- return 0
+ return 0, None
- if resp.status_code not in (200, 201):
+ message_id: str | None = None
+ if resp.status_code in (200, 201):
+ try:
+ raw_id = resp.json().get("id")
+ message_id = str(raw_id) if raw_id else None
+ except (ValueError, AttributeError, TypeError):
+ message_id = None
+ if message_id:
+ mark_teams_graph_message_seen(_get_team_id(team), channel_id, message_id)
+ else:
logger.warning("teams_graph_post_failed", status=resp.status_code, body=resp.text[:500], url=url, **ctx)
- return resp.status_code
+ return resp.status_code, message_id
def create_or_update_teams_ticket(
@@ -577,6 +588,27 @@ def create_or_update_teams_ticket(
)
return None
+ if activity_id and is_teams_graph_message_seen(team_id, channel_id, activity_id):
+ logger.debug(
+ "teams_thread_reply_duplicate_skipped",
+ team_id=team_id,
+ activity_id=activity_id,
+ ticket_id=str(ticket.id),
+ )
+ return ticket
+
+ if (
+ activity_id
+ and Comment.objects.filter(
+ team=team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ item_context__teams_graph_message_id=activity_id,
+ ).exists()
+ ):
+ mark_teams_graph_message_seen(team_id, channel_id, activity_id)
+ return ticket
+
Comment.objects.create(
team=team,
scope="conversations_ticket",
@@ -591,8 +623,10 @@ def create_or_update_teams_ticket(
"teams_user_id": teams_user_id,
"teams_author_name": user_info["name"],
"teams_author_email": user_info.get("email"),
+ "teams_graph_message_id": activity_id,
},
)
+ mark_teams_graph_message_seen(team_id, channel_id, activity_id)
if not is_team_member:
Ticket.objects.filter(id=ticket.id, team=team).update(
@@ -660,9 +694,13 @@ def create_or_update_teams_ticket(
"teams_user_id": teams_user_id,
"teams_author_name": user_info["name"],
"teams_author_email": user_info.get("email"),
+ "teams_graph_message_id": activity_id,
},
)
+ if activity_id:
+ mark_teams_graph_message_seen(team_id, channel_id, activity_id)
+
# 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:
@@ -826,7 +864,7 @@ def graph_message_to_activity(msg: dict, channel_id: str, service_url: str) -> d
if msg.get("deletedDateTime"):
return None
# Channel messages/delta returns root messages only; guard defensively in case
- # a reply ever shows up (reply sync is out of v1 scope).
+ # a reply ever shows up (thread replies are ingested via the reply poller).
if msg.get("replyToId"):
return None
@@ -860,3 +898,55 @@ def graph_message_to_activity(msg: dict, channel_id: str, service_url: str) -> d
"channelData": {"channel": {"id": channel_id}},
"serviceUrl": service_url,
}
+
+
+def graph_reply_to_activity(
+ msg: dict,
+ channel_id: str,
+ root_message_id: str,
+ service_url: str,
+) -> dict | None:
+ """Map a Graph thread ``chatMessage`` reply to a Bot Framework activity shape.
+
+ Used by the shared-channel reply poller. The activity uses the ticket's canonical
+ ``"<channelId>;messageid=<rootId>"`` conversation id so ``create_or_update_teams_ticket``
+ finds the existing ticket with ``is_thread_reply=True``.
+ """
+ if msg.get("messageType") != "message":
+ return None
+ if msg.get("deletedDateTime"):
+ return None
+
+ body = msg.get("body") or {}
+ content = body.get("content") or ""
+ if not content.strip():
+ return None
+
+ from_field = msg.get("from") or {}
+ user = from_field.get("user") or {}
+ aad_object_id = user.get("id")
+ if not aad_object_id:
+ return None
+
+ msg_id = msg.get("id")
+ if not msg_id:
+ return None
+
+ reply_to_id = msg.get("replyToId")
+ if reply_to_id and str(reply_to_id) != str(root_message_id):
+ return None
+
+ return {
+ "id": msg_id,
+ "type": "message",
+ "text": content,
+ "replyToId": reply_to_id or root_message_id,
+ "from": {
+ "id": aad_object_id,
+ "aadObjectId": aad_object_id,
+ "name": user.get("displayName") or "",
+ },
+ "conversation": {"id": f"{channel_id};messageid={root_message_id}"},
+ "channelData": {"channel": {"id": channel_id}},
+ "serviceUrl": service_url,
+ }