Skip to content

fix(telegram): recover when a group becomes a supergroup - #319

Open
Hansen1018 wants to merge 1 commit into
TNT-Likely:mainfrom
Hansen1018:fix/telegram-supergroup-chat-migration
Open

Hansen1018 wants to merge 1 commit into
TNT-Likely:mainfrom
Hansen1018:fix/telegram-supergroup-chat-migration

Conversation

@Hansen1018

@Hansen1018 Hansen1018 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Background

A Telegram channel that used to work stopped delivering, and the channel test only reported "测试通知发送失败" — the real reason was discarded.

The cause is a Telegram platform change, not a configuration mistake: when a group is upgraded to a supergroup, the old chat_id is invalidated. Telegram answers the old id with

{"ok": false, "error_code": 400,
 "description": "Bad Request: group chat was upgraded to a supergroup chat",
 "parameters": {"migrate_to_chat_id": -1006031292438}}

and the new id is only delivered inside the error payload. Two problems follow:

  1. Every notification fails, and the channel test hides the reason behind a generic message.
  2. The user has no way to learn the new chat_id, so the channel cannot be repaired without reading the server logs.

Reproduced with a real bot and a real group:

POST /api/channels/{id}/test  ->  500 测试通知发送失败
# 真实原因:Telegram API 错误: Bad Request: group chat was upgraded to a supergroup chat

Changes

  • src/platform/notifications/notifier.py — when the Telegram API returns parameters.migrate_to_chat_id, retry the send once with that id, as Telegram asks clients to do. The mapping is recorded in NotifierManager.telegram_migrations. If the retry fails as well, the error names the new id so the configuration can be fixed.
  • src/platform/notifications/notifier.py — Telegram is now always sent by PanWatch's own client instead of Apprise. Only our own request can read the Telegram error payload, so the migration and the real failure reason are reachable; through Apprise a failing channel only ever reported "notification failed".
  • src/modules/administration/api/channels.py — the channel test reports the underlying reason instead of a bare failure, and writes the migrated chat_id back into the channel configuration, telling the user which id is now in use. The verification fingerprint is recomputed after the write, so onboarding still reports the channel as verified.
  • tests/test_telegram_delivery.py, tests/test_onboarding.py — regression tests for the retry, for the actionable error, for the configuration update and for the onboarding verdict.

Scope

One outcome: a channel keeps working after its Telegram group is upgraded to a supergroup, and a failing test tells the user what to fix.

For a working channel the visible difference is the rendering: the title is sent as a bold line, the body is escaped and truncated at 3900 characters. The proxy option, the sanitising, the quiet-hours policy and the message limit are unchanged.

Excluded: no change to the other notification channels, to the notification policy, to the group/topic support, or to any API field.

Validation

Tested commit: 7d7a44b

Commands and results:

$ .venv/bin/python -m pytest -q tests/test_telegram_delivery.py tests/test_onboarding.py
34 passed, 5 warnings in 10.02s

$ .venv/bin/python -m pytest -q
1513 passed, 3 skipped, 33 warnings in 129.96s (0:02:09)

The full suite is green on the current main: the date-dependent tests/test_evaluations_api.py failures that made every pull request red were fixed by #322, which is merged.

Isolated acceptance (real Telegram Bot API)

Run in a private QA copy of the workspace (own DATA_DIR, own frontend build, 127.0.0.1 only, the running instance untouched) with the repository skill .agents/skills/panwatch-local-delivery:

PASS | A | 登录取得 JWT | http=200
PASS | A | 创建使用旧 chat_id 的 Telegram 渠道 | http=200
PASS | A | 测试通知成功并提示已迁移 | http=200 message='Telegram 群组已升级为超级群,chat_id 已自动更新为 -1006031292438'
PASS | A | 渠道配置已写回新的超级群 chat_id | chat_id='-1006031292438'
PASS | A | onboarding 判定该渠道为已验证 | verified=True
PASS | B | 失败时错误信息包含 Telegram 真实原因 | http=500 message='测试通知发送失败: telegram 发送失败: Telegram API 错误: Unauthorized: invalid token specified'
PASS | C | 重复测试仍然成功且不再重复迁移 | http=200

