Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions src/modules/administration/api/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,59 @@ async def test_channel(channel_id: int, db: Session = Depends(get_db)):
)
except Exception as exc:
record_check(db, "channel", channel.id, identity, False)
raise api_error(500, "channel_test_failed", "测试通知发送失败") from exc
raise api_error(500, "channel_test_failed", _failure_message(exc, english)) from exc

# 群组升级为超级群后旧 chat_id 失效:Telegram 会给出新的 chat_id,
# 这里把它写回渠道配置,避免用户每次都要手工改。
migrated_chat_id = _persist_telegram_migration(db, channel, notifier)
if migrated_chat_id:
# 指纹包含渠道配置:迁移后 chat_id 变了,必须用新指纹记录校验结果,
# 否则 onboarding 的 verified() 会拿旧指纹比对,误判为“未验证”。
identity = channel_fingerprint(channel)

if result.get("success"):
record_check(db, "channel", channel.id, identity, True)
return {"ok": True, "message": "Test notification sent" if english else "测试通知发送成功"}
if migrated_chat_id:
message = (
f"Telegram group was migrated to a supergroup; chat_id updated to {migrated_chat_id}"
if english
else f"Telegram 群组已升级为超级群,chat_id 已自动更新为 {migrated_chat_id}"
)
else:
message = "Test notification sent" if english else "测试通知发送成功"
return {"ok": True, "message": message}
else:
record_check(db, "channel", channel.id, identity, False)
raise api_error(500, "channel_test_failed", "测试通知发送失败")
raise api_error(
500,
"channel_test_failed",
_failure_message(result.get("error"), english),
)


def _failure_message(detail: object, english: bool) -> str:
"""把底层失败原因带进错误信息,别只丢一句“发送失败”。"""
base = "Test notification failed" if english else "测试通知发送失败"
text = str(detail or "").strip()
if not text:
return base
return f"{base}: {text}"


def _persist_telegram_migration(
db: Session, channel: NotifyChannel, notifier: NotifierManager
) -> str:
"""把 Telegram 升级后的新 chat_id 写回渠道配置,返回新 id(没有则空)。"""
if channel.type != "telegram":
return ""
config = dict(channel.config or {})
new_chat_id = (getattr(notifier, "telegram_migrations", {}) or {}).get(
str(config.get("chat_id") or "")
)
if not new_chat_id or new_chat_id == str(config.get("chat_id") or ""):
return ""
config["chat_id"] = new_chat_id
channel.config = config
db.commit()
db.refresh(channel)
return new_chat_id
52 changes: 43 additions & 9 deletions src/platform/notifications/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,10 @@ def build_apprise_url(channel_type: str, config: dict) -> str | None:
chat_id = config.get("chat_id", "")
if not bot_token or not chat_id:
raise ValueError("Telegram 需要 bot_token 和 chat_id")
# 如果配置了代理(渠道级或全局),返回 None,使用自定义方式发送
proxy = config.get("proxy", "").strip() or get_global_proxy()
if proxy:
return None
return f"tgram://{bot_token}/{chat_id}"
# Telegram 一律走自定义实现:只有自己发请求才能读到 Telegram 原始错误,
# 从而处理群组升级为超级群后的 chat_id 迁移,并把真实失败原因告知用户。
# 走 Apprise 时只会得到“发送失败”,迁移与排障都无从谈起。
return None

elif channel_type == "bark":
device_key = config.get("device_key", "")
Expand Down Expand Up @@ -212,6 +211,8 @@ def __init__(self, policy=None):
self._channel_specs: list[tuple[str, dict]] = []
# 钉钉关键字(可选):若群机器人启用“关键字”安全校验,则自动附加
self._dingtalk_keywords: set[str] = set()
# Telegram 群组升级为超级群时:旧 chat_id -> 新 chat_id
self.telegram_migrations: dict[str, str] = {}
self.policy = policy

