Skip to content

Conversation

xunxiing
Copy link

@xunxiing xunxiing commented Jun 22, 2025

解决了#1293

Motivation

引入了专门的 BlacklistCheckStage,并新增了 /bl/dbl 聊天命令,用于运行时管理黑名单。同时,配置元数据中新增了启用黑名单、黑名单列表及日志记录等选项;测试套件覆盖了用户 ID、群组 ID 和会话 ID 的黑名单拦截验证。

Modifications

  1. 新增 BlacklistCheckStage
    • initialize() 中加载黑名单配置:
  2. 新增 /bl/dbl 命令
    • /bl [list|<ID>]:查看或添加黑名单
    • /dbl <ID>:删除黑名单
    • 成功/失败消息反馈用户,避免重复添加。

Check

  • 😊 我的 Commit Message 符合良好的规范
  • 👀 我的更改经过良好的测试
  • 🤓 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到了 requirements.txtpyproject.toml 文件相应位置。
  • 😮 我的更改没有引入恶意代码

好的,这是将 pull request 总结翻译成中文的结果:

Sourcery 总结

将黑名单处理提取到专用管道阶段,并通过命令启用运行时黑名单管理,相应地更新配置模式,并为黑名单强制执行添加测试。

新功能:

  • 添加 BlacklistCheckStage,以便在启用黑名单时按用户、群组或会话 ID 阻止消息。
  • 引入“/bl”命令,供管理员在运行时列出或将 ID 添加到黑名单。
  • 引入“/dbl”命令,供管理员在运行时从黑名单中删除 ID。
  • 公开配置选项:enable_id_black_listid_blacklistid_blacklist_log

增强功能:

  • 在处理管道中的 WhitelistCheckStage 之前插入 BlacklistCheckStage
  • 启用 id_blacklist_log 后,在 INFO 级别记录消息拒绝。

测试:

  • 添加测试用例以验证用户 ID、群组 ID 和会话来源的黑名单拦截。
Original summary in English

Summary by Sourcery

Extract blacklist handling into a dedicated pipeline stage and enable runtime blacklist management via commands, update configuration schema accordingly, and add tests for blacklist enforcement.

New Features:

  • Add BlacklistCheckStage to block messages by user, group, or session ID when blacklisting is enabled.
  • Introduce "/bl" command for administrators to list or add IDs to the blacklist at runtime.
  • Introduce "/dbl" command for administrators to remove IDs from the blacklist at runtime.
  • Expose configuration options: enable_id_black_list, id_blacklist, and id_blacklist_log.

Enhancements:

  • Insert BlacklistCheckStage before WhitelistCheckStage in the processing pipeline.
  • Log message rejections at INFO level when id_blacklist_log is enabled.

Tests:

  • Add test cases to verify blacklist interception for user IDs, group IDs, and session origins.

Copy link
Contributor

sourcery-ai bot commented Jun 22, 2025

## Reviewer's Guide

此 PR 将黑名单处理重构为一个专用的管道阶段,引入了用于在运行时管理黑名单的管理员命令,使用黑名单选项扩展了配置元数据,并为黑名单强制执行添加了全面的测试。

#### Entity relationship diagram for updated blacklist config options

```mermaid
erDiagram
    PLATFORM_SETTINGS {
        bool enable_id_black_list
        list id_blacklist
        bool id_blacklist_log
    }
    PLATFORM_SETTINGS ||--o{ ID_BLACKLIST : contains
    ID_BLACKLIST {
        string id
    }

Class diagram for new BlacklistCheckStage and related changes

classDiagram
    class BlacklistCheckStage {
        +bool enable_blacklist
        +list blacklist
        +bool bl_log
        +initialize(ctx: PipelineContext) None
        +process(event: AstrMessageEvent) None | AsyncGenerator
    }
    BlacklistCheckStage --|> Stage
    Stage <|-- BlacklistCheckStage
    PipelineContext <.. BlacklistCheckStage : uses
    AstrMessageEvent <.. BlacklistCheckStage : uses
Loading

Class diagram for new admin blacklist commands

classDiagram
    class Main {
        +bl(event: AstrMessageEvent, uid: str=None)
        +dbl(event: AstrMessageEvent, uid: str)
    }
    Main : context
    Main : dwl(...)
    Main : provider(...)
    AstrMessageEvent <.. Main : uses
Loading

File-Level Changes

Change Details Files
Introduce BlacklistCheckStage for pipeline-based blacklist filtering
  • Register new stage in STAGES_ORDER and all
  • Create BlacklistCheckStage with initialize and process logic
  • Load enable flag, blacklist entries, and logging option from config
  • Halt event propagation and log when origin, sender, or group is blacklisted
astrbot/core/pipeline/__init__.py
astrbot/core/pipeline/blacklist_check/stage.py
Add admin chat commands for runtime blacklist management
  • Implement /bl command to list or add IDs to blacklist
  • Implement /dbl command to remove IDs from blacklist
  • Enforce admin-only permission on both commands
  • Persist config after modifications and provide user feedback
packages/astrbot/main.py
Extend configuration metadata with blacklist options
  • Add enable_id_black_list, id_blacklist, and id_blacklist_log in default settings
  • Expose corresponding schema entries with descriptions and hints
  • Ensure default blacklist is disabled and empty
  • Maintain consistency in JSON formatting
astrbot/core/config/default.py
Add test coverage for blacklist enforcement and commands
  • Define blacklist constants for user, group, and session IDs
  • Extend test scenarios to cover /bl and /dbl commands
  • Configure enable_id_black_list and initial blacklist entries
  • Add asynchronous tests to verify event suppression and logging
tests/test_pipeline.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

```
Original review guide in English

