Skip to content

The agent that grows with you

fix(discord): accept a pasted channel link at the _resolve_channel chokepoint too

teknium1c060a821d5ad
diff --git a/gateway/config.py b/gateway/config.py
index 5d5d3324725..0ff264aaf87 100644
--- a/gateway/config.py
+++ b/gateway/config.py
@@ -6,6 +6,7 @@ import contextlib
import logging
import math
import os
+import re
from pathlib import Path
from dataclasses import asdict, dataclass, field, fields, is_dataclass
from typing import Dict, List, Optional, Any, Callable
@@ -299,6 +300,17 @@ def platform_binds_port(platform_value: str, extra: Optional[dict] = None) -> bo
expected_mode = PORT_BINDING_CONDITIONAL_MODES.get(platform_value)
return expected_mode is None or str((extra or {}).get("connection_mode", "websocket")).strip().lower() == expected_mode
+_DISCORD_CHANNEL_LINK_RE = re.compile(
+ r"https://(?:(?:ptb|canary)\.)?discord(?:app)?\.com/channels/(?:[0-9]+|@me)/([0-9]+)/?")
+
+
+def discord_channel_id_from_link(value: str) -> Optional[str]:
+ """Channel id from a pasted Discord channel link (``https://discord.com/channels/<guild>/<channel>``),
+ else None. Message links (a third path segment) and anything that is not a channel link are
+ left alone so callers keep their own error path."""
+ match = _DISCORD_CHANNEL_LINK_RE.fullmatch(value)
+ return match.group(1) if match else None
+
@dataclass
class HomeChannel:
@@ -315,16 +327,8 @@ class HomeChannel:
def __post_init__(self) -> None:
# Copy Link is next to Copy Channel ID in Discord. Normalize at the
# shared home boundary so env, YAML and plugin-seeded homes agree.
- if self.platform != Platform.DISCORD or not isinstance(self.chat_id, str):
- return
- import re
- match = re.fullmatch(
- r"https://(?:(?:ptb|canary)\.)?discord(?:app)?\.com/channels/"
- r"(?:[0-9]+|@me)/([0-9]+)/?",
- self.chat_id.strip(),
- )
- if match:
- self.chat_id = match.group(1)
+ if self.platform == Platform.DISCORD and isinstance(self.chat_id, str):
+ self.chat_id = discord_channel_id_from_link(self.chat_id.strip()) or self.chat_id
def to_dict(self) -> Dict[str, Any]:
optional = {k: v for k in ("thread_id", "user_id", "scope_id") if (v := getattr(self, k))}
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 2ba3d2d53f7..b36bb1ebcb7 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -255,7 +255,7 @@ try:
except ImportError:
from ffmpeg_utils import resolve_ffmpeg_executable
-from gateway.config import Platform, PlatformConfig
+from gateway.config import Platform, PlatformConfig, discord_channel_id_from_link
from gateway.platforms.helpers import (
MessageDeduplicator, ThreadParticipationTracker, convert_table_to_bullets, is_discord_channel_obfuscated,
@@ -5180,7 +5180,13 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
return ""
async def _resolve_channel(self, channel_id: Any) -> Any:
- """Cached ``get_channel`` first, REST ``fetch_channel`` on miss (raises on API error)."""
+ """Cached ``get_channel`` first, REST ``fetch_channel`` on miss (raises on API error).
+
+ Every outbound target funnels through here (home channel, cron ``discord:<target>``,
+ thread metadata), so a pasted channel link is accepted at this one boundary instead of
+ dying in ``int()`` as a generic send failure."""
+ if isinstance(channel_id, str):
+ channel_id = discord_channel_id_from_link(channel_id.strip()) or channel_id
channel = self._client.get_channel(int(channel_id))
if not channel:
channel = await self._client.fetch_channel(int(channel_id))
diff --git a/tests/gateway/test_discord_home_link.py b/tests/gateway/test_discord_home_link.py
index 51440fb4689..e3a737c7364 100644
--- a/tests/gateway/test_discord_home_link.py
+++ b/tests/gateway/test_discord_home_link.py
@@ -1,6 +1,16 @@
-"""Discord home links must be normalized before any delivery consumer sees them."""
+"""Discord channel links are accepted wherever a channel id is (#115216).
+
+Copy Link sits next to Copy Channel ID in Discord's context menu; a pasted link used to reach
+``int()`` inside the adapter and every home-channel / cron delivery died as a generic send failure.
+"""
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
import pytest
+
from gateway.config import HomeChannel, Platform, load_gateway_config
+from plugins.platforms.discord.adapter import DiscordAdapter
@pytest.mark.parametrize("source", ["env", "yaml"])
@@ -17,27 +27,20 @@ def test_discord_home_link_loads_as_channel_id(tmp_path, monkeypatch, source):
(tmp_path / "config.yaml").write_text(config_text, encoding="utf-8")
home = load_gateway_config().platforms[Platform.DISCORD].home_channel
assert home.chat_id == channel_id
+ # Anything that is not a channel link keeps its own error path (message links included).
+ for target in ("123456789", "https://discord.com/channels/123/456/789", "123/456"):
+ assert HomeChannel(Platform.DISCORD, target, "Home").chat_id == target
+ assert HomeChannel(Platform.SLACK, link, "Home").chat_id == link
[email protected]("host", ["discord.com", "ptb.discord.com", "canary.discord.com", "discordapp.com"])
-def test_home_link_preserves_metadata_and_roundtrips(host):
- home = HomeChannel(Platform.DISCORD, f" https://{host}/channels/@me/123456789/ ",
- "Home", thread_id="987", user_id="u", scope_id="s")
- assert home.chat_id == "123456789"
- assert HomeChannel.from_dict(home.to_dict()) == home
- assert (home.thread_id, home.user_id, home.scope_id) == ("987", "u", "s")
-
-
[email protected]("target", [
- "123456789", "https://example.com/channels/123/456",
- "https://discord.com.evil.test/channels/123/456",
- "https://discord.com/channels/123/456/789", # message link, not channel
- "https://discord.com/channels/123/not-a-channel", "123/456",
-])
-def test_unrecognized_targets_are_not_reinterpreted(target):
- assert HomeChannel(Platform.DISCORD, target, "Home").chat_id == target
+def test_resolve_channel_accepts_a_pasted_link_for_explicit_targets():
+ """Cron ``deliver: discord:<link>`` bypasses HomeChannel, so the adapter's resolver — the
+ chokepoint every outbound target passes through — must accept the link too."""
+ adapter = object.__new__(DiscordAdapter)
+ channel = SimpleNamespace(id=456)
+ adapter._client = SimpleNamespace(get_channel=Mock(return_value=channel), fetch_channel=AsyncMock())
+ resolved = asyncio.run(adapter._resolve_channel(" https://ptb.discord.com/channels/123/456 "))
-def test_other_platform_home_is_unchanged():
- target = "https://discord.com/channels/123/456"
- assert HomeChannel(Platform.SLACK, target, "Home").chat_id == target
+ assert resolved is channel
+ adapter._client.get_channel.assert_called_once_with(456)