Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(discord): add replyToMessage parity with Telegram (#5800)
ZedingZhangea9d13cbebfb
diff --git a/docs/chat-apps.md b/docs/chat-apps.mdindex f986f2cbd..91f8dd53d 100644--- a/docs/chat-apps.md+++ b/docs/chat-apps.md@@ -298,7 +298,8 @@ If you prefer to configure manually, add the following to `~/.nanobot/config.jso"allowFrom": ["YOUR_USER_ID"],"allowChannels": [],"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.> `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.+> `replyToMessage` defaults to `false`. Enable it to use Discord's native reply UI for responses.**5. Invite the bot**- OAuth2 → URL Generatordiff --git a/docs/guides/discord-ai-agent.md b/docs/guides/discord-ai-agent.mdindex cc8dd9bbe..475f35971 100644--- a/docs/guides/discord-ai-agent.md+++ b/docs/guides/discord-ai-agent.md@@ -49,7 +49,8 @@ Merge this snippet into `~/.nanobot/config.json`:"token": "YOUR_BOT_TOKEN","allowChannels": [],"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.+Set `replyToMessage` to `true` to make responses use Discord's native reply UI.+It defaults to `false`, preserving the existing behavior.+## Run nanobot gateway```bashdiff --git a/nanobot/channels/discord/manifest.py b/nanobot/channels/discord/manifest.pyindex f398ffe10..80b769e58 100644--- a/nanobot/channels/discord/manifest.py+++ b/nanobot/channels/discord/manifest.py@@ -19,6 +19,7 @@ SETUP_SPEC = ChannelSetupSpec("workingEmoji": field(default="🔧"),"workingEmojiDelay": field("float", default=2.0),"streaming": field("bool", default=True),+ "replyToMessage": field("bool", default=False),},required=(required("token"),),official_url="https://discord.com/developers/applications",diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex 71083d62f..bcd5f6dad 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -62,6 +62,7 @@ class DiscordConfig(Base):working_emoji: str = "🔧"working_emoji_delay: float = 2.0streaming: bool = True+ reply_to_message: bool = Falseproxy: str | None = Noneproxy_username: str | None = Noneproxy_password: str | None = None@@ -280,15 +281,20 @@ if DISCORD_AVAILABLE:raisemessageable_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 = Falsefailed_media: list[str] = []- for index, media_path in enumerate(msg.media or []):+ for media_path in msg.media or []:if await self._send_file(messageable_channel,media_path,- reference=reference if index == 0 else None,+ reference=reference if not sent_media else None,mention_settings=mention_settings,):sent_media = True@@ -326,7 +332,7 @@ if DISCORD_AVAILABLE:channel: Messageable,file_path: str,*,- reference: discord.PartialMessage | None,+ reference: discord.MessageReference | None,mention_settings: discord.AllowedMentions,) -> bool:"""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)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):"""Discord channel using discord.py."""@@ -414,6 +402,40 @@ class DiscordChannel(BaseChannel):return cls._channel_key(parent)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):if isinstance(config, dict):config = DiscordConfig.model_validate(config)@@ -575,7 +597,17 @@ class DiscordChannel(BaseChannel):now = time.monotonic()if buf.message is None: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 = nowexcept Exception as e:self.logger.warning("stream initial send failed: {}", e)diff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.pyindex cdaeeba14..dba0aee1c 100644--- a/nanobot/channels/discord/tests/test_discord_channel.py+++ b/nanobot/channels/discord/tests/test_discord_channel.py@@ -81,8 +81,16 @@ class _FakeAttachment:class _FakePartialMessage:# 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.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:@@ -125,7 +133,7 @@ class _FakeChannel:return messagedef get_partial_message(self, message_id: int) -> _FakePartialMessage:- return _FakePartialMessage(message_id)+ return _FakePartialMessage(message_id, self.id)def typing(self):channel = self@@ -728,6 +736,13 @@ def test_supports_streaming_enabled_by_default() -> None: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.asyncioasync def test_send_delta_streams_by_editing_message(monkeypatch) -> None: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 == {}+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.asyncioasync def test_send_delta_merge_next_keeps_one_message(monkeypatch) -> None: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_paassert len(target.sent_payloads) == 3assert target.sent_payloads[0]["file_name"] == "demo.txt"- assert target.sent_payloads[0]["reference"].id == 55+ assert target.sent_payloads[0]["reference"].message_id == 55assert target.sent_payloads[1]["content"] == "a" * 2000assert target.sent_payloads[2]["content"] == "a" * 100+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+++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+++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.asyncioasync 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.diff --git a/nanobot/channels/discord/webui/locales/en.json b/nanobot/channels/discord/webui/locales/en.jsonindex a72a33564..15ab09f09 100644--- a/nanobot/channels/discord/webui/locales/en.json+++ b/nanobot/channels/discord/webui/locales/en.json@@ -50,6 +50,13 @@"true": "On","false": "Off"}+ },+ "replyToMessage": {+ "label": "Reply to message",+ "choices": {+ "true": "On",+ "false": "Off"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/es.json b/nanobot/channels/discord/webui/locales/es.jsonindex d59e479de..93d8d0eef 100644--- a/nanobot/channels/discord/webui/locales/es.json+++ b/nanobot/channels/discord/webui/locales/es.json@@ -50,6 +50,13 @@"true": "encendido","false": "Apagado"}+ },+ "replyToMessage": {+ "label": "Responder al mensaje",+ "choices": {+ "true": "encendido",+ "false": "Apagado"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/fr.json b/nanobot/channels/discord/webui/locales/fr.jsonindex 0cc69e573..36d79b9f1 100644--- a/nanobot/channels/discord/webui/locales/fr.json+++ b/nanobot/channels/discord/webui/locales/fr.json@@ -50,6 +50,13 @@"true": "Sur","false": "Désactivé"}+ },+ "replyToMessage": {+ "label": "Répondre au message",+ "choices": {+ "true": "Sur",+ "false": "Désactivé"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/id.json b/nanobot/channels/discord/webui/locales/id.jsonindex a251732a5..fd108e375 100644--- a/nanobot/channels/discord/webui/locales/id.json+++ b/nanobot/channels/discord/webui/locales/id.json@@ -50,6 +50,13 @@"true": "Aktif","false": "Mati"}+ },+ "replyToMessage": {+ "label": "Balas pesan",+ "choices": {+ "true": "Aktif",+ "false": "Mati"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/ja.json b/nanobot/channels/discord/webui/locales/ja.jsonindex 5d7b7e903..ac642d517 100644--- a/nanobot/channels/discord/webui/locales/ja.json+++ b/nanobot/channels/discord/webui/locales/ja.json@@ -50,6 +50,13 @@"true": "オン","false": "オフ"}+ },+ "replyToMessage": {+ "label": "メッセージに返信",+ "choices": {+ "true": "オン",+ "false": "オフ"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/ko.json b/nanobot/channels/discord/webui/locales/ko.jsonindex 19084d271..6430c6b8b 100644--- a/nanobot/channels/discord/webui/locales/ko.json+++ b/nanobot/channels/discord/webui/locales/ko.json@@ -50,6 +50,13 @@"true": "켜기","false": "끄기"}+ },+ "replyToMessage": {+ "label": "메시지에 답장",+ "choices": {+ "true": "켜기",+ "false": "끄기"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/pt-BR.json b/nanobot/channels/discord/webui/locales/pt-BR.jsonindex 00f815f97..cb640f4db 100644--- a/nanobot/channels/discord/webui/locales/pt-BR.json+++ b/nanobot/channels/discord/webui/locales/pt-BR.json@@ -50,6 +50,13 @@"true": "Ligado","false": "Desligado"}+ },+ "replyToMessage": {+ "label": "Responder à mensagem",+ "choices": {+ "true": "Ligado",+ "false": "Desligado"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/vi.json b/nanobot/channels/discord/webui/locales/vi.jsonindex 99b5a89a1..db6cf0523 100644--- a/nanobot/channels/discord/webui/locales/vi.json+++ b/nanobot/channels/discord/webui/locales/vi.json@@ -50,6 +50,13 @@"true": "Bật","false": "Tắt"}+ },+ "replyToMessage": {+ "label": "Trả lời tin nhắn",+ "choices": {+ "true": "Bật",+ "false": "Tắt"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/zh-CN.json b/nanobot/channels/discord/webui/locales/zh-CN.jsonindex 9f78658bd..27b4c9a78 100644--- a/nanobot/channels/discord/webui/locales/zh-CN.json+++ b/nanobot/channels/discord/webui/locales/zh-CN.json@@ -50,6 +50,13 @@"true": "开启","false": "关闭"}+ },+ "replyToMessage": {+ "label": "回复消息",+ "choices": {+ "true": "开启",+ "false": "关闭"+ }}}}diff --git a/nanobot/channels/discord/webui/locales/zh-TW.json b/nanobot/channels/discord/webui/locales/zh-TW.jsonindex 215fa4402..a5ba10426 100644--- a/nanobot/channels/discord/webui/locales/zh-TW.json+++ b/nanobot/channels/discord/webui/locales/zh-TW.json@@ -50,6 +50,13 @@"true": "開啟","false": "關閉"}+ },+ "replyToMessage": {+ "label": "回覆訊息",+ "choices": {+ "true": "開啟",+ "false": "關閉"+ }}}}