The message was really delivered to the authorized group; the server log shows the migration and both successful sends:

WARNING Telegram 群组已升级为超级群,旧 chat_id -5092912875 失效,改用 -1006031292438 重发
INFO    Telegram 通知发送成功: 测试通知

Tested source 7d7a44b; source content hash 6f376157ac179bc2594a657b77bf53f91a5637cce9096bf43a4e024babae7b18; frontend build hash f8866f517e9e3fbe0a3ed1e2c972611bdfb5fd8e0117152e77c51f6017834fa0; QA run 1df50909-0319-4479-bf00-44973417eb4d.

Test report

Report attachment pending: the REST API exposes no endpoint for uploading a ZIP to a pull request and no browser file-picker tool is available in this session, so the sanitized report could not be uploaded here. The complete package is kept locally and its content is reproduced in the review comment.

  • package: panwatch-pr319-acceptance-report.zip (8,025 bytes)
  • ZIP SHA256: 43f4b5b59aa92594e5cd7a07aa98e6cc331f1c78d1ab46a0c0cdfcbbfa6737ef
  • contents: report/index.html (offline, self-contained), report/OPEN.md, report/evidence/*.json, report/manifest.json, report/SHA256SUMS
  • verified: extracted into a new directory, sha256sum -c SHA256SUMS passes for every file, and no token or credential is present in the package

Acceptance evidence

Steps:

  1. Settings → Notification channels → add a Telegram bot with the bot token and the pre-upgrade group chat_id.
  2. Send the channel test notification.
  3. Repeat the test, and try the same with an invalid bot token.

Expected:

  • The notification is delivered even though the configured id is the old one, and the response says which id is now in use.
  • The channel configuration is updated to the new id, and onboarding reports the channel as verified.
  • An invalid token reports the real Telegram reason instead of a generic failure.

Observed:

PASS | A | 测试通知成功并提示已迁移 | http=200 message='Telegram 群组已升级为超级群,chat_id 已自动更新为 -1006031292438'
PASS | A | 渠道配置已写回新的超级群 chat_id | chat_id='-1006031292438'
PASS | A | onboarding 判定该渠道为已验证 | verified=True
PASS | B | 失败时错误信息包含 Telegram 真实原因 | http=500 message='测试通知发送失败: telegram 发送失败: Telegram API 错误: Unauthorized: invalid token specified'

Evidence: the new regression tests, the isolated acceptance run quoted above, and the sanitized report package described in the Validation section.

Boundaries and risks

  • The token is only used to talk to Telegram's API in the verification above; no credential is stored in the repository.
  • Moving Telegram off Apprise changes the wire format slightly (HTML with a bold title instead of plain text) and the truncation point (3900 characters). The proxy option, the sanitising and the quiet-hours policy are unchanged.
  • The migration is applied per send: until the channel test has written the new id back, every notification still costs one rejected request before the retry succeeds.
  • The acceptance was API level (live-api) against the real Telegram API; the browser UI was not clicked through by hand (live-ui not executed).

Follow-up

None.

@TNT-Likely TNT-Likely left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Hansen1018 感谢提交!这个问题场景很真实,分支改动也非常干净。Code review 时发现 2 处逻辑缺陷,麻烦修复后再合:

  1. 迁移成功后 Onboarding 校验指纹会失配(src/modules/administration/api/channels.py)

    • identity = channel_fingerprint(channel) 是在 _persist_telegram_migration(db, channel, notifier) 之前计算的;迁移把新 chat_id 写回 channel.config 后,record_check(db, "channel", channel.id, identity, True) 写入的仍然是旧 chat_id 的指纹。
    • 后续 onboarding 调用 verified() 比对最新 channel_fingerprint(channel) 时会判定为 False(未验证)。建议在 _persist_telegram_migration 返回新 chat_id 后重新计算 identity,并补充一条验证 /api/onboarding 中 verified == True 的回归断言。
  2. 重发新 chat_id 失败时,“请把 chat_id 改为 ...”的提示在真实场景不会命中(src/platform/notifications/notifier.py)

    • 当前在 allow_chat_migration=False 的第二次请求里是通过 if migrate_to: 拼装提示的;但第二次请求发往的已经是新的超级群 chat_id,真实 Telegram 返回 403/400(如 bot 被移出群或被拉黑)时不会再携带 parameters.migrate_to_chat_id(单测里是因为 mock 在第二次 403 响应里也额外塞了 migrate_to_chat_id 才通过的)。
    • 建议在第一次触发重试的调用外层捕获 RuntimeError,把 ;请把 chat_id 改为 {new_chat_id} 附加到重试异常信息中,并同步把单测里第二次 mock 响应的 parameters.migrate_to_chat_id 去掉以还原真实 Telegram 响应。

另外,修复完成后麻烦顺带用仓内的 .agents/skills/panwatch-local-delivery 跑一轮隔离验收,并将脱敏后的离线测试报告 ZIP 附到 PR 正文里,方便我们直接核对合并。谢谢!

@Hansen1018
Hansen1018 force-pushed the fix/telegram-supergroup-chat-migration branch from 0ad09d1 to a210ced Compare December 1, 2026 15:56
@github-actions github-actions Bot added the pr:needs-work PanWatch contribution policy; see docs/pr-policy.md label Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PanWatch contribution check

The mechanical PR requirements are satisfied. Product acceptance, evidence quality and code review remain maintainer decisions.

Scope: 2 production files, 106 added + deleted production lines. Tests, Markdown docs and known lockfiles are excluded.

Contribution policy

本检查只核对材料与改动规模,不代表产品或实现已经验收。首次提示后有14天整改窗口;第7天提醒,逾期仍未达标自动关闭。维护者可用 pr:hold 暂停;关闭后仍可重开或提交拆分版本。

@github-actions github-actions Bot removed the pr:needs-work PanWatch contribution policy; see docs/pr-policy.md label Dec 1, 2026
@Hansen1018

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest main.

main moved to 9d82d5d (this branch's #315, allow fractional holding quantities, merged 2026-12-01), so the branch was recreated from that commit and the single fix commit was re-applied on top of it. The change itself is unchanged — only the base moved, and the diff is still limited to the files listed above.

before after
base e7075e1 9d82d5d (latest main)
head 0ad09d1 a210ced
files 4 4 (src/platform/notifications/notifier.py, src/modules/administration/api/channels.py, tests/test_telegram_delivery.py, tests/test_onboarding.py)

Validation re-run on the new base:

$ .venv/bin/python -m pytest -q tests/test_telegram_delivery.py tests/test_onboarding.py
33 passed, 5 warnings in 6.53s

$ .venv/bin/python -m pytest -q
3 failed, 1507 passed, 3 skipped, 33 warnings in 129.00s (0:02:08)

The three failures are the pre-existing, date-dependent ones in tests/test_evaluations_api.py: the fixture pins prediction_date="2026-08-28" while the review API only returns rows from the last 90 days, so the fixture fell out of the window on 2026-11-27. They fail the same way on main without this pull request and are unrelated to Telegram.

For reference, the CI status of this pull request after the rebase:

  • frontend, triage, PR policy — green
  • Application regression / backend — red, failing on exactly those three test_evaluations_api.py cases (3 failed, 1507 passed), i.e. the same pre-existing failure and not something this pull request introduces

That failure was addressed by #316 (keep the review API cases inside the 90-day window), which was closed on 2026-12-01. If it is still wanted, it can be reopened — the fix only replaces the pinned date with a date relative to today, so the cases keep asserting the same window behaviour and stop expiring. Until then the backend job stays red for every pull request, including this one.

The Telegram behaviour itself was verified against the live Bot API on the previous base and is unchanged by the rebase: a group that was upgraded to a supergroup answers the old chat_id with migrate_to_chat_id, the sender now retries with that id, reports the new id when the retry fails as well, and the channel test writes the migrated id back into the channel configuration.

@TNT-Likely

Copy link
Copy Markdown
Owner

@Hansen1018 看到你已经把分支 rebase 到最新 main 了(另外 #322 已合入,main 的后端 CI 已恢复绿灯)。

提醒一下:刚才复查 a210ced 的 diff,上一条 Request Changes review 里指出的 2 处逻辑 bug 还没有修改:

  1. src/modules/administration/api/channels.py:_persist_telegram_migration 写回新 chat_id 后,record_check 仍在使用迁移前算出的旧 identity,会导致 onboarding verified() 判为 False;
  2. src/platform/notifications/notifier.py:第二次用新 chat_id 重发失败时,真实 Telegram 403/400 响应不会再携带 parameters.migrate_to_chat_id,因此 if migrate_to: 不会命中(需在首次触发重试的外层捕获异常并附带 new_chat_id,同时去掉单测第二次 mock 响应里的 migrate_to_chat_id)。

麻烦把这 2 处一并修复,并跑一轮隔离验收附上报告后再通知我们合入,谢谢!

@Hansen1018
Hansen1018 force-pushed the fix/telegram-supergroup-chat-migration branch from a210ced to 715345f Compare December 2, 2026 11:38
@github-actions github-actions Bot added the pr:needs-work PanWatch contribution policy; see docs/pr-policy.md label Dec 2, 2026
Telegram invalidates the chat id when a group is upgraded to a supergroup:
sending to the old id fails with "Bad Request: group chat was upgraded to
a supergroup chat" and the new id is only returned in the error payload.
The channel test then reported a bare "test notification failed", so the
real cause was invisible.

Retry once with the migrate_to_chat_id Telegram provides, report the new
id when the retry fails as well, and store the migrated id in the channel
configuration so the user does not have to change it by hand.

Telegram now always uses PanWatch's own sender instead of Apprise: only
our own request can read the Telegram error payload, so the migration and
the real failure reason are reachable. Through Apprise a failing channel
only ever reported "notification failed".

Two follow-up defects in that path are fixed here as well:

- The channel test recorded its verification result with the fingerprint of
  the channel as it was before the migration, so onboarding compared a new
  fingerprint (the chat id changed) and reported the channel as unverified.
  The fingerprint is recomputed after the migrated chat id is stored.

- The retry already addresses the new supergroup, so a failing retry no
  longer carries migrate_to_chat_id in the Telegram response and the
  "please change chat_id" hint was never produced. The retry error is caught
  in the call that triggered it and the new id is appended there.
@Hansen1018
Hansen1018 force-pushed the fix/telegram-supergroup-chat-migration branch from 715345f to 7d7a44b Compare December 2, 2026 11:54
@github-actions github-actions Bot removed the pr:needs-work PanWatch contribution policy; see docs/pr-policy.md label Dec 2, 2026
@Hansen1018

Copy link
Copy Markdown
Contributor Author

Both review findings are fixed, and the isolated acceptance run surfaced a third one that the unit tests could not see — thank you for the review, it made the change much stronger.

1. Onboarding fingerprint after the migration — fixed

_persist_telegram_migration now recomputes the fingerprint after the new chat_id is stored, and the verification result is recorded with it:

migrated_chat_id = _persist_telegram_migration(db, channel, notifier)
if migrated_chat_id:
    # 指纹包含渠道配置:迁移后 chat_id 变了,必须用新指纹记录校验结果,
    # 否则 onboarding 的 verified() 会拿旧指纹比对,误判为“未验证”。
    identity = channel_fingerprint(channel)

Regression test added: the onboarding endpoint has to report channels[0]["verified"] is True after the migration. It fails without the fix (assert False is True) and passes with it.

2. The "please change chat_id" hint — fixed

The retry now runs inside the call that triggered it, and that call catches the retry error and appends the new 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

The unit test now mocks the second response without migrate_to_chat_id, exactly like the real API, and asserts the hint is still produced. Without the fix it fails with '请把 chat_id 改为 -1006031292438' in 'Telegram API 错误: Forbidden: bot was blocked by the user'.

3. Found by the isolated acceptance run: Telegram never used our sender

Running the real flow in an isolated instance (.agents/skills/panwatch-local-delivery) showed the whole feature was unreachable: without a proxy, Telegram was delivered by Apprise, so our sender — and with it the migration and the readable error — was never called. The channel test only ever reported

测试通知发送失败: Apprise 通知发送失败(可能是网络问题或配置错误)

Apprise does not expose the Telegram response, so neither the migration nor the real reason can be read from it. Telegram therefore always uses PanWatch's own client now:

if channel_type == "telegram":
    ...
    # Telegram 一律走自定义实现:只有自己发请求才能读到 Telegram 原始错误,
    # 从而处理群组升级为超级群后的 chat_id 迁移,并把真实失败原因告知用户。
    # 走 Apprise 时只会得到“发送失败”,迁移与排障都无从谈起。
    return None

Covered by a new test (build_apprise_url("telegram", …) is None and the channel is registered as a custom channel), so the routing cannot silently regress.

Isolated acceptance (real Telegram Bot API)

Private QA copy of the workspace — own DATA_DIR, own frontend build, 127.0.0.1 only, the running instance untouched:

PASS | A | 登录取得 JWT | http=200
PASS | A | 创建使用旧 chat_id 的 Telegram 渠道 | http=200
PASS | A | 测试通知成功并提示已迁移 | http=200 message='Telegram 群组已升级为超级群,chat_id 已自动更新为 -1006031292438'
PASS | A | 渠道配置已写回新的超级群 chat_id | chat_id='-1006031292438'
PASS | A | onboarding 判定该渠道为已验证 | verified=True
PASS | B | 失败时错误信息包含 Telegram 真实原因 | http=500 message='测试通知发送失败: telegram 发送失败: Telegram API 错误: Unauthorized: invalid token specified'
PASS | C | 重复测试仍然成功且不再重复迁移 | http=200

The message was really delivered to the authorized group; the server log shows the migration and both successful sends:

WARNING Telegram 群组已升级为超级群,旧 chat_id -5092912875 失效,改用 -1006031292438 重发
INFO    Telegram 通知发送成功: 测试通知

Test report

Report attachment pending — the REST API has no endpoint for uploading a ZIP to a pull request and this session has no browser file-picker tool, so the sanitized package could not be attached here. It is kept locally and can be attached from the PR page:

  • package panwatch-pr319-acceptance-report.zip (8,025 bytes)
  • ZIP SHA256 43f4b5b59aa92594e5cd7a07aa98e6cc331f1c78d1ab46a0c0cdfcbbfa6737ef
  • contents: report/index.html (offline, self-contained), report/OPEN.md, report/evidence/*.json, report/manifest.json, report/SHA256SUMS
  • verified: extracted into a new directory, sha256sum -c SHA256SUMS passes for every file, no token or credential inside

Identities: source 7d7a44b, source content hash 6f376157ac179bc2594a657b77bf53f91a5637cce9096bf43a4e024babae7b18, frontend build hash f8866f517e9e3fbe0a3ed1e2c972611bdfb5fd8e0117152e77c51f6017834fa0, QA run 1df50909-0319-4479-bf00-44973417eb4d.

Branch state

Rebased onto the current main (ddb24df, which includes the merged #318 and #322), single commit 7d7a44b, four files changed:

$ .venv/bin/python -m pytest -q tests/test_telegram_delivery.py tests/test_onboarding.py
34 passed, 5 warnings in 10.02s

$ .venv/bin/python -m pytest -q
1513 passed, 3 skipped, 33 warnings in 129.96s (0:02:09)

Ready for another look — thanks for catching the two defects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants