fix(discord): 通知超出嵌入消息长度上限时截断而不是发送失败 (#7471)

* fix(discord): 通知超出嵌入消息长度上限时截断而不是发送失败

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(discord): keep embed limits type-safe

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: jxxghp <jxxghp@gmail.com>
This commit is contained in:
alexcastgonz
2026-11-18 22:43:33 -04:00
committed by GitHub
parent bd4d904319
commit 18f4aa90eb
2 changed files with 147 additions and 2 deletions

View File

@@ -20,6 +20,14 @@ from app.runtime.log import logger
from app.runtime.settings import get_runtime_setting
from app.schemas.types import MessageType
# Discord 嵌入消息长度上限:标题、描述、字段名、字段值、字段数和整条合计。
EMBED_TITLE_LIMIT = 256
EMBED_DESCRIPTION_LIMIT = 4096
EMBED_FIELD_NAME_LIMIT = 256
EMBED_FIELD_VALUE_LIMIT = 1024
EMBED_FIELD_COUNT_LIMIT = 25
EMBED_TOTAL_LIMIT = 6000
# 仅这些通知类型将正文拆为卡片字段,其他类型保留原始文本。
PARSE_FIELD_TYPES = {
# 下载资源通知。
@@ -1193,6 +1201,56 @@ class Discord:
logger.error(f"删除 Discord 消息失败:{err}")
return False
@staticmethod
def _clip(value: str, limit: int) -> str:
"""
按字符数截断文本,超出时以省略号结尾,总长不超过 limit。
"""
if not value or len(value) <= limit:
return value
return value[: limit - 1] + "…"
@staticmethod
def _limit_embed_content(
title: str, description: str, fields: List[Dict[str, str]]
) -> Tuple[str, str, List[Dict[str, str]]]:
"""
截断 Discord 嵌入消息内容,保证各文本字段及总长度均不超限。
:param title: 嵌入消息标题
:param description: 嵌入消息描述
:param fields: 按显示顺序排列的字段
:return: 截断后的标题、描述和字段
"""
title = Discord._clip(title, EMBED_TITLE_LIMIT)
description = Discord._clip(description, EMBED_DESCRIPTION_LIMIT)
fields = [
{
"name": Discord._clip(field["name"], EMBED_FIELD_NAME_LIMIT),
"value": Discord._clip(field["value"], EMBED_FIELD_VALUE_LIMIT),
}
for field in fields[:EMBED_FIELD_COUNT_LIMIT]
]
def _total() -> int:
"""
计算嵌入消息中计入总长度上限的字符数。
"""
return (
len(title)
+ len(description)
+ sum(len(field["name"]) + len(field["value"]) for field in fields)
)
overflow = _total() - EMBED_TOTAL_LIMIT
if overflow > 0 and description:
description = Discord._clip(
description, max(len(description) - overflow, 1)
)
while fields and _total() > EMBED_TOTAL_LIMIT:
fields.pop()
return title, description, fields
@staticmethod
def _build_embed(
title: str,
@@ -1207,7 +1265,7 @@ class Discord:
仅下载、整理、订阅和手动通知解析“字段:值”;书名括号、URL 和时间中的冒号
保留为普通正文,避免错误切分。未提供详情链接时使用项目主页。
"""
fields: List[Dict[str, Union[str, bool]]] = []
fields: List[Dict[str, str]] = []
desc_lines: List[str] = []
should_parse_fields = mtype in PARSE_FIELD_TYPES if mtype else False
@@ -1297,7 +1355,7 @@ class Discord:
value = m.group(2).strip(" ,,;;。、\t") or "-"
if name:
fields.append(
{"name": name, "value": value, "inline": False}
{"name": name, "value": value}
)
last_end = m.end()
# 匹配末尾后的文本
@@ -1309,6 +1367,10 @@ class Discord:
description = "\n".join(desc_lines).strip()
if not description and not fields and text:
description = text.strip()
# Discord 对嵌入消息有硬性长度上限,超出会被 API 拒绝,需要提前截断
title, description, fields = Discord._limit_embed_content(
title, description, fields
)
embed = discord.Embed(
title=title,
url=link or "https://github.com/jxxghp/MoviePilot",

View File

@@ -0,0 +1,83 @@
"""
验证 Discord 嵌入消息构建时遵守平台长度上限。
"""
from app.modules.discord.discord import Discord
from app.schemas.types import MessageType
def _embed_total(embed) -> int:
"""
统计嵌入消息中计入 6000 字符上限的全部文本长度。
"""
total = len(embed.title or "") + len(embed.description or "")
for field in embed.fields:
total += len(field.name) + len(field.value)
return total
def test_long_title_and_description_are_truncated():
"""
超长标题和描述应被截断到 256 / 4096 字符并以省略号结尾。
"""
embed = Discord._build_embed(
title="题" * 1000, text="文" * 9000, image=None, link=None
)
assert len(embed.title) == 256
assert embed.title.endswith("…")
assert len(embed.description) == 4096
assert embed.description.endswith("…")
def test_long_field_name_and_value_are_truncated():
"""
超长字段名和值分别被截断到 256 和 1024 字符。
"""
embed = Discord._build_embed(
title="标题",
text="名" * 3000 + ":" + "值" * 3000,
image=None,
link=None,
mtype=MessageType.Download,
)
assert len(embed.fields) == 1
assert len(embed.fields[0].name) == 256
assert embed.fields[0].name.endswith("…")
assert len(embed.fields[0].value) == 1024
assert embed.fields[0].value.endswith("…")
def test_field_count_and_total_length_are_limited():
"""
字段最多 25 个,整条嵌入合计不超过 6000 字符。
"""
text = "\n".join(f"字段{i}:{'值' * 900}" for i in range(40))
embed = Discord._build_embed(
title="标题",
text="描述" * 2000 + "\n" + text,
image=None,
link=None,
mtype=MessageType.Download,
)
assert len(embed.fields) <= 25
assert _embed_total(embed) <= 6000
def test_short_content_is_unchanged():
"""
未超限的内容保持原样。
"""
embed = Discord._build_embed(
title="标题",
text="名称:值\n说明",
image=None,
link=None,
mtype=MessageType.Download,
)
assert embed.title == "标题"
assert embed.description == "说明"
assert [(f.name, f.value) for f in embed.fields] == [("名称", "值")]