Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(discord): Discord collaboration bridge (CHOO-1365) (#34)

Christian McDermottd440c842116e
diff --git a/core/pyproject.toml b/core/pyproject.toml
index 5c9fa810a..6b598537e 100644
--- a/core/pyproject.toml
+++ b/core/pyproject.toml
@@ -37,6 +37,7 @@ dependencies = [
"authlib>=1.3,<2",
"itsdangerous>=2.1,<3",
"PyYAML>=6,<7",
+ "discord-py>=2.4,<3",
]
# Repo coordinates point at the public switch repo — see RELEASING.md.
diff --git a/core/switch_core/bridges/collaboration/discord/__init__.py b/core/switch_core/bridges/collaboration/discord/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
new file mode 100644
index 000000000..1275bf97c
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -0,0 +1,763 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+import re
+from collections import OrderedDict
+from collections.abc import Awaitable, Callable, Coroutine
+from typing import Any
+
+import discord
+
+from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.models import (
+ Attachment,
+ BridgeConnectionConfig,
+ ChannelType,
+ InboundAgentJoin,
+ InboundAppJoin,
+ InboundCommand,
+ InboundMessage,
+ InboundUserJoin,
+)
+
+logger = logging.getLogger(__name__)
+
+# Webhook minted by the bridge in each channel it posts to; agents share it
+# via per-message username/avatar overrides.
+_WEBHOOK_NAME = "Switch Bridge"
+
+_READY_TIMEOUT = 30.0
+
+
+class DiscordConnectionConfig(BridgeConnectionConfig):
+ bot_token: str
+ guild_id: str
+
+
+class DiscordAdapter(CollaborationAdapter):
+ """Discord collaboration bridge adapter.
+
+ Single-bot identity model like Slack: all agents post through one bot
+ application, differentiated per message via channel webhooks (Discord
+ webhooks accept a per-message username and avatar_url). Inbound events
+ arrive over a Gateway WebSocket session scoped to the configured guild
+ (an outbound connection — no public ingress needed); outbound goes
+ through the REST API.
+
+ Rooms are provisioned lazily: Discord has no "app invited to channel"
+ signal (the bot sees every channel its permissions allow), so a channel's
+ Switch room is created by the bridge core on the first bridged message
+ rather than eagerly for the whole guild.
+ """
+
+ def __init__(self, *, config: DiscordConnectionConfig) -> None:
+ super().__init__()
+ self._config = config
+ self._guild_id = int(config.guild_id)
+ self._client: discord.Client | None = None
+ self._connect_task: asyncio.Task[None] | None = None
+ self._bot_user_id: int = 0
+ # channel id -> webhook the bridge posts through in that channel.
+ self._webhooks: dict[int, discord.Webhook] = {}
+ # Ids of webhooks the bridge has minted/adopted, for echo dropping.
+ self._webhook_ids: set[int] = set()
+ self._seen_ids: OrderedDict[int, None] = OrderedDict()
+ self._seen_ids_max = 1000
+ # Discord user id ↔ username caches, for mention translation both ways.
+ self._user_names: dict[int, str] = {}
+ self._username_to_id: dict[str, int] = {}
+ # (channel_id, agent_name) -> message ref of the agent's live "working
+ # on it…" runtime-state message, so it can be deleted when the agent
+ # stops working. Webhook messages delete cleanly on Discord, so a
+ # persistent message is preferable to the one-shot typing indicator.
+ self._working_msg: dict[tuple[str, str], str] = {}
+ # (channel_id, agent_name) -> refs of the live "needs your input" pings,
+ # kept so they can be removed when the turn ends. The working indicator
+ # stays up alongside these — the agent is mid-turn, just paused.
+ self._input_pings: dict[tuple[str, str], list[str]] = {}
+
+ # ── Lifecycle ────────────────────────────────────────────────────────────
+
+ async def start(
+ self,
+ on_message: Callable[[InboundMessage], Awaitable[None]],
+ on_command: Callable[[InboundCommand], Awaitable[None]],
+ on_agent_joined: Callable[[InboundAgentJoin], Awaitable[None]],
+ on_user_joined: Callable[[InboundUserJoin], Awaitable[None]],
+ on_app_joined: Callable[[InboundAppJoin], Awaitable[None]],
+ ) -> None:
+ self._on_message = on_message
+ self._on_command = on_command
+ # Single-bot identity model: agents share the one Discord bot via
+ # per-message webhook username/avatar override, so there is no
+ # per-agent join to detect. Channel joins have no Discord signal
+ # either (visibility is permission-based), so rooms are created
+ # lazily on first message and the join callbacks stay unused.
+ self._on_agent_joined = on_agent_joined
+ self._on_user_joined = on_user_joined
+ self._on_app_joined = on_app_joined
+
+ intents = discord.Intents.none()
+ intents.guilds = True
+ intents.guild_messages = True
+ intents.dm_messages = True
+ intents.message_content = True
+ intents.members = True
+
+ client = discord.Client(intents=intents)
+ client.event(self._make_on_message())
+ self._client = client
+
+ await client.login(self._config.bot_token)
+ self._connect_task = asyncio.create_task(
+ client.connect(), name=f"discord-gateway-{self._config.guild_id}"
+ )
+ ready = asyncio.ensure_future(client.wait_until_ready())
+ done, _ = await asyncio.wait(
+ {ready, self._connect_task},
+ timeout=_READY_TIMEOUT,
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if self._connect_task in done:
+ ready.cancel()
+ exc = self._connect_task.exception()
+ raise RuntimeError("Discord gateway connection failed") from exc
+ if ready not in done:
+ ready.cancel()
+ await self.stop()
+ raise RuntimeError(f"Discord gateway not ready after {_READY_TIMEOUT:.0f}s")
+
+ assert client.user is not None
+ self._bot_user_id = client.user.id
+ logger.info(
+ "Discord adapter connected as %s (guild %s)",
+ client.user,
+ self._config.guild_id,
+ )
+
+ def _make_on_message(
+ self,
+ ) -> Callable[[discord.Message], Coroutine[Any, Any, None]]:
+ # client.event registers by function __name__, so hand it a closure
+ # named exactly like the gateway event.
+ async def on_message(message: discord.Message) -> None:
+ try:
+ await self._handle_message(message)
+ except Exception:
+ logger.exception("Failed to handle inbound Discord message")
+
+ return on_message
+
+ async def stop(self) -> None:
+ if self._client:
+ try:
+ await self._client.close()
+ except Exception:
+ pass
+ task = self._connect_task
+ self._connect_task = None
+ if task:
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception):
+ pass
+ self._client = None
+ self._webhooks.clear()
+ logger.info("Discord adapter stopped")
+
+ def _require_client(self) -> discord.Client:
+ if self._client is None:
+ raise RuntimeError("Discord client not connected")
+ return self._client
+
+ # ── Agent icon ───────────────────────────────────────────────────────────
+
+ @staticmethod
+ def _get_agent_icon(agent_name: str) -> str:
+ name = agent_name.replace("_", "+")
+ return f"https://ui-avatars.com/api/?name={name}&background=random&size=128"
+
+ # ── Messaging ────────────────────────────────────────────────────────────
+
+ async def send_message(
+ self,
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ try:
+ target = await self._get_channel(int(channel_id))
+ except Exception:
+ logger.exception("Cannot resolve Discord channel %s", channel_id)
+ return None
+
+ if self._channel_type_of(target) == "lobby":
+ # DM channels have no webhooks, so no per-message identity — fall
+ # back to a bot post with the agent name inlined.
+ try:
+ msg = await target.send(
+ f"**{sender_name}**: {content}", suppress_embeds=True
+ )
+ return f"{msg.channel.id}:{msg.id}"
+ except discord.HTTPException:
+ logger.exception("Failed to send Discord DM in %s", channel_id)
+ return None
+
+ thread: Any = None
+ if thread_root_id:
+ try:
+ thread = await self._ensure_thread(int(channel_id), thread_root_id)
+ except Exception:
+ logger.exception(
+ "Failed to resolve Discord thread for root %s — posting at channel root",
+ thread_root_id,
+ )
+
+ try:
+ webhook = await self._get_webhook(int(channel_id))
+ kwargs: dict[str, Any] = {}
+ if thread is not None:
+ kwargs["thread"] = thread
+ sent: Any = await webhook.send(
+ content=content,
+ username=sender_name,
+ avatar_url=self._get_agent_icon(sender_name),
+ suppress_embeds=True,
+ wait=True,
+ **kwargs,
+ )
+ return f"{sent.channel.id}:{sent.id}"
+ except discord.HTTPException as e:
+ logger.error(
+ "Failed to send message to Discord channel %s: %s", channel_id, e
+ )
+ return None
+
+ async def admin_message(
+ self,
+ channel_id: str,
+ content: str,
+ thread_root_id: str | None = None,
+ *,
+ message_type: str | None = None,
+ ) -> str | None:
+ # Admin/system messages post as the bot application itself — no
+ # webhook username override — so they read as the platform speaking,
+ # not an agent.
+ try:
+ target = await self._get_channel(int(channel_id))
+ if thread_root_id:
+ try:
+ target = await self._ensure_thread(int(channel_id), thread_root_id)
+ except Exception:
+ logger.exception(
+ "Failed to resolve Discord thread for admin message — posting at channel root"
+ )
+ msg = await target.send(content, suppress_embeds=True)
+ return f"{msg.channel.id}:{msg.id}"
+ except (discord.HTTPException, RuntimeError) as e:
+ logger.error(
+ "Failed to post admin message to Discord channel %s: %s",
+ channel_id,
+ e,
+ )
+ return None
+
+ async def update_message(
+ self, channel_id: str, message_ref: str, new_content: str
+ ) -> None:
+ location_id, message_id = self._parse_message_ref(message_ref)
+ if not message_id:
+ logger.error("Cannot update message: invalid message ref %s", message_ref)
+ return
+
+ kwargs: dict[str, Any] = {}
+ if location_id and location_id != channel_id:
+ kwargs["thread"] = discord.Object(id=int(location_id))
+ try:
+ webhook = await self._get_webhook(int(channel_id))
+ await webhook.edit_message(int(message_id), content=new_content, **kwargs)
+ return
+ except discord.NotFound:
+ pass
+ except discord.HTTPException as e:
+ logger.error("Failed to update Discord message %s: %s", message_ref, e)
+ return
+
+ # Not a message of our webhook — e.g. an admin (bot) post: edit via
+ # the bot's own message object instead.
+ try:
+ target = await self._get_channel(int(location_id or channel_id))
+ msg = await target.fetch_message(int(message_id))
+ await msg.edit(content=new_content)
+ except discord.HTTPException as e:
+ logger.error("Failed to update Discord message %s: %s", message_ref, e)
+
+ async def delete_message(self, channel_id: str, message_ref: str) -> None:
+ location_id, message_id = self._parse_message_ref(message_ref)
+ if not message_id:
+ logger.error("Cannot delete message: invalid message ref %s", message_ref)
+ return
+ try:
+ target = await self._get_channel(int(location_id or channel_id))
+ await target.get_partial_message(int(message_id)).delete()
+ except discord.HTTPException as e:
+ logger.error("Failed to delete Discord message %s: %s", message_ref, e)
+
+ # ── Typing ───────────────────────────────────────────────────────────────
+
+ async def send_typing(
+ self, channel_id: str, sender_name: str, is_typing: bool
+ ) -> None:
+ if not is_typing:
+ # Discord's typing indicator is a one-shot (~10s) trigger with no
+ # cancel API; it simply expires.
+ return
+ try:
+ target = await self._get_channel(int(channel_id))
+ await target.typing()
+ except Exception:
+ logger.exception(
+ "Failed to trigger typing in Discord channel %s", channel_id
+ )
+
+ # ── Runtime state ────────────────────────────────────────────────────────
+
+ async def apply_runtime_state(
+ self,
+ channel_id: str,
+ agent_name: str,
+ state: str,
+ *,
+ notify_user: str | None,
+ thread_root_id: str | None,
+ deeplink_url: str | None = None,
+ detail: str | None = None,
+ ) -> None:
+ """Render runtime state as persistent, truly-deletable status messages.
+
+ Discord deletes webhook messages cleanly (no tombstone), so — like
+ Slack — the "working on it…" indicator and any "needs your input"
+ pings are posted while relevant and deleted when the turn ends. The
+ working indicator stays up through `awaiting-input` (the agent is
+ mid-turn, just paused) and the pings are removed alongside it when
+ the turn goes idle or resumes to `working`. When the agent was
+ addressed in a thread, messages surface in that thread.
+ """
+ key = (channel_id, agent_name)
+ if state == "working":
+ await self._clear_input_pings(channel_id, agent_name)
+ # Posted under the agent's own name/icon, so the body just states
+ # the activity — no need to repeat the agent name in the text.
+ body = self._working_body(detail, deeplink_url)
+ existing = self._working_msg.get(key)
+ if existing is not None:
+ await self.update_message(channel_id, existing, body)
+ return
+ ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
+ if ref is not None:
+ self._working_msg[key] = ref
+ elif state == "awaiting-input":
+ ref = await self._ping_operator(
+ channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ )
+ if ref is not None:
+ self._input_pings.setdefault(key, []).append(ref)
+ else:
+ await self._clear_working(channel_id, agent_name)
+ await self._clear_input_pings(channel_id, agent_name)
+
+ async def _clear_working(self, channel_id: str, agent_name: str) -> None:
+ ref = self._working_msg.pop((channel_id, agent_name), None)
+ if ref is not None:
+ await self.delete_message(channel_id, ref)
+
+ async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:
+ refs = self._input_pings.pop((channel_id, agent_name), [])
+ for ref in refs:
+ await self.delete_message(channel_id, ref)
+
+ # ── Channels ─────────────────────────────────────────────────────────────
+
+ async def create_channel(
+ self,
+ name: str,
+ topic: str,
+ *,
+ channel_type: ChannelType = "channel_public",
+ ) -> str:
+ if channel_type in ("group", "direct"):
+ raise ValueError(
+ f"Cannot create {channel_type} channels — they are initiated from the messaging platform"
+ )
+
+ guild = await self._get_guild()
+ channel = await guild.create_text_channel(
+ name=self._sanitize_channel_name(name),
+ topic=topic,
+ overwrites=(
+ self._private_channel_overwrites(guild)
+ if channel_type == "channel_private"
+ else {}
+ ),
+ )
+ return str(channel.id)
+
+ async def create_dm_channel(
+ self,
+ *,
+ agent_name: str,
+ user_name: str,
+ user_external_id: str,
+ ) -> str:
+ # Discord bots can open real DMs, but DM channels have no webhooks —
+ # so no per-agent identity — and DM traffic maps to the deprecated
+ # "lobby" flow. Mirror Slack instead: a private channel named after
+ # the pair, visible only to the bridge and the user.
+ guild = await self._get_guild()
+ channel = await guild.create_text_channel(
+ name=self._sanitize_channel_name(f"dm-{user_name}-{agent_name}"),
+ topic=f"Direct conversation between {user_name} and {agent_name}",
+ overwrites=self._private_channel_overwrites(guild),
+ )
+ member = await self._get_member(guild, user_external_id)
+ await channel.set_permissions(member, view_channel=True)
+ return str(channel.id)
+
+ @staticmethod
+ def _sanitize_channel_name(name: str) -> str:
+ return re.sub(r"[^a-z0-9_-]", "-", name.lower()).strip("-")[:100]
+
+ @staticmethod
+ def _private_channel_overwrites(
+ guild: Any,
+ ) -> dict[Any, discord.PermissionOverwrite]:
+ overwrites: dict[Any, discord.PermissionOverwrite] = {
+ guild.default_role: discord.PermissionOverwrite(view_channel=False)
+ }
+ me = getattr(guild, "me", None)
+ if me is not None:
+ overwrites[me] = discord.PermissionOverwrite(view_channel=True)
+ return overwrites
+
+ async def channel_deeplink(self, external_channel_id: str) -> str | None:
+ """`https://discord.com/channels/<guild>/<channel>` — Discord's
+ canonical channel link; the desktop app claims it. Pure: built from
+ the configured guild id, no API call needed."""
+ if not external_channel_id:
+ return None
+ return f"https://discord.com/channels/{self._config.guild_id}/{external_channel_id}"
+
+ async def get_channel_type(self, channel_id: str) -> ChannelType:
+ target = await self._get_channel(int(channel_id))
+ return self._channel_type_of(target)
+
+ def _channel_type_of(self, channel: Any) -> ChannelType:
+ """Map a Discord channel object to the bridge's ChannelType.
+
+ DMs/group DMs have no guild → lobby (parity with Slack's im/mpim).
+ A guild channel is private when @everyone's view_channel is denied
+ via permission overwrites. Threads defer to their parent channel.
+ """
+ guild = getattr(channel, "guild", None)
+ if guild is None:
+ return "lobby"
+ if getattr(channel, "parent_id", None) is not None:
+ parent = getattr(channel, "parent", None)
+ if parent is None:
+ return "channel_public"
+ return self._channel_type_of(parent)
+ default_role = getattr(guild, "default_role", None)
+ if default_role is None:
+ return "channel_public"
+ overwrite = channel.overwrites_for(default_role)
+ if overwrite.view_channel is False:
+ return "channel_private"
+ return "channel_public"
+
+ async def add_agents_to_channel(
+ self, channel_id: str, agent_names: list[str]
+ ) -> None:
+ pass
+
+ async def add_users_to_channel(
+ self,
+ channel_id: str,
+ user_names: list[str],
+ user_external_ids: list[str],
+ ) -> None:
+ channel = await self._get_channel(int(channel_id))
+ if self._channel_type_of(channel) != "channel_private":
+ # Public guild channels are visible to every member — there is no
+ # per-channel membership to grant.
+ return
+ guild = channel.guild
+ for user_name, user_id in zip(user_names, user_external_ids):
+ try:
+ member = await self._get_member(guild, user_id)
+ await channel.set_permissions(member, view_channel=True)
+ except (discord.HTTPException, ValueError) as e:
+ logger.error(
+ "Failed to grant Discord user %s (%s) access to channel %s: %s",
+ user_name,
+ user_id,
+ channel_id,
+ e,
+ )
+
+ # ── Agent identity ───────────────────────────────────────────────────────
+
+ async def create_agent_identity(
+ self, agent_name: str, agent_description: str
+ ) -> None:
+ pass
+
+ async def remove_agent_identity(self, agent_name: str) -> None:
+ pass
+
+ async def get_channel_agent_names(self, channel_id: str) -> list[str]:
+ return []
+
+ # ── Translation ──────────────────────────────────────────────────────────
+
+ def translate_outbound(self, content: str) -> str:
+ # Discord renders markdown natively (bold, code, headers, masked
+ # links), so only @username mentions need rewriting to real Discord
+ # mentions for users we have resolved. Agents and unknown names stay
+ # plain text.
+ def _replace(match: re.Match[str]) -> str:
+ user_id = self._username_to_id.get(match.group(1))
+ return f"<@{user_id}>" if user_id else match.group(0)
+
+ return re.sub(r"@([a-z0-9][a-z0-9._-]*)", _replace, content)
+
+ def translate_inbound(self, raw_message: str) -> str:
+ def _replace_user(match: re.Match[str]) -> str:
+ name = self._user_names.get(int(match.group(1)))
+ return f"@{name}" if name else match.group(0)
+
+ def _replace_channel(match: re.Match[str]) -> str:
+ channel = (
+ self._client.get_channel(int(match.group(1))) if self._client else None
+ )
+ name = getattr(channel, "name", None)
+ return f"#{name}" if name else match.group(0)
+
+ message = re.sub(r"<@!?(\d+)>", _replace_user, raw_message)
+ return re.sub(r"<#(\d+)>", _replace_channel, message)
+
+ # ── Gateway event handling ───────────────────────────────────────────────
+
+ # Message types we treat as real posts: plain messages and replies.
+ # Everything else (pins, joins, boosts, thread starters, …) is skipped.
+ _ALLOWED_MESSAGE_TYPES = frozenset(
+ {discord.MessageType.default, discord.MessageType.reply}
+ )
+
+ async def _handle_message(self, message: Any) -> None:
+ guild = getattr(message, "guild", None)
+ if guild is not None and guild.id != self._guild_id:
+ return
+
+ author = message.author
+ # Drop only our own posts (loop prevention): the bot itself and the
+ # bridge's webhooks. Third-party bots/webhooks are still bridged.
+ if author.id == self._bot_user_id:
+ return
+ webhook_id = getattr(message, "webhook_id", None)
+ if webhook_id and webhook_id in self._webhook_ids:
+ return
+ if message.type not in self._ALLOWED_MESSAGE_TYPES:
+ return
+
+ if message.id in self._seen_ids:
+ return
+ self._seen_ids[message.id] = None
+ if len(self._seen_ids) > self._seen_ids_max:
+ self._seen_ids.popitem(last=False)
+
+ channel = message.channel
+ # A message inside a thread is bridged into the PARENT channel's room,
+ # threaded under the thread's root message (thread id == root message
+ # id on Discord).
+ parent_id = getattr(channel, "parent_id", None)
+ root_id: str | None = None
+ if parent_id is not None:
+ channel_id = str(parent_id)
+ root_id = f"{parent_id}:{channel.id}"
+ channel_name = getattr(getattr(channel, "parent", None), "name", None)
+ else:
+ channel_id = str(channel.id)
+ channel_name = getattr(channel, "name", None)
+
+ username = str(author.name)
+ self._user_names[author.id] = username
+ self._username_to_id[username] = author.id
+
+ content = str(message.content or "")
+ channel_type = self._channel_type_of(channel)
+ message_ref = f"{channel.id}:{message.id}"
+
+ stripped = content.strip()
+ if stripped.startswith("!") and self._on_command:
+ parts = stripped.split(None, 1)
+ await self._on_command(
+ InboundCommand(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ sender_id=str(author.id),
+ sender_name=username,
+ command=parts[0].lstrip("!"),
+ args=parts[1].strip() if len(parts) > 1 else "",
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ )
+ )
+ return
+
+ if self._on_message is None:
+ return
+
+ attachments = await self._fetch_image_attachments(
+ getattr(message, "attachments", []) or []
+ )
+ self_mention = (
+ bool(self._bot_user_id)
+ and re.search(rf"<@!?{self._bot_user_id}>", content) is not None
+ )
+ await self._on_message(
+ InboundMessage(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ sender_id=str(author.id),
+ sender_name=username,
+ content=content,
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ attachments=attachments,
+ self_mention_token=str(self._bot_user_id) if self_mention else None,
+ )
+ )
+
+ # ── Attachments ──────────────────────────────────────────────────────────
+
+ async def _fetch_image_attachments(self, files: list[Any]) -> list[Attachment]:
+ """Download image attachments from a Discord message.
+
+ Non-image files are skipped (images-only for now, mirroring Slack and
+ Mattermost). A single file that fails to download is logged and
+ skipped rather than dropping the whole message.
+ """
+ attachments: list[Attachment] = []
+ for file in files:
+ mimetype = str(getattr(file, "content_type", "") or "")
+ if not mimetype.startswith("image/"):
+ logger.debug(
+ "Skipping non-image Discord attachment %s (%s)",
+ getattr(file, "id", "?"),
+ mimetype or "unknown",
+ )
+ continue
+ filename = str(getattr(file, "filename", "") or "image")
+ try:
+ data = await file.read()
+ except Exception:
+ logger.exception("Failed to download Discord attachment %s", filename)
+ continue
+ attachments.append(
+ Attachment(filename=filename, mimetype=mimetype, data=data)
+ )
+ return attachments
+
+ # ── Webhooks & channels ──────────────────────────────────────────────────
+
+ async def _get_channel(self, channel_id: int) -> Any:
+ client = self._require_client()
+ channel = client.get_channel(channel_id)
+ if channel is None:
+ channel = await client.fetch_channel(channel_id)
+ return channel
+
+ async def _get_guild(self) -> Any:
+ client = self._require_client()
+ guild = client.get_guild(self._guild_id)
+ if guild is None:
+ guild = await client.fetch_guild(self._guild_id)
+ return guild
+
+ @staticmethod
+ async def _get_member(guild: Any, user_external_id: str) -> Any:
+ member = guild.get_member(int(user_external_id))
+ if member is None:
+ member = await guild.fetch_member(int(user_external_id))
+ return member
+
+ async def _get_webhook(self, channel_id: int) -> discord.Webhook:
+ cached = self._webhooks.get(channel_id)
+ if cached is not None:
+ return cached
+
+ channel = await self._get_channel(channel_id)
+ webhook: discord.Webhook | None = None
+ for existing in await channel.webhooks():
+ if existing.name == _WEBHOOK_NAME and existing.token:
+ webhook = existing
+ break
+ if webhook is None:
+ webhook = await channel.create_webhook(name=_WEBHOOK_NAME)
+
+ self._webhooks[channel_id] = webhook
+ self._webhook_ids.add(webhook.id)
+ return webhook
+
+ async def _ensure_thread(self, channel_id: int, thread_root_ref: str) -> Any:
+ """Resolve (creating if needed) the Discord thread rooted at the given
+ external message ref, for posting a threaded reply.
+
+ On Discord a thread is a channel whose id equals the id of the message
+ it was created from, so an existing thread is a straight channel
+ lookup. When none exists yet, one is created from the root message.
+ """
+ _, root_mid = self._parse_message_ref(thread_root_ref)
+ root_message_id = int(root_mid if root_mid else thread_root_ref)
+
+ client = self._require_client()
+ thread = client.get_channel(root_message_id)
+ if thread is not None:
+ return thread
+
+ channel = await self._get_channel(channel_id)
+ name = "Switch thread"
+ root_message = None
+ try:
+ root_message = await channel.fetch_message(root_message_id)
+ root_content = str(root_message.content or "").strip()
+ if root_content:
+ name = root_content[:60]
+ except discord.HTTPException:
+ pass
+
+ try:
+ if root_message is not None:
+ return await root_message.create_thread(name=name)
+ return await channel.get_partial_message(root_message_id).create_thread(
+ name=name
+ )
+ except discord.HTTPException:
+ # A thread already exists for this message — fetch it by id.
+ return await client.fetch_channel(root_message_id)
+
+ # ── Helpers ──────────────────────────────────────────────────────────────
+
+ @staticmethod
+ def _parse_message_ref(message_ref: str) -> tuple[str, str]:
+ parts = message_ref.split(":", 1)
+ if len(parts) != 2:
+ logger.error("Invalid Discord message ref format: %s", message_ref)
+ return "", ""
+ return parts[0], parts[1]
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index b418e961b..f72e4af4e 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -25,6 +25,10 @@ from switch_core.bridges.agent.server_connectors.opencode.connector import (
OpenCodeConnector,
)
from switch_core.bridges.collaboration.app import create_collaboration_bridge_app
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
@@ -318,6 +322,9 @@ async def run() -> None:
"mattermost", MattermostAdapter, MattermostConnectionConfig
)
collab_lifecycle.register_adapter("slack", SlackAdapter, SlackConnectionConfig)
+ collab_lifecycle.register_adapter(
+ "discord", DiscordAdapter, DiscordConnectionConfig
+ )
# Health check and collab bridge mounted on the agent bridge app
@agent_bridge_app.get("/health")
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
index bbb6f128b..5ef752ada 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
@@ -2,6 +2,10 @@ from __future__ import annotations
import pytest
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
from switch_core.bridges.collaboration.lifecycle_service import (
CollaborationBridgeLifecycleService,
)
@@ -47,6 +51,16 @@ def test_get_registered_types_lists_registered() -> None:
assert sorted(service.get_registered_types()) == ["mattermost", "slack"]
+def test_discord_adapter_registers_with_expected_required_fields() -> None:
+ service = _service()
+ service.register_adapter("discord", DiscordAdapter, DiscordConnectionConfig)
+
+ assert service.get_registered_types() == ["discord"]
+ schema = service.get_config_schema("discord")
+ assert set(schema["properties"]) == {"bot_token", "guild_id"}
+ assert set(schema["required"]) == {"bot_token", "guild_id"}
+
+
def test_get_config_schema_exposes_required_fields() -> None:
service = _service()
service.register_adapter("slack", SlackAdapter, SlackConnectionConfig)
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
new file mode 100644
index 000000000..b286b51f9
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
@@ -0,0 +1,889 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import patch
+
+import discord
+import pytest
+
+from switch_core.bridges.collaboration.discord import adapter as adapter_module
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
+from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage
+
+GUILD_ID = 900
+CHANNEL_ID = 100
+BOT_USER_ID = 42
+BRIDGE_WEBHOOK_ID = 77
+
+
+def _adapter() -> DiscordAdapter:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ adapter._bot_user_id = BOT_USER_ID
+ return adapter
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeRole:
+ pass
+
+
+class _FakeGuild:
+ def __init__(self, guild_id: int = GUILD_ID) -> None:
+ self.id = guild_id
+ self.default_role = _FakeRole()
+
+
+class _FakeOverwrite:
+ def __init__(self, view_channel: bool | None) -> None:
+ self.view_channel = view_channel
+
+
+class _FakeMessage:
+ def __init__(self, channel: Any, message_id: int = 1) -> None:
+ self.id = message_id
+ self.channel = channel
+ self.content = ""
+ self.threads_created: list[str] = []
+
+ async def edit(self, *, content: str) -> None:
+ self.edited = content
+
+ async def create_thread(self, *, name: str) -> Any:
+ self.threads_created.append(name)
+ return _FakeThread(parent=self.channel, thread_id=self.id)
+
+
+class _FakePartialMessage:
+ def __init__(self, channel: _FakeChannel, message_id: int) -> None:
+ self.id = message_id
+ self._channel = channel
+
+ async def delete(self) -> None:
+ self._channel.deleted_ids.append(self.id)
+
+ async def create_thread(self, *, name: str) -> Any:
+ return _FakeThread(parent=self._channel, thread_id=self.id)
+
+
+class _FakeChannel:
+ def __init__(
+ self,
+ channel_id: int = CHANNEL_ID,
+ *,
+ guild: Any | None = None,
+ name: str | None = "general",
+ everyone_can_view: bool | None = True,
+ ) -> None:
+ self.id = channel_id
+ self.guild = guild if guild is not None else _FakeGuild()
+ self.name = name
+ self._everyone_can_view = everyone_can_view
+ self.sent: list[dict[str, Any]] = []
+ self.deleted_ids: list[int] = []
+ self.typing_count = 0
+ self.existing_webhooks: list[Any] = []
+ self.created_webhooks: list[str] = []
+ self.messages: dict[int, _FakeMessage] = {}
+
+ def overwrites_for(self, role: Any) -> _FakeOverwrite:
+ return _FakeOverwrite(self._everyone_can_view)
+
+ async def send(self, content: str, **kwargs: Any) -> Any:
+ self.sent.append({"content": content, **kwargs})
+ msg = _FakeMessage(self, message_id=500 + len(self.sent))
+ return msg
+
+ async def typing(self) -> None:
+ self.typing_count += 1
+
+ async def webhooks(self) -> list[Any]:
+ return self.existing_webhooks
+
+ async def create_webhook(self, *, name: str) -> Any:
+ self.created_webhooks.append(name)
+ return _FakeWebhook(name=name)
+
+ async def fetch_message(self, message_id: int) -> _FakeMessage:
+ msg = self.messages.get(message_id)
+ if msg is None:
+ raise discord.NotFound(_FakeResponse(), "message not found")
+ return msg
+
+ def get_partial_message(self, message_id: int) -> _FakePartialMessage:
+ return _FakePartialMessage(self, message_id)
+
+
+class _FakeDMChannel(_FakeChannel):
+ def __init__(self, channel_id: int = 555) -> None:
+ super().__init__(channel_id, name=None)
+ self.guild = None
+
+
+class _FakeThread:
+ def __init__(self, parent: _FakeChannel, thread_id: int) -> None:
+ self.id = thread_id
+ self.parent = parent
+ self.parent_id = parent.id
+ self.guild = parent.guild
+ self.name = "a thread"
+ self.sent: list[dict[str, Any]] = []
+
+ async def send(self, content: str, **kwargs: Any) -> Any:
+ self.sent.append({"content": content, **kwargs})
+ return _FakeMessage(self, message_id=600 + len(self.sent))
+
+
+class _FakeResponse:
+ status = 404
+ reason = "Not Found"
+
+
+class _FakeWebhook:
+ def __init__(
+ self,
+ name: str = "Switch Bridge",
+ webhook_id: int = BRIDGE_WEBHOOK_ID,
+ token: str | None = "tok",
+ ) -> None:
+ self.id = webhook_id
+ self.name = name
+ self.token = token
+ self.sent: list[dict[str, Any]] = []
+ self.edits: list[dict[str, Any]] = []
+ self.edit_raises_not_found = False
+
+ async def send(self, **kwargs: Any) -> Any:
+ self.sent.append(kwargs)
+ thread = kwargs.get("thread")
+ channel = thread if thread is not None else _FakeChannel()
+ return _FakeMessage(channel, message_id=900 + len(self.sent))
+
+ async def edit_message(self, message_id: int, **kwargs: Any) -> None:
+ if self.edit_raises_not_found:
+ raise discord.NotFound(_FakeResponse(), "unknown message")
+ self.edits.append({"message_id": message_id, **kwargs})
+
+
+class _FakeClient:
+ def __init__(self, channels: dict[int, Any]) -> None:
+ self._channels = channels
+
+ def get_channel(self, channel_id: int) -> Any | None:
+ return self._channels.get(channel_id)
+
+ async def fetch_channel(self, channel_id: int) -> Any:
+ channel = self._channels.get(channel_id)
+ if channel is None:
+ raise discord.NotFound(_FakeResponse(), "unknown channel")
+ return channel
+
+
+class _Author:
+ def __init__(self, user_id: int, name: str) -> None:
+ self.id = user_id
+ self.name = name
+
+
+def _gateway_message(
+ *,
+ channel: Any,
+ content: str = "hello",
+ author: _Author | None = None,
+ message_id: int = 1000,
+ webhook_id: int | None = None,
+ message_type: discord.MessageType = discord.MessageType.default,
+ attachments: list[Any] | None = None,
+) -> Any:
+ class _Msg:
+ pass
+
+ msg = _Msg()
+ msg.id = message_id # type: ignore[attr-defined]
+ msg.channel = channel # type: ignore[attr-defined]
+ msg.guild = channel.guild # type: ignore[attr-defined]
+ msg.author = author or _Author(7, "louis") # type: ignore[attr-defined]
+ msg.content = content # type: ignore[attr-defined]
+ msg.webhook_id = webhook_id # type: ignore[attr-defined]
+ msg.type = message_type # type: ignore[attr-defined]
+ msg.attachments = attachments or [] # type: ignore[attr-defined]
+ return msg
+
+
+def _capture_messages(adapter: DiscordAdapter) -> list[InboundMessage]:
+ captured: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ captured.append(msg)
+
+ adapter._on_message = on_message
+ return captured
+
+
+def _capture_commands(adapter: DiscordAdapter) -> list[InboundCommand]:
+ captured: list[InboundCommand] = []
+
+ async def on_command(cmd: InboundCommand) -> None:
+ captured.append(cmd)
+
+ adapter._on_command = on_command
+ return captured
+
+
+# ── Inbound messages ─────────────────────────────────────────────────────────
+
+
+def test_inbound_message_bridged() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+ channel = _FakeChannel()
+
+ _run(adapter._handle_message(_gateway_message(channel=channel, content="hi there")))
+
+ assert len(captured) == 1
+ msg = captured[0]
+ assert msg.channel_id == str(CHANNEL_ID)
+ assert msg.channel_type == "channel_public"
+ assert msg.sender_id == "7"
+ assert msg.sender_name == "louis"
+ assert msg.content == "hi there"
+ assert msg.message_ref == f"{CHANNEL_ID}:1000"
+ assert msg.root_id is None
+ assert msg.channel_name == "general"
+ assert msg.self_mention_token is None
+
+
+def test_own_bot_message_dropped() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=_FakeChannel(), author=_Author(BOT_USER_ID, "switch-bot")
+ )
+ )
+ )
+
+ assert captured == []
+
+
+def test_own_webhook_message_dropped_but_foreign_webhook_bridged() -> None:
+ adapter = _adapter()
+ adapter._webhook_ids.add(BRIDGE_WEBHOOK_ID)
+ captured = _capture_messages(adapter)
+ channel = _FakeChannel()
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=channel, webhook_id=BRIDGE_WEBHOOK_ID, message_id=1
+ )
+ )
+ )
+ _run(
+ adapter._handle_message(
+ _gateway_message(channel=channel, webhook_id=12345, message_id=2)
+ )
+ )
+
+ assert len(captured) == 1
+ assert captured[0].message_ref == f"{CHANNEL_ID}:2"
+
+
+def test_other_guild_and_system_messages_skipped() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ other_guild_channel = _FakeChannel(guild=_FakeGuild(guild_id=999))
+ _run(adapter._handle_message(_gateway_message(channel=other_guild_channel)))
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=_FakeChannel(), message_type=discord.MessageType.pins_add
+ )
+ )
+ )
+
+ assert captured == []
+
+
+def test_duplicate_message_ids_deduplicated() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+ channel = _FakeChannel()
+
+ _run(adapter._handle_message(_gateway_message(channel=channel, message_id=5)))
+ _run(adapter._handle_message(_gateway_message(channel=channel, message_id=5)))
+
+ assert len(captured) == 1
+
+
+def test_thread_message_bridged_into_parent_channel() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+ parent = _FakeChannel()
+ thread = _FakeThread(parent=parent, thread_id=2000)
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(channel=thread, content="reply", message_id=2001)
+ )
+ )
+
+ assert len(captured) == 1
+ msg = captured[0]
+ assert msg.channel_id == str(CHANNEL_ID)
+ assert msg.root_id == f"{CHANNEL_ID}:2000"
+ assert msg.message_ref == "2000:2001"
+ assert msg.channel_name == "general"
+
+
+def test_private_channel_and_dm_channel_types() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ private = _FakeChannel(channel_id=101, everyone_can_view=False)
+ _run(adapter._handle_message(_gateway_message(channel=private, message_id=1)))
+
+ dm = _FakeDMChannel()
+ _run(adapter._handle_message(_gateway_message(channel=dm, message_id=2)))
+
+ assert captured[0].channel_type == "channel_private"
+ assert captured[1].channel_type == "lobby"
+ assert captured[1].channel_name is None
+
+
+def test_self_mention_token_set_when_bot_mentioned() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=_FakeChannel(), content=f"hey <@!{BOT_USER_ID}> help"
+ )
+ )
+ )
+
+ assert captured[0].self_mention_token == str(BOT_USER_ID)
+
+
+def test_bang_command_routed_to_on_command() -> None:
+ adapter = _adapter()
+ messages = _capture_messages(adapter)
+ commands = _capture_commands(adapter)
+ parent = _FakeChannel()
+ thread = _FakeThread(parent=parent, thread_id=3000)
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(
+ channel=thread, content="!invite-agent @helper now", message_id=3001
+ )
+ )
+ )
+
+ assert messages == []
+ assert len(commands) == 1
+ cmd = commands[0]
+ assert cmd.command == "invite-agent"
+ assert cmd.args == "@helper now"
+ assert cmd.channel_id == str(CHANNEL_ID)
+ assert cmd.message_ref == "3000:3001"
+ assert cmd.root_id == f"{CHANNEL_ID}:3000"
+
+
+# ── Attachments ──────────────────────────────────────────────────────────────
+
+
+class _FakeFile:
+ def __init__(
+ self,
+ filename: str,
+ content_type: str | None,
+ data: bytes = b"x",
+ fail: bool = False,
+ ) -> None:
+ self.id = 1
+ self.filename = filename
+ self.content_type = content_type
+ self._data = data
+ self._fail = fail
+
+ async def read(self) -> bytes:
+ if self._fail:
+ raise RuntimeError("boom")
+ return self._data
+
+
+def test_image_attachments_downloaded_others_skipped() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+ files = [
+ _FakeFile("shot.png", "image/png", b"png-bytes"),
+ _FakeFile("notes.pdf", "application/pdf"),
+ _FakeFile("broken.jpg", "image/jpeg", fail=True),
+ _FakeFile("unknown.bin", None),
+ ]
+
+ _run(
+ adapter._handle_message(
+ _gateway_message(channel=_FakeChannel(), attachments=files)
+ )
+ )
+
+ atts = captured[0].attachments
+ assert len(atts) == 1
+ assert atts[0].filename == "shot.png"
+ assert atts[0].mimetype == "image/png"
+ assert atts[0].data == b"png-bytes"
+
+
+# ── Outbound messaging ───────────────────────────────────────────────────────
+
+
+def test_send_message_posts_via_webhook_with_agent_identity() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+
+ ref = _run(adapter.send_message(str(CHANNEL_ID), "my-agent", "**hello**"))
+
+ assert len(webhook.sent) == 1
+ call = webhook.sent[0]
+ assert call["content"] == "**hello**"
+ assert call["username"] == "my-agent"
+ assert "my-agent" in call["avatar_url"]
+ assert call["suppress_embeds"] is True
+ assert call["wait"] is True
+ assert "thread" not in call
+ assert ref == f"{CHANNEL_ID}:901"
+
+
+def test_send_message_with_thread_root_posts_into_thread() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ root = _FakeMessage(channel, message_id=4000)
+ root.content = "the root message"
+ channel.messages[4000] = root
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+
+ ref = _run(
+ adapter.send_message(
+ str(CHANNEL_ID), "my-agent", "reply", thread_root_id=f"{CHANNEL_ID}:4000"
+ )
+ )
+
+ assert root.threads_created == ["the root message"]
+ thread = webhook.sent[0]["thread"]
+ assert thread.id == 4000
+ assert ref == "4000:901"
+
+
+def test_send_message_reuses_existing_thread() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ thread = _FakeThread(parent=channel, thread_id=4000)
+ adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+
+ _run(
+ adapter.send_message(
+ str(CHANNEL_ID), "my-agent", "reply", thread_root_id=f"{CHANNEL_ID}:4000"
+ )
+ )
+
+ assert webhook.sent[0]["thread"] is thread
+
+
+def test_send_message_to_dm_falls_back_to_bot_post() -> None:
+ adapter = _adapter()
+ dm = _FakeDMChannel()
+ adapter._client = _FakeClient({dm.id: dm})
+
+ ref = _run(adapter.send_message(str(dm.id), "my-agent", "hi"))
+
+ assert dm.sent[0]["content"] == "**my-agent**: hi"
+ assert ref == f"{dm.id}:501"
+
+
+def test_admin_message_posts_as_bot_not_webhook() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+
+ ref = _run(adapter.admin_message(str(CHANNEL_ID), "system notice"))
+
+ assert channel.sent[0]["content"] == "system notice"
+ assert channel.sent[0]["suppress_embeds"] is True
+ assert ref == f"{CHANNEL_ID}:501"
+
+
+def test_update_message_edits_via_webhook_with_thread() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+
+ _run(adapter.update_message(str(CHANNEL_ID), "4000:901", "new text"))
+
+ edit = webhook.edits[0]
+ assert edit["message_id"] == 901
+ assert edit["content"] == "new text"
+ assert edit["thread"].id == 4000
+
+
+def test_update_message_falls_back_to_bot_message_edit() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ bot_msg = _FakeMessage(channel, message_id=502)
+ channel.messages[502] = bot_msg
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ webhook.edit_raises_not_found = True
+ adapter._webhooks[CHANNEL_ID] = webhook
+
+ _run(adapter.update_message(str(CHANNEL_ID), f"{CHANNEL_ID}:502", "edited"))
+
+ assert bot_msg.edited == "edited"
+
+
+def test_delete_message_uses_partial_message_in_location_channel() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ thread = _FakeThread(parent=channel, thread_id=4000)
+ thread.deleted_ids = [] # type: ignore[attr-defined]
+ thread.get_partial_message = lambda mid: _FakePartialMessage(thread, mid) # type: ignore[attr-defined]
+ adapter._client = _FakeClient({CHANNEL_ID: channel, 4000: thread})
+
+ _run(adapter.delete_message(str(CHANNEL_ID), "4000:901"))
+
+ assert thread.deleted_ids == [901] # type: ignore[attr-defined]
+
+
+def test_send_typing_triggers_once_and_off_is_noop() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+
+ _run(adapter.send_typing(str(CHANNEL_ID), "my-agent", True))
+ _run(adapter.send_typing(str(CHANNEL_ID), "my-agent", False))
+
+ assert channel.typing_count == 1
+
+
+# ── Runtime state (working-on-it activity) ──────────────────────────────────
+
+
+def _runtime_setup() -> tuple[DiscordAdapter, _FakeChannel, _FakeWebhook]:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[CHANNEL_ID] = webhook
+ return adapter, channel, webhook
+
+
+def test_runtime_state_working_posts_persistent_indicator() -> None:
+ adapter, _, webhook = _runtime_setup()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+
+ assert len(webhook.sent) == 1
+ assert webhook.sent[0]["content"] == "⚙️ _Working on it…_"
+ assert webhook.sent[0]["username"] == "my-agent"
+ assert adapter._working_msg[(str(CHANNEL_ID), "my-agent")] == f"{CHANNEL_ID}:901"
+
+
+def test_runtime_state_detail_edits_message_in_place() -> None:
+ adapter, _, webhook = _runtime_setup()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ detail="Editing adapter.py",
+ )
+ )
+
+ assert len(webhook.sent) == 1
+ assert len(webhook.edits) == 1
+ assert webhook.edits[0]["message_id"] == 901
+ assert webhook.edits[0]["content"] == "⚙️ Editing adapter.py"
+ assert adapter._working_msg[(str(CHANNEL_ID), "my-agent")] == f"{CHANNEL_ID}:901"
+
+
+def test_runtime_state_idle_clears_working_message() -> None:
+ adapter, channel, _ = _runtime_setup()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID), "my-agent", "idle", notify_user=None, thread_root_id=None
+ )
+ )
+
+ assert channel.deleted_ids == [901]
+ assert (str(CHANNEL_ID), "my-agent") not in adapter._working_msg
+
+
+def test_runtime_state_awaiting_input_pings_and_resume_clears_pings() -> None:
+ adapter, channel, webhook = _runtime_setup()
+
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "awaiting-input",
+ notify_user="louis",
+ thread_root_id=None,
+ )
+ )
+
+ # Working indicator stays up; a ping was posted and tracked.
+ assert len(webhook.sent) == 2
+ assert "@louis" in webhook.sent[1]["content"]
+ assert "needs your input" in webhook.sent[1]["content"]
+ assert adapter._input_pings[(str(CHANNEL_ID), "my-agent")] == [f"{CHANNEL_ID}:902"]
+
+ # Resuming work means the input was provided — the ping is deleted, the
+ # working indicator is refreshed in place.
+ _run(
+ adapter.apply_runtime_state(
+ str(CHANNEL_ID),
+ "my-agent",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ assert channel.deleted_ids == [902]
+ assert (str(CHANNEL_ID), "my-agent") not in adapter._input_pings
+
+
+# ── Webhook management ───────────────────────────────────────────────────────
+
+
+def test_get_webhook_adopts_existing_bridge_webhook() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ existing = _FakeWebhook(name="Switch Bridge", webhook_id=555)
+ channel.existing_webhooks = [_FakeWebhook(name="other", webhook_id=1), existing]
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+
+ webhook = _run(adapter._get_webhook(CHANNEL_ID))
+
+ assert webhook is existing
+ assert channel.created_webhooks == []
+ assert 555 in adapter._webhook_ids
+
+
+def test_get_webhook_creates_when_missing() -> None:
+ adapter = _adapter()
+ channel = _FakeChannel()
+ adapter._client = _FakeClient({CHANNEL_ID: channel})
+
+ webhook = _run(adapter._get_webhook(CHANNEL_ID))
+
+ assert channel.created_webhooks == ["Switch Bridge"]
+ assert webhook.id in adapter._webhook_ids
+ # Cached: second call does not re-create.
+ again = _run(adapter._get_webhook(CHANNEL_ID))
+ assert again is webhook
+ assert channel.created_webhooks == ["Switch Bridge"]
+
+
+# ── Translation ──────────────────────────────────────────────────────────────
+
+
+def test_translate_inbound_converts_user_and_channel_mentions() -> None:
+ adapter = _adapter()
+ adapter._user_names[7] = "louis"
+ adapter._client = _FakeClient({CHANNEL_ID: _FakeChannel(name="general")})
+
+ out = adapter.translate_inbound(f"hi <@7> and <@!7>, see <#{CHANNEL_ID}> or <@99>")
+
+ assert out == "hi @louis and @louis, see #general or <@99>"
+
+
+def test_translate_outbound_rewrites_known_usernames() -> None:
+ adapter = _adapter()
+ adapter._username_to_id["louis"] = 7
+
+ out = adapter.translate_outbound("ping @louis and @unknown-agent")
+
+ assert out == "ping <@7> and @unknown-agent"
+
+
+# ── Gateway lifecycle (start / stop) ──────────────────────────────────────────
+
+
+class _BotUser:
+ def __init__(self, user_id: int) -> None:
+ self.id = user_id
+
+ def __str__(self) -> str:
+ return f"bot#{self.id}"
+
+
+class _FakeGatewayClient:
+ """Controllable stand-in for ``discord.Client`` used by ``start()``.
+
+ ``connect_behavior`` selects how the gateway task behaves: ``"hang"`` keeps
+ the connection alive (awaits an event that only ``close()`` sets), while
+ ``"raise"`` fails the connection like a bad token. Readiness is gated on
+ ``ready_event`` so a test decides whether ``wait_until_ready()`` resolves.
+ """
+
+ def __init__(self) -> None:
+ self.user = _BotUser(BOT_USER_ID)
+ self.logged_in = False
+ self.closed = False
+ self.registered_events: list[Any] = []
+ self.connect_behavior = "hang"
+ self.connect_exc: BaseException = RuntimeError("gateway boom")
+ self._ready_event = asyncio.Event()
+ self._closed_event = asyncio.Event()
+
+ def event(self, coro: Any) -> Any:
+ self.registered_events.append(coro)
+ return coro
+
+ async def login(self, token: str) -> None:
+ self.logged_in = True
+
+ async def connect(self) -> None:
+ if self.connect_behavior == "raise":
+ raise self.connect_exc
+ await self._closed_event.wait()
+
+ async def wait_until_ready(self) -> None:
+ await self._ready_event.wait()
+
+ async def close(self) -> None:
+ self.closed = True
+ self._closed_event.set()
+
+
+def _noop_callbacks() -> tuple[Any, ...]:
+ async def _cb(*args: Any, **kwargs: Any) -> None:
+ return None
+
+ return (_cb, _cb, _cb, _cb, _cb)
+
+
+def test_start_becomes_ready_then_stop_closes_client() -> None:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ fake = _FakeGatewayClient()
+ fake._ready_event.set() # ready as soon as start() waits
+
+ async def scenario() -> None:
+ with patch.object(adapter_module.discord, "Client", lambda **kw: fake):
+ await adapter.start(*_noop_callbacks())
+ assert adapter._client is fake
+ assert fake.logged_in
+ assert fake.registered_events # on_message handler registered
+ assert adapter._bot_user_id == BOT_USER_ID
+
+ await adapter.stop()
+ assert fake.closed
+ assert adapter._client is None
+
+ _run(scenario())
+
+
+def test_start_raises_when_gateway_connection_fails() -> None:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ fake = _FakeGatewayClient()
+ fake.connect_behavior = "raise"
+ fake.connect_exc = RuntimeError("login failed")
+ # ready never fires, so the failing connect task is what completes first.
+
+ async def scenario() -> None:
+ with patch.object(adapter_module.discord, "Client", lambda **kw: fake):
+ with pytest.raises(RuntimeError, match="gateway connection failed") as exc:
+ await adapter.start(*_noop_callbacks())
+ assert isinstance(exc.value.__cause__, RuntimeError)
+ assert str(exc.value.__cause__) == "login failed"
+
+ _run(scenario())
+
+
+def test_start_times_out_when_never_ready_and_stops() -> None:
+ adapter = DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+ fake = _FakeGatewayClient() # hangs on connect, never becomes ready
+
+ async def scenario() -> None:
+ with (
+ patch.object(adapter_module.discord, "Client", lambda **kw: fake),
+ patch.object(adapter_module, "_READY_TIMEOUT", 0.05),
+ ):
+ with pytest.raises(RuntimeError, match="not ready"):
+ await adapter.start(*_noop_callbacks())
+ # Timeout path tears the half-open client down.
+ assert fake.closed
+ assert adapter._client is None
+
+ _run(scenario())
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py
new file mode 100644
index 000000000..49cdfd039
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import discord
+import pytest
+
+from switch_core.bridges.collaboration.discord.adapter import (
+ DiscordAdapter,
+ DiscordConnectionConfig,
+)
+
+GUILD_ID = 900
+
+
+def _adapter() -> DiscordAdapter:
+ return DiscordAdapter(
+ config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
+ )
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeRole:
+ pass
+
+
+class _FakeMember:
+ def __init__(self, user_id: int) -> None:
+ self.id = user_id
+
+
+class _FakeCreatedChannel:
+ def __init__(self, channel_id: int, guild: _FakeGuild) -> None:
+ self.id = channel_id
+ self.guild = guild
+ self.permission_grants: list[tuple[Any, dict[str, Any]]] = []
+
+ async def set_permissions(self, target: Any, **kwargs: Any) -> None:
+ self.permission_grants.append((target, kwargs))
+
+
+class _FakeGuild:
+ def __init__(self) -> None:
+ self.id = GUILD_ID
+ self.default_role = _FakeRole()
+ self.me = _FakeMember(42)
+ self.created: list[dict[str, Any]] = []
+ self.members: dict[int, _FakeMember] = {}
+ self._next_channel_id = 100
+
+ async def create_text_channel(self, **kwargs: Any) -> _FakeCreatedChannel:
+ self.created.append(kwargs)
+ self._next_channel_id += 1
+ return _FakeCreatedChannel(self._next_channel_id, self)
+
+ def get_member(self, user_id: int) -> _FakeMember | None:
+ return self.members.get(user_id)
+
+ async def fetch_member(self, user_id: int) -> _FakeMember:
+ member = self.members.get(user_id)
+ if member is None:
+ raise _not_found()
+ return member
+
+
+class _FakeClient:
+ def __init__(
+ self, guild: _FakeGuild, channels: dict[int, Any] | None = None
+ ) -> None:
+ self._guild = guild
+ self._channels = channels or {}
+
+ def get_guild(self, guild_id: int) -> _FakeGuild | None:
+ return self._guild if guild_id == self._guild.id else None
+
+ def get_channel(self, channel_id: int) -> Any | None:
+ return self._channels.get(channel_id)
+
+ async def fetch_channel(self, channel_id: int) -> Any:
+ channel = self._channels.get(channel_id)
+ if channel is None:
+ raise _not_found()
+ return channel
+
+
+class _FakeResponse:
+ status = 404
+ reason = "Not Found"
+
+
+def _not_found() -> discord.NotFound:
+ return discord.NotFound(_FakeResponse(), "not found")
+
+
+class _FakePrivateChannel:
+ def __init__(self, channel_id: int, guild: _FakeGuild, private: bool) -> None:
+ self.id = channel_id
+ self.guild = guild
+ self._private = private
+ self.permission_grants: list[tuple[Any, dict[str, Any]]] = []
+
+ def overwrites_for(self, role: Any) -> Any:
+ class _Overwrite:
+ view_channel = False if self._private else None
+
+ return _Overwrite()
+
+ async def set_permissions(self, target: Any, **kwargs: Any) -> None:
+ if isinstance(target, _FakeMember) and target.id == 666:
+ raise discord.HTTPException(_FakeResponse(), "boom")
+ self.permission_grants.append((target, kwargs))
+
+
+def _wire(
+ adapter: DiscordAdapter, guild: _FakeGuild, channels: dict[int, Any] | None = None
+) -> None:
+ adapter._client = _FakeClient(guild, channels) # type: ignore[assignment]
+
+
+# ── create_channel ───────────────────────────────────────────────────────────
+
+
+def test_create_public_channel_sanitizes_name_and_sets_topic() -> None:
+ adapter = _adapter()
+ guild = _FakeGuild()
+ _wire(adapter, guild)
+
+ channel_id = _run(adapter.create_channel("My Feature Room!", "workstream topic"))
+
+ assert channel_id == "101"
+ created = guild.created[0]
+ assert created["name"] == "my-feature-room"
+ assert created["topic"] == "workstream topic"
+ assert created["overwrites"] == {}
+
+
+def test_create_private_channel_denies_everyone_and_allows_bot() -> None:
+ adapter = _adapter()
+ guild = _FakeGuild()
+ _wire(adapter, guild)
+
+ _run(adapter.create_channel("secret", "t", channel_type="channel_private"))
+
+ overwrites = guild.created[0]["overwrites"]
+ assert overwrites[guild.default_role].view_channel is False
+ assert overwrites[guild.me].view_channel is True
+
+
+def test_create_group_or_direct_channel_rejected() -> None:
+ adapter = _adapter()
+ _wire(adapter, _FakeGuild())
+
+ for channel_type in ("group", "direct"):
+ with pytest.raises(ValueError, match="initiated from the messaging platform"):
+ _run(adapter.create_channel("x", "t", channel_type=channel_type)) # type: ignore[arg-type]
+
+
+def test_create_dm_channel_provisions_private_channel_with_user() -> None:
+ adapter = _adapter()
+ guild = _FakeGuild()
+ guild.members[7] = _FakeMember(7)
+ _wire(adapter, guild)
+
+ channel_id = _run(
+ adapter.create_dm_channel(
+ agent_name="my-agent", user_name="louis", user_external_id="7"
+ )
+ )
+
+ assert channel_id == "101"
+ created = guild.created[0]
+ assert created["name"] == "dm-louis-my-agent"
+ assert created["overwrites"][guild.default_role].view_channel is False
+
+
+# ── add_users_to_channel ─────────────────────────────────────────────────────
+
+
+def test_add_users_to_private_channel_grants_view_per_user() -> None:
+ adapter = _adapter()
+ guild = _FakeGuild()
+ guild.members[7] = _FakeMember(7)
+ guild.members[8] = _FakeMember(8)
+ channel = _FakePrivateChannel(200, guild, private=True)
+ _wire(adapter, guild, {200: channel})
+
+ _run(adapter.add_users_to_channel("200", ["louis", "ana"], ["7", "8"]))
+
+ granted_ids = [target.id for target, _ in channel.permission_grants]
+ assert granted_ids == [7, 8]
+ assert all(
+ kwargs == {"view_channel": True} for _, kwargs in channel.permission_grants
+ )
+
+
+def test_add_users_failure_is_isolated_per_user() -> None:
+ adapter = _adapter()
+ guild = _FakeGuild()
+ guild.members[666] = _FakeMember(666)
+ guild.members[8] = _FakeMember(8)
+ channel = _FakePrivateChannel(200, guild, private=True)
+ _wire(adapter, guild, {200: channel})
+
+ _run(adapter.add_users_to_channel("200", ["bad", "ana"], ["666", "8"]))
+
+ assert [target.id for target, _ in channel.permission_grants] == [8]
+
+
+def test_add_users_to_public_channel_is_noop() -> None:
+ adapter = _adapter()
+ guild = _FakeGuild()
+ guild.members[7] = _FakeMember(7)
+ channel = _FakePrivateChannel(200, guild, private=False)
+ _wire(adapter, guild, {200: channel})
+
+ _run(adapter.add_users_to_channel("200", ["louis"], ["7"]))
+
+ assert channel.permission_grants == []
+
+
+# ── Deeplinks ────────────────────────────────────────────────────────────────
+
+
+def test_channel_deeplink_built_from_guild_and_channel() -> None:
+ adapter = _adapter()
+
+ link = _run(adapter.channel_deeplink("12345"))
+
+ assert link == f"https://discord.com/channels/{GUILD_ID}/12345"
+ assert _run(adapter.channel_deeplink("")) is None
diff --git a/core/uv.lock b/core/uv.lock
index 2d020c04d..436f2baa1 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -3,7 +3,8 @@ revision = 3
requires-python = ">=3.12"
resolution-markers = [
"python_full_version >= '3.15'",
- "python_full_version < '3.15'",
+ "python_full_version >= '3.13' and python_full_version < '3.15'",
+ "python_full_version < '3.13'",
]
[[package]]
@@ -294,6 +295,62 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" },
]
+[[package]]
+name = "audioop-lts"
+version = "0.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/38/53/946db57842a50b2da2e0c1e34bd37f36f5aadba1a929a3971c5d7841dbca/audioop_lts-0.2.2.tar.gz", hash = "sha256:64d0c62d88e67b98a1a5e71987b7aa7b5bcffc7dcee65b635823dbdd0a8dbbd0", size = 30686, upload-time = "2025-08-05T16:43:17.409Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/d4/94d277ca941de5a507b07f0b592f199c22454eeaec8f008a286b3fbbacd6/audioop_lts-0.2.2-cp313-abi3-macosx_10_13_universal2.whl", hash = "sha256:fd3d4602dc64914d462924a08c1a9816435a2155d74f325853c1f1ac3b2d9800", size = 46523, upload-time = "2025-08-05T16:42:20.836Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/5a/656d1c2da4b555920ce4177167bfeb8623d98765594af59702c8873f60ec/audioop_lts-0.2.2-cp313-abi3-macosx_10_13_x86_64.whl", hash = "sha256:550c114a8df0aafe9a05442a1162dfc8fec37e9af1d625ae6060fed6e756f303", size = 27455, upload-time = "2025-08-05T16:42:22.283Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/83/ea581e364ce7b0d41456fb79d6ee0ad482beda61faf0cab20cbd4c63a541/audioop_lts-0.2.2-cp313-abi3-macosx_11_0_arm64.whl", hash = "sha256:9a13dc409f2564de15dd68be65b462ba0dde01b19663720c68c1140c782d1d75", size = 26997, upload-time = "2025-08-05T16:42:23.849Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/3b/e8964210b5e216e5041593b7d33e97ee65967f17c282e8510d19c666dab4/audioop_lts-0.2.2-cp313-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:51c916108c56aa6e426ce611946f901badac950ee2ddaf302b7ed35d9958970d", size = 85844, upload-time = "2025-08-05T16:42:25.208Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/2e/0a1c52faf10d51def20531a59ce4c706cb7952323b11709e10de324d6493/audioop_lts-0.2.2-cp313-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:47eba38322370347b1c47024defbd36374a211e8dd5b0dcbce7b34fdb6f8847b", size = 85056, upload-time = "2025-08-05T16:42:26.559Z" },
+ { url = "https://files.pythonhosted.org/packages/75/e8/cd95eef479656cb75ab05dfece8c1f8c395d17a7c651d88f8e6e291a63ab/audioop_lts-0.2.2-cp313-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ba7c3a7e5f23e215cb271516197030c32aef2e754252c4c70a50aaff7031a2c8", size = 93892, upload-time = "2025-08-05T16:42:27.902Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/1e/a0c42570b74f83efa5cca34905b3eef03f7ab09fe5637015df538a7f3345/audioop_lts-0.2.2-cp313-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def246fe9e180626731b26e89816e79aae2276f825420a07b4a647abaa84becc", size = 96660, upload-time = "2025-08-05T16:42:28.9Z" },
+ { url = "https://files.pythonhosted.org/packages/50/d5/8a0ae607ca07dbb34027bac8db805498ee7bfecc05fd2c148cc1ed7646e7/audioop_lts-0.2.2-cp313-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e160bf9df356d841bb6c180eeeea1834085464626dc1b68fa4e1d59070affdc3", size = 79143, upload-time = "2025-08-05T16:42:29.929Z" },
+ { url = "https://files.pythonhosted.org/packages/12/17/0d28c46179e7910bfb0bb62760ccb33edb5de973052cb2230b662c14ca2e/audioop_lts-0.2.2-cp313-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:4b4cd51a57b698b2d06cb9993b7ac8dfe89a3b2878e96bc7948e9f19ff51dba6", size = 84313, upload-time = "2025-08-05T16:42:30.949Z" },
+ { url = "https://files.pythonhosted.org/packages/84/ba/bd5d3806641564f2024e97ca98ea8f8811d4e01d9b9f9831474bc9e14f9e/audioop_lts-0.2.2-cp313-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:4a53aa7c16a60a6857e6b0b165261436396ef7293f8b5c9c828a3a203147ed4a", size = 93044, upload-time = "2025-08-05T16:42:31.959Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/5e/435ce8d5642f1f7679540d1e73c1c42d933331c0976eb397d1717d7f01a3/audioop_lts-0.2.2-cp313-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:3fc38008969796f0f689f1453722a0f463da1b8a6fbee11987830bfbb664f623", size = 78766, upload-time = "2025-08-05T16:42:33.302Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/3b/b909e76b606cbfd53875693ec8c156e93e15a1366a012f0b7e4fb52d3c34/audioop_lts-0.2.2-cp313-abi3-musllinux_1_2_s390x.whl", hash = "sha256:15ab25dd3e620790f40e9ead897f91e79c0d3ce65fe193c8ed6c26cffdd24be7", size = 87640, upload-time = "2025-08-05T16:42:34.854Z" },
+ { url = "https://files.pythonhosted.org/packages/30/e7/8f1603b4572d79b775f2140d7952f200f5e6c62904585d08a01f0a70393a/audioop_lts-0.2.2-cp313-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:03f061a1915538fd96272bac9551841859dbb2e3bf73ebe4a23ef043766f5449", size = 86052, upload-time = "2025-08-05T16:42:35.839Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/96/c37846df657ccdda62ba1ae2b6534fa90e2e1b1742ca8dcf8ebd38c53801/audioop_lts-0.2.2-cp313-abi3-win32.whl", hash = "sha256:3bcddaaf6cc5935a300a8387c99f7a7fbbe212a11568ec6cf6e4bc458c048636", size = 26185, upload-time = "2025-08-05T16:42:37.04Z" },
+ { url = "https://files.pythonhosted.org/packages/34/a5/9d78fdb5b844a83da8a71226c7bdae7cc638861085fff7a1d707cb4823fa/audioop_lts-0.2.2-cp313-abi3-win_amd64.whl", hash = "sha256:a2c2a947fae7d1062ef08c4e369e0ba2086049a5e598fda41122535557012e9e", size = 30503, upload-time = "2025-08-05T16:42:38.427Z" },
+ { url = "https://files.pythonhosted.org/packages/34/25/20d8fde083123e90c61b51afb547bb0ea7e77bab50d98c0ab243d02a0e43/audioop_lts-0.2.2-cp313-abi3-win_arm64.whl", hash = "sha256:5f93a5db13927a37d2d09637ccca4b2b6b48c19cd9eda7b17a2e9f77edee6a6f", size = 24173, upload-time = "2025-08-05T16:42:39.704Z" },
+ { url = "https://files.pythonhosted.org/packages/58/a7/0a764f77b5c4ac58dc13c01a580f5d32ae8c74c92020b961556a43e26d02/audioop_lts-0.2.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:73f80bf4cd5d2ca7814da30a120de1f9408ee0619cc75da87d0641273d202a09", size = 47096, upload-time = "2025-08-05T16:42:40.684Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/ed/ebebedde1a18848b085ad0fa54b66ceb95f1f94a3fc04f1cd1b5ccb0ed42/audioop_lts-0.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:106753a83a25ee4d6f473f2be6b0966fc1c9af7e0017192f5531a3e7463dce58", size = 27748, upload-time = "2025-08-05T16:42:41.992Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/6e/11ca8c21af79f15dbb1c7f8017952ee8c810c438ce4e2b25638dfef2b02c/audioop_lts-0.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fbdd522624141e40948ab3e8cdae6e04c748d78710e9f0f8d4dae2750831de19", size = 27329, upload-time = "2025-08-05T16:42:42.987Z" },
+ { url = "https://files.pythonhosted.org/packages/84/52/0022f93d56d85eec5da6b9da6a958a1ef09e80c39f2cc0a590c6af81dcbb/audioop_lts-0.2.2-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:143fad0311e8209ece30a8dbddab3b65ab419cbe8c0dde6e8828da25999be911", size = 92407, upload-time = "2025-08-05T16:42:44.336Z" },
+ { url = "https://files.pythonhosted.org/packages/87/1d/48a889855e67be8718adbc7a01f3c01d5743c325453a5e81cf3717664aad/audioop_lts-0.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dfbbc74ec68a0fd08cfec1f4b5e8cca3d3cd7de5501b01c4b5d209995033cde9", size = 91811, upload-time = "2025-08-05T16:42:45.325Z" },
+ { url = "https://files.pythonhosted.org/packages/98/a6/94b7213190e8077547ffae75e13ed05edc488653c85aa5c41472c297d295/audioop_lts-0.2.2-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cfcac6aa6f42397471e4943e0feb2244549db5c5d01efcd02725b96af417f3fe", size = 100470, upload-time = "2025-08-05T16:42:46.468Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/e9/78450d7cb921ede0cfc33426d3a8023a3bda755883c95c868ee36db8d48d/audioop_lts-0.2.2-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:752d76472d9804ac60f0078c79cdae8b956f293177acd2316cd1e15149aee132", size = 103878, upload-time = "2025-08-05T16:42:47.576Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/e2/cd5439aad4f3e34ae1ee852025dc6aa8f67a82b97641e390bf7bd9891d3e/audioop_lts-0.2.2-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:83c381767e2cc10e93e40281a04852facc4cd9334550e0f392f72d1c0a9c5753", size = 84867, upload-time = "2025-08-05T16:42:49.003Z" },
+ { url = "https://files.pythonhosted.org/packages/68/4b/9d853e9076c43ebba0d411e8d2aa19061083349ac695a7d082540bad64d0/audioop_lts-0.2.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c0022283e9556e0f3643b7c3c03f05063ca72b3063291834cca43234f20c60bb", size = 90001, upload-time = "2025-08-05T16:42:50.038Z" },
+ { url = "https://files.pythonhosted.org/packages/58/26/4bae7f9d2f116ed5593989d0e521d679b0d583973d203384679323d8fa85/audioop_lts-0.2.2-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:a2d4f1513d63c795e82948e1305f31a6d530626e5f9f2605408b300ae6095093", size = 99046, upload-time = "2025-08-05T16:42:51.111Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/67/a9f4fb3e250dda9e9046f8866e9fa7d52664f8985e445c6b4ad6dfb55641/audioop_lts-0.2.2-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:c9c8e68d8b4a56fda8c025e538e639f8c5953f5073886b596c93ec9b620055e7", size = 84788, upload-time = "2025-08-05T16:42:52.198Z" },
+ { url = "https://files.pythonhosted.org/packages/70/f7/3de86562db0121956148bcb0fe5b506615e3bcf6e63c4357a612b910765a/audioop_lts-0.2.2-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:96f19de485a2925314f5020e85911fb447ff5fbef56e8c7c6927851b95533a1c", size = 94472, upload-time = "2025-08-05T16:42:53.59Z" },
+ { url = "https://files.pythonhosted.org/packages/f1/32/fd772bf9078ae1001207d2df1eef3da05bea611a87dd0e8217989b2848fa/audioop_lts-0.2.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e541c3ef484852ef36545f66209444c48b28661e864ccadb29daddb6a4b8e5f5", size = 92279, upload-time = "2025-08-05T16:42:54.632Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/41/affea7181592ab0ab560044632571a38edaf9130b84928177823fbf3176a/audioop_lts-0.2.2-cp313-cp313t-win32.whl", hash = "sha256:d5e73fa573e273e4f2e5ff96f9043858a5e9311e94ffefd88a3186a910c70917", size = 26568, upload-time = "2025-08-05T16:42:55.627Z" },
+ { url = "https://files.pythonhosted.org/packages/28/2b/0372842877016641db8fc54d5c88596b542eec2f8f6c20a36fb6612bf9ee/audioop_lts-0.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:9191d68659eda01e448188f60364c7763a7ca6653ed3f87ebb165822153a8547", size = 30942, upload-time = "2025-08-05T16:42:56.674Z" },
+ { url = "https://files.pythonhosted.org/packages/ee/ca/baf2b9cc7e96c179bb4a54f30fcd83e6ecb340031bde68f486403f943768/audioop_lts-0.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:c174e322bb5783c099aaf87faeb240c8d210686b04bd61dfd05a8e5a83d88969", size = 24603, upload-time = "2025-08-05T16:42:57.571Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/73/413b5a2804091e2c7d5def1d618e4837f1cb82464e230f827226278556b7/audioop_lts-0.2.2-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:f9ee9b52f5f857fbaf9d605a360884f034c92c1c23021fb90b2e39b8e64bede6", size = 47104, upload-time = "2025-08-05T16:42:58.518Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/8c/daa3308dc6593944410c2c68306a5e217f5c05b70a12e70228e7dd42dc5c/audioop_lts-0.2.2-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:49ee1a41738a23e98d98b937a0638357a2477bc99e61b0f768a8f654f45d9b7a", size = 27754, upload-time = "2025-08-05T16:43:00.132Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/86/c2e0f627168fcf61781a8f72cab06b228fe1da4b9fa4ab39cfb791b5836b/audioop_lts-0.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5b00be98ccd0fc123dcfad31d50030d25fcf31488cde9e61692029cd7394733b", size = 27332, upload-time = "2025-08-05T16:43:01.666Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/bd/35dce665255434f54e5307de39e31912a6f902d4572da7c37582809de14f/audioop_lts-0.2.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a6d2e0f9f7a69403e388894d4ca5ada5c47230716a03f2847cfc7bd1ecb589d6", size = 92396, upload-time = "2025-08-05T16:43:02.991Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/d2/deeb9f51def1437b3afa35aeb729d577c04bcd89394cb56f9239a9f50b6f/audioop_lts-0.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f9b0b8a03ef474f56d1a842af1a2e01398b8f7654009823c6d9e0ecff4d5cfbf", size = 91811, upload-time = "2025-08-05T16:43:04.096Z" },
+ { url = "https://files.pythonhosted.org/packages/76/3b/09f8b35b227cee28cc8231e296a82759ed80c1a08e349811d69773c48426/audioop_lts-0.2.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2b267b70747d82125f1a021506565bdc5609a2b24bcb4773c16d79d2bb260bbd", size = 100483, upload-time = "2025-08-05T16:43:05.085Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/15/05b48a935cf3b130c248bfdbdea71ce6437f5394ee8533e0edd7cfd93d5e/audioop_lts-0.2.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0337d658f9b81f4cd0fdb1f47635070cc084871a3d4646d9de74fdf4e7c3d24a", size = 103885, upload-time = "2025-08-05T16:43:06.197Z" },
+ { url = "https://files.pythonhosted.org/packages/83/80/186b7fce6d35b68d3d739f228dc31d60b3412105854edb975aa155a58339/audioop_lts-0.2.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:167d3b62586faef8b6b2275c3218796b12621a60e43f7e9d5845d627b9c9b80e", size = 84899, upload-time = "2025-08-05T16:43:07.291Z" },
+ { url = "https://files.pythonhosted.org/packages/49/89/c78cc5ac6cb5828f17514fb12966e299c850bc885e80f8ad94e38d450886/audioop_lts-0.2.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0d9385e96f9f6da847f4d571ce3cb15b5091140edf3db97276872647ce37efd7", size = 89998, upload-time = "2025-08-05T16:43:08.335Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/4b/6401888d0c010e586c2ca50fce4c903d70a6bb55928b16cfbdfd957a13da/audioop_lts-0.2.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:48159d96962674eccdca9a3df280e864e8ac75e40a577cc97c5c42667ffabfc5", size = 99046, upload-time = "2025-08-05T16:43:09.367Z" },
+ { url = "https://files.pythonhosted.org/packages/de/f8/c874ca9bb447dae0e2ef2e231f6c4c2b0c39e31ae684d2420b0f9e97ee68/audioop_lts-0.2.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:8fefe5868cd082db1186f2837d64cfbfa78b548ea0d0543e9b28935ccce81ce9", size = 84843, upload-time = "2025-08-05T16:43:10.749Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/c0/0323e66f3daebc13fd46b36b30c3be47e3fc4257eae44f1e77eb828c703f/audioop_lts-0.2.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:58cf54380c3884fb49fdd37dfb7a772632b6701d28edd3e2904743c5e1773602", size = 94490, upload-time = "2025-08-05T16:43:12.131Z" },
+ { url = "https://files.pythonhosted.org/packages/98/6b/acc7734ac02d95ab791c10c3f17ffa3584ccb9ac5c18fd771c638ed6d1f5/audioop_lts-0.2.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:088327f00488cdeed296edd9215ca159f3a5a5034741465789cad403fcf4bec0", size = 92297, upload-time = "2025-08-05T16:43:13.139Z" },
+ { url = "https://files.pythonhosted.org/packages/13/c3/c3dc3f564ce6877ecd2a05f8d751b9b27a8c320c2533a98b0c86349778d0/audioop_lts-0.2.2-cp314-cp314t-win32.whl", hash = "sha256:068aa17a38b4e0e7de771c62c60bbca2455924b67a8814f3b0dee92b5820c0b3", size = 27331, upload-time = "2025-08-05T16:43:14.19Z" },
+ { url = "https://files.pythonhosted.org/packages/72/bb/b4608537e9ffcb86449091939d52d24a055216a36a8bf66b936af8c3e7ac/audioop_lts-0.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:a5bf613e96f49712073de86f20dbdd4014ca18efd4d34ed18c75bd808337851b", size = 31697, upload-time = "2025-08-05T16:43:15.193Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/22/91616fe707a5c5510de2cac9b046a30defe7007ba8a0c04f9c08f27df312/audioop_lts-0.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:b492c3b040153e68b9fdaff5913305aaaba5bb433d8a7f73d5cf6a64ed3cc1dd", size = 25206, upload-time = "2025-08-05T16:43:16.444Z" },
+]
+
[[package]]
name = "authlib"
version = "1.7.2"
@@ -633,6 +690,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/4e/d0/17b6b7d5f64dea337a7a409a1e4e0eeceda724046b9acd158fd1aa2f2328/cyclopts-4.12.0-py3-none-any.whl", hash = "sha256:ee03d2b9ef790d866cb3823a7e54b2be5252c82d34536579846fce068b30c38f", size = 213706, upload-time = "2026-05-13T13:26:29.744Z" },
]
+[[package]]
+name = "discord-py"
+version = "2.7.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "audioop-lts", marker = "python_full_version >= '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ef/57/9a2d9abdabdc9db8ef28ce0cf4129669e1c8717ba28d607b5ba357c4de3b/discord_py-2.7.1.tar.gz", hash = "sha256:24d5e6a45535152e4b98148a9dd6b550d25dc2c9fb41b6d670319411641249da", size = 1106326, upload-time = "2026-03-03T18:40:46.24Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f7/a7/17208c3b3f92319e7fad259f1c6d5a5baf8fd0654c54846ced329f83c3eb/discord_py-2.7.1-py3-none-any.whl", hash = "sha256:849dca2c63b171146f3a7f3f8acc04248098e9e6203412ce3cf2745f284f7439", size = 1227550, upload-time = "2026-03-03T18:40:44.492Z" },
+]
+
[[package]]
name = "distlib"
version = "0.4.0"
@@ -2370,6 +2440,7 @@ dependencies = [
{ name = "asyncpg" },
{ name = "authlib" },
{ name = "bcrypt" },
+ { name = "discord-py" },
{ name = "fastapi" },
{ name = "fastmcp" },
{ name = "httpx" },
@@ -2402,6 +2473,7 @@ requires-dist = [
{ name = "asyncpg", specifier = ">=0.29,<1" },
{ name = "authlib", specifier = ">=1.3,<2" },
{ name = "bcrypt", specifier = ">=4.0,<5" },
+ { name = "discord-py", specifier = ">=2.4,<3" },
{ name = "fastapi", specifier = ">=0.115,<1" },
{ name = "fastmcp", specifier = ">=3.2.0,<4" },
{ name = "httpx", specifier = ">=0.28,<1" },