Skip to content

The agent that grows with you

fix(discord): send plain audio as an attachment, voice messages only as Ogg/Opus

Tekniume2fe88cf7a0a
diff --git a/plugins/platforms/discord/adapter_media.py b/plugins/platforms/discord/adapter_media.py
index 73e3d3de3be..734ca023a08 100644
--- a/plugins/platforms/discord/adapter_media.py
+++ b/plugins/platforms/discord/adapter_media.py
@@ -2,6 +2,8 @@
from __future__ import annotations
import asyncio
+import base64
+import contextlib
import json
import logging
import os
@@ -22,6 +24,25 @@ logger = logging.getLogger("plugins.platforms.discord.adapter")
_DISCORD_DEFAULT_UPLOAD_LIMIT_BYTES = 20 * 1024 * 1024
+_OPUS_GRANULE_RATE = 48000 # Ogg/Opus granule positions always count 48 kHz samples (RFC 7845 §4)
+
+
+def _ogg_opus_duration(data: bytes) -> Optional[float]:
+ """Playback seconds of an Ogg/Opus stream (last page's granule position minus the OpusHead
+ pre-skip), or None when ``data`` is not Ogg/Opus. Dependency-free: Discord needs the real
+ length for the voice-message scrubber, and a byte-size guess is wrong for every bitrate."""
+ if data[:4] != b"OggS" or len(data) < 27:
+ return None
+ head = 27 + data[26] # first packet follows the page header and its segment table
+ if data[head:head + 8] != b"OpusHead" or len(data) < head + 12:
+ return None
+ pre_skip = int.from_bytes(data[head + 10:head + 12], "little")
+ last = data.rfind(b"OggS\x00")
+ granule = int.from_bytes(data[last + 6:last + 14], "little", signed=True)
+ secs = (granule - pre_skip) / _OPUS_GRANULE_RATE
+ return secs if secs > 0 else None
+
+
class DiscordMediaMixin:
@staticmethod
def _discord_upload_limit_bytes(channel: Any) -> int:
@@ -277,9 +298,19 @@ class DiscordMediaMixin:
async def send_voice(
self, chat_id: str, audio_path: str, caption: Optional[str] = None,
- reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None, **kwargs,
+ reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None,
+ is_voice: Optional[bool] = None, **kwargs,
) -> SendResult:
- """Send audio as a Discord file attachment."""
+ """Deliver audio. ``is_voice=False`` is the media dispatch's plain audio attachment (sound
+ effect, music, an mp3 without ``[[audio_as_voice]]``): it goes out as a regular file under
+ its real name, which Discord renders with an inline player. Voice intent (``True`` from
+ ``[[audio_as_voice]]``, or no flag: auto-TTS and voice replies) becomes a native voice
+ message, which Discord only plays as Ogg/Opus."""
+ if is_voice is False:
+ return await self._send_local_file(
+ chat_id, audio_path, caption, not_found="Audio file not found", kind="audio",
+ metadata=metadata,
+ )
from plugins.platforms.discord.adapter import _prompt_target_id, discord
try:
@@ -294,57 +325,83 @@ class DiscordMediaMixin:
if rejected is not None:
return rejected
reference = self._reply_reference_for_send(reply_to, channel)
- file_data = await asyncio.to_thread(Path(audio_path).read_bytes)
# Forum channels reject POST /messages (native voice path too); create a thread post instead.
if self._is_forum_parent(channel):
+ file_data = await asyncio.to_thread(Path(audio_path).read_bytes)
forum_file = discord.File(io.BytesIO(file_data), filename=filename)
return await self._forum_post_file(
channel, content=(caption or "").strip(), file=forum_file,
)
- # Try sending as a native voice message via raw API (flags=8192).
- try:
- import base64
+ voice = await self._ogg_opus_voice_payload(audio_path)
+ if voice is not None:
try:
- from mutagen.oggopus import OggOpus
- duration_secs = OggOpus(audio_path).info.length
- except Exception:
- duration_secs = max(1.0, len(file_data) / 2000.0)
- payload_data = {
- "flags": 8192,
- "attachments": [{
- "id": "0", "filename": "voice-message.ogg", "duration_secs": round(duration_secs, 2),
- "waveform": base64.b64encode(bytes([128] * 256)).decode(),
- }],
- }
- if reference is not None:
- payload_data["message_reference"] = {"message_id": str(reply_to), "fail_if_not_exists": False}
- form = [
- {"name": "payload_json", "value": json.dumps(payload_data)},
- {
- "name": "files[0]", "value": file_data, "filename": "voice-message.ogg",
- "content_type": "audio/ogg",
- },
- ]
- msg_data = await self._client.http.request(
- discord.http.Route("POST", "/channels/{channel_id}/messages", channel_id=channel.id),
- form=form,
- )
- return SendResult(success=True, message_id=str(msg_data["id"]))
- 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)
- try:
- msg = await channel.send(file=file, reference=reference)
- except Exception as send_err:
- if reference is not None and self._is_reply_reference_rejected(send_err):
- msg = await channel.send(file=file, reference=None)
- else:
- raise
- return SendResult(success=True, message_id=str(msg.id))
+ return await self._post_voice_message(channel, *voice, reply_to=reply_to, reference=reference)
+ except Exception as voice_err:
+ logger.debug("Voice message flag failed, falling back to file: %s", voice_err)
+ else:
+ logger.warning(
+ "[%s] %s is not Ogg/Opus and could not be transcoded (install ffmpeg for voice "
+ "messages); sending it as an audio attachment", self.name, filename)
+ file_data = await asyncio.to_thread(Path(audio_path).read_bytes)
+ file = discord.File(io.BytesIO(file_data), filename=filename)
+ try:
+ msg = await channel.send(file=file, reference=reference)
+ except Exception as send_err:
+ if reference is not None and self._is_reply_reference_rejected(send_err):
+ 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: %s", self.name, e, exc_info=True)
return SendResult(success=False, error=str(e))
+ @staticmethod
+ async def _ogg_opus_voice_payload(audio_path: str) -> Optional[tuple[bytes, float]]:
+ """``(ogg_opus_bytes, duration_secs)`` for a voice message: the file itself when it already
+ is Ogg/Opus, else an ffmpeg transcode; None when neither yields Ogg/Opus."""
+ from gateway.platforms.base import transcode_to_ogg_opus
+
+ data = await asyncio.to_thread(Path(audio_path).read_bytes)
+ duration = _ogg_opus_duration(data)
+ if duration is not None:
+ return data, duration
+ converted = await asyncio.to_thread(transcode_to_ogg_opus, audio_path, bitrate="48k", timeout=30)
+ if not converted:
+ return None
+ try:
+ data = await asyncio.to_thread(Path(converted).read_bytes)
+ finally:
+ with contextlib.suppress(OSError):
+ os.unlink(converted)
+ duration = _ogg_opus_duration(data)
+ return (data, duration) if duration is not None else None
+
+ async def _post_voice_message(
+ self, channel: Any, data: bytes, duration_secs: float, *, reply_to: Optional[str], reference: Any,
+ ) -> SendResult:
+ """POST a native voice message (flags=8192) with Ogg/Opus ``data`` via the raw API."""
+ from plugins.platforms.discord.adapter import discord
+
+ payload_data: dict[str, Any] = {
+ "flags": 8192,
+ "attachments": [{
+ "id": "0", "filename": "voice-message.ogg", "duration_secs": round(duration_secs, 2),
+ "waveform": base64.b64encode(bytes([128] * 256)).decode(),
+ }],
+ }
+ if reference is not None:
+ payload_data["message_reference"] = {"message_id": str(reply_to), "fail_if_not_exists": False}
+ form = [
+ {"name": "payload_json", "value": json.dumps(payload_data)},
+ {"name": "files[0]", "value": data, "filename": "voice-message.ogg", "content_type": "audio/ogg"},
+ ]
+ msg_data = await self._client.http.request(
+ discord.http.Route("POST", "/channels/{channel_id}/messages", channel_id=channel.id),
+ form=form,
+ )
+ return SendResult(success=True, message_id=str(msg_data["id"]))
+
async def _send_local_file(self, chat_id, path, caption, *, file_name=None, not_found: str, kind: str, metadata=None):
"""A failed attachment is a failed delivery, never a successful text notice."""
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index 46fbeae062c..43465160525 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -1865,10 +1865,15 @@ class FeishuAdapter(BasePlatformAdapter):
async def send_voice(
self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
- metadata: Optional[dict[str, Any]] = None, **kwargs,
+ metadata: Optional[dict[str, Any]] = None, is_voice: Optional[bool] = None, **kwargs,
) -> SendResult:
"""Native voice message (Feishu only accepts Opus): non-opus audio is transcoded via ffmpeg
- first; without ffmpeg the original file goes out as a file attachment."""
+ first; without ffmpeg the original file goes out as a file attachment. ``is_voice=False``
+ (an audio MEDIA file without [[audio_as_voice]]: music, a sound effect) is a file
+ attachment under its real name, never transcoded into a voice note."""
+ if is_voice is False:
+ return await self.send_document(
+ chat_id, audio_path, caption=caption, reply_to=reply_to, metadata=metadata)
transcoded_path: Optional[str] = None
ext = Path(audio_path).suffix.lower()
if ext not in _FEISHU_OPUS_UPLOAD_EXTENSIONS:
diff --git a/tests/gateway/test_discord_audio_delivery.py b/tests/gateway/test_discord_audio_delivery.py
new file mode 100644
index 00000000000..44c9b1613ba
--- /dev/null
+++ b/tests/gateway/test_discord_audio_delivery.py
@@ -0,0 +1,92 @@
+"""Discord audio delivery: plain audio is an attachment, voice messages are real Ogg/Opus."""
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.discord.adapter import DiscordAdapter
+
+
+def _ogg_opus(seconds: float, pre_skip: int = 312) -> bytes:
+ """Minimal Ogg/Opus stream: an OpusHead page and a final page whose granule ends the audio."""
+ def page(header_type: int, granule: int, seq: int, packet: bytes) -> bytes:
+ return (b"OggS" + bytes([0, header_type]) + granule.to_bytes(8, "little") + b"\x01\x00\x00\x00"
+ + seq.to_bytes(4, "little") + b"\x00" * 4 + bytes([1, len(packet)]) + packet)
+ head = b"OpusHead" + bytes([1, 1]) + pre_skip.to_bytes(2, "little") + (48000).to_bytes(4, "little") + b"\x00" * 3
+ return page(2, 0, 0, head) + page(4, int(seconds * 48000) + pre_skip, 1, b"\xfc" * 8)
+
+
+class Channel:
+ """One text channel: records raw voice-message POSTs and regular attachment sends."""
+
+ id = 222
+ guild = None
+
+ def __init__(self):
+ self.http = self
+ self.voice_posts = []
+ self.attachments = []
+
+ def get_channel(self, channel_id):
+ return self if channel_id == self.id else None
+
+ async def request(self, route, *, form):
+ payload = json.loads(form[0]["value"])
+ self.voice_posts.append({"payload": payload, "file": form[1]})
+ return {"id": "901"}
+
+ async def send(self, **kwargs):
+ files = kwargs.get("files", []) or ([kwargs["file"]] if kwargs.get("file") else [])
+ self.attachments.extend(f.filename for f in files)
+ return SimpleNamespace(id=902, attachments=files)
+
+
+def _adapter():
+ adapter = DiscordAdapter(PlatformConfig())
+ adapter._client = channel = Channel()
+ return adapter, channel
+
+
[email protected]("name, data", [
+ ("door_knock.mp3", b"ID3\x04" + b"\x00" * 64),
+ ("theme.wav", b"RIFF" + b"\x00" * 64),
+ ("ambient.ogg", _ogg_opus(4.0)),
+], ids=["mp3", "wav", "ogg-opus"])
+async def test_plain_audio_media_is_a_named_attachment_not_a_voice_message(tmp_path, name, data):
+ """``is_voice=False`` (an audio MEDIA file without [[audio_as_voice]]) keeps its real name
+ and format as a regular attachment; it never becomes a ``voice-message.ogg`` voice note."""
+ adapter, channel = _adapter()
+ path = tmp_path / name
+ path.write_bytes(data)
+
+ result = await adapter.send_voice("222", str(path), is_voice=False)
+
+ assert result.success
+ assert channel.attachments == [name]
+ assert channel.voice_posts == []
+
+
[email protected]("flag", [{"is_voice": True}, {}], ids=["audio_as_voice", "auto-tts"])
+async def test_voice_message_carries_ogg_opus_bytes_and_their_real_duration(tmp_path, monkeypatch, flag):
+ """Voice intent ([[audio_as_voice]] or an auto-TTS reply with no flag) posts a native voice
+ message whose duration is the stream's own length; audio that cannot become Ogg/Opus (no
+ ffmpeg) goes out as a playable attachment instead of a mislabelled voice note."""
+ adapter, channel = _adapter()
+ opus = tmp_path / "reply.ogg"
+ opus.write_bytes(_ogg_opus(3.0))
+
+ assert (await adapter.send_voice("222", str(opus), **flag)).success
+ [post] = channel.voice_posts
+ assert post["payload"]["flags"] == 8192
+ assert post["payload"]["attachments"][0]["duration_secs"] == 3.0
+ assert post["file"]["value"] == opus.read_bytes()
+
+ monkeypatch.setattr("gateway.platforms.base.transcode_to_ogg_opus", lambda *a, **k: None)
+ mp3 = tmp_path / "spoken.mp3"
+ mp3.write_bytes(b"ID3\x04" + b"\x00" * 64)
+ assert (await adapter.send_voice("222", str(mp3), **flag)).success
+ assert len(channel.voice_posts) == 1
+ assert channel.attachments == ["spoken.mp3"]
diff --git a/tests/gateway/test_feishu_audio_delivery.py b/tests/gateway/test_feishu_audio_delivery.py
new file mode 100644
index 00000000000..157cc2e5bed
--- /dev/null
+++ b/tests/gateway/test_feishu_audio_delivery.py
@@ -0,0 +1,50 @@
+"""Feishu audio delivery: plain audio MEDIA is a named file, only voice intent is a voice note."""
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.feishu.adapter import FeishuAdapter
+
+
+def _recording_adapter():
+ adapter = FeishuAdapter(PlatformConfig())
+ sent = {"uploads": [], "messages": []}
+
+ class _FileAPI:
+ def create(self, request):
+ body = request.request_body
+ sent["uploads"].append((body.file_type, body.file_name))
+ return SimpleNamespace(success=lambda: True, data=SimpleNamespace(file_key="file_1"))
+
+ class _MessageAPI:
+ def create(self, request):
+ sent["messages"].append(request.request_body.msg_type)
+ return SimpleNamespace(success=lambda: True, data=SimpleNamespace(message_id="om_1"))
+
+ adapter._client = SimpleNamespace(im=SimpleNamespace(v1=SimpleNamespace(file=_FileAPI(), message=_MessageAPI())))
+ return adapter, sent
+
+
+async def _direct(func, *args, **kwargs):
+ return func(*args, **kwargs)
+
+
[email protected]("name", ["door_knock.mp3", "theme.wav"])
+def test_plain_audio_media_is_a_named_file_not_a_transcoded_voice_note(tmp_path, name):
+ adapter, sent = _recording_adapter()
+ path = tmp_path / name
+ path.write_bytes(b"\x00" * 64)
+
+ def transcode_must_not_run(*_a, **_k):
+ raise AssertionError("plain audio must not be transcoded into a voice note")
+
+ with patch("plugins.platforms.feishu.adapter.asyncio.to_thread", side_effect=_direct), \
+ patch("gateway.platforms.base.transcode_to_ogg_opus", transcode_must_not_run):
+ result = asyncio.run(adapter.send_voice("oc_chat", str(path), is_voice=False))
+
+ assert result.success
+ assert sent["uploads"] == [("stream", name)]
+ assert sent["messages"] == ["file"]