feat(discord): add replyToMessage parity with Telegram (#5800)

* feat(discord): add configurable native replies

* fix(discord): tolerate deleted reply targets
This commit is contained in:
ZedingZhang authored and GitHub committed 2026-09-18 15:13:31 +08:00
1 parent 4420ad58e1
commit ea9d13cbeb
15 files changed
+249 -28

No files matched your search

+3 -1
View File
@@ -298,7 +298,8 @@ If you prefer to configure manually, add the following to `~/.nanobot/config.jso
"allowFrom": ["YOUR_USER_ID"], "allowFrom": ["YOUR_USER_ID"],
"allowChannels": [], "allowChannels": [],
"groupPolicy": "mention", "groupPolicy": "mention",
"streaming": true "streaming": true,
"replyToMessage": false
} }
} }
} }
@@ -311,6 +312,7 @@ If you prefer to configure manually, add the following to `~/.nanobot/config.jso
> - If you set group policy to open create new threads as private threads and then @ the bot into it. Otherwise the thread itself and the channel in which you spawned it will spawn a bot session. > - If you set group policy to open create new threads as private threads and then @ the bot into it. Otherwise the thread itself and the channel in which you spawned it will spawn a bot session.
> `allowChannels` restricts the bot to specific Discord channel IDs. Empty (default) means respond in every channel the bot can see. Example: `["1234567890", "0987654321"]`. The filter applies after `allowFrom`, so both must pass. Discord threads under an allowed parent channel are also allowed; for Forum channels, allowing the parent Forum channel allows all threads/posts in that forum. > `allowChannels` restricts the bot to specific Discord channel IDs. Empty (default) means respond in every channel the bot can see. Example: `["1234567890", "0987654321"]`. The filter applies after `allowFrom`, so both must pass. Discord threads under an allowed parent channel are also allowed; for Forum channels, allowing the parent Forum channel allows all threads/posts in that forum.
> `streaming` defaults to `true`. Disable it only if you explicitly want non-streaming replies. > `streaming` defaults to `true`. Disable it only if you explicitly want non-streaming replies.
> `replyToMessage` defaults to `false`. Enable it to use Discord's native reply UI for responses.
**5. Invite the bot** **5. Invite the bot**
- OAuth2 → URL Generator - OAuth2 → URL Generator
+5 -1
View File
@@ -49,7 +49,8 @@ Merge this snippet into `~/.nanobot/config.json`:
"token": "YOUR_BOT_TOKEN", "token": "YOUR_BOT_TOKEN",
"allowChannels": [], "allowChannels": [],
"groupPolicy": "mention", "groupPolicy": "mention",
"streaming": true "streaming": true,
"replyToMessage": false
} }
} }
} }
@@ -60,6 +61,9 @@ first, get a pairing code, and be approved before using the bot in servers.
Invite the bot with permissions to read history and send messages. Invite the bot with permissions to read history and send messages.
Set `replyToMessage` to `true` to make responses use Discord's native reply UI.
It defaults to `false`, preserving the existing behavior.
## Run nanobot gateway ## Run nanobot gateway
```bash ```bash
+1
View File
@@ -19,6 +19,7 @@ SETUP_SPEC = ChannelSetupSpec(
"workingEmoji": field(default="🔧"), "workingEmoji": field(default="🔧"),
"workingEmojiDelay": field("float", default=2.0), "workingEmojiDelay": field("float", default=2.0),
"streaming": field("bool", default=True), "streaming": field("bool", default=True),
"replyToMessage": field("bool", default=False),
}, },
required=(required("token"),), required=(required("token"),),
official_url="https://discord.com/developers/applications", official_url="https://discord.com/developers/applications",
+55 -23
View File
@@ -62,6 +62,7 @@ class DiscordConfig(Base):
working_emoji: str = "🔧" working_emoji: str = "🔧"
working_emoji_delay: float = 2.0 working_emoji_delay: float = 2.0
streaming: bool = True streaming: bool = True
reply_to_message: bool = False
proxy: str | None = None proxy: str | None = None
proxy_username: str | None = None proxy_username: str | None = None
proxy_password: str | None = None proxy_password: str | None = None
@@ -280,15 +281,20 @@ if DISCORD_AVAILABLE:
raise raise
messageable_channel = cast(Messageable, channel) messageable_channel = cast(Messageable, channel)
reference, mention_settings = self._build_reply_context(messageable_channel, msg.reply_to) reply_to = self._channel._reply_target(msg.metadata, explicit=msg.reply_to)
reference, mention_settings = self._channel._build_reply_context(
messageable_channel,
reply_to,
fail_if_not_exists=msg.reply_to is not None,
)
sent_media = False sent_media = False
failed_media: list[str] = [] failed_media: list[str] = []
for index, media_path in enumerate(msg.media or []): for media_path in msg.media or []:
if await self._send_file( if await self._send_file(
messageable_channel, messageable_channel,
media_path, media_path,
reference=reference if index == 0 else None, reference=reference if not sent_media else None,
mention_settings=mention_settings, mention_settings=mention_settings,
): ):
sent_media = True sent_media = True
@@ -326,7 +332,7 @@ if DISCORD_AVAILABLE:
channel: Messageable, channel: Messageable,
file_path: str, file_path: str,
*, *,
reference: discord.PartialMessage | None, reference: discord.MessageReference | None,
mention_settings: discord.AllowedMentions, mention_settings: discord.AllowedMentions,
) -> bool: ) -> bool:
"""Send a file attachment via discord.py.""" """Send a file attachment via discord.py."""
@@ -360,24 +366,6 @@ if DISCORD_AVAILABLE:
fallback = "\n".join(f"[attachment: {name} - send failed]" for name in failed_media) fallback = "\n".join(f"[attachment: {name} - send failed]" for name in failed_media)
return split_message(fallback, MAX_MESSAGE_LEN) return split_message(fallback, MAX_MESSAGE_LEN)
def _build_reply_context(
self,
channel: Messageable,
reply_to: str | None,
) -> tuple[discord.PartialMessage | None, discord.AllowedMentions]:
"""Build reply context for outbound messages."""
mention_settings = discord.AllowedMentions(replied_user=False)
if not reply_to:
return None, mention_settings
try:
message_id = int(reply_to)
except ValueError:
self._channel.logger.warning("Invalid reply target: {}", reply_to)
return None, mention_settings
return cast(Any, channel).get_partial_message(message_id), mention_settings
class DiscordChannel(BaseChannel): class DiscordChannel(BaseChannel):
"""Discord channel using discord.py.""" """Discord channel using discord.py."""
@@ -414,6 +402,40 @@ class DiscordChannel(BaseChannel):
return cls._channel_key(parent) return cls._channel_key(parent)
return None return None
def _reply_target(
self,
metadata: dict[str, Any] | None,
*,
explicit: str | None = None,
) -> str | None:
"""Choose an explicit reply target, or the triggering message when enabled."""
if explicit:
return explicit
if not self.config.reply_to_message or not metadata:
return None
message_id = metadata.get("message_id")
return str(message_id) if message_id is not None else None
def _build_reply_context(
self,
channel: Messageable,
reply_to: str | None,
*,
fail_if_not_exists: bool,
) -> tuple[discord.MessageReference | None, discord.AllowedMentions]:
"""Build a native Discord reply without pinging the replied-to user."""
mention_settings = discord.AllowedMentions(replied_user=False)
if not reply_to:
return None, mention_settings
try:
message_id = int(reply_to)
except ValueError:
self.logger.warning("Invalid reply target: {}", reply_to)
return None, mention_settings
partial = cast(Any, channel).get_partial_message(message_id)
return partial.to_reference(fail_if_not_exists=fail_if_not_exists), mention_settings
def __init__(self, config: Any, bus: MessageBus): def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict): if isinstance(config, dict):
config = DiscordConfig.model_validate(config) config = DiscordConfig.model_validate(config)
@@ -575,7 +597,17 @@ class DiscordChannel(BaseChannel):
now = time.monotonic() now = time.monotonic()
if buf.message is None: if buf.message is None:
try: try:
buf.message = await target.send(content=buf.text) reply_to = self._reply_target(metadata)
reference, mention_settings = self._build_reply_context(
target,
reply_to,
fail_if_not_exists=False,
)
kwargs: dict[str, Any] = {"content": buf.text}
if reference is not None:
kwargs["reference"] = reference
kwargs["allowed_mentions"] = mention_settings
buf.message = await target.send(**kwargs)
buf.last_edit = now buf.last_edit = now
except Exception as e: except Exception as e:
self.logger.warning("stream initial send failed: {}", e) self.logger.warning("stream initial send failed: {}", e)
@@ -81,8 +81,16 @@ class _FakeAttachment:
class _FakePartialMessage: class _FakePartialMessage:
# Lightweight stand-in for Discord partial message references used in replies. # Lightweight stand-in for Discord partial message references used in replies.
def __init__(self, message_id: int) -> None: def __init__(self, message_id: int, channel_id: int) -> None:
self.id = message_id self.id = message_id
self.channel_id = channel_id
def to_reference(self, *, fail_if_not_exists: bool = True) -> discord.MessageReference:
return discord.MessageReference(
message_id=self.id,
channel_id=self.channel_id,
fail_if_not_exists=fail_if_not_exists,
)
class _FakeSentMessage: class _FakeSentMessage:
@@ -125,7 +133,7 @@ class _FakeChannel:
return message return message
def get_partial_message(self, message_id: int) -> _FakePartialMessage: def get_partial_message(self, message_id: int) -> _FakePartialMessage:
return _FakePartialMessage(message_id) return _FakePartialMessage(message_id, self.id)
def typing(self): def typing(self):
channel = self channel = self
@@ -728,6 +736,13 @@ def test_supports_streaming_enabled_by_default() -> None:
assert channel.supports_streaming is True assert channel.supports_streaming is True
def test_reply_to_message_is_disabled_by_default() -> None:
config = DiscordConfig(enabled=True, allow_from=["*"])
assert config.reply_to_message is False
assert config.model_dump(by_alias=True)["replyToMessage"] is False
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_send_delta_streams_by_editing_message(monkeypatch) -> None: async def test_send_delta_streams_by_editing_message(monkeypatch) -> None:
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus()) owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
@@ -749,6 +764,26 @@ async def test_send_delta_streams_by_editing_message(monkeypatch) -> None:
assert owner._stream_bufs == {} assert owner._stream_bufs == {}
@pytest.mark.asyncio
async def test_send_delta_replies_to_triggering_message_when_enabled() -> None:
owner = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], reply_to_message=True),
MessageBus(),
)
client = _FakeDiscordClient(owner, intents=None)
owner._client = client
owner._running = True
target = _FakeChannel(channel_id=123)
client.channels[123] = target
await owner.send_delta("123", "hello", {"message_id": "789"}, stream_id="s1")
reference = target.sent_payloads[0]["reference"]
assert reference.message_id == 789
assert reference.to_dict()["fail_if_not_exists"] is False
assert target.sent_payloads[0]["allowed_mentions"].replied_user is False
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_send_delta_merge_next_keeps_one_message(monkeypatch) -> None: async def test_send_delta_merge_next_keeps_one_message(monkeypatch) -> None:
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus()) owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
@@ -1077,11 +1112,88 @@ async def test_client_send_outbound_chunks_text_replies_and_uploads_files(tmp_pa
assert len(target.sent_payloads) == 3 assert len(target.sent_payloads) == 3
assert target.sent_payloads[0]["file_name"] == "demo.txt" assert target.sent_payloads[0]["file_name"] == "demo.txt"
assert target.sent_payloads[0]["reference"].id == 55 assert target.sent_payloads[0]["reference"].message_id == 55
assert target.sent_payloads[1]["content"] == "a" * 2000 assert target.sent_payloads[1]["content"] == "a" * 2000
assert target.sent_payloads[2]["content"] == "a" * 100 assert target.sent_payloads[2]["content"] == "a" * 100
@pytest.mark.asyncio
async def test_client_send_outbound_replies_to_triggering_message_when_enabled() -> None:
owner = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], reply_to_message=True),
MessageBus(),
)
client = DiscordBotClient(owner, intents=discord.Intents.none())
target = _FakeChannel(channel_id=123)
client.get_channel = lambda channel_id: target if channel_id == 123 else None # type: ignore[method-assign]
await client.send_outbound(
OutboundMessage(
channel="discord",
chat_id="123",
content="hello",
metadata={"message_id": "789"},
)
)
reference = target.sent_payloads[0]["reference"]
assert reference.message_id == 789
assert reference.to_dict()["fail_if_not_exists"] is False
assert target.sent_payloads[0]["allowed_mentions"].replied_user is False
@pytest.mark.asyncio
async def test_client_send_outbound_explicit_reply_takes_precedence() -> None:
owner = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], reply_to_message=True),
MessageBus(),
)
client = DiscordBotClient(owner, intents=discord.Intents.none())
target = _FakeChannel(channel_id=123)
client.get_channel = lambda channel_id: target if channel_id == 123 else None # type: ignore[method-assign]
await client.send_outbound(
OutboundMessage(
channel="discord",
chat_id="123",
content="hello",
reply_to="55",
metadata={"message_id": "789"},
)
)
reference = target.sent_payloads[0]["reference"]
assert reference.message_id == 55
assert reference.to_dict()["fail_if_not_exists"] is True
@pytest.mark.asyncio
async def test_client_send_outbound_replies_on_first_successful_attachment(tmp_path) -> None:
owner = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], reply_to_message=True),
MessageBus(),
)
client = DiscordBotClient(owner, intents=discord.Intents.none())
target = _FakeChannel(channel_id=123)
client.get_channel = lambda channel_id: target if channel_id == 123 else None # type: ignore[method-assign]
missing_file = tmp_path / "missing.txt"
valid_file = tmp_path / "valid.txt"
valid_file.write_text("hi")
await client.send_outbound(
OutboundMessage(
channel="discord",
chat_id="123",
content="",
media=[str(missing_file), str(valid_file)],
metadata={"message_id": "789"},
)
)
assert target.sent_payloads[0]["file_name"] == "valid.txt"
assert target.sent_payloads[0]["reference"].message_id == 789
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_client_send_outbound_reports_failed_attachments_when_no_text(tmp_path) -> None: async def test_client_send_outbound_reports_failed_attachments_when_no_text(tmp_path) -> None:
# If all attachment sends fail and no text exists, emit a failure placeholder message. # If all attachment sends fail and no text exists, emit a failure placeholder message.
@@ -50,6 +50,13 @@
"true": "On", "true": "On",
"false": "Off" "false": "Off"
} }
},
"replyToMessage": {
"label": "Reply to message",
"choices": {
"true": "On",
"false": "Off"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "encendido", "true": "encendido",
"false": "Apagado" "false": "Apagado"
} }
},
"replyToMessage": {
"label": "Responder al mensaje",
"choices": {
"true": "encendido",
"false": "Apagado"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "Sur", "true": "Sur",
"false": "Désactivé" "false": "Désactivé"
} }
},
"replyToMessage": {
"label": "Répondre au message",
"choices": {
"true": "Sur",
"false": "Désactivé"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "Aktif", "true": "Aktif",
"false": "Mati" "false": "Mati"
} }
},
"replyToMessage": {
"label": "Balas pesan",
"choices": {
"true": "Aktif",
"false": "Mati"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "オン", "true": "オン",
"false": "オフ" "false": "オフ"
} }
},
"replyToMessage": {
"label": "メッセージに返信",
"choices": {
"true": "オン",
"false": "オフ"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "켜기", "true": "켜기",
"false": "끄기" "false": "끄기"
} }
},
"replyToMessage": {
"label": "메시지에 답장",
"choices": {
"true": "켜기",
"false": "끄기"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "Ligado", "true": "Ligado",
"false": "Desligado" "false": "Desligado"
} }
},
"replyToMessage": {
"label": "Responder à mensagem",
"choices": {
"true": "Ligado",
"false": "Desligado"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "Bật", "true": "Bật",
"false": "Tắt" "false": "Tắt"
} }
},
"replyToMessage": {
"label": "Trả lời tin nhắn",
"choices": {
"true": "Bật",
"false": "Tắt"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "开启", "true": "开启",
"false": "关闭" "false": "关闭"
} }
},
"replyToMessage": {
"label": "回复消息",
"choices": {
"true": "开启",
"false": "关闭"
}
} }
} }
} }
@@ -50,6 +50,13 @@
"true": "開啟", "true": "開啟",
"false": "關閉" "false": "關閉"
} }
},
"replyToMessage": {
"label": "回覆訊息",
"choices": {
"true": "開啟",
"false": "關閉"
}
} }
} }
} }