Reviewer's Guide

This PR refactors blacklist handling into a dedicated pipeline stage, introduces admin commands for managing the blacklist at runtime, extends configuration metadata with blacklist options, and adds comprehensive tests for blacklist enforcement.

Entity relationship diagram for updated blacklist config options

erDiagram
    PLATFORM_SETTINGS {
        bool enable_id_black_list
        list id_blacklist
        bool id_blacklist_log
    }
    PLATFORM_SETTINGS ||--o{ ID_BLACKLIST : contains
    ID_BLACKLIST {
        string id
    }
Loading

Class diagram for new BlacklistCheckStage and related changes

classDiagram
    class BlacklistCheckStage {
        +bool enable_blacklist
        +list blacklist
        +bool bl_log
        +initialize(ctx: PipelineContext) None
        +process(event: AstrMessageEvent) None | AsyncGenerator
    }
    BlacklistCheckStage --|> Stage
    Stage <|-- BlacklistCheckStage
    PipelineContext <.. BlacklistCheckStage : uses
    AstrMessageEvent <.. BlacklistCheckStage : uses
Loading

Class diagram for new admin blacklist commands

classDiagram
    class Main {
        +bl(event: AstrMessageEvent, uid: str=None)
        +dbl(event: AstrMessageEvent, uid: str)
    }
    Main : context
    Main : dwl(...)
    Main : provider(...)
    AstrMessageEvent <.. Main : uses
Loading

File-Level Changes

Change Details Files
Introduce BlacklistCheckStage for pipeline-based blacklist filtering
  • Register new stage in STAGES_ORDER and all
  • Create BlacklistCheckStage with initialize and process logic
  • Load enable flag, blacklist entries, and logging option from config
  • Halt event propagation and log when origin, sender, or group is blacklisted
astrbot/core/pipeline/__init__.py
astrbot/core/pipeline/blacklist_check/stage.py
Add admin chat commands for runtime blacklist management
  • Implement /bl command to list or add IDs to blacklist
  • Implement /dbl command to remove IDs from blacklist
  • Enforce admin-only permission on both commands
  • Persist config after modifications and provide user feedback
packages/astrbot/main.py
Extend configuration metadata with blacklist options
  • Add enable_id_black_list, id_blacklist, and id_blacklist_log in default settings
  • Expose corresponding schema entries with descriptions and hints
  • Ensure default blacklist is disabled and empty
  • Maintain consistency in JSON formatting
astrbot/core/config/default.py
Add test coverage for blacklist enforcement and commands
  • Define blacklist constants for user, group, and session IDs
  • Extend test scenarios to cover /bl and /dbl commands
  • Configure enable_id_black_list and initial blacklist entries
  • Add asynchronous tests to verify event suppression and logging
tests/test_pipeline.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
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.

@xunxiing - 我已经审查了你的更改 - 这里有一些反馈:

  • /bl/dbl 处理程序在每次调用时都会写入配置,这可能会阻塞;考虑批量处理或防抖 save_config() 以减少 I/O 开销。
  • 黑名单命令在改变条目之前,不会验证 enable_id_black_list 是否已打开;添加一个保护,以防止在禁用该功能时进行修改。
  • 列出黑名单的测试仅检查子字符串“黑名单”;通过断言确切的列表内容来收紧这一点,以避免误报。
AI 代理的提示
请解决此代码审查中的评论:
## 总体评论
- `/bl``/dbl` 处理程序在每次调用时都会写入配置,这可能会阻塞;考虑批量处理或防抖 `save_config()` 以减少 I/O 开销。
- 黑名单命令在改变条目之前,不会验证 `enable_id_black_list` 是否已打开;添加一个保护,以防止在禁用该功能时进行修改。
- 列出黑名单的测试仅检查子字符串“黑名单”;通过断言确切的列表内容来收紧这一点,以避免误报。

## 个别评论

### 评论 1
<location> `tests/test_pipeline.py:251` </location>
<code_context>
+    with caplog.at_level(logging.INFO):
+        await pipeline_scheduler.execute(mock_event)
+    assert any("黑名单" in message for message in caplog.messages)
+    config["platform_settings"]["id_blacklist"].remove(BLACKLIST_SESSION)
+
     mock_event = FakeAstrMessageEvent.create_fake_event("test", sender_id="123")
</code_context>

<issue_to_address>
考虑添加禁用黑名单功能的测试。

请添加一个测试,其中 enable_id_black_list 为 False,以确认在禁用黑名单时,黑名单中的 ID 不会被阻止。
</issue_to_address>

### 评论 2
<location> `astrbot/core/config/default.py:28` </location>
<code_context>
         "id_whitelist_log": True,
         "wl_ignore_admin_on_group": True,
         "wl_ignore_admin_on_friend": True,
+        "enable_id_black_list": False,
+        "id_blacklist": [],
+        "id_blacklist_log": True,
</code_context>

<issue_to_address>
考虑将默认值和模式定义保存在不同的部分,以保持关注点的清晰分离。

无需采取任何措施——这些部分服务于不同的目的(默认值与模式定义),应保持分离。
</issue_to_address>

Sourcery 对开源是免费的 - 如果你喜欢我们的评论,请考虑分享它们 ✨
帮助我更有用!请点击每个评论上的 👍 或 👎,我将使用反馈来改进你的评论。
Original comment in English

Hey @xunxiing - I've reviewed your changes - here's some feedback:

  • The /bl and /dbl handlers write the config on every call which may block; consider batching or debouncing save_config() to reduce I/O overhead.
  • The blacklist commands don’t verify if enable_id_black_list is turned on before mutating entries; add a guard to prevent modifications when the feature is disabled.
  • The test for listing the blacklist only checks for the substring “黑名单”; tighten this by asserting the exact list contents to avoid false positives.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The `/bl` and `/dbl` handlers write the config on every call which may block; consider batching or debouncing `save_config()` to reduce I/O overhead.
- The blacklist commands don’t verify if `enable_id_black_list` is turned on before mutating entries; add a guard to prevent modifications when the feature is disabled.
- The test for listing the blacklist only checks for the substring “黑名单”; tighten this by asserting the exact list contents to avoid false positives.

## Individual Comments

### Comment 1
<location> `tests/test_pipeline.py:251` </location>
<code_context>
+    with caplog.at_level(logging.INFO):
+        await pipeline_scheduler.execute(mock_event)
+    assert any("黑名单" in message for message in caplog.messages)
+    config["platform_settings"]["id_blacklist"].remove(BLACKLIST_SESSION)
+
     mock_event = FakeAstrMessageEvent.create_fake_event("test", sender_id="123")
</code_context>

<issue_to_address>
Consider adding tests for disabling blacklist functionality.

Please add a test where enable_id_black_list is False to confirm that blacklisted IDs are not blocked when the blacklist is disabled.
</issue_to_address>

### Comment 2
<location> `astrbot/core/config/default.py:28` </location>
<code_context>
         "id_whitelist_log": True,
         "wl_ignore_admin_on_group": True,
         "wl_ignore_admin_on_friend": True,
+        "enable_id_black_list": False,
+        "id_blacklist": [],
+        "id_blacklist_log": True,
</code_context>

<issue_to_address>
Consider keeping default values and schema definitions in separate sections to maintain clear separation of concerns.

No action needed—these sections serve different purposes (default values vs. schema definitions) and should remain separate.
</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.

with caplog.at_level(logging.INFO):
await pipeline_scheduler.execute(mock_event)
assert any("黑名单" in message for message in caplog.messages)
config["platform_settings"]["id_blacklist"].remove(BLACKLIST_SESSION)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): 考虑添加禁用黑名单功能的测试。

