Skip to content

Self-improving AI Employees for everyone

feat(discord): gateway connections and the inbound message trigger

trohitg4c03115d941d
diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.json
index 74564cf4..1e9fc079 100644
--- a/server/config/node_allowlist.json
+++ b/server/config/node_allowlist.json
@@ -36,6 +36,7 @@
"discordSend",
"discordAction",
+ "discordReceive",
"whatsappBusinessSend",
"whatsappBusinessReceive",
diff --git a/server/constants.py b/server/constants.py
index f249e09f..98f04133 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -356,6 +356,7 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset(
"whatsappReceive",
"whatsappBusinessReceive",
"whatsappBusinessStatus",
+ "discordReceive",
"twitterReceive",
"workflowTrigger",
"chatTrigger",
@@ -403,6 +404,7 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset(
# canvas-only today.
"whatsappBusinessReceive",
"whatsappBusinessStatus",
+ "discordReceive",
"workflowTrigger",
"chatTrigger",
"taskTrigger",
diff --git a/server/nodes/discord/__init__.py b/server/nodes/discord/__init__.py
index d976ce62..b2f5df2b 100644
--- a/server/nodes/discord/__init__.py
+++ b/server/nodes/discord/__init__.py
@@ -11,28 +11,55 @@ than report anything. The gateway imports it inside a function.
from __future__ import annotations
+from services.deployment.canary_registry import register_canary_trigger_type
+from services.event_waiter import register_filter_builder, register_trigger_precheck
from services.node_output_schemas import register_output_schema
+from services.plugin.shutdown_hooks import register_shutdown_hook
from services.plugin.social_provider_registry import register_social_send_handler
-from services.ws_handler_registry import register_option_loader
+from services.status_broadcaster import register_service_refresh
+from services.ws_handler_registry import register_option_loader, register_ws_handlers
from ._credentials import DiscordBotCredential
+from ._events import MESSAGE_RECEIVED_TYPE
+from ._filters import build_discord_filter
+from ._gateway import stop_all_gateways
+from ._handlers import WS_HANDLERS
from ._option_loaders import load_accounts, load_channels, load_guilds
+from ._refresh import precheck_discord_trigger, refresh_discord_status
from ._social import social_send_adapter
from .discord_action import DiscordActionNode, DiscordActionOutput
+from .discord_receive import DiscordReceiveNode, DiscordReceiveOutput
from .discord_send import DiscordSendNode, DiscordSendOutput
+register_ws_handlers(WS_HANDLERS)
+
register_option_loader("discordAccounts", load_accounts)
register_option_loader("discordGuilds", load_guilds)
register_option_loader("discordChannels", load_channels)
register_output_schema(DiscordSendNode.type, DiscordSendOutput)
register_output_schema(DiscordActionNode.type, DiscordActionOutput)
+register_output_schema(DiscordReceiveNode.type, DiscordReceiveOutput)
+
+register_filter_builder(DiscordReceiveNode.type, build_discord_filter)
+register_trigger_precheck(DiscordReceiveNode.type, precheck_discord_trigger)
+register_service_refresh(refresh_discord_status)
+
+# The second argument becomes the EventType Search Attribute the Temporal
+# Visibility query matches on, so it must equal the type the envelope in
+# _events.py carries. A mismatch is silent: the listener starts and never
+# receives a signal.
+register_canary_trigger_type(DiscordReceiveNode.type, MESSAGE_RECEIVED_TYPE)
-# socialSend routes by platform id.
-register_social_send_handler("discord", social_send_adapter)
+# Sessions left open count against the account's concurrent-session limit
+# until Discord times them out, which across dev restarts looks like a second
+# instance that will not go away.
+register_shutdown_hook("discord_gateway", stop_all_gateways)
__all__ = [
"DiscordActionNode",
"DiscordBotCredential",
+ "DiscordReceiveNode",
"DiscordSendNode",
+ "WS_HANDLERS",
]
diff --git a/server/nodes/discord/_dispatch.py b/server/nodes/discord/_dispatch.py
new file mode 100644
index 00000000..2dd40a4f
--- /dev/null
+++ b/server/nodes/discord/_dispatch.py
@@ -0,0 +1,98 @@
+"""Turn a discord.py message object into a flat event payload.
+
+Every snowflake is stringified here. discord.py exposes them as int, while
+Discord's own JSON uses strings, and an id past 2^53 loses precision the
+moment anything treats it as a number -- edge conditions comparing an id are
+the most natural thing a user writes, and two distinct 18-digit ids comparing
+equal is a bug with no visible cause.
+
+Attachments travel as metadata, never bytes. A node result is persisted,
+broadcast, and replayed into LLM context, so the payload is a reference and
+discordAction fetches it on demand.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+# Enough to fetch the file later and to decide whether it is worth fetching.
+# Deliberately scalar-only: no nested media objects, no thumbnails.
+_ATTACHMENT_FIELDS = ("id", "filename", "size", "url", "content_type", "width", "height")
+
+
+def _sid(value: Any) -> Optional[str]:
+ """Snowflake to string, preserving None."""
+ return None if value is None else str(value)
+
+
+def shape_attachment(attachment: Any) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {}
+ for field in _ATTACHMENT_FIELDS:
+ value = getattr(attachment, field, None)
+ if value is not None:
+ payload[field] = _sid(value) if field == "id" else value
+ return payload
+
+
+def shape_message(message: Any, *, account_id: str) -> Dict[str, Any]:
+ """Flatten one message into the trigger's output shape."""
+ author = getattr(message, "author", None)
+ guild = getattr(message, "guild", None)
+ channel = getattr(message, "channel", None)
+ reference = getattr(message, "reference", None)
+
+ attachments = [shape_attachment(a) for a in (getattr(message, "attachments", None) or [])]
+
+ return {
+ "account_id": account_id,
+ "message_id": _sid(getattr(message, "id", None)),
+ "channel_id": _sid(getattr(channel, "id", None)),
+ "channel_name": getattr(channel, "name", None),
+ "guild_id": _sid(getattr(guild, "id", None)),
+ "guild_name": getattr(guild, "name", None),
+ # None for a DM, which is also how a consumer tells the two apart.
+ "is_dm": guild is None,
+ "author_id": _sid(getattr(author, "id", None)),
+ "author_name": getattr(author, "name", None),
+ "author_display_name": getattr(author, "display_name", None),
+ "author_is_bot": bool(getattr(author, "bot", False)),
+ "content": getattr(message, "content", "") or "",
+ "timestamp": (
+ message.created_at.isoformat() if getattr(message, "created_at", None) else None
+ ),
+ "attachments": attachments,
+ "has_attachments": bool(attachments),
+ "mentions_me": _mentions_me(message),
+ "reply_to_message_id": _sid(getattr(reference, "message_id", None)),
+ }
+
+
+def _mentions_me(message: Any) -> bool:
+ """Whether the bot was mentioned.
+
+ Useful as a filter because without the message-content intent this is one
+ of the few signals that still arrives populated.
+ """
+ try:
+ state = getattr(message, "_state", None)
+ me = getattr(state, "user", None) if state else None
+ if me is None:
+ return False
+ return any(getattr(u, "id", None) == me.id for u in (message.mentions or []))
+ except Exception:
+ return False
+
+
+async def dispatch_message(message: Any, *, account_id: str) -> None:
+ """Shape and emit one inbound message."""
+ from ._events import dispatch_discord_message_received
+
+ payload = shape_message(message, account_id=account_id)
+ await dispatch_discord_message_received(payload)
+
+
+__all__ = ["dispatch_message", "shape_attachment", "shape_message"]
diff --git a/server/nodes/discord/_filters.py b/server/nodes/discord/_filters.py
new file mode 100644
index 00000000..ee9faed1
--- /dev/null
+++ b/server/nodes/discord/_filters.py
@@ -0,0 +1,63 @@
+"""Filter builder for discordReceive.
+
+Reads every parameter once at build time and closes over the result, so the
+per-event path is plain comparisons. The fields it inspects are exactly those
+``_dispatch.shape_message`` produces -- the two move together.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Callable, Dict
+
+
+def build_discord_filter(params: Dict[str, Any]) -> Callable[[Dict[str, Any]], bool]:
+ """Return a predicate deciding whether one event should fire this node."""
+ params = params or {}
+
+ account_id = (params.get("account_id") or "").strip()
+ scope = params.get("scope") or "all"
+ guild_id = (params.get("guild_id") or "").strip()
+ channel_id = (params.get("channel_id") or "").strip()
+ author_id = (params.get("author_id") or "").strip()
+ keywords = [k.strip().lower() for k in (params.get("keywords") or "").split(",") if k.strip()]
+ ignore_bots = params.get("ignore_bots", True)
+ require_mention = params.get("require_mention", False)
+ require_attachment = params.get("require_attachment", False)
+
+ def matches(event: Dict[str, Any]) -> bool:
+ # An account filter is not a convenience: without it, connecting a
+ # second bot would make every trigger fire for both.
+ if account_id and event.get("account_id") != account_id:
+ return False
+
+ if ignore_bots and event.get("author_is_bot"):
+ return False
+
+ if scope == "dm" and not event.get("is_dm"):
+ return False
+ if scope == "guild" and event.get("is_dm"):
+ return False
+
+ if guild_id and event.get("guild_id") != guild_id:
+ return False
+ if channel_id and event.get("channel_id") != channel_id:
+ return False
+ if author_id and event.get("author_id") != author_id:
+ return False
+
+ if require_mention and not event.get("mentions_me"):
+ return False
+ if require_attachment and not event.get("has_attachments"):
+ return False
+
+ if keywords:
+ content = (event.get("content") or "").lower()
+ if not any(word in content for word in keywords):
+ return False
+
+ return True
+
+ return matches
+
+
+__all__ = ["build_discord_filter"]
diff --git a/server/nodes/discord/_gateway.py b/server/nodes/discord/_gateway.py
new file mode 100644
index 00000000..2af865aa
--- /dev/null
+++ b/server/nodes/discord/_gateway.py
@@ -0,0 +1,271 @@
+"""Gateway connections, one per Discord bot account.
+
+discord.py owns the socket. What it handles is exactly the part that is
+miserable to re-derive and fails silently when wrong: zlib-stream framing,
+heartbeat/ACK tracking with jitter, RESUME versus IDENTIFY on the right close
+codes, resume_gateway_url, and IDENTIFY concurrency. A hand-rolled client
+stays "connected" and quietly stops receiving messages hours later.
+
+REST is deliberately not borrowed from it -- see _base. The two never cross:
+gateway traffic goes through the client here, every REST call goes through
+_base, and each has its own rate limiting. Calling ``client.http`` from node
+code would put requests behind a limiter that knows nothing about the
+process-wide invalid-request budget.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Dict, Optional
+
+from core.logging import get_logger
+from services._supervisor import register_supervisor
+from services._supervisor.base import BaseSupervisor, RestartPolicy
+from services.plugin import NodeUserError
+
+from ._accounts import DEFAULT_ACCOUNT, resolve_secrets
+
+logger = get_logger(__name__)
+
+# How long to wait for READY before treating the connection as failed.
+READY_TIMEOUT_SECONDS = 60.0
+
+# Close conditions that no amount of retrying will fix. Feeding these to the
+# restart policy would hammer Discord and burn the 1000-IDENTIFY daily budget,
+# which ends in a reset token and an email to the app owner.
+_TERMINAL_ERRORS = ("PrivilegedIntentsRequired", "LoginFailure")
+
+
+def _resolve_intents(discord_module: Any) -> Any:
+ """The intent set every Discord node needs.
+
+ Computed in one place because ``Intents`` must be final before the client
+ is constructed -- adding one later means restarting every connection. A
+ future capability (voice, presence) widens this function and nothing else.
+
+ message_content is privileged. Without it approved in the Developer Portal
+ the gateway still connects and simply delivers empty ``content``, which is
+ why the credential probe reports on it rather than leaving it to surface
+ as "the Discord node returns blank text".
+ """
+ intents = discord_module.Intents.none()
+ intents.guilds = True
+ intents.guild_messages = True
+ intents.dm_messages = True
+ intents.message_content = True
+ intents.reactions = True
+ return intents
+
+
+class DiscordGateway(BaseSupervisor):
+ """One live gateway connection for one bot account."""
+
+ def __init__(self, account_id: str = DEFAULT_ACCOUNT) -> None:
+ super().__init__()
+ self.account_id = account_id
+ # Distinct per account: the supervisor registry keys on this, and a
+ # shared label would mean the second account silently replaced the
+ # first.
+ self.name = f"discord-gateway:{account_id}"
+ self._client: Optional[Any] = None
+ self._task: Optional[asyncio.Task] = None
+ self._terminal_error: Optional[str] = None
+
+ # ---- lifecycle ------------------------------------------------------
+
+ def is_running(self) -> bool:
+ return self._client is not None and not self._client.is_closed()
+
+ async def _do_start(self) -> None:
+ # Imported here, never at module scope: nodes/__init__.py swallows
+ # import errors during discovery, so a failure at import time would
+ # make the whole plugin vanish without a word.
+ import discord
+
+ secrets = await resolve_secrets(self.account_id)
+ token = secrets["token"]
+
+ client = discord.Client(intents=_resolve_intents(discord))
+ self._register_handlers(client, discord)
+ self._client = client
+
+ # start(), never run(): run() installs signal handlers and would
+ # fight uvicorn's own.
+ self._task = asyncio.create_task(client.start(token), name=self.name)
+
+ # Race readiness against the connection task rather than just
+ # awaiting readiness. Login failures surface inside start(), so
+ # waiting on wait_until_ready() alone would sit out the full timeout
+ # and report "not ready" for what is really a rejected token.
+ ready = asyncio.create_task(client.wait_until_ready())
+ try:
+ done, _ = await asyncio.wait(
+ {ready, self._task},
+ timeout=READY_TIMEOUT_SECONDS,
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ finally:
+ if not ready.done():
+ ready.cancel()
+
+ if self._task in done:
+ # start() returned or raised before the client became ready.
+ failure = self._task.exception()
+ await self._do_stop()
+ if failure is not None:
+ raise self._translate_start_error(failure) from failure
+ raise NodeUserError("Discord gateway closed before it finished connecting.")
+
+ if ready not in done:
+ await self._do_stop()
+ raise NodeUserError(
+ f"Discord gateway did not become ready within {READY_TIMEOUT_SECONDS:.0f}s. "
+ "Check that this host can reach discord.com."
+ )
+
+ logger.info(
+ "discord gateway ready",
+ account_id=self.account_id,
+ user=str(getattr(client.user, "name", "")),
+ guilds=len(getattr(client, "guilds", []) or []),
+ )
+
+ async def _do_stop(self) -> None:
+ client, task = self._client, self._task
+ self._client, self._task = None, None
+
+ if client is not None:
+ try:
+ await client.close()
+ except Exception as exc:
+ logger.debug("discord gateway close failed", error=str(exc))
+
+ if task is not None:
+ if not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ # Ours, from the cancel above.
+ pass
+ except Exception as exc:
+ # The task's own failure is already reported by whoever
+ # awaited start(); losing it here would mask nothing.
+ logger.debug("discord gateway task ended", error=str(exc))
+
+ def _extra_status(self) -> Dict[str, Any]:
+ client = self._client
+ user = getattr(client, "user", None) if client else None
+ latency = getattr(client, "latency", None) if client else None
+ return {
+ "account_id": self.account_id,
+ "bot_username": str(getattr(user, "name", "")) if user else None,
+ "bot_id": str(getattr(user, "id", "")) if user else None,
+ "guild_count": len(getattr(client, "guilds", []) or []) if client else 0,
+ # discord.py reports infinity before the first heartbeat.
+ "latency_ms": round(latency * 1000) if latency and latency != float("inf") else None,
+ "terminal_error": self._terminal_error,
+ }
+
+ # ---- errors ---------------------------------------------------------
+
+ def _translate_start_error(self, exc: Exception) -> Exception:
+ """Terminal failures must not be retried.
+
+ A wrong token or an unapproved privileged intent fails identically on
+ every attempt, so backing off just spends the daily IDENTIFY budget.
+ """
+ name = type(exc).__name__
+ if name in _TERMINAL_ERRORS:
+ self._terminal_error = name
+ if name == "PrivilegedIntentsRequired":
+ return NodeUserError(
+ "Discord refused the connection because a privileged intent is not "
+ "enabled. Turn on Message Content under Bot > Privileged Gateway "
+ "Intents in the Developer Portal."
+ )
+ return NodeUserError(
+ "Discord rejected the bot token. Copy it again from the Developer "
+ "Portal; resetting a token invalidates the old one."
+ )
+ return exc
+
+ def can_retry(self) -> bool:
+ """False once a terminal condition has been seen."""
+ return self._terminal_error is None
+
+ # ---- event wiring ---------------------------------------------------
+
+ def _register_handlers(self, client: Any, discord_module: Any) -> None:
+ account_id = self.account_id
+
+ @client.event
+ async def on_message(message: Any) -> None: # noqa: ANN401 - discord.py type
+ # The bot's own messages would otherwise loop straight back into
+ # any workflow that replies.
+ if client.user is not None and message.author.id == client.user.id:
+ return
+ from ._dispatch import dispatch_message
+
+ try:
+ await dispatch_message(message, account_id=account_id)
+ except Exception as exc:
+ # One malformed message must not kill the receive loop.
+ logger.warning("discord message dispatch failed", error=str(exc))
+
+
+# --------------------------------------------------------------------------
+# Per-account registry
+# --------------------------------------------------------------------------
+#
+# BaseSupervisor.get_instance() is a per-subclass singleton, so it cannot hold
+# N connections. The registry below is the multi-account equivalent, and each
+# gateway still registers with services._supervisor so shutdown_all_supervisors
+# reaches it.
+
+_GATEWAYS: Dict[str, DiscordGateway] = {}
+_REGISTRY_LOCK = asyncio.Lock()
+
+
+async def get_gateway(account_id: str = DEFAULT_ACCOUNT) -> DiscordGateway:
+ """Return the gateway for one account, creating it on first use."""
+ async with _REGISTRY_LOCK:
+ gateway = _GATEWAYS.get(account_id)
+ if gateway is None:
+ gateway = DiscordGateway(account_id)
+ _GATEWAYS[account_id] = gateway
+ register_supervisor(gateway)
+ return gateway
+
+
+def running_gateways() -> Dict[str, DiscordGateway]:
+ return {aid: gw for aid, gw in _GATEWAYS.items() if gw.is_running()}
+
+
+def known_gateways() -> Dict[str, DiscordGateway]:
+ return dict(_GATEWAYS)
+
+
+async def stop_all_gateways() -> None:
+ """Close every connection on shutdown.
+
+ Sessions left open count against the account's concurrent-session limit
+ until Discord times them out, which in a dev restart loop looks like a
+ second instance that will not go away.
+ """
+ for gateway in list(_GATEWAYS.values()):
+ try:
+ await gateway.stop()
+ except Exception as exc:
+ logger.debug("discord gateway stop failed", label=gateway.label, error=str(exc))
+
+
+__all__ = [
+ "DiscordGateway",
+ "READY_TIMEOUT_SECONDS",
+ "RestartPolicy",
+ "get_gateway",
+ "known_gateways",
+ "running_gateways",
+ "stop_all_gateways",
+]
diff --git a/server/nodes/discord/_handlers.py b/server/nodes/discord/_handlers.py
new file mode 100644
index 00000000..0cf5d89b
--- /dev/null
+++ b/server/nodes/discord/_handlers.py
@@ -0,0 +1,102 @@
+"""WebSocket commands for the credentials modal.
+
+The message-type strings are the frontend contract. Renaming one is a
+breaking change regardless of what happens on this side.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Awaitable, Callable, Dict
+
+from fastapi import WebSocket
+
+from core.logging import get_logger
+from services.plugin.ws import ws_response
+
+from ._accounts import DEFAULT_ACCOUNT, list_accounts
+
+logger = get_logger(__name__)
+
+
+def _account_id(data: Dict[str, Any]) -> str:
+ return (data or {}).get("account_id") or DEFAULT_ACCOUNT
+
+
+async def _snapshot() -> Dict[str, Any]:
+ """Every known account plus its live connection state.
+
+ Accounts come from stored credentials rather than from the gateway
+ registry, so one that has never been connected still appears.
+ """
+ from ._gateway import known_gateways
+
+ gateways = known_gateways()
+ accounts = []
+ for account in await list_accounts():
+ gateway = gateways.get(account.account_id)
+ entry = {
+ "account_id": account.account_id,
+ "label": account.label,
+ "application_id": account.application_id,
+ "connected": bool(gateway and gateway.is_running()),
+ }
+ if gateway is not None:
+ entry.update(gateway.status_snapshot())
+ accounts.append(entry)
+ return {
+ "connected": any(a["connected"] for a in accounts),
+ "accounts": accounts,
+ }
+
+
+@ws_response
+async def handle_discord_connect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ from ._gateway import get_gateway
+
+ gateway = await get_gateway(_account_id(data))
+ await gateway.start()
+ return {"success": True, **await _snapshot()}
+
+
+@ws_response
+async def handle_discord_disconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ from ._gateway import get_gateway
+
+ gateway = await get_gateway(_account_id(data))
+ await gateway.stop()
+ return {"success": True, **await _snapshot()}
+
+
+@ws_response
+async def handle_discord_reconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ from ._gateway import get_gateway
+
+ gateway = await get_gateway(_account_id(data))
+ # No RestartPolicy: a failed reconnect is usually a bad token or a
+ # missing intent, and retrying those spends the daily IDENTIFY budget to
+ # reach the same answer.
+ await gateway.restart()
+ return {"success": True, **await _snapshot()}
+
+
+@ws_response
+async def handle_discord_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ return {"success": True, **await _snapshot()}
+
+
+@ws_response
+async def handle_discord_accounts(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ snapshot = await _snapshot()
+ return {"success": True, "accounts": snapshot["accounts"]}
+
+
+WS_HANDLERS: Dict[str, Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]] = {
+ "discord_connect": handle_discord_connect,
+ "discord_disconnect": handle_discord_disconnect,
+ "discord_reconnect": handle_discord_reconnect,
+ "discord_status": handle_discord_status,
+ "discord_accounts": handle_discord_accounts,
+}
+
+
+__all__ = ["WS_HANDLERS"]
diff --git a/server/nodes/discord/_refresh.py b/server/nodes/discord/_refresh.py
new file mode 100644
index 00000000..9d4b2d12
--- /dev/null
+++ b/server/nodes/discord/_refresh.py
@@ -0,0 +1,69 @@
+"""Status refresh and trigger pre-check.
+
+The refresh is deliberately passive: it reports what is connected and does
+not connect anything. Telegram auto-reconnects here, but that plugin holds at
+most one bot. Firing up every stored Discord account on each WebSocket client
+connect would open sessions nobody asked for and spend the account's
+concurrent-session budget.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Dict, Optional
+
+from core.logging import get_logger
+
+if TYPE_CHECKING: # pragma: no cover
+ from services.status_broadcaster import StatusBroadcaster
+
+logger = get_logger(__name__)
+
+
+async def refresh_discord_status(broadcaster: "StatusBroadcaster") -> None:
+ """Broadcast per-account gateway state on WebSocket connect."""
+ try:
+ from ._accounts import list_accounts
+ from ._events import broadcast_discord_status
+ from ._gateway import known_gateways
+
+ gateways = known_gateways()
+ accounts = []
+ for account in await list_accounts():
+ gateway = gateways.get(account.account_id)
+ accounts.append(
+ {
+ "account_id": account.account_id,
+ "label": account.label,
+ "connected": bool(gateway and gateway.is_running()),
+ }
+ )
+
+ await broadcast_discord_status(
+ connected=any(a["connected"] for a in accounts),
+ accounts=accounts,
+ )
+ except Exception as exc:
+ # A failed refresh must never break a client connecting.
+ logger.debug("discord status refresh failed", error=str(exc))
+
+
+async def precheck_discord_trigger(parameters: Dict[str, Any]) -> Optional[str]:
+ """Refuse to arm a trigger with no connection behind it.
+
+ Returning a string short-circuits the wait with that message instead of
+ registering a waiter that can never resolve.
+ """
+ from ._accounts import DEFAULT_ACCOUNT
+ from ._gateway import known_gateways
+
+ account_id = (parameters or {}).get("account_id") or DEFAULT_ACCOUNT
+ gateway = known_gateways().get(account_id)
+ if gateway is None or not gateway.is_running():
+ return (
+ "Discord bot is not connected. Connect it from the Credentials modal "
+ "before deploying this trigger."
+ )
+ return None
+
+
+__all__ = ["precheck_discord_trigger", "refresh_discord_status"]
diff --git a/server/nodes/discord/discord_receive.py b/server/nodes/discord/discord_receive.py
new file mode 100644
index 00000000..7cdb13e4
--- /dev/null
+++ b/server/nodes/discord/discord_receive.py
@@ -0,0 +1,171 @@
+"""discordReceive — fire a workflow on an inbound Discord message.
+
+Attachments arrive as metadata only. Downloading here would put the payload
+into the trigger's result, which is persisted, broadcast and replayed into LLM
+context -- and on a deployed workflow this node body never runs at all, since
+the engine marks the trigger pre-executed and passes its output through
+verbatim. Wire discordAction[download_attachments] downstream to fetch them.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Callable, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.plugin import NodeContext, Operation, TaskQueue, TriggerNode
+
+from ._credentials import DiscordBotCredential
+from ._events import MESSAGE_RECEIVED_TYPE
+
+
+class DiscordAttachment(BaseModel):
+ """A reference to a Discord attachment, never its bytes.
+
+ ``url`` is signed and expires, so it is resolved at download time rather
+ than trusted from a stored node output.
+ """
+
+ id: Optional[str] = None
+ filename: Optional[str] = None
+ size: Optional[int] = None
+ url: Optional[str] = None
+ content_type: Optional[str] = None
+ width: Optional[int] = None
+ height: Optional[int] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class DiscordReceiveParams(BaseModel):
+ account_id: str = Field(
+ default="",
+ description="Which bot to listen as. Blank listens on the default credential.",
+ json_schema_extra={"loadOptionsMethod": "discordAccounts"},
+ )
+ scope: Literal["all", "guild", "dm"] = Field(
+ default="all",
+ description="Listen to server channels, direct messages, or both.",
+ )
+ guild_id: str = Field(
+ default="",
+ description="Only fire for this server.",
+ json_schema_extra={"displayOptions": {"show": {"scope": ["all", "guild"]}}},
+ )
+ channel_id: str = Field(
+ default="",
+ description="Only fire for this channel.",
+ )
+ author_id: str = Field(
+ default="",
+ description="Only fire for messages from this user.",
+ )
+ keywords: str = Field(
+ default="",
+ description="Comma-separated words; fires only if the message contains one.",
+ )
+ require_mention: bool = Field(
+ default=False,
+ description="Only fire when the bot is mentioned.",
+ )
+ require_attachment: bool = Field(
+ default=False,
+ description="Only fire for messages carrying a file.",
+ )
+ ignore_bots: bool = Field(
+ default=True,
+ description="Ignore messages from other bots. Leaving this off can create loops.",
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class DiscordReceiveOutput(BaseModel):
+ account_id: Optional[str] = None
+ message_id: Optional[str] = None
+ channel_id: Optional[str] = None
+ channel_name: Optional[str] = None
+ guild_id: Optional[str] = None
+ guild_name: Optional[str] = None
+ is_dm: Optional[bool] = None
+ author_id: Optional[str] = None
+ author_name: Optional[str] = None
+ author_display_name: Optional[str] = None
+ author_is_bot: Optional[bool] = None
+ content: Optional[str] = None
+ timestamp: Optional[str] = None
+ attachments: List[DiscordAttachment] = Field(default_factory=list)
+ has_attachments: Optional[bool] = None
+ mentions_me: Optional[bool] = None
+ reply_to_message_id: Optional[str] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class DiscordReceiveNode(TriggerNode):
+ type = "discordReceive"
+ display_name = "Discord Receive"
+ subtitle = "Inbound Message"
+ group = ("discord", "trigger")
+ description = "Trigger a workflow when a Discord message arrives"
+ component_kind = "trigger"
+ handles = (
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ credentials = (DiscordBotCredential,)
+ task_queue = TaskQueue.TRIGGERS_EVENT
+ mode = "event"
+ # Legacy snake_case key for the event-waiter registry. The CloudEvents
+ # type in _events.py is what the deployed listener actually routes on.
+ event_type = "discord_message_received"
+
+ Params = DiscordReceiveParams
+ Output = DiscordReceiveOutput
+
+ def build_filter(self, params: BaseModel) -> Callable[[Dict[str, Any]], bool]:
+ """Normally unreachable: the plugin pre-registers the builder with
+ event_waiter, which short-circuits the auto-populate path. Kept so the
+ contract holds if that registration is ever removed."""
+ from ._filters import build_discord_filter
+
+ return build_discord_filter(params.model_dump())
+
+ async def execute(
+ self, node_id: str, parameters: Dict[str, Any], context: NodeContext
+ ) -> Dict[str, Any]:
+ """Refuse to wait when no gateway is connected.
+
+ Without this the Run button registers a waiter that can never resolve,
+ which looks like a hung node rather than a missing connection.
+ """
+ import time
+
+ from ._accounts import DEFAULT_ACCOUNT
+ from ._gateway import known_gateways
+
+ account_id = (parameters or {}).get("account_id") or DEFAULT_ACCOUNT
+ gateway = known_gateways().get(account_id)
+ if gateway is None or not gateway.is_running():
+ return self._wrap_error(
+ start_time=time.time(),
+ error=(
+ "Discord bot is not connected. Connect it from the Credentials "
+ "modal before running this trigger."
+ ),
+ )
+ return await super().execute(node_id, parameters, context)
+
+ @Operation("wait")
+ async def wait(self, ctx: NodeContext, params: DiscordReceiveParams) -> DiscordReceiveOutput:
+ """Never called. Event triggers resolve through event_waiter; this
+ exists so the class satisfies the one-operation contract."""
+ raise NotImplementedError("discordReceive resolves through the event waiter")
+
+
+__all__ = [
+ "DiscordAttachment",
+ "DiscordReceiveNode",
+ "DiscordReceiveOutput",
+ "DiscordReceiveParams",
+ "MESSAGE_RECEIVED_TYPE",
+]
diff --git a/server/tests/nodes/test_discord.py b/server/tests/nodes/test_discord.py
index c8ad4d42..d00438b5 100644
--- a/server/tests/nodes/test_discord.py
+++ b/server/tests/nodes/test_discord.py
@@ -24,6 +24,7 @@ from nodes.discord._accounts import (
storage_scope,
)
from nodes.discord.discord_action import DiscordActionNode, DiscordActionParams
+from nodes.discord.discord_receive import DiscordReceiveNode
from nodes.discord.discord_send import (
MAX_CONTENT,
DiscordSendNode,
@@ -392,3 +393,265 @@ class TestToolSchema:
"""A Params field called `type` is silently dropped from the served
schema, so the node would ship a parameter the panel never renders."""
assert "type" not in node_cls.Params.model_fields
+
+
+class TestTriggerIsDeployable:
+ """Membership in the constants frozensets is what makes deploy see it.
+
+ Omitting a trigger there is a silent failure, not an error:
+ find_trigger_nodes filters on the set, so deploy simply ignores the node
+ -- no listener, no warning. constants.py says so in a comment for exactly
+ this reason.
+ """
+
+ def test_registered_for_deployment(self):
+ from constants import (
+ EVENT_TRIGGER_TYPES,
+ POLLING_TRIGGER_TYPES,
+ WORKFLOW_TRIGGER_TYPES,
+ )
+
+ assert DiscordReceiveNode.type in EVENT_TRIGGER_TYPES
+ assert DiscordReceiveNode.type in WORKFLOW_TRIGGER_TYPES
+ # Push-based: a polling entry would spawn a poll loop that duplicates
+ # every gateway event.
+ assert DiscordReceiveNode.type not in POLLING_TRIGGER_TYPES
+
+ def test_canary_type_matches_the_emitted_envelope(self):
+ """The registered string becomes the EventType Search Attribute the
+ Visibility query matches on. If it drifted from what the envelope
+ carries, the listener would start and never fire."""
+ from nodes.discord._events import MESSAGE_RECEIVED_TYPE, discord_message_received
+ from services.deployment.canary_registry import cloudevent_type_for
+
+ assert cloudevent_type_for(DiscordReceiveNode.type) == MESSAGE_RECEIVED_TYPE
+ assert discord_message_received({"channel_id": "c1"}).type == MESSAGE_RECEIVED_TYPE
+
+ def test_trigger_has_no_input_handles(self):
+ kinds = [h["kind"] for h in DiscordReceiveNode.handles]
+ assert "output" in kinds
+ assert "input" not in kinds
+
+ def test_filter_builder_is_registered(self):
+ from services.event_waiter import FILTER_BUILDERS
+
+ assert DiscordReceiveNode.type in FILTER_BUILDERS
+
+
+class TestEventShaping:
+ """_dispatch.shape_message feeds _filters; the two move together."""
+
+ def _message(self, **overrides):
+ base = SimpleNamespace(
+ id=111111111111111111,
+ content="hello",
+ created_at=None,
+ attachments=[],
+ mentions=[],
+ reference=None,
+ author=SimpleNamespace(id=222222222222222222, name="bob", display_name="Bob", bot=False),
+ guild=SimpleNamespace(id=333333333333333333, name="Guild"),
+ channel=SimpleNamespace(id=444444444444444444, name="general"),
+ _state=None,
+ )
+ for key, value in overrides.items():
+ setattr(base, key, value)
+ return base
+
+ def test_snowflakes_are_stringified(self):
+ """discord.py exposes ids as int. Past 2^53 a numeric comparison
+ collapses distinct ids, and comparing an id is the most natural edge
+ condition a user writes."""
+ from nodes.discord._dispatch import shape_message
+
+ event = shape_message(self._message(), account_id="default")
+ for field in ("message_id", "channel_id", "guild_id", "author_id"):
+ assert isinstance(event[field], str), field
+
+ def test_dm_has_no_guild(self):
+ from nodes.discord._dispatch import shape_message
+
+ event = shape_message(self._message(guild=None), account_id="default")
+ assert event["is_dm"] is True
+ assert event["guild_id"] is None
+
+ def test_attachments_are_metadata_not_bytes(self):
+ from nodes.discord._dispatch import shape_message
+
+ attachment = SimpleNamespace(
+ id=555555555555555555,
+ filename="a.png",
+ size=10,
+ url="https://cdn.discordapp.com/x",
+ content_type="image/png",
+ width=1,
+ height=2,
+ )
+ event = shape_message(self._message(attachments=[attachment]), account_id="default")
+
+ assert event["has_attachments"] is True
+ rendered = str(event["attachments"])
+ assert "bytes" not in rendered and "base64" not in rendered
+ assert event["attachments"][0]["id"] == "555555555555555555"
+
+
+class TestFilters:
+ def _event(self, **overrides):
+ base = {
+ "account_id": "default",
+ "content": "hello world",
+ "author_is_bot": False,
+ "is_dm": False,
+ "guild_id": "g1",
+ "channel_id": "c1",
+ "author_id": "u1",
+ "mentions_me": False,
+ "has_attachments": False,
+ }
+ base.update(overrides)
+ return base
+
+ def _matches(self, params, **event_overrides):
+ from nodes.discord._filters import build_discord_filter
+
+ return build_discord_filter(params)(self._event(**event_overrides))
+
+ def test_empty_filter_matches(self):
+ assert self._matches({})
+
+ def test_bots_ignored_by_default(self):
+ """Two bots replying to each other is the loop this prevents."""
+ assert not self._matches({}, author_is_bot=True)
+ assert self._matches({"ignore_bots": False}, author_is_bot=True)
+
+ def test_account_scoping(self):
+ """Without this, connecting a second bot makes every trigger fire
+ twice."""
+ assert not self._matches({"account_id": "other"})
+ assert self._matches({"account_id": "default"})
+
+ @pytest.mark.parametrize(
+ "params, overrides, expected",
+ [
+ ({"scope": "dm"}, {"is_dm": False}, False),
+ ({"scope": "dm"}, {"is_dm": True}, True),
+ ({"scope": "guild"}, {"is_dm": True}, False),
+ ({"guild_id": "g2"}, {}, False),
+ ({"channel_id": "c1"}, {}, True),
+ ({"author_id": "u2"}, {}, False),
+ ({"require_mention": True}, {}, False),
+ ({"require_mention": True}, {"mentions_me": True}, True),
+ ({"require_attachment": True}, {}, False),
+ ({"keywords": "world"}, {}, True),
+ ({"keywords": "absent"}, {}, False),
+ ({"keywords": "WORLD"}, {}, True),
+ ],
+ )
+ def test_filter_matrix(self, params, overrides, expected):
+ assert self._matches(params, **overrides) is expected
+
+
+class TestGatewayLifecycle:
+ def test_each_account_gets_its_own_label(self):
+ """The supervisor registry keys on the label; a shared one would mean
+ the second account silently replaced the first."""
+ from nodes.discord._gateway import DiscordGateway
+
+ assert DiscordGateway("a").label != DiscordGateway("b").label
+
+ def test_terminal_errors_are_not_retried(self):
+ """A bad token or an unapproved intent fails identically every time,
+ so retrying only spends the daily IDENTIFY budget."""
+ from nodes.discord._gateway import DiscordGateway
+
+ gateway = DiscordGateway("acct")
+ assert gateway.can_retry()
+
+ class PrivilegedIntentsRequired(Exception):
+ pass
+
+ translated = gateway._translate_start_error(PrivilegedIntentsRequired("nope"))
+ assert isinstance(translated, NodeUserError)
+ assert not gateway.can_retry()
+ assert "Message Content" in str(translated)
+
+ def test_unknown_errors_pass_through_for_retry(self):
+ from nodes.discord._gateway import DiscordGateway
+
+ gateway = DiscordGateway("acct")
+ original = ConnectionResetError("socket died")
+ assert gateway._translate_start_error(original) is original
+ assert gateway.can_retry()
+
+ def test_intents_request_message_content(self):
+ """Without it the gateway connects and delivers empty content, with
+ no error anywhere."""
+ import discord
+
+ from nodes.discord._gateway import _resolve_intents
+
+ intents = _resolve_intents(discord)
+ assert intents.message_content
+ assert intents.guild_messages
+ assert intents.dm_messages
+
+ def test_login_failure_surfaces_immediately(self):
+ """A rejected token raises inside client.start(), not out of
+ wait_until_ready(). Awaiting readiness alone would sit out the whole
+ 60s timeout and then report "not ready" for a bad credential."""
+ import sys
+
+ from nodes.discord._gateway import READY_TIMEOUT_SECONDS, DiscordGateway
+
+ class LoginFailure(Exception):
+ pass
+
+ class _FakeClient:
+ def __init__(self, *a, **kw):
+ self._closed = False
+ self.user = None
+ self.guilds = []
+
+ def event(self, fn):
+ return fn
+
+ def is_closed(self):
+ return self._closed
+
+ async def start(self, token):
+ raise LoginFailure("Improper token")
+
+ async def wait_until_ready(self):
+ await asyncio.sleep(READY_TIMEOUT_SECONDS * 10)
+
+ async def close(self):
+ self._closed = True
+
+ fake_discord = SimpleNamespace(
+ Client=_FakeClient,
+ Intents=SimpleNamespace(none=lambda: SimpleNamespace()),
+ )
+
+ async def _resolve(account_id):
+ return {"token": "bad"}
+
+ gateway = DiscordGateway("acct")
+ with (
+ patch.dict(sys.modules, {"discord": fake_discord}),
+ patch("nodes.discord._gateway.resolve_secrets", new=_resolve),
+ patch("nodes.discord._gateway._resolve_intents", return_value=None),
+ ):
+ with pytest.raises(NodeUserError) as excinfo:
+ _run(gateway._do_start())
+
+ assert "token" in str(excinfo.value).lower()
+ assert not gateway.can_retry()
+
+ def test_receive_refuses_to_wait_without_a_connection(self):
+ """Otherwise the Run button registers a waiter that can never
+ resolve, which reads as a hung node."""
+ from nodes.discord.discord_receive import DiscordReceiveNode
+
+ result = _run(DiscordReceiveNode().execute("d1", {}, _ctx()))
+ assert result["success"] is False
+ assert "not connected" in result["error"].lower()
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index f7a024e6..df7c2b06 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -79,6 +79,7 @@ _MIGRATED_PLUGINS = (
_PLUGINS_WITH_HANDLERS = (
"android",
"cloudflare",
+ "discord",
"gcloud",
"github",
"google",