Skip to content

Self-improving AI Employees for everyone

feat(discord): bot credential, REST layer, send and action nodes

trohitg99fd40909e32
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index 2badee38..16e2678b 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -382,6 +382,35 @@
],
"instructions": "Create a Meta app with the WhatsApp use case, then copy the Phone Number ID and WhatsApp Business Account ID from API Setup. Generate a permanent token under Business Settings > System users. The App Secret and Verify Token are only needed if you also want to receive messages."
},
+ "discord": {
+ "name": "Discord Bot",
+ "category": "social",
+ "category_label": "Social Media",
+ "color": "theme.categoryChat",
+ "kind": "apiKey",
+ "icon_ref": "/api/schemas/credentials/discord/icon",
+ "fields": [
+ {
+ "key": "apiKey",
+ "label": "Bot Token",
+ "type": "password",
+ "secret": true,
+ "placeholder": "Bot token from the Discord Developer Portal",
+ "required": true,
+ "help": "Bot > Token in the Discord Developer Portal. Resetting the token in Discord invalidates this one."
+ },
+ {
+ "key": "discord_application_id",
+ "label": "Application ID (optional)",
+ "type": "text",
+ "secret": false,
+ "placeholder": "e.g. 1234567890123456789",
+ "required": false,
+ "help": "General Information > Application ID. Used to label this bot when several are connected."
+ }
+ ],
+ "instructions": "Create an application in the Discord Developer Portal, add a Bot to it, and copy the token. Enable the Message Content intent under Bot > Privileged Gateway Intents, or inbound message text arrives empty. Invite the bot to a server with the bot scope before using it."
+ },
"twitter": {
"name": "Twitter/X",
"category": "social",
diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.json
index aa40ca8a..74564cf4 100644
--- a/server/config/node_allowlist.json
+++ b/server/config/node_allowlist.json
@@ -34,6 +34,9 @@
"telegramSend",
"telegramReceive",
+ "discordSend",
+ "discordAction",
+
"whatsappBusinessSend",
"whatsappBusinessReceive",
"whatsappBusinessStatus",
diff --git a/server/nodes/discord/__init__.py b/server/nodes/discord/__init__.py
new file mode 100644
index 00000000..d976ce62
--- /dev/null
+++ b/server/nodes/discord/__init__.py
@@ -0,0 +1,38 @@
+"""Discord plugin: bot messaging, REST actions and inbound events.
+
+Pure wiring. Importing the node modules is what registers them --
+``BaseNode.__init_subclass__`` does that work.
+
+``import discord`` never appears at module scope anywhere in this package.
+``nodes/__init__.py`` swallows import errors during discovery, so a library
+import that failed here would make the whole plugin silently disappear rather
+than report anything. The gateway imports it inside a function.
+"""
+
+from __future__ import annotations
+
+from services.node_output_schemas import register_output_schema
+from services.plugin.social_provider_registry import register_social_send_handler
+from services.ws_handler_registry import register_option_loader
+
+from ._credentials import DiscordBotCredential
+from ._option_loaders import load_accounts, load_channels, load_guilds
+from ._social import social_send_adapter
+from .discord_action import DiscordActionNode, DiscordActionOutput
+from .discord_send import DiscordSendNode, DiscordSendOutput
+
+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)
+
+# socialSend routes by platform id.
+register_social_send_handler("discord", social_send_adapter)
+
+__all__ = [
+ "DiscordActionNode",
+ "DiscordBotCredential",
+ "DiscordSendNode",
+]
diff --git a/server/nodes/discord/_accounts.py b/server/nodes/discord/_accounts.py
new file mode 100644
index 00000000..6d025c46
--- /dev/null
+++ b/server/nodes/discord/_accounts.py
@@ -0,0 +1,139 @@
+"""The one file that knows how a Discord account maps onto stored credentials.
+
+API keys are stored under a ``{session_id}_{provider}`` key, so the session_id
+column is a free scoping axis. A Discord bot account claims one scope:
+
+ account_id "default" -> session_id "default"
+ account_id "<app_id>" -> session_id "discord:<app_id>"
+
+``"default"`` is the row the unmodified credentials modal already writes, so a
+single-bot install needs no account concept at all and multi-account is purely
+additive.
+
+Everything else in the plugin asks this module for secrets and never touches
+session ids. ``ctx.connection()`` is deliberately not used for the account
+path: it resolves one fixed scope, so it can only ever reach the default
+account.
+
+Not to be confused with ``credential_customer_id`` (services/plugin/context.py),
+which is per-execution-context tenancy -- two nodes in one workflow could never
+target two different bots through it.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Dict, List
+
+CREDENTIAL_ID = "discord"
+DEFAULT_ACCOUNT = "default"
+
+# Stored per account scope. The token uses the bare credential id so the
+# existing modal, which writes provider="discord", lands on the default
+# account without special-casing.
+TOKEN_KEY = CREDENTIAL_ID
+APPLICATION_ID_KEY = "discord_application_id"
+PUBLIC_KEY_KEY = "discord_public_key"
+LABEL_KEY = "discord_label"
+
+_EXTRA_KEYS = (APPLICATION_ID_KEY, PUBLIC_KEY_KEY, LABEL_KEY)
+
+
+@dataclass(frozen=True)
+class AccountRef:
+ """What the account dropdown and the status panel need to show a bot."""
+
+ account_id: str
+ label: str
+ application_id: str
+ has_token: bool
+ has_public_key: bool
+
+
+def storage_scope(account_id: str) -> str:
+ """Map an account id onto the session_id its credentials live under."""
+ resolved = (account_id or "").strip()
+ if resolved in ("", DEFAULT_ACCOUNT):
+ return DEFAULT_ACCOUNT
+ return f"{CREDENTIAL_ID}:{resolved}"
+
+
+def account_id_from_scope(scope: str) -> str:
+ """Inverse of :func:`storage_scope`."""
+ prefix = f"{CREDENTIAL_ID}:"
+ return scope[len(prefix) :] if scope.startswith(prefix) else scope
+
+
+async def resolve_secrets(account_id: str = DEFAULT_ACCOUNT) -> Dict[str, Any]:
+ """Read one account's stored credential fields.
+
+ Raises:
+ PermissionError: annotated with provider/reason/auth so the framework
+ emits its credential envelope and the modal lights up the right
+ provider, matching ``ApiKeyCredential.resolve``.
+ """
+ from services.plugin.deps import get_auth_service
+
+ auth = get_auth_service()
+ scope = storage_scope(account_id)
+
+ token = await auth.get_api_key(TOKEN_KEY, scope)
+ if not token:
+ err = PermissionError(
+ f"No Discord bot token stored for account '{account_id or DEFAULT_ACCOUNT}'. "
+ "Add one via the Credentials modal."
+ )
+ err.provider = CREDENTIAL_ID # type: ignore[attr-defined]
+ err.reason = "missing" # type: ignore[attr-defined]
+ err.auth = "api_key" # type: ignore[attr-defined]
+ raise err
+
+ secrets: Dict[str, Any] = {"token": token}
+ for key in _EXTRA_KEYS:
+ value = await auth.get_api_key(key, scope)
+ if value:
+ secrets[key] = value
+ return secrets
+
+
+async def list_accounts() -> List[AccountRef]:
+ """Enumerate every account with a stored token.
+
+ Scopes come from the credential store rather than a separate index, so
+ there is nothing that can disagree with the rows themselves.
+ """
+ from services.plugin.deps import get_auth_service
+
+ auth = get_auth_service()
+ accounts: List[AccountRef] = []
+
+ for scope in await auth.list_key_scopes(TOKEN_KEY):
+ account_id = account_id_from_scope(scope)
+ application_id = await auth.get_api_key(APPLICATION_ID_KEY, scope) or ""
+ label = await auth.get_api_key(LABEL_KEY, scope) or ""
+ public_key = await auth.get_api_key(PUBLIC_KEY_KEY, scope) or ""
+ accounts.append(
+ AccountRef(
+ account_id=account_id,
+ label=label or application_id or account_id,
+ application_id=application_id,
+ has_token=True,
+ has_public_key=bool(public_key),
+ )
+ )
+ return accounts
+
+
+__all__ = [
+ "APPLICATION_ID_KEY",
+ "AccountRef",
+ "CREDENTIAL_ID",
+ "DEFAULT_ACCOUNT",
+ "LABEL_KEY",
+ "PUBLIC_KEY_KEY",
+ "TOKEN_KEY",
+ "account_id_from_scope",
+ "list_accounts",
+ "resolve_secrets",
+ "storage_scope",
+]
diff --git a/server/nodes/discord/_base.py b/server/nodes/discord/_base.py
new file mode 100644
index 00000000..af355155
--- /dev/null
+++ b/server/nodes/discord/_base.py
@@ -0,0 +1,315 @@
+"""Shared HTTP plumbing for the Discord nodes.
+
+One place owns the API version pin, the request helper, the path guard and the
+error translation, so the node files hold message shaping and nothing else.
+
+REST lives here rather than going through discord.py's HTTPClient. The nodes
+must work with no gateway connection at all, ``discordAction`` needs arbitrary
+routes the library's typed methods do not expose, and the invalid-request
+guard has to be process-wide across accounts, which a per-client limiter
+cannot express.
+"""
+
+from __future__ import annotations
+
+import json as jsonlib
+from typing import Any, Dict, Optional, Tuple
+
+import httpx
+
+from core.logging import get_logger
+from services.plugin import ActionNode, NodeUserError
+
+from . import _ratelimit
+from ._accounts import CREDENTIAL_ID, DEFAULT_ACCOUNT, resolve_secrets
+
+logger = get_logger(__name__)
+
+
+class AccountScopedNode(ActionNode, abstract=True):
+ """ActionNode whose ``server_controlled_fields`` survive the tool path.
+
+ ``BaseNode.execute_as_tool`` enforces ``server_controlled_fields`` only in
+ its ToolNode branch. A dual-purpose ActionNode takes an earlier return
+ that merges ``{**node_params, **tool_args}`` with model arguments winning,
+ so the declaration alone protects nothing here.
+
+ That matters because inbound Discord messages are the realistic source of
+ hostile tool arguments, and ``account_id`` selects which bot identity
+ sends. Stripping the locked fields from the model's arguments before the
+ merge is what makes the declaration real. whatsapp_business solves the
+ same problem by sourcing its sending number from the credential instead;
+ that is not available here, because choosing between several stored
+ accounts is the point.
+ """
+
+ async def execute_as_tool(
+ self,
+ tool_args: Dict[str, Any],
+ node_params: Dict[str, Any],
+ context: Any,
+ ) -> Dict[str, Any]:
+ locked = getattr(type(self), "server_controlled_fields", frozenset())
+ sanitized = {k: v for k, v in (tool_args or {}).items() if k not in locked}
+ return await super().execute_as_tool(sanitized, node_params, context)
+
+API_BASE_URL = "https://discord.com/api"
+
+# Pinned, never interpolated per call site. Discord keeps old versions alive
+# for a long time, so drift shows up as behaviour changes rather than errors.
+API_VERSION = "v10"
+
+# Discord blocks requests without a descriptive User-Agent. The format is
+# documented and enforced.
+USER_AGENT = "DiscordBot (https://github.com/trohitg/opencompany, 1.0)"
+
+REQUEST_TIMEOUT_SECONDS = 30.0
+
+# Only these hosts may receive a bot token or a webhook post.
+_ALLOWED_HOSTS = frozenset({"discord.com", "discordapp.com", "ptb.discord.com", "canary.discord.com"})
+
+
+# --------------------------------------------------------------------------
+# Error classification
+# --------------------------------------------------------------------------
+#
+# Discord returns a numeric JSON error code alongside the HTTP status. The
+# split that matters is retryable-vs-terminal: NodeUserError is in the shared
+# non-retryable list, so classifying a transient failure as one fails fast
+# instead of backing off, and classifying a permanent rejection as retryable
+# burns three attempts to reach the same answer.
+#
+# Codes from discord.com/developers/topics/opcodes-and-status-codes
+
+# The token is wrong or was reset. Retrying with the same token cannot help.
+# Code 0 is deliberately absent: Discord uses it for a general/malformed
+# request, and it is also what an empty error body parses to, so treating it
+# as auth would mislabel every unclassified failure.
+_AUTH_CODES = frozenset({40001, 50014})
+
+# The bot is authenticated but lacks access. Terminal until someone changes
+# permissions in Discord.
+_PERMISSION_CODES = frozenset({50001, 50013, 50021, 160002})
+
+# The target does not exist, or the request is malformed. User-correctable.
+_NOT_FOUND_CODES = frozenset({10003, 10004, 10008, 10013, 10062})
+
+
+def classify_error(code: int, status_code: int) -> Tuple[str, bool]:
+ """Return ``(category, retryable)`` for a Discord error."""
+ if code in _AUTH_CODES or status_code == 401:
+ return "auth", False
+ if code in _PERMISSION_CODES or status_code == 403:
+ return "permission", False
+ if code in _NOT_FOUND_CODES or status_code == 404:
+ return "not_found", False
+ if status_code == 429:
+ return "throttle", True
+ if status_code >= 500:
+ return "transient", True
+ return "unknown", False
+
+
+def _friendly_message(code: int, category: str, detail: str) -> str:
+ if category == "auth":
+ return (
+ f"Discord rejected the bot token. Check it in the Credentials modal; "
+ f"a reset token must be re-copied from the Developer Portal. "
+ f"(error {code}: {detail})"
+ )
+ if category == "permission":
+ return (
+ f"The bot lacks permission for this action. Check its role and the "
+ f"channel's permission overwrites in Discord. (error {code}: {detail})"
+ )
+ if category == "not_found":
+ return (
+ f"Discord could not find that resource. Check the id, and that the "
+ f"bot is in the server. (error {code}: {detail})"
+ )
+ return f"Discord API error {code}: {detail}"
+
+
+def raise_for_discord_error(payload: Dict[str, Any], status_code: int) -> None:
+ """Translate a Discord error body into the right exception type."""
+ code = int((payload or {}).get("code") or 0)
+ detail = (payload or {}).get("message") or "no detail provided"
+ category, retryable = classify_error(code, status_code)
+
+ logger.warning(
+ "discord api error",
+ code=code,
+ category=category,
+ retryable=retryable,
+ status_code=status_code,
+ errors=(payload or {}).get("errors"),
+ )
+
+ if category == "auth":
+ # An annotated PermissionError gets the framework's credential
+ # envelope and a reconnect affordance that a NodeUserError does not.
+ exc = PermissionError(_friendly_message(code, category, detail))
+ exc.provider = CREDENTIAL_ID # type: ignore[attr-defined]
+ exc.reason = "invalid" # type: ignore[attr-defined]
+ exc.auth = "api_key" # type: ignore[attr-defined]
+ raise exc
+
+ if retryable:
+ raise RuntimeError(_friendly_message(code, category, detail))
+
+ raise NodeUserError(_friendly_message(code, category, detail))
+
+
+# --------------------------------------------------------------------------
+# Path handling
+# --------------------------------------------------------------------------
+
+
+def build_url(path: str) -> str:
+ """Join a relative API path onto the pinned base, refusing anything else.
+
+ ``discordAction``'s custom operation lets a workflow name its own route.
+ Without this guard that is an SSRF primitive that would send the bot token
+ to whatever host the path pointed at, so the check lives here rather than
+ in the node -- no future call site can skip it.
+ """
+ candidate = (path or "").strip()
+ if not candidate:
+ raise NodeUserError("An API path is required, for example 'users/@me'.")
+ if "://" in candidate or candidate.startswith("//"):
+ raise NodeUserError(
+ f"'{path}' looks like a full URL. Give a path relative to the Discord "
+ "API instead, for example 'channels/123/messages'."
+ )
+ if ".." in candidate:
+ raise NodeUserError(f"'{path}' may not contain '..'.")
+ return f"{API_BASE_URL}/{API_VERSION}/{candidate.lstrip('/')}"
+
+
+def assert_discord_host(url: str) -> None:
+ """Refuse to post to anything but Discord.
+
+ Used for the webhook URL, which is operator-supplied and is itself the
+ credential -- posting it anywhere else both leaks it and is an SSRF.
+ """
+ host = httpx.URL(url).host
+ if host not in _ALLOWED_HOSTS:
+ raise NodeUserError(
+ f"'{host}' is not a Discord host. A webhook URL looks like "
+ "https://discord.com/api/webhooks/<id>/<token>."
+ )
+
+
+# --------------------------------------------------------------------------
+# Requests
+# --------------------------------------------------------------------------
+
+
+def _parse(response: httpx.Response) -> Dict[str, Any]:
+ if not response.content:
+ return {}
+ try:
+ parsed = response.json()
+ except (ValueError, jsonlib.JSONDecodeError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {"data": parsed}
+
+
+async def request(
+ method: str,
+ path: str,
+ *,
+ account_id: str = DEFAULT_ACCOUNT,
+ json: Optional[Any] = None,
+ params: Optional[Dict[str, Any]] = None,
+ files: Optional[Any] = None,
+ data: Optional[Dict[str, Any]] = None,
+ token: Optional[str] = None,
+) -> Any:
+ """Call the Discord API for one account and translate failures.
+
+ Args:
+ token: Pre-resolved bot token. Saves a credential read when the caller
+ already holds one; otherwise it is resolved from ``account_id``.
+ """
+ url = build_url(path)
+ bot_token = token or (await resolve_secrets(account_id))["token"]
+
+ guard = _ratelimit.invalid_request_guard()
+ guard.check()
+ limiter = _ratelimit.limiter_for(account_id)
+ await limiter.acquire()
+
+ headers = {
+ # Not ApiKeyCredential.inject: its "bearer" mode hardcodes the literal
+ # "Bearer " prefix, and Discord bot auth is "Bot <token>".
+ "Authorization": f"Bot {bot_token}",
+ "User-Agent": USER_AGENT,
+ }
+
+ async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS) as client:
+ response = await client.request(
+ method, url, headers=headers, json=json, params=params, files=files, data=data
+ )
+
+ guard.record(response.status_code)
+
+ if response.status_code == 429:
+ response_headers = dict(response.headers)
+ if _ratelimit.is_cloudflare_ban(response_headers):
+ raise NodeUserError(
+ "Discord's edge is rejecting this host's requests outright, which "
+ "happens after too many invalid requests. It clears on its own; "
+ "check that stored bot tokens are valid before retrying."
+ )
+ payload = _parse(response)
+ retry_after = _ratelimit.parse_retry_after(payload, response_headers)
+ if _ratelimit.is_global_limit(payload, response_headers):
+ limiter.hold(retry_after)
+ raise _ratelimit.RateLimitExceeded(retry_after)
+
+ payload = _parse(response)
+ if response.status_code >= 400:
+ raise_for_discord_error(payload, response.status_code)
+
+ # 204 No Content is the success shape for deletes.
+ return payload
+
+
+async def get(path: str, *, account_id: str = DEFAULT_ACCOUNT, params: Optional[Dict[str, Any]] = None) -> Any:
+ return await request("GET", path, account_id=account_id, params=params)
+
+
+async def post(
+ path: str,
+ body: Optional[Any] = None,
+ *,
+ account_id: str = DEFAULT_ACCOUNT,
+ files: Optional[Any] = None,
+ data: Optional[Dict[str, Any]] = None,
+) -> Any:
+ return await request("POST", path, account_id=account_id, json=body, files=files, data=data)
+
+
+async def patch(path: str, body: Optional[Any] = None, *, account_id: str = DEFAULT_ACCOUNT) -> Any:
+ return await request("PATCH", path, account_id=account_id, json=body)
+
+
+async def delete(path: str, *, account_id: str = DEFAULT_ACCOUNT) -> Any:
+ return await request("DELETE", path, account_id=account_id)
+
+
+__all__ = [
+ "API_BASE_URL",
+ "API_VERSION",
+ "USER_AGENT",
+ "assert_discord_host",
+ "build_url",
+ "classify_error",
+ "delete",
+ "get",
+ "patch",
+ "post",
+ "raise_for_discord_error",
+ "request",
+]
diff --git a/server/nodes/discord/_credentials.py b/server/nodes/discord/_credentials.py
new file mode 100644
index 00000000..a16b818f
--- /dev/null
+++ b/server/nodes/discord/_credentials.py
@@ -0,0 +1,94 @@
+"""Discord bot-token credential."""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+import httpx
+
+from services.plugin.credential import ApiKeyCredential, ProbeResult
+
+from ._accounts import APPLICATION_ID_KEY, LABEL_KEY, PUBLIC_KEY_KEY
+
+# Application flags. The message-content intent is privileged: without it the
+# gateway delivers empty `content` on most messages and reports no error at
+# all, which surfaces as "the Discord node returns blank text". Reading it at
+# validation time is the only cheap way to warn before that happens.
+_FLAG_MESSAGE_CONTENT = 1 << 18
+_FLAG_MESSAGE_CONTENT_LIMITED = 1 << 19
+
+
+class DiscordBotCredential(ApiKeyCredential):
+ id = "discord"
+ display_name = "Discord Bot"
+ category = "Social"
+ key_name = "Authorization"
+ key_location = "header"
+ extra_fields = (APPLICATION_ID_KEY, PUBLIC_KEY_KEY, LABEL_KEY)
+ docs_url = "https://discord.com/developers/docs/intro"
+
+ @classmethod
+ def inject(cls, secrets: Dict[str, Any], request: Dict[str, Any]) -> Dict[str, Any]:
+ """Attach ``Authorization: Bot <token>``.
+
+ The inherited implementation offers header / query / bearer, and
+ "bearer" hardcodes the literal ``Bearer `` prefix. Discord bot auth
+ uses ``Bot ``, and sending the wrong scheme is a silent 401.
+ """
+ headers = dict(request.get("headers") or {})
+ headers["Authorization"] = f"Bot {secrets.get('api_key', '')}"
+ return {**request, "headers": headers}
+
+ @classmethod
+ async def _probe(cls, api_key: str) -> ProbeResult:
+ """Identify the bot, and report whether message content is available.
+
+ Two calls: ``/users/@me`` proves the token, ``/applications/@me``
+ carries the flags. The second is best-effort -- a token valid for the
+ first but not the second is still a usable token.
+ """
+ from ._base import API_BASE_URL, API_VERSION, USER_AGENT
+
+ headers = {"Authorization": f"Bot {api_key}", "User-Agent": USER_AGENT}
+ base = f"{API_BASE_URL}/{API_VERSION}"
+
+ async with httpx.AsyncClient(timeout=cls.probe_timeout_seconds) as client:
+ response = await client.get(f"{base}/users/@me", headers=headers)
+ response.raise_for_status()
+ user = response.json()
+
+ flags = 0
+ application_id = ""
+ try:
+ app_response = await client.get(f"{base}/applications/@me", headers=headers)
+ if app_response.status_code == 200:
+ application = app_response.json()
+ flags = int(application.get("flags") or 0)
+ application_id = str(application.get("id") or "")
+ except httpx.HTTPError:
+ pass
+
+ username = user.get("username") or "unknown"
+ has_message_content = bool(flags & (_FLAG_MESSAGE_CONTENT | _FLAG_MESSAGE_CONTENT_LIMITED))
+
+ message = f"Connected as {username}"
+ if not has_message_content:
+ message += (
+ ". Note: the Message Content intent is not enabled, so inbound "
+ "message text will be empty. Enable it under Bot > Privileged "
+ "Gateway Intents in the Developer Portal."
+ )
+
+ return ProbeResult(
+ valid=True,
+ message=message,
+ extra={
+ "bot_id": str(user.get("id") or ""),
+ "bot_username": username,
+ "application_id": application_id or str(user.get("id") or ""),
+ "has_message_content_intent": has_message_content,
+ },
+ )
+
+
+__all__ = ["DiscordBotCredential"]
diff --git a/server/nodes/discord/_events.py b/server/nodes/discord/_events.py
new file mode 100644
index 00000000..40420107
--- /dev/null
+++ b/server/nodes/discord/_events.py
@@ -0,0 +1,92 @@
+"""CloudEvents factories for the Discord plugin.
+
+The type constants live here and nowhere else. The canary registration in
+``__init__.py`` passes the same string to
+``register_canary_trigger_type``, where it becomes the ``EventType`` Search
+Attribute a Temporal Visibility query matches on. If the two ever differed,
+the trigger listener would start cleanly and then never fire -- a failure with
+no error anywhere.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Mapping
+
+from services.events.envelope import WorkflowEvent
+
+SOURCE = "opencompany://nodes/discord"
+
+MESSAGE_RECEIVED_TYPE = "com.opencompany.discord.message.received"
+INTERACTION_CREATED_TYPE = "com.opencompany.discord.interaction.created"
+CONNECTION_OPENED_TYPE = "com.opencompany.discord.connection.opened"
+CONNECTION_CLOSED_TYPE = "com.opencompany.discord.connection.closed"
+
+# Shared across plugins; the frontend routes on envelope.source.
+STATUS_WIRE_KEY = "plugin_connection_status"
+MESSAGE_WIRE_KEY = "discord_message_received"
+
+
+def discord_message_received(event_data: Mapping[str, Any]) -> WorkflowEvent:
+ """Envelope for one inbound Discord message."""
+ return WorkflowEvent(
+ source=SOURCE,
+ type=MESSAGE_RECEIVED_TYPE,
+ # Snowflakes are stringified upstream, in _dispatch. The envelope
+ # requires a string subject regardless.
+ subject=str(event_data.get("channel_id") or ""),
+ data=dict(event_data),
+ )
+
+
+def discord_connection_status(
+ *,
+ connected: bool,
+ accounts: list[dict[str, Any]] | None = None,
+) -> WorkflowEvent:
+ """Envelope describing every account's gateway state.
+
+ ``connected`` stays a plain boolean so single-connection renderers keep
+ working; per-account detail rides in ``accounts``.
+ """
+ return WorkflowEvent(
+ source=SOURCE,
+ type=CONNECTION_OPENED_TYPE if connected else CONNECTION_CLOSED_TYPE,
+ subject="discord",
+ data={"connected": connected, "accounts": accounts or []},
+ )
+
+
+async def broadcast_discord_status(
+ *, connected: bool, accounts: list[dict[str, Any]] | None = None
+) -> None:
+ from services.status_broadcaster import get_status_broadcaster
+
+ event = discord_connection_status(connected=connected, accounts=accounts)
+ broadcaster = get_status_broadcaster()
+ await broadcaster.broadcast(
+ {"type": STATUS_WIRE_KEY, "data": event.model_dump(mode="json", exclude_none=True)}
+ )
+
+
+async def dispatch_discord_message_received(event_data: Mapping[str, Any]) -> None:
+ """Single delivery path: Temporal listeners and the in-process socket.
+
+ ``emit`` is a no-op unless ``Settings.event_framework_enabled``, so the
+ legacy path stays the default.
+ """
+ from services.events.dispatch import emit
+
+ await emit(discord_message_received(event_data), wire_routing_key=MESSAGE_WIRE_KEY)
+
+
+__all__ = [
+ "CONNECTION_CLOSED_TYPE",
+ "CONNECTION_OPENED_TYPE",
+ "INTERACTION_CREATED_TYPE",
+ "MESSAGE_RECEIVED_TYPE",
+ "SOURCE",
+ "broadcast_discord_status",
+ "discord_connection_status",
+ "discord_message_received",
+ "dispatch_discord_message_received",
+]
diff --git a/server/nodes/discord/_option_loaders.py b/server/nodes/discord/_option_loaders.py
new file mode 100644
index 00000000..73ec4381
--- /dev/null
+++ b/server/nodes/discord/_option_loaders.py
@@ -0,0 +1,70 @@
+"""Dropdown loaders for the parameter panel."""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+async def load_accounts(params: Dict[str, Any] | None = None) -> List[Dict[str, str]]:
+ """Bot accounts with a stored token.
+
+ The blank entry is first and is not a placeholder: it selects the default
+ credential, which is what a single-bot install has.
+ """
+ from ._accounts import DEFAULT_ACCOUNT, list_accounts
+
+ options = [{"name": "Default credential", "value": ""}]
+ for account in await list_accounts():
+ if account.account_id == DEFAULT_ACCOUNT:
+ continue
+ options.append({"name": account.label, "value": account.account_id})
+ return options
+
+
+async def load_guilds(params: Dict[str, Any] | None = None) -> List[Dict[str, str]]:
+ """Servers the bot is a member of."""
+ from . import _base
+ from ._accounts import DEFAULT_ACCOUNT
+
+ account_id = (params or {}).get("account_id") or DEFAULT_ACCOUNT
+ try:
+ guilds = await _base.get("users/@me/guilds", account_id=account_id)
+ except Exception as exc:
+ # A dropdown that cannot load must not break the panel.
+ logger.debug("discord guild list unavailable", error=str(exc))
+ return []
+ return [
+ {"name": g.get("name") or g.get("id", ""), "value": str(g.get("id", ""))}
+ for g in (guilds if isinstance(guilds, list) else [])
+ ]
+
+
+async def load_channels(params: Dict[str, Any] | None = None) -> List[Dict[str, str]]:
+ """Text channels in the selected server."""
+ from . import _base
+ from ._accounts import DEFAULT_ACCOUNT
+
+ params = params or {}
+ guild_id = params.get("guild_id")
+ if not guild_id:
+ return []
+ account_id = params.get("account_id") or DEFAULT_ACCOUNT
+ try:
+ channels = await _base.get(f"guilds/{guild_id}/channels", account_id=account_id)
+ except Exception as exc:
+ logger.debug("discord channel list unavailable", error=str(exc))
+ return []
+ # Types 0 and 5 are text and announcement channels; the rest cannot take
+ # a plain message.
+ return [
+ {"name": f"#{c.get('name', '')}", "value": str(c.get("id", ""))}
+ for c in (channels if isinstance(channels, list) else [])
+ if c.get("type") in (0, 5)
+ ]
+
+
+__all__ = ["load_accounts", "load_channels", "load_guilds"]
diff --git a/server/nodes/discord/_ratelimit.py b/server/nodes/discord/_ratelimit.py
new file mode 100644
index 00000000..2237faa6
--- /dev/null
+++ b/server/nodes/discord/_ratelimit.py
@@ -0,0 +1,189 @@
+"""Discord rate-limit bookkeeping. Pure state, no IO.
+
+Reactive rather than predictive: this reads 429 responses and holds requests
+that follow, but does not track ``X-RateLimit-Remaining`` to sleep before
+hitting zero. Preemptive per-bucket accounting is a real optimisation and a
+real pile of state; it can be added when 429s actually show up.
+
+Three scopes, and conflating any two of them is a bug:
+
+* per account -- the global 50 req/s ceiling is per bot token.
+* per account -- a global 429 pauses that token's traffic entirely.
+* **per process** -- the invalid-request ban is enforced by Cloudflare on the
+ source IP, not the token. Three misconfigured bots on one host share one
+ budget, and blowing it bans the host including the healthy accounts. This is
+ the piece most likely to get "simplified" into the per-account limiter later.
+ It must not be.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from typing import Dict, Optional
+
+# Discord's documented global ceiling for a bot token.
+GLOBAL_REQUESTS_PER_SECOND = 50
+
+# Cloudflare bans an IP for 10 minutes past 10,000 invalid responses (401,
+# 403, 429) in a 10-minute window. Stopping early is the whole point: the ban
+# takes out every account on the host, so local failure is strictly cheaper.
+INVALID_REQUEST_WINDOW_SECONDS = 600
+INVALID_REQUEST_LIMIT = 10_000
+INVALID_REQUEST_SAFETY_MARGIN = 9_000
+_INVALID_STATUSES = frozenset({401, 403, 429})
+
+# Past this, holding an activity slot open costs more than failing and letting
+# Temporal's own backoff re-dispatch. Well under the 10-minute activity budget.
+MAX_INLINE_WAIT_SECONDS = 30.0
+
+
+class RateLimitExceeded(RuntimeError):
+ """A wait too long to sit through. Retryable: Temporal re-dispatches.
+
+ Deliberately not NodeUserError -- that type is non-retryable, so raising
+ one here would turn a transient throttle into a permanent failure.
+ """
+
+ def __init__(self, retry_after: float, scope: str = "") -> None:
+ super().__init__(
+ f"Discord rate limit: retry after {retry_after:.1f}s"
+ + (f" (scope={scope})" if scope else "")
+ )
+ self.retry_after = retry_after
+ self.scope = scope
+
+
+class InvalidRequestBudgetExhausted(RuntimeError):
+ """Local stop before Cloudflare bans the host IP."""
+
+
+class _InvalidRequestGuard:
+ """Process-wide, shared across every account. See the module docstring."""
+
+ def __init__(self) -> None:
+ self._events: list[float] = []
+
+ def record(self, status_code: int, now: Optional[float] = None) -> None:
+ if status_code not in _INVALID_STATUSES:
+ return
+ moment = now if now is not None else time.monotonic()
+ self._events.append(moment)
+ self._prune(moment)
+
+ def _prune(self, now: float) -> None:
+ cutoff = now - INVALID_REQUEST_WINDOW_SECONDS
+ self._events = [t for t in self._events if t >= cutoff]
+
+ def count(self, now: Optional[float] = None) -> int:
+ moment = now if now is not None else time.monotonic()
+ self._prune(moment)
+ return len(self._events)
+
+ def check(self, now: Optional[float] = None) -> None:
+ if self.count(now) >= INVALID_REQUEST_SAFETY_MARGIN:
+ raise InvalidRequestBudgetExhausted(
+ "Too many rejected Discord requests from this host in the last "
+ "10 minutes. Continuing would trigger a Cloudflare IP ban "
+ "affecting every Discord account on this server. Check that "
+ "stored bot tokens are valid and that the bot has access to "
+ "the channels being used."
+ )
+
+
+_INVALID_REQUEST_GUARD = _InvalidRequestGuard()
+
+
+def invalid_request_guard() -> _InvalidRequestGuard:
+ return _INVALID_REQUEST_GUARD
+
+
+class AccountLimiter:
+ """Per-token pacing and global-429 hold."""
+
+ def __init__(self, requests_per_second: int = GLOBAL_REQUESTS_PER_SECOND) -> None:
+ self._min_interval = 1.0 / max(requests_per_second, 1)
+ self._last_request = 0.0
+ self._hold_until = 0.0
+ self._lock = asyncio.Lock()
+
+ async def acquire(self) -> None:
+ """Pace one request, waiting out any active global hold."""
+ async with self._lock:
+ now = time.monotonic()
+ wait = max(self._hold_until - now, self._last_request + self._min_interval - now)
+ if wait > MAX_INLINE_WAIT_SECONDS:
+ raise RateLimitExceeded(wait, "global")
+ if wait > 0:
+ await asyncio.sleep(wait)
+ self._last_request = time.monotonic()
+
+ def hold(self, seconds: float) -> None:
+ self._hold_until = max(self._hold_until, time.monotonic() + seconds)
+
+
+def parse_retry_after(payload: Optional[dict], headers: Optional[dict]) -> float:
+ """Seconds to wait after a 429.
+
+ The JSON body carries sub-second precision; the ``Retry-After`` header is
+ rounded to whole seconds, so it is only the fallback. Both are attacker-
+ adjacent input, so a malformed value degrades to 1s rather than raising.
+ """
+ if payload:
+ value = payload.get("retry_after")
+ if isinstance(value, (int, float)) and value >= 0:
+ return float(value)
+ if headers:
+ raw = headers.get("Retry-After") or headers.get("retry-after")
+ try:
+ parsed = float(raw) # type: ignore[arg-type]
+ if parsed >= 0:
+ return parsed
+ except (TypeError, ValueError):
+ pass
+ return 1.0
+
+
+def is_global_limit(payload: Optional[dict], headers: Optional[dict]) -> bool:
+ if payload and payload.get("global") is True:
+ return True
+ headers = headers or {}
+ scope = headers.get("X-RateLimit-Scope") or headers.get("x-ratelimit-scope")
+ return scope == "global"
+
+
+def is_cloudflare_ban(headers: Optional[dict]) -> bool:
+ """A 429 that is not Discord's.
+
+ Discord's own 429 is always JSON. An HTML one is the edge rejecting the
+ host IP, which is a different problem with a different remedy -- and one
+ that looks like an hour of unexplained rate limiting if reported as a
+ normal throttle.
+ """
+ content_type = (headers or {}).get("Content-Type") or (headers or {}).get("content-type") or ""
+ return "application/json" not in content_type.lower()
+
+
+_LIMITERS: Dict[str, AccountLimiter] = {}
+
+
+def limiter_for(account_id: str) -> AccountLimiter:
+ """Per-account limiter, created on first use and kept for the process."""
+ limiter = _LIMITERS.get(account_id)
+ if limiter is None:
+ limiter = AccountLimiter()
+ _LIMITERS[account_id] = limiter
+ return limiter
+
+
+__all__ = [
+ "AccountLimiter",
+ "InvalidRequestBudgetExhausted",
+ "MAX_INLINE_WAIT_SECONDS",
+ "RateLimitExceeded",
+ "invalid_request_guard",
+ "is_cloudflare_ban",
+ "is_global_limit",
+ "limiter_for",
+ "parse_retry_after",
+]
diff --git a/server/nodes/discord/_social.py b/server/nodes/discord/_social.py
new file mode 100644
index 00000000..ee8db054
--- /dev/null
+++ b/server/nodes/discord/_social.py
@@ -0,0 +1,43 @@
+"""Adapter mapping ``socialSend``'s generic shape onto discordSend.
+
+Registered as the ``"discord"`` platform from this package's ``__init__.py``.
+The send operation is called on the node itself rather than reimplemented, so
+the splitting, attachment handling and error mapping stay in one place.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from services.plugin import NodeUserError
+
+
+async def social_send_adapter(payload: Dict[str, Any], ctx: Any) -> Dict[str, Any]:
+ """Translate a ``socialSend`` payload into a ``discordSend`` call."""
+ from .discord_send import DiscordSendNode, DiscordSendParams
+
+ recipient = payload.get("recipient", "")
+ recipient_type = payload.get("recipient_type", "channel")
+ message_type = payload.get("message_type", "text")
+
+ if message_type != "text":
+ raise NodeUserError(
+ f"socialSend can only send text through Discord, not '{message_type}'. "
+ "Use the discordSend node for embeds and attachments."
+ )
+
+ # socialSend addresses a person as "user" and everything else by id.
+ target_type = "user" if recipient_type == "user" else "channel"
+ params = DiscordSendParams(
+ target_type=target_type,
+ channel_id="" if target_type == "user" else recipient,
+ user_id=recipient if target_type == "user" else "",
+ message=payload.get("message", ""),
+ )
+ result = await DiscordSendNode().send(ctx, params)
+
+ # The operation raises on failure, so reaching here is success.
+ return {"success": True, **result.model_dump(mode="json", exclude_none=True)}
+
+
+__all__ = ["social_send_adapter"]
diff --git a/server/nodes/discord/discord.svg b/server/nodes/discord/discord.svg
new file mode 100644
index 00000000..da7ee22f
--- /dev/null
+++ b/server/nodes/discord/discord.svg
@@ -0,0 +1 @@
+<svg role="img" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><title>Discord</title><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg>
diff --git a/server/nodes/discord/discord_action.py b/server/nodes/discord/discord_action.py
new file mode 100644
index 00000000..3574af2d
--- /dev/null
+++ b/server/nodes/discord/discord_action.py
@@ -0,0 +1,391 @@
+"""discordAction — the rest of the Discord REST surface.
+
+Includes ``download_attachments``, which is where inbound media is fetched.
+It is an operation here rather than a flag on the trigger because a deployed
+trigger never runs its node body -- the engine marks it pre-executed and
+passes its output through verbatim -- so a download flag there would work on
+the canvas and silently do nothing once deployed. Wiring
+``discordReceive -> discordAction`` puts the fetch on the workflow's own time.
+This mirrors whatsappBusinessMedia, which exists for the same reason.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.plugin import NodeContext, NodeUserError, Operation, TaskQueue
+
+from . import _base
+from ._accounts import DEFAULT_ACCOUNT
+from ._base import AccountScopedNode
+from ._credentials import DiscordBotCredential
+
+
+def _show(**conditions: Any) -> Dict[str, Any]:
+ """displayOptions helper. The frontend ANDs the conditions."""
+ return {"displayOptions": {"show": conditions}}
+
+
+class DiscordActionParams(BaseModel):
+ operation: Literal[
+ "list_guilds",
+ "list_channels",
+ "get_channel",
+ "create_thread",
+ "list_messages",
+ "get_message",
+ "edit_message",
+ "delete_message",
+ "add_reaction",
+ "pin_message",
+ "download_attachments",
+ "execute_webhook",
+ "custom",
+ ] = Field(default="list_channels", description="What to do.")
+
+ account_id: str = Field(
+ default="",
+ description="Which Discord bot to act as. Blank uses the default credential.",
+ json_schema_extra={"loadOptionsMethod": "discordAccounts"},
+ )
+
+ guild_id: str = Field(
+ default="",
+ description="Server ID.",
+ json_schema_extra=_show(operation=["list_channels"]),
+ )
+ channel_id: str = Field(
+ default="",
+ description="Channel ID.",
+ json_schema_extra=_show(
+ operation=[
+ "get_channel",
+ "create_thread",
+ "list_messages",
+ "get_message",
+ "edit_message",
+ "delete_message",
+ "add_reaction",
+ "pin_message",
+ ]
+ ),
+ )
+ message_id: str = Field(
+ default="",
+ description="Message ID.",
+ json_schema_extra=_show(
+ operation=["get_message", "edit_message", "delete_message", "add_reaction", "pin_message"]
+ ),
+ )
+ content: str = Field(
+ default="",
+ description="Replacement message text.",
+ json_schema_extra={"rows": 3, **_show(operation=["edit_message"])},
+ )
+ emoji: str = Field(
+ default="",
+ description="Emoji to react with, e.g. a unicode emoji or name:id for a custom one.",
+ json_schema_extra=_show(operation=["add_reaction"]),
+ )
+ thread_name: str = Field(
+ default="",
+ description="Name for the new thread.",
+ json_schema_extra=_show(operation=["create_thread"]),
+ )
+ limit: int = Field(
+ default=50,
+ ge=1,
+ le=100,
+ description="How many messages to return.",
+ json_schema_extra=_show(operation=["list_messages"]),
+ )
+
+ attachments: List[dict] = Field(
+ default_factory=list,
+ description=(
+ "Attachment objects from a discordReceive message. Each needs url "
+ "and filename."
+ ),
+ json_schema_extra=_show(operation=["download_attachments"]),
+ )
+
+ webhook_url: str = Field(
+ default="",
+ description="Discord webhook URL. Posts without a bot token.",
+ json_schema_extra={"password": True, **_show(operation=["execute_webhook"])},
+ )
+ webhook_content: str = Field(
+ default="",
+ description="Message to post through the webhook.",
+ json_schema_extra={"rows": 3, **_show(operation=["execute_webhook"])},
+ )
+
+ method: Literal["GET", "POST", "PATCH", "PUT", "DELETE"] = Field(
+ default="GET",
+ description="HTTP method for the custom call.",
+ json_schema_extra=_show(operation=["custom"]),
+ )
+ path: str = Field(
+ default="",
+ description="API path relative to the Discord API root, e.g. 'users/@me'.",
+ json_schema_extra=_show(operation=["custom"]),
+ )
+ body: dict = Field(
+ default_factory=dict,
+ description="JSON body for the custom call.",
+ json_schema_extra=_show(operation=["custom"]),
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class DiscordActionOutput(BaseModel):
+ # Parsed API response. A list result lands in `items` so the declared
+ # shape stays an object.
+ result: Optional[dict] = None
+ items: List[Any] = Field(default_factory=list)
+ count: Optional[int] = None
+ # download_attachments returns references, never bytes.
+ files: List[dict] = Field(default_factory=list)
+
+ model_config = ConfigDict(extra="allow")
+
+
+class DiscordActionNode(AccountScopedNode):
+ type = "discordAction"
+ display_name = "Discord"
+ subtitle = "Discord API"
+ group = ("discord",)
+ description = "Read and manage Discord servers, channels, messages and attachments"
+ component_kind = "square"
+ tool_name = "discord"
+ tool_description = (
+ "Work with Discord: list servers and channels, read and manage messages, "
+ "add reactions, create threads, and download attachments from an inbound "
+ "message into the workspace."
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ credentials = (DiscordBotCredential,)
+ annotations = {"destructive": True, "readonly": False, "open_world": True}
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+ # See DiscordSendNode: which bot acts is operator configuration.
+ server_controlled_fields = frozenset({"account_id"})
+ hide_input_handle = False
+ hide_output_handle = False
+
+ Params = DiscordActionParams
+ Output = DiscordActionOutput
+
+ # ---- reads ----------------------------------------------------------
+
+ @Operation("list_guilds", cost={"service": "discord", "action": "list_guilds", "count": 1})
+ async def list_guilds(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ result = await _base.get("users/@me/guilds", account_id=self._account(params))
+ return _as_list(result)
+
+ @Operation("list_channels", cost={"service": "discord", "action": "list_channels", "count": 1})
+ async def list_channels(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ guild_id = _require(params.guild_id, "guild ID")
+ result = await _base.get(f"guilds/{guild_id}/channels", account_id=self._account(params))
+ return _as_list(result)
+
+ @Operation("get_channel")
+ async def get_channel(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ result = await _base.get(f"channels/{channel_id}", account_id=self._account(params))
+ return DiscordActionOutput(result=result)
+
+ @Operation("list_messages", cost={"service": "discord", "action": "list_messages", "count": 1})
+ async def list_messages(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ result = await _base.get(
+ f"channels/{channel_id}/messages",
+ account_id=self._account(params),
+ params={"limit": params.limit},
+ )
+ return _as_list(result)
+
+ @Operation("get_message")
+ async def get_message(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ message_id = _require(params.message_id, "message ID")
+ result = await _base.get(
+ f"channels/{channel_id}/messages/{message_id}", account_id=self._account(params)
+ )
+ return DiscordActionOutput(result=result)
+
+ # ---- writes ---------------------------------------------------------
+
+ @Operation("edit_message", cost={"service": "discord", "action": "edit_message", "count": 1})
+ async def edit_message(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ message_id = _require(params.message_id, "message ID")
+ result = await _base.patch(
+ f"channels/{channel_id}/messages/{message_id}",
+ {"content": params.content},
+ account_id=self._account(params),
+ )
+ return DiscordActionOutput(result=result)
+
+ @Operation("delete_message", cost={"service": "discord", "action": "delete_message", "count": 1})
+ async def delete_message(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ message_id = _require(params.message_id, "message ID")
+ await _base.delete(
+ f"channels/{channel_id}/messages/{message_id}", account_id=self._account(params)
+ )
+ return DiscordActionOutput(result={"deleted": True, "message_id": message_id})
+
+ @Operation("add_reaction")
+ async def add_reaction(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ from urllib.parse import quote
+
+ channel_id = _require(params.channel_id, "channel ID")
+ message_id = _require(params.message_id, "message ID")
+ emoji = _require(params.emoji, "emoji")
+ await _base.request(
+ "PUT",
+ f"channels/{channel_id}/messages/{message_id}/reactions/{quote(emoji, safe='')}/@me",
+ account_id=self._account(params),
+ )
+ return DiscordActionOutput(result={"reacted": True, "emoji": emoji})
+
+ @Operation("pin_message")
+ async def pin_message(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ message_id = _require(params.message_id, "message ID")
+ await _base.request(
+ "PUT", f"channels/{channel_id}/pins/{message_id}", account_id=self._account(params)
+ )
+ return DiscordActionOutput(result={"pinned": True, "message_id": message_id})
+
+ @Operation("create_thread", cost={"service": "discord", "action": "create_thread", "count": 1})
+ async def create_thread(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ channel_id = _require(params.channel_id, "channel ID")
+ name = _require(params.thread_name, "thread name")
+ # 11 is GUILD_PUBLIC_THREAD.
+ result = await _base.post(
+ f"channels/{channel_id}/threads",
+ {"name": name, "type": 11},
+ account_id=self._account(params),
+ )
+ return DiscordActionOutput(result=result)
+
+ # ---- media ----------------------------------------------------------
+
+ @Operation("download_attachments", cost={"service": "discord", "action": "download", "count": 1})
+ async def download_attachments(
+ self, ctx: NodeContext, params: DiscordActionParams
+ ) -> DiscordActionOutput:
+ """Fetch inbound attachments into the workspace as references.
+
+ Discord CDN URLs are signed and expire, so they are fetched here and
+ not persisted. ``fetch_to_workspace`` performs the SSRF check, streams
+ with a size cap and writes inside the workspace root.
+ """
+ from services.media import fetch_to_workspace
+ from services.media.preview import preview_kind
+
+ if not params.attachments:
+ raise NodeUserError(
+ "No attachments supplied. Connect a discordReceive node and map "
+ "its `attachments` output into this field."
+ )
+
+ files: List[dict] = []
+ for attachment in params.attachments:
+ url = (attachment or {}).get("url")
+ if not url:
+ continue
+ filename = (attachment or {}).get("filename") or "attachment"
+ stem = filename.rsplit(".", 1)[0] or "attachment"
+ mime_type = (attachment or {}).get("content_type") or ""
+ ref = await fetch_to_workspace(
+ url,
+ ctx=ctx,
+ stem=stem,
+ # Never "audio": that kind asserts a real container probe, and
+ # a download measures nothing.
+ kind=_ref_kind(preview_kind(mime_type)),
+ )
+ files.append(ref.model_dump(mode="json"))
+
+ return DiscordActionOutput(files=files, count=len(files))
+
+ # ---- escape hatches -------------------------------------------------
+
+ @Operation("execute_webhook", cost={"service": "discord", "action": "execute_webhook", "count": 1})
+ async def execute_webhook(
+ self, ctx: NodeContext, params: DiscordActionParams
+ ) -> DiscordActionOutput:
+ """Post through a webhook URL, which carries its own auth.
+
+ No bot token is involved, so this reaches channels the bot is not in.
+ """
+ import httpx
+
+ url = _require(params.webhook_url, "webhook URL")
+ _base.assert_discord_host(url)
+ content = _require(params.webhook_content, "message")
+
+ async with httpx.AsyncClient(timeout=_base.REQUEST_TIMEOUT_SECONDS) as client:
+ response = await client.post(
+ url,
+ json={"content": content},
+ headers={"User-Agent": _base.USER_AGENT},
+ params={"wait": "true"},
+ )
+ if response.status_code >= 400:
+ # Never echo the URL: it is the credential.
+ raise NodeUserError(
+ f"Discord rejected the webhook post with HTTP {response.status_code}. "
+ "Check that the webhook still exists."
+ )
+ return DiscordActionOutput(result=response.json() if response.content else {"sent": True})
+
+ @Operation("custom", cost={"service": "discord", "action": "custom", "count": 1})
+ async def custom(self, ctx: NodeContext, params: DiscordActionParams) -> DiscordActionOutput:
+ """Call any Discord API route. The path is validated in _base.build_url."""
+ path = _require(params.path, "API path")
+ result = await _base.request(
+ params.method,
+ path,
+ account_id=self._account(params),
+ json=params.body or None,
+ )
+ if isinstance(result, dict) and "data" in result and isinstance(result["data"], list):
+ return _as_list(result["data"])
+ return DiscordActionOutput(result=result if isinstance(result, dict) else None)
+
+ # ---- helpers --------------------------------------------------------
+
+ @staticmethod
+ def _account(params: DiscordActionParams) -> str:
+ return params.account_id or DEFAULT_ACCOUNT
+
+
+def _require(value: str, label: str) -> str:
+ cleaned = (value or "").strip()
+ if not cleaned:
+ raise NodeUserError(f"A {label} is required for this operation.")
+ return cleaned
+
+
+def _as_list(result: Any) -> DiscordActionOutput:
+ """Wrap a list response so the declared Output stays an object."""
+ items = result.get("data") if isinstance(result, dict) else result
+ items = items if isinstance(items, list) else []
+ return DiscordActionOutput(items=items, count=len(items))
+
+
+def _ref_kind(preview: str) -> str:
+ return preview if preview in {"image", "video"} else "file"
+
+
+__all__ = ["DiscordActionNode", "DiscordActionOutput", "DiscordActionParams"]
diff --git a/server/nodes/discord/discord_send.py b/server/nodes/discord/discord_send.py
new file mode 100644
index 00000000..4cfba27f
--- /dev/null
+++ b/server/nodes/discord/discord_send.py
@@ -0,0 +1,239 @@
+"""discordSend — post a message to a channel or a user.
+
+Separate from ``discordAction`` for the same reason telegram and
+whatsapp_business split send from the rest: it is the high-frequency
+agent-facing operation, and a focused schema makes a far better LLM tool than
+a twenty-operation union.
+"""
+
+from __future__ import annotations
+
+import json as jsonlib
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.plugin import NodeContext, NodeUserError, Operation, TaskQueue
+
+from . import _base
+from ._accounts import DEFAULT_ACCOUNT
+from ._base import AccountScopedNode
+from ._credentials import DiscordBotCredential
+
+# Discord counts message content in Unicode code points, so len() is the right
+# measure here -- unlike Telegram, which measures UTF-16 code units.
+MAX_CONTENT = 2000
+
+# Suppresses the link/embed preview on the sent message.
+_FLAG_SUPPRESS_EMBEDS = 1 << 2
+
+
+def split_content(text: str, limit: int = MAX_CONTENT) -> List[str]:
+ """Split at the cleanest boundary that still fills most of a chunk.
+
+ Preferring a paragraph, then a line, then a sentence keeps code blocks and
+ lists intact far more often than a hard cut. The halfway floor stops a
+ boundary near the start from producing a stream of tiny messages.
+ """
+ if not text:
+ return []
+
+ chunks: List[str] = []
+ remaining = text
+ while len(remaining) > limit:
+ window = remaining[:limit]
+ cut = -1
+ for boundary in ("\n\n", "\n", ". ", "! ", "? ", " "):
+ found = window.rfind(boundary)
+ if found > limit // 2:
+ cut = found + len(boundary)
+ break
+ if cut <= 0:
+ cut = limit
+ chunks.append(remaining[:cut].rstrip())
+ remaining = remaining[cut:].lstrip()
+ if remaining:
+ chunks.append(remaining)
+ return chunks
+
+
+class DiscordSendParams(BaseModel):
+ account_id: str = Field(
+ default="",
+ description="Which Discord bot to send as. Blank uses the default credential.",
+ json_schema_extra={"loadOptionsMethod": "discordAccounts"},
+ )
+ target_type: Literal["channel", "user"] = Field(
+ default="channel",
+ description="Post in a channel, or open a DM with a user.",
+ )
+ channel_id: str = Field(
+ default="",
+ description="Channel ID. Enable Developer Mode in Discord to copy one.",
+ json_schema_extra={"displayOptions": {"show": {"target_type": ["channel"]}}},
+ )
+ user_id: str = Field(
+ default="",
+ description="User ID. A DM channel is opened automatically.",
+ json_schema_extra={"displayOptions": {"show": {"target_type": ["user"]}}},
+ )
+ message: str = Field(
+ default="",
+ description="Message text. Longer than 2000 characters is split across messages.",
+ json_schema_extra={"rows": 4},
+ )
+ embeds: List[dict] = Field(
+ default_factory=list,
+ description="Rich embed objects. Up to 10, 6000 characters across all of them.",
+ )
+ attachment: Any = Field(
+ default=None,
+ description="A file to attach.",
+ json_schema_extra={"widget": "file", "accept": "*/*"},
+ )
+ reply_to_message_id: str = Field(
+ default="",
+ description="Reply to a message by ID.",
+ )
+ suppress_embeds: bool = Field(
+ default=False,
+ description="Hide link previews on this message.",
+ )
+ tts: bool = Field(
+ default=False,
+ description="Send as a text-to-speech message.",
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class DiscordSendOutput(BaseModel):
+ message_id: Optional[str] = None
+ channel_id: Optional[str] = None
+ # Populated when the text was long enough to split.
+ parts: Optional[int] = None
+ message_ids: List[str] = Field(default_factory=list)
+
+ model_config = ConfigDict(extra="allow")
+
+
+class DiscordSendNode(AccountScopedNode):
+ type = "discordSend"
+ display_name = "Discord Send"
+ subtitle = "Send Message"
+ group = ("discord",)
+ description = "Send a message, embed or file to a Discord channel or user"
+ component_kind = "square"
+ tool_name = "discord_send"
+ tool_description = (
+ "Send a message to a Discord channel or user. Supports plain text, rich "
+ "embeds and a file attachment."
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ credentials = (DiscordBotCredential,)
+ annotations = {"destructive": False, "readonly": False, "open_world": True}
+ task_queue = TaskQueue.MESSAGING
+ usable_as_tool = True
+ # Which bot sends is operator configuration, not a model decision.
+ # AccountScopedNode is what enforces this on the tool path.
+ server_controlled_fields = frozenset({"account_id"})
+ # Canvas handles are auto-hidden for usable_as_tool nodes; this one is
+ # meant to be wired into a workflow as well.
+ hide_input_handle = False
+ hide_output_handle = False
+
+ Params = DiscordSendParams
+ Output = DiscordSendOutput
+
+ @Operation("send", cost={"service": "discord", "action": "send", "count": 1})
+ async def send(self, ctx: NodeContext, params: DiscordSendParams) -> DiscordSendOutput:
+ account_id = params.account_id or DEFAULT_ACCOUNT
+ channel_id = await self._resolve_channel(params, account_id)
+
+ if not params.message.strip() and not params.embeds and params.attachment in (None, ""):
+ raise NodeUserError("Provide a message, an embed or an attachment to send.")
+
+ if len(params.embeds) > 10:
+ raise NodeUserError(f"Discord accepts at most 10 embeds; got {len(params.embeds)}.")
+
+ chunks = split_content(params.message) or [""]
+ flags = _FLAG_SUPPRESS_EMBEDS if params.suppress_embeds else 0
+
+ message_ids: List[str] = []
+ first: Dict[str, Any] = {}
+
+ for index, chunk in enumerate(chunks):
+ is_last = index == len(chunks) - 1
+ body: Dict[str, Any] = {"content": chunk, "tts": params.tts}
+ if flags:
+ body["flags"] = flags
+ # Embeds and the attachment ride the final message so they appear
+ # after the text they belong to.
+ if is_last and params.embeds:
+ body["embeds"] = params.embeds
+ if index == 0 and params.reply_to_message_id.strip():
+ body["message_reference"] = {"message_id": params.reply_to_message_id.strip()}
+
+ if is_last and params.attachment not in (None, ""):
+ sent = await self._post_with_attachment(ctx, channel_id, body, params, account_id)
+ else:
+ sent = await _base.post(
+ f"channels/{channel_id}/messages", body, account_id=account_id
+ )
+
+ message_id = str(sent.get("id") or "")
+ if message_id:
+ message_ids.append(message_id)
+ if index == 0:
+ first = sent
+
+ return DiscordSendOutput(
+ message_id=str(first.get("id") or ""),
+ channel_id=str(first.get("channel_id") or channel_id),
+ parts=len(chunks) if len(chunks) > 1 else None,
+ message_ids=message_ids,
+ )
+
+ async def _resolve_channel(self, params: DiscordSendParams, account_id: str) -> str:
+ """Channel id to post to, opening a DM channel when targeting a user."""
+ if params.target_type == "user":
+ user_id = params.user_id.strip()
+ if not user_id:
+ raise NodeUserError("A user ID is required to send a direct message.")
+ dm = await _base.post("users/@me/channels", {"recipient_id": user_id}, account_id=account_id)
+ return str(dm.get("id") or "")
+
+ channel_id = params.channel_id.strip()
+ if not channel_id:
+ raise NodeUserError("A channel ID is required. Enable Developer Mode in Discord to copy one.")
+ return channel_id
+
+ async def _post_with_attachment(
+ self,
+ ctx: NodeContext,
+ channel_id: str,
+ body: Dict[str, Any],
+ params: DiscordSendParams,
+ account_id: str,
+ ) -> Dict[str, Any]:
+ """Send as multipart, with the JSON body alongside the file part.
+
+ The file is passed as bytes rather than a handle: the request layer may
+ replay the same kwargs, and a consumed handle would resend as empty.
+ """
+ from services.media import coerce_file_param
+
+ filename, blob = coerce_file_param(params.attachment, ctx=ctx)
+ body["attachments"] = [{"id": 0, "filename": filename}]
+ return await _base.post(
+ f"channels/{channel_id}/messages",
+ account_id=account_id,
+ files={"files[0]": (filename, blob)},
+ data={"payload_json": jsonlib.dumps(body)},
+ )
+
+
+__all__ = ["DiscordSendNode", "DiscordSendOutput", "DiscordSendParams", "split_content"]
diff --git a/server/nodes/discord/icon.svg b/server/nodes/discord/icon.svg
new file mode 100644
index 00000000..da7ee22f
--- /dev/null
+++ b/server/nodes/discord/icon.svg
@@ -0,0 +1 @@
+<svg role="img" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><title>Discord</title><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg>
diff --git a/server/nodes/discord/meta.json b/server/nodes/discord/meta.json
new file mode 100644
index 00000000..b8f0e88f
--- /dev/null
+++ b/server/nodes/discord/meta.json
@@ -0,0 +1 @@
+{"color": "#5865F2"}
diff --git a/server/nodes/groups.py b/server/nodes/groups.py
index 457c28b9..5e62d852 100644
--- a/server/nodes/groups.py
+++ b/server/nodes/groups.py
@@ -58,6 +58,7 @@ register_group(
key="whatsapp_business",
metadata={"label": "WhatsApp Business", "icon": "💼", "color": "#128C7E", "visibility": "normal"},
)
+register_group(key="discord", metadata={"label": "Discord", "icon": "💬", "color": "#5865F2", "visibility": "dev"})
register_group(key="email", metadata={"label": "Email", "icon": "✉️", "color": "#8be9fd", "visibility": "dev"})
register_group(key="payments", metadata={"label": "Payments", "icon": "asset:stripe", "color": "#635BFF", "visibility": "dev"})
register_group(key="deployment", metadata={"label": "Deployment", "icon": "lobehub:Vercel", "color": "#666666", "visibility": "dev"})
diff --git a/server/tests/nodes/test_discord.py b/server/tests/nodes/test_discord.py
new file mode 100644
index 00000000..c8ad4d42
--- /dev/null
+++ b/server/tests/nodes/test_discord.py
@@ -0,0 +1,394 @@
+"""Contract for the Discord plugin.
+
+The security-relevant test is ``TestModelCannotChooseTheAccount``. On a
+dual-purpose ActionNode ``BaseNode.execute_as_tool`` merges
+``{**node_params, **tool_args}`` with model arguments winning, so the only
+thing standing between a prompt injection in an inbound Discord message and
+sending as a different bot is ``server_controlled_fields``. This asserts it
+actually holds through the real tool path, not just the schema.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import typing
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from nodes.discord import _base, _ratelimit
+from nodes.discord._accounts import (
+ DEFAULT_ACCOUNT,
+ account_id_from_scope,
+ storage_scope,
+)
+from nodes.discord.discord_action import DiscordActionNode, DiscordActionParams
+from nodes.discord.discord_send import (
+ MAX_CONTENT,
+ DiscordSendNode,
+ DiscordSendParams,
+ split_content,
+)
+from services.plugin import NodeUserError
+
+pytestmark = pytest.mark.unit
+
+
+def _run(coro):
+ return asyncio.new_event_loop().run_until_complete(coro)
+
+
+def _ctx(**raw):
+ return SimpleNamespace(
+ node_id="discord-1",
+ node_type="discordSend",
+ workflow_id="wf-1",
+ session_id="default",
+ user_id="owner",
+ workspace_dir=None,
+ outputs={},
+ nodes=[],
+ edges=[],
+ raw=dict(raw),
+ )
+
+
+class TestAccountScoping:
+ """account_id <-> session_id is the whole multi-account mechanism."""
+
+ def test_default_account_uses_the_unprefixed_scope(self):
+ """The credentials modal writes session_id="default" with no account
+ concept at all. If that did not map to the default account, a
+ single-bot install would see no credential."""
+ assert storage_scope("") == DEFAULT_ACCOUNT
+ assert storage_scope(DEFAULT_ACCOUNT) == DEFAULT_ACCOUNT
+
+ def test_named_account_is_namespaced(self):
+ assert storage_scope("123456") == "discord:123456"
+
+ @pytest.mark.parametrize("account_id", ["", "default", "123456", "999"])
+ def test_scope_round_trips(self, account_id):
+ expected = account_id or DEFAULT_ACCOUNT
+ assert account_id_from_scope(storage_scope(account_id)) == expected
+
+ def test_scope_does_not_collide_with_another_provider(self):
+ """The prefix is what keeps a Discord account from reading a scope
+ some other plugin created."""
+ assert storage_scope("123").startswith("discord:")
+
+
+class TestPathGuard:
+ """discordAction's custom operation lets a workflow name its own route.
+
+ Without this guard that is an SSRF primitive that would send the bot
+ token to an arbitrary host.
+ """
+
+ def test_relative_path_is_joined_onto_the_pinned_base(self):
+ assert _base.build_url("users/@me") == f"{_base.API_BASE_URL}/{_base.API_VERSION}/users/@me"
+
+ def test_leading_slash_is_tolerated(self):
+ assert _base.build_url("/users/@me").endswith("/users/@me")
+
+ @pytest.mark.parametrize(
+ "path",
+ [
+ "https://evil.example/steal",
+ "http://evil.example/steal",
+ "//evil.example/steal",
+ "../../../etc/passwd",
+ "users/../../admin",
+ "",
+ " ",
+ ],
+ )
+ def test_escaping_paths_are_refused(self, path):
+ with pytest.raises(NodeUserError):
+ _base.build_url(path)
+
+ @pytest.mark.parametrize("url", ["https://evil.example/api/webhooks/1/t", "https://discord.com.evil.io/x"])
+ def test_webhook_host_is_whitelisted(self, url):
+ with pytest.raises(NodeUserError):
+ _base.assert_discord_host(url)
+
+ def test_real_webhook_host_is_allowed(self):
+ _base.assert_discord_host("https://discord.com/api/webhooks/1/token")
+
+
+class TestErrorClassification:
+ """The split that matters is retryable vs terminal.
+
+ NodeUserError is non-retryable in the shared policy, so classifying a
+ throttle as one fails fast instead of backing off; classifying a
+ permanent rejection as retryable burns three attempts to reach the same
+ answer.
+ """
+
+ @pytest.mark.parametrize(
+ "code, status, category, retryable",
+ [
+ (0, 401, "auth", False),
+ (40001, 401, "auth", False),
+ (50001, 403, "permission", False),
+ (50013, 403, "permission", False),
+ (10003, 404, "not_found", False),
+ (0, 429, "throttle", True),
+ (0, 500, "transient", True),
+ (0, 502, "transient", True),
+ (0, 400, "unknown", False),
+ ],
+ )
+ def test_classification(self, code, status, category, retryable):
+ assert _base.classify_error(code, status) == (category, retryable)
+
+ def test_auth_failure_raises_annotated_permission_error(self):
+ """An annotated PermissionError gets the framework's credential
+ envelope and a reconnect affordance; a NodeUserError does not."""
+ with pytest.raises(PermissionError) as excinfo:
+ _base.raise_for_discord_error({"code": 40001, "message": "Unauthorized"}, 401)
+ assert excinfo.value.provider == "discord"
+ assert excinfo.value.reason == "invalid"
+ assert excinfo.value.auth == "api_key"
+
+ def test_permission_failure_is_a_user_error(self):
+ with pytest.raises(NodeUserError):
+ _base.raise_for_discord_error({"code": 50013, "message": "Missing Permissions"}, 403)
+
+ def test_server_failure_is_retryable_not_a_user_error(self):
+ with pytest.raises(RuntimeError) as excinfo:
+ _base.raise_for_discord_error({"code": 0, "message": "boom"}, 502)
+ assert not isinstance(excinfo.value, NodeUserError)
+
+
+class TestRateLimit:
+ def test_body_retry_after_beats_the_rounded_header(self):
+ """The header is whole seconds; the body carries sub-second
+ precision. Preferring the header would over-wait on every 429."""
+ assert _ratelimit.parse_retry_after({"retry_after": 0.35}, {"Retry-After": "1"}) == 0.35
+
+ def test_header_is_the_fallback(self):
+ assert _ratelimit.parse_retry_after(None, {"Retry-After": "2"}) == 2.0
+
+ def test_malformed_retry_after_degrades_instead_of_raising(self):
+ """These values are attacker-adjacent; a parse error must not become
+ an unhandled exception mid-send."""
+ assert _ratelimit.parse_retry_after({"retry_after": "soon"}, {"Retry-After": "nope"}) == 1.0
+
+ def test_global_limit_detected_from_body_or_scope_header(self):
+ assert _ratelimit.is_global_limit({"global": True}, {})
+ assert _ratelimit.is_global_limit(None, {"X-RateLimit-Scope": "global"})
+ assert not _ratelimit.is_global_limit({"global": False}, {"X-RateLimit-Scope": "user"})
+
+ def test_non_json_429_is_recognised_as_the_edge_ban(self):
+ """Discord's own 429 is always JSON. An HTML one is Cloudflare
+ rejecting the host IP, which has a different remedy and would
+ otherwise read as an hour of unexplained rate limiting."""
+ assert _ratelimit.is_cloudflare_ban({"Content-Type": "text/html"})
+ assert not _ratelimit.is_cloudflare_ban({"Content-Type": "application/json"})
+
+ def test_invalid_request_guard_trips_before_the_ban(self):
+ guard = _ratelimit._InvalidRequestGuard()
+ for _ in range(_ratelimit.INVALID_REQUEST_SAFETY_MARGIN):
+ guard.record(401, now=1000.0)
+ with pytest.raises(_ratelimit.InvalidRequestBudgetExhausted):
+ guard.check(now=1000.0)
+
+ def test_guard_only_counts_rejections(self):
+ guard = _ratelimit._InvalidRequestGuard()
+ for _ in range(100):
+ guard.record(200, now=1000.0)
+ assert guard.count(now=1000.0) == 0
+
+ def test_guard_window_expires(self):
+ guard = _ratelimit._InvalidRequestGuard()
+ guard.record(429, now=1000.0)
+ assert guard.count(now=1000.0) == 1
+ assert guard.count(now=1000.0 + _ratelimit.INVALID_REQUEST_WINDOW_SECONDS + 1) == 0
+
+ def test_guard_is_process_wide(self):
+ """The ban is enforced per source IP, not per token, so three bots on
+ one host share one budget. A per-account guard would not stop the
+ ban it exists to prevent."""
+ assert _ratelimit.invalid_request_guard() is _ratelimit.invalid_request_guard()
+
+
+class TestContentSplitting:
+ def test_short_text_is_one_chunk(self):
+ assert split_content("hello") == ["hello"]
+
+ def test_empty_text_produces_no_chunks(self):
+ assert split_content("") == []
+
+ def test_every_chunk_is_within_the_limit(self):
+ chunks = split_content("word " * 2000)
+ assert chunks
+ assert all(len(c) <= MAX_CONTENT for c in chunks)
+
+ def test_split_prefers_a_paragraph_boundary(self):
+ first = "a" * 1200
+ second = "b" * 1200
+ chunks = split_content(f"{first}\n\n{second}")
+ assert chunks[0] == first
+
+ def test_unsplittable_text_is_hard_cut_rather_than_dropped(self):
+ text = "x" * 5000
+ chunks = split_content(text)
+ assert all(len(c) <= MAX_CONTENT for c in chunks)
+ assert "".join(chunks) == text
+
+
+class TestModelCannotChooseTheAccount:
+ """Which bot sends is operator configuration, not a model decision."""
+
+ def test_tool_args_cannot_override_the_configured_account(self):
+ node = DiscordSendNode()
+ captured = {}
+
+ async def _fake_post(path, body=None, *, account_id=DEFAULT_ACCOUNT, **kwargs):
+ captured["account_id"] = account_id
+ captured["path"] = path
+ return {"id": "123", "channel_id": "c1"}
+
+ with patch("nodes.discord.discord_send._base.post", new=_fake_post):
+ _run(
+ node.execute_as_tool(
+ {"channel_id": "c1", "message": "hi", "account_id": "ATTACKER"},
+ {"account_id": "operator-account", "channel_id": "c1"},
+ _ctx(),
+ )
+ )
+
+ assert captured["account_id"] == "operator-account"
+
+ def test_account_is_declared_server_controlled_on_both_nodes(self):
+ for node_cls in (DiscordSendNode, DiscordActionNode):
+ assert "account_id" in node_cls.server_controlled_fields
+
+ def test_action_node_account_cannot_be_overridden(self):
+ node = DiscordActionNode()
+ captured = {}
+
+ async def _fake_get(path, *, account_id=DEFAULT_ACCOUNT, params=None):
+ captured["account_id"] = account_id
+ return []
+
+ with patch("nodes.discord.discord_action._base.get", new=_fake_get):
+ _run(
+ node.execute_as_tool(
+ {"operation": "list_guilds", "account_id": "ATTACKER"},
+ {"operation": "list_guilds", "account_id": "operator-account"},
+ _ctx(),
+ )
+ )
+
+ assert captured["account_id"] == "operator-account"
+
+
+class TestSendShape:
+ def _capture(self, params, **patches):
+ node = DiscordSendNode()
+ captured = {"posts": []}
+
+ async def _fake_post(path, body=None, *, account_id=DEFAULT_ACCOUNT, **kwargs):
+ captured["posts"].append({"path": path, "body": body, "kwargs": kwargs})
+ return {"id": f"m{len(captured['posts'])}", "channel_id": "c1"}
+
+ with patch("nodes.discord.discord_send._base.post", new=_fake_post):
+ captured["result"] = _run(node.send(_ctx(), params))
+ return captured
+
+ def test_channel_send_posts_to_the_channel_messages_route(self):
+ captured = self._capture(DiscordSendParams(channel_id="c1", message="hi"))
+ assert captured["posts"][0]["path"] == "channels/c1/messages"
+ assert captured["posts"][0]["body"]["content"] == "hi"
+
+ def test_dm_opens_a_channel_first(self):
+ """Discord has no send-to-user route; a DM channel must be opened."""
+ captured = self._capture(DiscordSendParams(target_type="user", user_id="u1", message="hi"))
+ assert captured["posts"][0]["path"] == "users/@me/channels"
+
+ def test_long_message_is_split_across_posts(self):
+ captured = self._capture(DiscordSendParams(channel_id="c1", message="word " * 2000))
+ assert len(captured["posts"]) > 1
+ assert captured["result"].parts == len(captured["posts"])
+ assert len(captured["result"].message_ids) == len(captured["posts"])
+
+ def test_reply_reference_rides_only_the_first_message(self):
+ captured = self._capture(
+ DiscordSendParams(channel_id="c1", message="word " * 2000, reply_to_message_id="m0")
+ )
+ assert "message_reference" in captured["posts"][0]["body"]
+ assert all("message_reference" not in p["body"] for p in captured["posts"][1:])
+
+ def test_embeds_ride_the_final_message(self):
+ """So they render after the text they belong to."""
+ captured = self._capture(
+ DiscordSendParams(channel_id="c1", message="word " * 2000, embeds=[{"title": "t"}])
+ )
+ assert "embeds" not in captured["posts"][0]["body"]
+ assert captured["posts"][-1]["body"]["embeds"] == [{"title": "t"}]
+
+ def test_empty_send_is_refused(self):
+ node = DiscordSendNode()
+ with pytest.raises(NodeUserError):
+ _run(node.send(_ctx(), DiscordSendParams(channel_id="c1")))
+
+ def test_too_many_embeds_is_refused_locally(self):
+ """Discord rejects the whole message, so failing here is clearer."""
+ node = DiscordSendNode()
+ with pytest.raises(NodeUserError):
+ _run(
+ node.send(
+ _ctx(),
+ DiscordSendParams(channel_id="c1", embeds=[{"title": str(i)} for i in range(11)]),
+ )
+ )
+
+ def test_missing_channel_is_a_clear_error(self):
+ node = DiscordSendNode()
+ with pytest.raises(NodeUserError):
+ _run(node.send(_ctx(), DiscordSendParams(message="hi")))
+
+
+class TestActionShape:
+ def test_every_operation_has_a_method(self):
+ declared = set(typing.get_args(DiscordActionParams.model_fields["operation"].annotation))
+ implemented = {spec.name for spec in DiscordActionNode._operations.values()}
+ assert declared == implemented
+
+ def test_download_attachments_without_input_is_a_clear_error(self):
+ node = DiscordActionNode()
+ with pytest.raises(NodeUserError):
+ _run(node.download_attachments(_ctx(), DiscordActionParams(operation="download_attachments")))
+
+ def test_required_ids_are_validated(self):
+ node = DiscordActionNode()
+ with pytest.raises(NodeUserError):
+ _run(node.list_channels(_ctx(), DiscordActionParams(operation="list_channels")))
+
+
+class TestToolSchema:
+ """Corpus-wide invariant, asserted locally so the reason is visible."""
+
+ @pytest.mark.parametrize("node_cls", [DiscordSendNode, DiscordActionNode])
+ def test_tool_schema_carries_no_unresolvable_ref(self, node_cls):
+ """A $ref with no $defs alongside it is a pointer the LLM cannot
+ follow. Nested models are fine -- they are inlined before emission."""
+ schema = node_cls.Params.model_json_schema()
+ rendered = str(schema)
+ assert "$ref" not in rendered or "$defs" in rendered
+
+ @pytest.mark.parametrize("node_cls", [DiscordSendNode, DiscordActionNode])
+ def test_locked_fields_are_stripped_from_model_arguments(self, node_cls):
+ """The guarantee AccountScopedNode exists to provide, at the class
+ level: every locked field must be removed from tool_args before the
+ merge that would otherwise let the model win."""
+ assert node_cls.server_controlled_fields
+ assert node_cls.execute_as_tool is not _base.ActionNode.execute_as_tool
+
+ @pytest.mark.parametrize("node_cls", [DiscordSendNode, DiscordActionNode])
+ def test_no_param_is_named_type(self, node_cls):
+ """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
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index 99a32fb2..f7a024e6 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -61,6 +61,7 @@ _MIGRATED_PLUGINS = (
"browser",
"cloudflare",
"code",
+ "discord",
"email",
"gcloud",
"github",