请添加一个测试,其中 enable_id_black_list 为 False,以确认在禁用黑名单时,黑名单中的 ID 不会被阻止。

Original comment in English

suggestion (testing): Consider adding tests for disabling blacklist functionality.

Please add a test where enable_id_black_list is False to confirm that blacklisted IDs are not blocked when the blacklist is disabled.

@@ -25,6 +25,9 @@
"id_whitelist_log": True,
"wl_ignore_admin_on_group": True,
"wl_ignore_admin_on_friend": True,
"enable_id_black_list": False,
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): 考虑将默认值和模式定义保存在不同的部分,以保持关注点的清晰分离。

无需采取任何措施——这些部分服务于不同的目的(默认值与模式定义),应保持分离。

Original comment in English

issue (complexity): Consider keeping default values and schema definitions in separate sections to maintain clear separation of concerns.

No action needed—these sections serve different purposes (default values vs. schema definitions) and should remain separate.

event.set_result(MessageEventResult().message(msg))
return

uid = str(uid)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): 删除不必要的 int、str、float 或 bool 转换(remove-unnecessary-cast

Suggested change
uid = str(uid)
uid = uid
Original comment in English

suggestion (code-quality): Remove unnecessary casts to int, str, float or bool (remove-unnecessary-cast)

Suggested change
uid = str(uid)
uid = uid

@xunxiing
Copy link
Author

xunxiing commented Jun 22, 2025

@sourcery-ai
我已经按照你的要求提交了新的修改

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