Skip to content

fix(telegram): normalize reply sender_id to self_id for bot replies#8237

Open
woleigedouer wants to merge 3 commits into
AstrBotDevs:masterfrom
woleigedouer:fix/telegram-reply-wake
Open

fix(telegram): normalize reply sender_id to self_id for bot replies#8237
woleigedouer wants to merge 3 commits into
AstrBotDevs:masterfrom
woleigedouer:fix/telegram-reply-wake

Conversation

@woleigedouer
Copy link
Copy Markdown

@woleigedouer woleigedouer commented May 19, 2026

Telegram adapter stored Reply.sender_id as numeric user ID while self_id is the bot username, causing WakingCheckStage to never match replies to bot messages in groups.

When the / wake prefix is removed, replying to a bot message in a Telegram group should still wake the bot through the generic Reply wake check. Before this change, Telegram replies only worked in some text-message cases because of the existing /@bot fallback path, not because Reply.sender_id matched event.get_self_id().

Modifications / 改动点

  • Normalize Telegram Reply.sender_id to message.self_id only when the replied message was sent by the bot.
  • Keep replies to normal users using their original numeric Telegram user ID.
  • Keep message.self_id as the Telegram bot username to avoid affecting @bot_username wake behavior.
  • Keep the existing Telegram text reply /@bot fallback for compatibility.
  • Add Telegram adapter tests for bot replies and normal user replies.
  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

.\venv\Scripts\python.exe -m pytest tests\test_telegram_adapter.py -q
11 passed
.\venv\Scripts\python.exe -m ruff format . --check
426 files already formatted
.\venv\Scripts\python.exe -m ruff check .
All checks passed!

Manual verification:

  • With this fix applied, replying to a Telegram bot message wakes the bot even after removing / from wake_prefix.
  • Without this fix, replying to a Telegram bot message does not wake the bot when / is removed.
  • Adding / back makes the old fallback path work again, confirming the previous behavior depended on the /@bot text fallback instead of the generic Reply wake check.

Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Normalize Telegram reply metadata so replies to bot messages use the bot self ID while preserving existing behavior for user replies.

Bug Fixes:

  • Ensure Telegram replies to bot messages correctly match the bot self ID so generic reply-based wake checks work in group chats.

Tests:

  • Add Telegram adapter tests verifying sender_id normalization for replies to bot messages and preservation of numeric IDs for replies to normal users.

Telegram adapter stored Reply.sender_id as numeric user ID while
self_id is the bot username, causing WakingCheckStage to never
match replies to bot messages in groups.
@auto-assign auto-assign Bot requested review from Soulter and anka-afk May 19, 2026 07:14
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. area:platform The bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on. labels May 19, 2026
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In the tests, _find_reply_component uses next(...) without a default, which will raise an opaque StopIteration if the Reply component is missing; consider asserting or using a safer helper that fails with a clearer message.
  • When normalizing reply_sender_id, you assign either str(reply_abm.sender.user_id) or message.self_id, which may represent different identifier formats (numeric ID vs username); it would be helpful to make the intended invariant for sender_id explicit in code (e.g., via a short comment) to avoid future confusion.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the tests, `_find_reply_component` uses `next(...)` without a default, which will raise an opaque `StopIteration` if the `Reply` component is missing; consider asserting or using a safer helper that fails with a clearer message.
- When normalizing `reply_sender_id`, you assign either `str(reply_abm.sender.user_id)` or `message.self_id`, which may represent different identifier formats (numeric ID vs username); it would be helpful to make the intended invariant for `sender_id` explicit in code (e.g., via a short comment) to avoid future confusion.

## Individual Comments

### Comment 1
<location path="tests/test_telegram_adapter.py" line_range="145-150" />
<code_context>
+        reply_to_message=reply_to_message,
+    )
+
+    result = await adapter.convert_message(update, _build_context())
+
+    assert result is not None
+    reply = _find_reply_component(result)
+    assert reply.sender_id == "87654321"
+    assert reply.qq == 87654321
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Consider asserting more of the Reply payload (id and chain) to ensure reply metadata is preserved

The tests currently verify `sender_id` and `qq`, but not that reply metadata like `id` and `chain` still match `reply_to_message`. Please also assert something like `reply.id == reply_to_message.message_id` and add a minimal check on `reply.chain` (e.g., non-empty or contains the original text) to ensure normalization doesn’t inadvertently alter these fields.

```suggestion
    result = await adapter.convert_message(update, _build_context())

    assert result is not None
    reply = _find_reply_component(result)
    assert reply.sender_id == "87654321"
    assert reply.qq == 87654321
    # reply metadata should be preserved
    assert reply.id == reply_to_message.message_id
    assert reply.chain
    # ensure the reply chain still carries the original reply text
    if getattr(reply_to_message, "text", None):
        assert any(
            getattr(component, "text", None) == reply_to_message.text
            for component in reply.chain
        )
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/test_telegram_adapter.py
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request updates the Telegram adapter to normalize the sender ID when a message is a reply to the bot, ensuring it matches the bot's self_id. Corresponding unit tests were added to verify this behavior for both bot and user replies. Feedback was provided to remove a redundant string conversion for the sender ID to improve code readability.

Comment thread astrbot/core/platform/sources/telegram/tg_adapter.py Outdated
woleigedouer and others added 2 commits May 19, 2026 16:22
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:platform The bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on. size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant