Skip to content

Commit d8ef9dd

Browse files
authored
fix: send Discord video components as attachments (#10423)
* fix: send Discord video components as attachments * fix: stream Discord video attachments from disk * fix: preserve Discord video filenames from URLs
1 parent 6b2e417 commit d8ef9dd

2 files changed

Lines changed: 104 additions & 3 deletions

File tree

‎astrbot/core/platform/sources/discord/discord_platform_event.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from io import BytesIO
44
from pathlib import Path
55
from typing import cast
6+
from urllib.parse import unquote, urlparse
67

78
import discord
89
from discord.types.interactions import ComponentInteractionData
@@ -16,6 +17,7 @@
1617
Plain,
1718
Record,
1819
Reply,
20+
Video,
1921
)
2022
from astrbot.api.platform import (
2123
AstrBotMessage,
@@ -386,6 +388,22 @@ async def _parse_to_discord(
386388
describe_media_ref(audio_ref),
387389
exc_info=True,
388390
)
391+
elif isinstance(i, Video):
392+
try:
393+
path = Path(await i.convert_to_file_path())
394+
filename = path.name
395+
if i.file.startswith(("http://", "https://")):
396+
url_path = unquote(urlparse(i.file).path).replace("\\", "/")
397+
url_filename = url_path.rsplit("/", 1)[-1]
398+
if url_filename not in ("", ".", ".."):
399+
filename = url_filename
400+
files.append(discord.File(path, filename=filename))
401+
except Exception:
402+
logger.warning(
403+
"[Discord] Failed to process video: %s",
404+
describe_media_ref(i.file),
405+
exc_info=True,
406+
)
389407
elif isinstance(i, File):
390408
try:
391409
file_path_str = await i.get_file()

‎tests/test_discord_adapter.py‎

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import base64
2-
from io import BytesIO
2+
from io import BufferedReader, BytesIO
33
from types import SimpleNamespace
4-
from unittest.mock import AsyncMock
4+
from unittest.mock import AsyncMock, MagicMock
55

66
import pytest
77

8-
from astrbot.api.message_components import Image, Record
8+
from astrbot.api.message_components import File, Image, Plain, Record, Video
99
from astrbot.api.platform import Group, MessageType
1010
from astrbot.core.message.message_event_result import MessageChain
1111
from astrbot.core.platform.sources.discord import (
@@ -26,6 +26,89 @@
2626
_WAV_PATH = "/tmp/discord_voice.wav"
2727

2828

29+
@pytest.mark.asyncio
30+
@pytest.mark.parametrize("component_type", ["video", "video_url", "file"])
31+
@pytest.mark.parametrize("with_text", [False, True])
32+
async def test_discord_sends_video_attachment(
33+
tmp_path, monkeypatch, component_type, with_text
34+
):
35+
video_path = tmp_path / (
36+
"media_video_test.mp4" if component_type == "video_url" else "repro.mp4"
37+
)
38+
video_bytes = b"video attachment payload"
39+
video_path.write_bytes(video_bytes)
40+
if component_type == "video":
41+
component = Video.fromFileSystem(str(video_path))
42+
elif component_type == "video_url":
43+
component = Video.fromURL("https://example.com/repro.mp4")
44+
monkeypatch.setattr(
45+
Video,
46+
"convert_to_file_path",
47+
AsyncMock(return_value=str(video_path)),
48+
)
49+
else:
50+
component = File(name=video_path.name, file=str(video_path))
51+
52+
channel = MagicMock(spec=discord_platform_event.discord.abc.Messageable)
53+
channel.send = AsyncMock()
54+
event = DiscordPlatformEvent.__new__(DiscordPlatformEvent)
55+
event.interaction_followup_webhook = None
56+
event._get_channel = AsyncMock(return_value=channel)
57+
monkeypatch.setattr(discord_platform_event.AstrMessageEvent, "send", AsyncMock())
58+
chain = [Plain("Video test"), component] if with_text else [component]
59+
60+
await event.send(MessageChain(chain=chain))
61+
62+
channel.send.assert_awaited_once()
63+
kwargs = channel.send.call_args.kwargs
64+
assert kwargs.get("content", "") == ("Video test" if with_text else "")
65+
assert len(kwargs["files"]) == 1
66+
attachment = kwargs["files"][0]
67+
try:
68+
assert attachment.filename == "repro.mp4"
69+
if component_type != "file":
70+
assert isinstance(attachment.fp, BufferedReader)
71+
assert attachment.fp.tell() == 0
72+
assert attachment.fp.read() == video_bytes
73+
finally:
74+
attachment.close()
75+
if component_type != "file":
76+
assert attachment.fp.closed
77+
78+
79+
@pytest.mark.asyncio
80+
@pytest.mark.parametrize(
81+
("url", "expected_name"),
82+
[
83+
("https://example.com/clips/demo.mp4", "demo.mp4"),
84+
("https://example.com/demo.mp4?token=test#preview", "demo.mp4"),
85+
("https://example.com/%E6%B5%8B%E8%AF%95%20video.mp4", "测试 video.mp4"),
86+
("https://example.com", "media_video_test.mp4"),
87+
("https://example.com/clips/?token=test", "media_video_test.mp4"),
88+
],
89+
)
90+
async def test_discord_video_url_attachment_filename(
91+
tmp_path, monkeypatch, url, expected_name
92+
):
93+
video_path = tmp_path / "media_video_test.mp4"
94+
video_path.write_bytes(b"video attachment payload")
95+
monkeypatch.setattr(
96+
Video, "convert_to_file_path", AsyncMock(return_value=str(video_path))
97+
)
98+
event = DiscordPlatformEvent.__new__(DiscordPlatformEvent)
99+
100+
_, files, _, _, _ = await event._parse_to_discord(
101+
MessageChain(chain=[Video.fromURL(url)])
102+
)
103+
104+
assert len(files) == 1
105+
try:
106+
assert files[0].filename == expected_name
107+
assert files[0].fp.name == str(video_path)
108+
finally:
109+
files[0].close()
110+
111+
29112
@pytest.mark.asyncio
30113
async def test_discord_group_message_includes_guild_and_channel_name():
31114
adapter = DiscordPlatformAdapter.__new__(DiscordPlatformAdapter)

0 commit comments

Comments
 (0)