def add_channel(self, channel_type: str, config: dict):
Expand All @@ -221,10 +222,10 @@ def add_channel(self, channel_type: str, config: dict):
if channel_type in _APPRISE_TYPES:
url = build_apprise_url(channel_type, config)
if url is None:
# 需要自定义实现(如带代理的 Telegram)
# 需要自定义实现(Telegram 等,必须自己发请求才能读到原始错误)
self._custom_channels.append((channel_type, config))
self._channel_count += 1
logger.info(f"注册自定义通知渠道: {channel_type} (带代理)")
logger.info(f"注册自定义通知渠道: {channel_type}")
elif self._ap.add(url):
self._channel_count += 1
logger.info(f"注册通知渠道: {channel_type}")
Expand Down Expand Up @@ -381,11 +382,21 @@ async def _send_custom(self, ch_type: str, config: dict, title: str, content: st
else:
raise ValueError(f"Unsupported notification channel: {ch_type}")

async def _send_telegram(self, config: dict, title: str, content: str):
async def _send_telegram(
self,
config: dict,
title: str,
content: str,
*,
allow_chat_migration: bool = True,
):
"""Telegram Bot API(支持代理)

先将正文转为纯文本并截断,再转义为 HTML,仅保留标题加粗。
正文中的下划线等符号不会参与 Markdown 解析,截断也不会切开 HTML 实体。

群组升级为超级群后旧 chat_id 会失效,Telegram 会返回
`migrate_to_chat_id`;此时按官方要求改用新 chat_id 重发一次。
"""
bot_token = config.get("bot_token", "")
chat_id = config.get("chat_id", "")
Expand Down Expand Up @@ -431,7 +442,30 @@ async def _send_telegram(self, config: dict, title: str, content: str):
resp = await client.post(url, json=payload)
data = resp.json()
if not data.get("ok"):
raise RuntimeError(f"Telegram API 错误: {data.get('description')}")
description = str(data.get("description") or "")
migrate_to = (data.get("parameters") or {}).get("migrate_to_chat_id")
if migrate_to and allow_chat_migration:
new_chat_id = str(migrate_to)
logger.warning(
"Telegram 群组已升级为超级群,旧 chat_id %s 失效,改用 %s 重发",
chat_id,
new_chat_id,
)
self.telegram_migrations[str(chat_id)] = new_chat_id
try:
return await self._send_telegram(
{**config, "chat_id": new_chat_id},
title,
content,
allow_chat_migration=False,
)
except Exception as exc:
# 重发请求发往的已经是新的超级群,真实响应不再带
# migrate_to_chat_id,所以在这里补上新 ID。
raise RuntimeError(
f"{exc};请把 chat_id 改为 {new_chat_id}"
) from exc
raise RuntimeError(f"Telegram API 错误: {description}")
logger.info(f"Telegram 通知发送成功: {title}")
except httpx.ConnectError as e:
if proxy:
Expand Down
39 changes: 39 additions & 0 deletions tests/test_onboarding.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,45 @@ async def failure(*a, **kw): raise RuntimeError("receiver unavailable")
assert not client.get("/api/onboarding").json()["channels"][0]["verified"]


def test_channel_test_failure_reports_the_underlying_reason(setup, monkeypatch):
"""测试失败时必须带上底层原因,而不是只丢一句“发送失败”。"""
client, factory = setup
response = client.post("/api/channels", json={"name": "TG", "type": "telegram", "config": {"bot_token": "t", "chat_id": "-1"}})
channel_id = response.json()["id"]
monkeypatch.setattr(channels.NotifierManager, "add_channel", lambda *a: None)
async def failure(*a, **kw):
return {"success": False, "error": "telegram 发送失败: Telegram API 错误: Bad Request: chat not found"}
monkeypatch.setattr(channels.NotifierManager, "notify_with_result", failure)

failed = client.post(f"/api/channels/{channel_id}/test")
assert failed.status_code == 500
assert "chat not found" in failed.json()["detail"]["message"]


def test_channel_test_persists_the_migrated_supergroup_chat_id(setup, monkeypatch):
"""群组升级为超级群后,新 chat_id 要写回渠道配置,且仍判定为已验证。"""
client, factory = setup
response = client.post("/api/channels", json={"name": "TG", "type": "telegram", "config": {"bot_token": "t", "chat_id": "-5092912875"}})
channel_id = response.json()["id"]
monkeypatch.setattr(channels.NotifierManager, "add_channel", lambda *a: None)

async def success(self, *a, **kw):
self.telegram_migrations = {"-5092912875": "-1006031292438"}
return {"success": True}
monkeypatch.setattr(channels.NotifierManager, "notify_with_result", success)

ok = client.post(f"/api/channels/{channel_id}/test")
assert ok.status_code == 200
assert "-1006031292438" in ok.json()["message"]
with factory() as db:
stored = db.query(NotifyChannel).filter(NotifyChannel.id == channel_id).one()
assert stored.config["chat_id"] == "-1006031292438"
# 指纹包含渠道配置:迁移后必须用新指纹记录校验结果,否则 onboarding 误判未验证。
assert client.get("/api/onboarding").json()["channels"][0]["verified"] is True
# 指纹包含渠道配置:迁移后必须用新指纹记录校验结果,否则 onboarding 误判未验证。
assert client.get("/api/onboarding").json()["channels"][0]["verified"] is True


def test_only_enabled_unexpired_alerts_for_selected_stock_count(setup):
client, factory = setup
client.patch("/api/onboarding", json={"stock_id": 1})
Expand Down
79 changes: 79 additions & 0 deletions tests/test_telegram_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,82 @@ def test_telegram_truncates_before_html_escaping_and_preserves_report_link(monke
assert body == escape(plain) # Every escaped entity remains intact.
assert len("盘中报告\n\n" + plain) <= 3900
assert "内容过长已截断" in plain and plain.endswith(link)


def test_telegram_always_uses_the_custom_sender(monkeypatch):
"""Telegram 一律走自定义发送:只有自己发请求才能读到迁移与错误码。"""
from src.platform.notifications.notifier import build_apprise_url

config = {"bot_token": "test-token", "chat_id": "-1006031292438"}
# 没有代理时也不能退回 Apprise:Apprise 只会给出“发送失败”。
assert build_apprise_url("telegram", config) is None

notifier = NotifierManager()
notifier.add_channel("telegram", config)
assert notifier._custom_channels == [("telegram", config)]
assert notifier._channel_count == 1


def test_telegram_retries_with_migrated_supergroup_chat_id(monkeypatch):
"""群组升级为超级群后,旧 chat_id 失效,应按 migrate_to_chat_id 重发一次。"""
responses = [
{
"ok": False,
"error_code": 400,
"description": "Bad Request: group chat was upgraded to a supergroup chat",
"parameters": {"migrate_to_chat_id": -1006031292438},
},
{"ok": True, "result": {"message_id": 5}},
]
client = AsyncMock()
client.post.side_effect = [MagicMock(json=lambda: responses[0]), MagicMock(json=lambda: responses[1])]
context = AsyncMock()
context.__aenter__.return_value = client
monkeypatch.setattr("src.platform.notifications.notifier.httpx.AsyncClient", lambda **kwargs: context)
monkeypatch.setattr("src.platform.notifications.notifier.get_global_proxy", lambda: "")

notifier = NotifierManager()
asyncio.run(notifier._send_telegram(
{"bot_token": "test-token", "chat_id": "-5092912875"}, "测试通知", "内容"))

assert client.post.call_count == 2
assert client.post.call_args_list[0].kwargs["json"]["chat_id"] == "-5092912875"
assert client.post.call_args_list[1].kwargs["json"]["chat_id"] == "-1006031292438"
assert notifier.telegram_migrations == {"-5092912875": "-1006031292438"}


def test_telegram_reports_the_new_chat_id_when_the_retry_also_fails(monkeypatch):
"""重发仍失败时,错误信息要带上新的 chat_id,便于直接修复配置。

真实的第二次请求发往新的超级群,Telegram 不会再返回 migrate_to_chat_id,
所以这条提示由首次触发重试的那一层补上。
"""
responses = [
{
"ok": False,
"error_code": 400,
"description": "Bad Request: group chat was upgraded to a supergroup chat",
"parameters": {"migrate_to_chat_id": -1006031292438},
},
{
"ok": False,
"error_code": 403,
"description": "Forbidden: bot was blocked by the user",
},
]
client = AsyncMock()
client.post.side_effect = [MagicMock(json=lambda: responses[0]), MagicMock(json=lambda: responses[1])]
context = AsyncMock()
context.__aenter__.return_value = client
monkeypatch.setattr("src.platform.notifications.notifier.httpx.AsyncClient", lambda **kwargs: context)
monkeypatch.setattr("src.platform.notifications.notifier.get_global_proxy", lambda: "")

notifier = NotifierManager()
with pytest.raises(RuntimeError) as excinfo:
asyncio.run(notifier._send_telegram(
{"bot_token": "test-token", "chat_id": "-5092912875"}, "测试通知", "内容"))

message = str(excinfo.value)
assert "Forbidden: bot was blocked by the user" in message
assert "请把 chat_id 改为 -1006031292438" in message
assert client.post.call_count == 2 # 只重试一次,不无限递归
Loading