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:
1 parent
4420ad58e1
commit
ea9d13cbeb
15 files changed
+249
-28
No files matched your search
+3
-1
@@ -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 Generator
|
||||
|
||||
@@ -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
|
||||
|
||||
```bash
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -62,6 +62,7 @@ class DiscordConfig(Base):
|
||||
working_emoji: str = "🔧"
|
||||
working_emoji_delay: float = 2.0
|
||||
streaming: bool = True
|
||||
reply_to_message: bool = False
|
||||
proxy: str | None = None
|
||||
proxy_username: str | None = None
|
||||
proxy_password: str | None = None
|
||||
@@ -280,15 +281,20 @@ if DISCORD_AVAILABLE:
|
||||
raise
|
||||
|
||||
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
|
||||
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(
|
||||
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 = now
|
||||
except Exception as e:
|
||||
self.logger.warning("stream initial send failed: {}", e)
|
||||
|
||||
@@ -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 message
|
||||
|
||||
def 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.asyncio
|
||||
async 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 == {}
|
||||
|
||||
|
||||
@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
|
||||
async 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_pa
|
||||
|
||||
assert len(target.sent_payloads) == 3
|
||||
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[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
|
||||
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.
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "On",
|
||||
"false": "Off"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "Reply to message",
|
||||
"choices": {
|
||||
"true": "On",
|
||||
"false": "Off"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "encendido",
|
||||
"false": "Apagado"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "Responder al mensaje",
|
||||
"choices": {
|
||||
"true": "encendido",
|
||||
"false": "Apagado"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "Sur",
|
||||
"false": "Désactivé"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "Répondre au message",
|
||||
"choices": {
|
||||
"true": "Sur",
|
||||
"false": "Désactivé"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "Aktif",
|
||||
"false": "Mati"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "Balas pesan",
|
||||
"choices": {
|
||||
"true": "Aktif",
|
||||
"false": "Mati"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "オン",
|
||||
"false": "オフ"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "メッセージに返信",
|
||||
"choices": {
|
||||
"true": "オン",
|
||||
"false": "オフ"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "켜기",
|
||||
"false": "끄기"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "메시지에 답장",
|
||||
"choices": {
|
||||
"true": "켜기",
|
||||
"false": "끄기"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "Ligado",
|
||||
"false": "Desligado"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "Responder à mensagem",
|
||||
"choices": {
|
||||
"true": "Ligado",
|
||||
"false": "Desligado"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "开启",
|
||||
"false": "关闭"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "回复消息",
|
||||
"choices": {
|
||||
"true": "开启",
|
||||
"false": "关闭"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,13 @@
|
||||
"true": "開啟",
|
||||
"false": "關閉"
|
||||
}
|
||||
},
|
||||
"replyToMessage": {
|
||||
"label": "回覆訊息",
|
||||
"choices": {
|
||||
"true": "開啟",
|
||||
"false": "關閉"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user