Skip to content

The agent that grows with you

fix(discord): preserve voice reply threading

luyifana5b32a721a37
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 821971d7f10..310061439cd 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -3599,6 +3599,17 @@ class DiscordAdapter(BasePlatformAdapter):
filename = os.path.basename(audio_path)
+ reference = None
+ if reply_to and self._reply_to_mode != "off":
+ try:
+ ref_msg = await channel.fetch_message(int(reply_to))
+ if hasattr(ref_msg, "to_reference"):
+ reference = ref_msg.to_reference(fail_if_not_exists=False)
+ else:
+ reference = ref_msg
+ except Exception as e:
+ logger.debug("Could not fetch voice reply-to message: %s", e)
+
with open(audio_path, "rb") as f:
file_data = f.read()
@@ -3630,7 +3641,7 @@ class DiscordAdapter(BasePlatformAdapter):
waveform_b64 = base64.b64encode(waveform_bytes).decode()
import json as _json
- payload = _json.dumps({
+ payload_data = {
"flags": 8192,
"attachments": [{
"id": "0",
@@ -3638,7 +3649,13 @@ class DiscordAdapter(BasePlatformAdapter):
"duration_secs": round(duration_secs, 2),
"waveform": waveform_b64,
}],
- })
+ }
+ if reference is not None:
+ payload_data["message_reference"] = {
+ "message_id": str(reply_to),
+ "fail_if_not_exists": False,
+ }
+ payload = _json.dumps(payload_data)
form = [
{"name": "payload_json", "value": payload},
{
@@ -3656,7 +3673,23 @@ class DiscordAdapter(BasePlatformAdapter):
except Exception as voice_err:
logger.debug("Voice message flag failed, falling back to file: %s", voice_err)
file = discord.File(io.BytesIO(file_data), filename=filename)
- msg = await channel.send(file=file)
+ try:
+ msg = await channel.send(file=file, reference=reference)
+ except Exception as send_err:
+ err_text = str(send_err)
+ if (
+ reference is not None
+ and (
+ (
+ "error code: 50035" in err_text
+ and "Cannot reply to a system message" in err_text
+ )
+ or "error code: 10008" in err_text
+ )
+ ):
+ msg = await channel.send(file=file, reference=None)
+ else:
+ raise
return SendResult(success=True, message_id=str(msg.id))
except Exception as e: # pragma: no cover - defensive logging
logger.error("[%s] Failed to send audio, falling back to base adapter: %s", self.name, e, exc_info=True)
diff --git a/tests/gateway/test_discord_send.py b/tests/gateway/test_discord_send.py
index dd178ac52b3..9db579f11e4 100644
--- a/tests/gateway/test_discord_send.py
+++ b/tests/gateway/test_discord_send.py
@@ -1,4 +1,5 @@
import asyncio
+import json
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -46,6 +47,95 @@ _ensure_discord_mock()
from plugins.platforms.discord.adapter import DiscordAdapter # noqa: E402
+def _voice_adapter(reference_obj, *, native_result=None, native_error=None):
+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))
+ ref_msg = SimpleNamespace(id=99, to_reference=MagicMock(return_value=reference_obj))
+ channel = SimpleNamespace(
+ id=555,
+ fetch_message=AsyncMock(return_value=ref_msg),
+ send=AsyncMock(return_value=SimpleNamespace(id=888)),
+ )
+ request = AsyncMock(return_value=native_result or {"id": "777"})
+ if native_error is not None:
+ request.side_effect = native_error
+ adapter._client = SimpleNamespace(
+ get_channel=lambda _chat_id: channel,
+ fetch_channel=AsyncMock(),
+ http=SimpleNamespace(request=request),
+ )
+ return adapter, channel, request
+
+
+def _native_voice_payload(request):
+ form = request.await_args.kwargs["form"]
+ payload = next(part["value"] for part in form if part["name"] == "payload_json")
+ return json.loads(payload)
+
+
+async def test_send_voice_native_payload_preserves_reply_reference(tmp_path):
+ reference = object()
+ adapter, channel, request = _voice_adapter(reference)
+ audio_path = tmp_path / "reply.ogg"
+ audio_path.write_bytes(b"fake ogg")
+
+ result = await adapter.send_voice("555", str(audio_path), reply_to="99")
+
+ assert result.success
+ assert result.message_id == "777"
+ assert _native_voice_payload(request)["message_reference"] == {
+ "message_id": "99",
+ "fail_if_not_exists": False,
+ }
+ channel.fetch_message.assert_awaited_once_with(99)
+ channel.send.assert_not_awaited()
+
+
+async def test_send_voice_file_fallback_preserves_reply_reference(tmp_path):
+ reference = object()
+ adapter, channel, _request = _voice_adapter(
+ reference,
+ native_error=RuntimeError("native voice unavailable"),
+ )
+ audio_path = tmp_path / "reply.ogg"
+ audio_path.write_bytes(b"fake ogg")
+
+ result = await adapter.send_voice("555", str(audio_path), reply_to="99")
+
+ assert result.success
+ assert result.message_id == "888"
+ assert channel.send.await_args.kwargs["reference"] is reference
+
+
+async def test_send_voice_reply_mode_off_omits_reference(tmp_path):
+ reference = object()
+ adapter, channel, request = _voice_adapter(reference)
+ adapter._reply_to_mode = "off"
+ audio_path = tmp_path / "reply.ogg"
+ audio_path.write_bytes(b"fake ogg")
+
+ result = await adapter.send_voice("555", str(audio_path), reply_to="99")
+
+ assert result.success
+ assert "message_reference" not in _native_voice_payload(request)
+ channel.fetch_message.assert_not_awaited()
+
+
+async def test_send_voice_missing_reply_target_sends_without_reference(tmp_path):
+ adapter, channel, request = _voice_adapter(object())
+ channel.fetch_message.side_effect = RuntimeError("Unknown Message")
+ audio_path = tmp_path / "reply.ogg"
+ audio_path.write_bytes(b"fake ogg")
+
+ result = await adapter.send_voice("555", str(audio_path), reply_to="99")
+
+ assert result.success
+ assert "message_reference" not in _native_voice_payload(request)
+
+
@pytest.mark.asyncio
async def test_send_retries_without_reference_when_reply_target_is_system_message():
adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))