Skip to content

style: enforce PEP8 compliance and update documentation structure#23

Closed
akaBoyLovesToCode wants to merge 7 commits intoembyplus:mainfrom
akaBoyLovesToCode:readme
Closed

style: enforce PEP8 compliance and update documentation structure#23
akaBoyLovesToCode wants to merge 7 commits intoembyplus:mainfrom
akaBoyLovesToCode:readme

Conversation

@akaBoyLovesToCode
Copy link
Contributor

@akaBoyLovesToCode akaBoyLovesToCode commented Feb 14, 2025

This PR introduces the following changes:

  1. Ruff Configuration Update:

    • Adjusted Ruff settings to enforce PEP8 compliance.
    • Set the line-length to 79 to conform with PEP8 standards.
    • Removed the ignore rule for E501, enabling line-length checks.
    • Ensured that the overall formatting aligns with PEP8 requirements.
  2. Documentation Filename Update:

    • Removed the old readme.md file in order to rename it with an uppercase filename.
  3. README and Contribution Guide Refactor:

    • Refactored and enhanced the content of README.md for better clarity.
    • Moved the contribution guide to a separate CONTRIBUTING.md file to better organize documentation.

These changes aim to improve code style consistency and enhance project documentation.

Sourcery 总结

在整个项目中强制执行 PEP8 合规性并更新文档结构。将 README 文件名更新为大写,将贡献指南移至单独的文件,并重构 ensure_args 方法以使用装饰器。改进整个项目的日志记录和错误处理。

增强功能:

  • 重构 ensure_args 方法以使用装饰器来检查命令参数,从而简化命令函数。
  • 改进日志消息,以实现更好的调试和错误跟踪。
  • 更新 _parse_args 方法以更有效地处理命令参数。
  • 更新 _send_error 方法以提供更丰富的信息性错误消息。
  • 改进 get_user_telegram_id 函数中的错误处理和日志记录。
  • 改进 Emby API 客户端中的错误处理和日志记录。
  • 改进 Emby Router API 客户端中的错误处理和日志记录。
  • 改进 parse_iso8601parse_timestamp_to_normal_date 函数中的错误处理。
  • 更新 user_in_group_on_filteradmin_user_on_filter 函数以处理频道成员。
  • 更新 emby_user_on_filter 函数以改进错误处理。
  • 更新 User 模型以包含 telegram_name 字段并改进 check_use_redeem_code 方法。
  • 更新 InviteCode 模型以使用更清晰的命名约定。
  • 更新 Config 模型以使用更清晰的命名约定。
  • 更新 BotClient 初始化以简化该过程。
  • 更新 fetch_group_members 函数以处理多个组 ID。
  • 更新 CommandHandler 初始化以改进依赖项注入。
  • 更新 group_member_change_handler 函数以更有效地处理成员更改。
  • 更新 handle_callback_query 函数以改进错误处理和用户反馈。
  • 更新 count 函数以更优雅地处理缺少的数据。
  • 更新 register_untilregister_amount 函数以改进输入验证。
  • 更新 ban_embyunban_emby 函数以改进错误处理和用户反馈。
  • 更新 select_line 函数以更优雅地处理缺少的路由器列表。
  • 更新 new_codenew_whitelist_code 函数以更有效地处理消息回复。
  • 更新 reset_emby_password 函数以改进错误处理和用户反馈。
  • 更新 info 函数以更清楚地显示 ban 信息。
  • 更新 use_code 函数以更有效地处理不同的邀请码类型。
  • 更新 create_user 函数以改进错误处理和用户反馈。
  • 更新 help_command 函数以提供更全面的帮助信息。
  • 更新 setup_commands 函数以改进命令注册。
  • 更新 main 函数以改进日志记录和初始化。
  • 更新 get_or_create_user_by_telegram_id 函数以处理缺少的用户名。
  • 更新 must_get_emby_user 函数以提供更具体的错误消息。
  • 更新 _emby_create_user 函数以更有效地处理 Emby API 错误。
  • 更新 emby_create_user 函数以更准确地处理注册权限。
  • 更新 _check_register_permission 函数以处理过期的注册时间。
  • 更新 redeem_code 函数以防止竞争情况。
  • 更新 reset_password 函数以改进错误处理。
  • 更新 emby_banemby_unban 函数以处理管理员权限。
  • 更新 set_emby_config 函数以处理管理员权限。
  • 更新 update_user_router 函数以改进类型处理。
  • 更新 get_router_list 函数以处理缺少的 Emby 用户信息。
  • 更新 parse_args 函数以处理空参数。
  • 更新 create_user, info, use_code, reset_emby_password, new_code, new_whitelist_code, ban_emby, unban_emby, register_until, register_amount 命令函数以使用新的 ensure_args 装饰器。
  • 更新 first_or_create_emby_config 函数以确保配置初始化。
  • 更新 emby_info 函数以处理缺少的 Emby 用户数据。
  • 更新 get_user_router 函数以处理缺少的 Emby 用户数据。
  • 更新 update_user_router 函数以处理缺少的 Emby 用户数据。
  • 更新 get_router_list 函数以处理缺少的 Emby 用户数据。
  • 更新 call_api 函数以处理 API 密钥授权。
  • 更新 query_all_route, query_user_route, 和 update_user_route 函数以处理 API 错误。
  • 更新 get_user, create_user, ban_user, set_default_policy, update_user_policy, reset_user_password, set_user_password, check_emby_site, 和 count 函数以处理 API 错误。
  • 更新 gen_default_passwd, gen_register_code, 和 gen_whitelist_code 函数以提高代码清晰度。
  • 更新 create_invite_codecreate_whitelist_code 函数以处理用户权限。
  • 更新 emby_ban_info 函数以提高代码清晰度。
  • 更新 idle 函数以提高代码清晰度。
  • 更新 stop 函数以提高代码清晰度。
  • 更新 create_database_if_not_exists 函数以提高代码清晰度。
  • 更新 _init_db 函数以提高代码清晰度。
  • 更新 _init_logger 函数以改进日志记录配置。
  • 更新 _init_tz 函数以改进错误处理。
  • 更新 setup_bot 函数以提高代码清晰度。
  • 更新 fetch_group_members 函数以提高代码清晰度。
  • 更新 main 函数以提高代码清晰度和日志记录。

文档:

  • 将 README 文件名更新为大写,并将贡献指南移至单独的 CONTRIBUTING.md 文件。
  • 重构和改进 README 和贡献指南的内容,以获得更好的清晰度和组织性。
  • 删除旧的 readme.md 文件
Original summary in English

Summary by Sourcery

Enforce PEP8 compliance across the project and update the documentation structure. Update the README filename to uppercase, move the contribution guidelines to a separate file, and refactor the ensure_args method to use a decorator. Improve logging and error handling throughout the project.

Enhancements:

  • Refactor the ensure_args method to use a decorator for checking command arguments, simplifying command functions.
  • Improve logging messages for better debugging and error tracking.
  • Update the _parse_args method to handle command arguments more efficiently.
  • Update the _send_error method to provide more informative error messages.
  • Improve error handling and logging in the get_user_telegram_id function.
  • Improve error handling and logging in the Emby API client.
  • Improve error handling and logging in the Emby Router API client.
  • Improve error handling in the parse_iso8601 and parse_timestamp_to_normal_date functions.
  • Update the user_in_group_on_filter and admin_user_on_filter functions to handle channel members.
  • Update the emby_user_on_filter function to improve error handling.
  • Update the User model to include a telegram_name field and improve the check_use_redeem_code method.
  • Update the InviteCode model to use clearer naming conventions.
  • Update the Config model to use clearer naming conventions.
  • Update the BotClient initialization to simplify the process.
  • Update the fetch_group_members function to handle multiple group IDs.
  • Update the CommandHandler initialization to improve dependency injection.
  • Update the group_member_change_handler function to handle member changes more efficiently.
  • Update the handle_callback_query function to improve error handling and user feedback.
  • Update the count function to handle missing data more gracefully.
  • Update the register_until and register_amount functions to improve input validation.
  • Update the ban_emby and unban_emby functions to improve error handling and user feedback.
  • Update the select_line function to handle missing router list more gracefully.
  • Update the new_code and new_whitelist_code functions to handle message replies more efficiently.
  • Update the reset_emby_password function to improve error handling and user feedback.
  • Update the info function to display ban information more clearly.
  • Update the use_code function to handle different invitation code types more effectively.
  • Update the create_user function to improve error handling and user feedback.
  • Update the help_command function to provide more comprehensive help information.
  • Update the setup_commands function to improve command registration.
  • Update the main function to improve logging and initialization.
  • Update the get_or_create_user_by_telegram_id function to handle missing usernames.
  • Update the must_get_emby_user function to provide more specific error messages.
  • Update the _emby_create_user function to handle Emby API errors more effectively.
  • Update the emby_create_user function to handle registration permissions more accurately.
  • Update the _check_register_permission function to handle expired registration times.
  • Update the redeem_code function to prevent race conditions.
  • Update the reset_password function to improve error handling.
  • Update the emby_ban and emby_unban functions to handle admin permissions.
  • Update the set_emby_config function to handle admin permissions.
  • Update the update_user_router function to improve type handling.
  • Update the get_router_list function to handle missing Emby user information.
  • Update the parse_args function to handle empty arguments.
  • Update the create_user, info, use_code, reset_emby_password, new_code, new_whitelist_code, ban_emby, unban_emby, register_until, register_amount command functions to use the new ensure_args decorator.
  • Update the first_or_create_emby_config function to ensure config initialization.
  • Update the emby_info function to handle missing Emby user data.
  • Update the get_user_router function to handle missing Emby user data.
  • Update the update_user_router function to handle missing Emby user data.
  • Update the get_router_list function to handle missing Emby user data.
  • Update the call_api function to handle API key authorization.
  • Update the query_all_route, query_user_route, and update_user_route functions to handle API errors.
  • Update the get_user, create_user, ban_user, set_default_policy, update_user_policy, reset_user_password, set_user_password, check_emby_site, and count functions to handle API errors.
  • Update the gen_default_passwd, gen_register_code, and gen_whitelist_code functions to improve code clarity.
  • Update the create_invite_code and create_whitelist_code functions to handle user permissions.
  • Update the emby_ban_info function to improve code clarity.
  • Update the idle function to improve code clarity.
  • Update the stop function to improve code clarity.
  • Update the create_database_if_not_exists function to improve code clarity.
  • Update the _init_db function to improve code clarity.
  • Update the _init_logger function to improve logging configuration.
  • Update the _init_tz function to improve error handling.
  • Update the setup_bot function to improve code clarity.
  • Update the fetch_group_members function to improve code clarity.
  • Update the main function to improve code clarity and logging.

Documentation:

  • Update the README file name to uppercase and move the contribution guidelines to a separate CONTRIBUTING.md file.
  • Refactor and improve the content of the README and contribution guide for better clarity and organization.
  • Remove the old readme.md file

- Resolved AttributeError caused by attempting to call 'get' on a 'User' object
- Updated code to properly check if group member data exists before accessing 'username'
- Changed logger to output to both terminal and log file
- Added StreamHandler to output logs to terminal for easier debugging in IDEs
- Retained FileHandler to write logs to default.log for persistence
- Set logging level based on config.log_level
- Set line-length to 79 to conform with PEP8 standards
- Removed ignore for E501 to enable line-length checks
- Ensured formatting aligns with PEP8 requirements
@sourcery-ai
Copy link

sourcery-ai bot commented Feb 14, 2025

## Sourcery 代码审查指南

本次 PR 通过更新 Ruff 配置来强制执行 PEP8 规范,并通过创建单独的贡献指南来重构文档结构。它还引入了一个用于命令参数验证的装饰器,并向 `Config` 类中的 `group_members` 属性添加了类型提示。

#### CommandHandler 的更新类图

```mermaid
classDiagram
    class CommandHandler {
        - bot_client: BotClient
        - user_service: UserService
        + _parse_args(message: Message) list[str]
        + ensure_args(min_len: int, usage: str) decorator
        + _send_error(message: Message, error: Exception, prefix: str) void
        + create_user(message: Message, args: list[str])
        + info(message: Message)
        + use_code(message: Message, args: list[str])
        + reset_emby_password(message: Message)
        + new_code(message: Message)
        + new_whitelist_code(message: Message)
        + ban_emby(message: Message)
        + unban_emby(message: Message)
        + select_line(message: Message)
        + group_member_change_handler(clent, message: Message)
        + handle_callback_query(client, callback_query: CallbackQuery)
        + count(message: Message)
        + register_until(message: Message, args: list[str])
        + register_amount(message: Message, args: list[str])
        + help_command(message: Message)
        + setup_commands()
    }
    note for CommandHandler "ensure_args 方法现在是一个静态方法,并用作装饰器。"

文件级别变更

变更 详情 文件
实现了装饰器以确保足够的命令行参数,从而提高代码可读性并减少冗余。
  • 添加了一个静态方法 ensure_args,它接受 min_lenusage 作为参数。
  • ensure_args 中创建了一个装饰器来包装命令函数。
  • 从包装器函数中的消息中解析参数。
  • 检查解析的参数数量是否满足最小长度要求。
  • 如果参数不足,则回复用法消息。
  • 如果参数足够,则将解析的参数传递给包装的函数。
bot/commands.py
更新了 Ruff 配置以强制执行 PEP8 规范,将行长度设置为 79 并启用行长度检查。
  • line-length 设置为 79。
  • 删除了 E501 的忽略规则。
ruff.toml
通过更新 README 并创建单独的贡献指南来重构和增强项目文档。
  • 删除了旧的 readme.md 文件。
  • 重构和增强了 README.md 的内容,以提高清晰度。
  • 将贡献指南移动到单独的 CONTRIBUTING.md 文件。
README.md
CONTRIBUTING.md
Config 类中的 group_members 属性添加类型提示。
  • Config 类中的 group_members 属性添加了 dict[int, Any] 类型提示。
config.py

提示和命令

与 Sourcery 互动

  • 触发新的审查: 在 pull request 上评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审查评论。
  • 从审查评论生成 GitHub issue: 通过回复审查评论,要求 Sourcery 从审查评论创建一个 issue。您也可以回复审查评论并使用 @sourcery-ai issue 从中创建一个 issue。
  • 生成 pull request 标题: 在 pull request 标题中的任何位置写入 @sourcery-ai 以随时生成标题。您也可以在 pull request 上评论 @sourcery-ai title 以随时(重新)生成标题。
  • 生成 pull request 摘要: 在 pull request 正文中的任何位置写入 @sourcery-ai summary 以随时在您想要的位置生成 PR 摘要。您也可以在 pull request 上评论 @sourcery-ai summary 以随时(重新)生成摘要。
  • 生成审查员指南: 在 pull request 上评论 @sourcery-ai guide 以随时(重新)生成审查员指南。
  • 解决所有 Sourcery 评论: 在 pull request 上评论 @sourcery-ai resolve 以解决所有 Sourcery 评论。如果您已经解决了所有评论并且不想再看到它们,这将非常有用。
  • 驳回所有 Sourcery 审查: 在 pull request 上评论 @sourcery-ai dismiss 以驳回所有现有的 Sourcery 审查。如果您想重新开始新的审查,这将特别有用 - 不要忘记评论 @sourcery-ai review 以触发新的审查!
  • 为 issue 生成行动计划: 在 issue 上评论 @sourcery-ai plan 以为其生成行动计划。

自定义您的体验

访问您的 仪表板 以:

  • 启用或禁用审查功能,例如 Sourcery 生成的 pull request 摘要、审查员指南等。
  • 更改审查语言。
  • 添加、删除或编辑自定义审查说明。
  • 调整其他审查设置。

获得帮助

```
Original review guide in English

Reviewer's Guide by Sourcery

This PR enforces PEP8 compliance by updating the Ruff configuration and refactors the documentation structure by creating a separate contribution guide. It also introduces a decorator for command argument validation and adds type hints to the group_members attribute in the Config class.

Updated class diagram for CommandHandler

classDiagram
    class CommandHandler {
        - bot_client: BotClient
        - user_service: UserService
        + _parse_args(message: Message) list[str]
        + ensure_args(min_len: int, usage: str) decorator
        + _send_error(message: Message, error: Exception, prefix: str) void
        + create_user(message: Message, args: list[str])
        + info(message: Message)
        + use_code(message: Message, args: list[str])
        + reset_emby_password(message: Message)
        + new_code(message: Message)
        + new_whitelist_code(message: Message)
        + ban_emby(message: Message)
        + unban_emby(message: Message)
        + select_line(message: Message)
        + group_member_change_handler(clent, message: Message)
        + handle_callback_query(client, callback_query: CallbackQuery)
        + count(message: Message)
        + register_until(message: Message, args: list[str])
        + register_amount(message: Message, args: list[str])
        + help_command(message: Message)
        + setup_commands()
    }
    note for CommandHandler "The ensure_args method is now a static method and is used as a decorator."
Loading

File-Level Changes

Change Details Files
Implemented a decorator to ensure sufficient command-line arguments, improving code readability and reducing redundancy.
  • Added a static method ensure_args that takes min_len and usage as arguments.
  • Created a decorator within ensure_args to wrap command functions.
  • Parsed arguments from the message within the wrapper function.
  • Checked if the number of parsed arguments meets the minimum length requirement.
  • Replied with a usage message if arguments are insufficient.
  • Passed the parsed arguments to the wrapped function if arguments are sufficient.
bot/commands.py
Updated the Ruff configuration to enforce PEP8 compliance, setting the line length to 79 and enabling line length checks.
  • Set the line-length to 79.
  • Removed the ignore rule for E501.
ruff.toml
Refactored and enhanced project documentation by updating the README and creating a separate contribution guide.
  • Removed the old readme.md file.
  • Refactored and enhanced the content of README.md for better clarity.
  • Moved the contribution guide to a separate CONTRIBUTING.md file.
README.md
CONTRIBUTING.md
Add type hints to the group_members attribute in the Config class.
  • Added dict[int, Any] type hint to the group_members attribute in the Config class.
config.py

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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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

@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.

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

总体评论

  • 考虑使用 ruff format 自动应用格式更改,而不是手动更改代码。
  • 新的装饰器 @ensure_args 看起来是减少样板代码的好方法。
这是我在审查期间查看的内容
  • 🟡 一般问题:发现 3 个问题
  • 🟢 安全性:一切看起来都很好
  • 🟡 测试:发现 2 个问题
  • 🟡 复杂性:发现 1 个问题
  • 🟢 文档:一切看起来都很好

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

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

Overall Comments:

  • Consider using ruff format to automatically apply formatting changes instead of manually changing the code.
  • The new decorator @ensure_args looks like a good way to reduce boilerplate code.
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 2 issues found
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

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.

telegram_id=telegram_id,
is_admin=telegram_id in config.admin_list,
telegram_name=config.group_members.get(telegram_id, {}).get('username'),
telegram_name=config.group_members.get(
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): 字典上的属性访问可能存在问题。

从使用 get('username') 更改为访问 .username 属性,假设 config.group_members 中的值是一个具有 username 属性的对象,而不是一个字典。请验证此更改在 group_members 条目是字典的上下文中是否是故意的且正确。

Original comment in English

issue (bug_risk): Potential issue with attribute access on a dictionary.

The change from using get('username') to accessing the .username attribute assumes that the value in config.group_members is an object with a username attribute rather than a dict. Verify that this change is intentional and correct in contexts where group_members entries are dictionaries.

Comment on lines 20 to +24
# Initialize logger
logger = logging.getLogger(__name__)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): 多个日志处理程序可能会导致重复的日志消息。

app.py 中的日志配置现在同时添加了控制台处理程序和文件处理程序,并且 _init_logger() 添加了额外的处理程序。请确保重复初始化不会无意中注册重复的处理程序,这将导致重复的日志输出。

Suggested change
# Initialize logger
logger = logging.getLogger(__name__)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
# 初始化日志记录器
logger = logging.getLogger(__name__)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
if not any(isinstance(handler, logging.StreamHandler) for handler in logger.handlers):
logger.addHandler(console_handler)
Original comment in English

suggestion (bug_risk): Multiple logger handlers may lead to duplicate log messages.

The logger configuration in app.py now adds both a console handler and a file handler, and _init_logger() adds additional handlers. Make sure that repeated initialization does not inadvertently register duplicate handlers, which would result in repeated logging outputs.

Suggested change
# Initialize logger
logger = logging.getLogger(__name__)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
# Initialize logger
logger = logging.getLogger(__name__)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
if not any(isinstance(handler, logging.StreamHandler) for handler in logger.handlers):
logger.addHandler(console_handler)

<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json" alt="uv">
</a>
<a href="https://results.pre-commit.ci/latest/github/nonebot/nonebot2/master">
<img src="https://results.pre-commit.ci/badge/github/nonebot/nonebot2/master.svg" alt="pre-commit" />
Copy link

Choose a reason for hiding this comment

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

issue (typo): 错别字:"pre-commit" 中缺少空格

在徽章链接中的 "pre" 和 "commit" 之间添加一个空格。

Suggested change
<img src="https://results.pre-commit.ci/badge/github/nonebot/nonebot2/master.svg" alt="pre-commit" />
<img src="https://results.pre-commit.ci/badge/github/nonebot/nonebot2/master.svg" alt="pre commit" />
Original comment in English

issue (typo): Typo: Missing space in "pre-commit"

Add a space between "pre" and "commit" in the badge link.

Suggested change
<img src="https://results.pre-commit.ci/badge/github/nonebot/nonebot2/master.svg" alt="pre-commit" />
<img src="https://results.pre-commit.ci/badge/github/nonebot/nonebot2/master.svg" alt="pre commit" />


```bash
git clone https://github.com/embyplus/embyBot
```
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): 占位符内容:单元测试

“单元测试”部分似乎不完整。要么用实际内容充实它,要么暂时删除它。

建议的实现方式:

<!-- 删除不完整的单元测试部分 -->

如果您稍后决定向“单元测试”添加内容,只需插入一个包含适当信息或测试的新部分即可。

Original comment in English

suggestion (testing): Placeholder content: Unit Tests

The "Unit Tests" section seems incomplete. Either flesh it out with actual content or remove it for now.

Suggested implementation:

<!-- Removed incomplete Unit Tests section -->

If you later decide to add content to "Unit Tests", simply insert a new section with the appropriate information or tests.

Comment on lines +104 to +106
### Integration Tests

Continuous integration with [Sourcery-ai](https://sourcery.ai//).
Copy link

Choose a reason for hiding this comment

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

issue (testing): 链接损坏且内容不完整:集成测试

指向 Sourcery-ai 的链接已损坏(缺少斜杠)。此外,请考虑添加有关集成测试的更多详细信息。

Original comment in English

issue (testing): Broken link and incomplete content: Integration Tests

The link to Sourcery-ai is broken (missing a slash). Also, consider adding more details about the integration tests.

return parts[1:] if len(parts) > 1 else []

async def _ensure_args(self, message: Message, args: list, min_len: int, usage: str):
@staticmethod
Copy link

Choose a reason for hiding this comment

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

issue (complexity): 考虑将参数验证装饰器移动到单独的辅助模块,以获得更好的代码组织和可读性。

您可以通过将装饰器提取到单独的辅助模块来减少额外的嵌套(由内联装饰器引起)。这样,命令函数保持专注,控制流程更清晰。例如,创建一个单独的文件 (decorators.py):

# decorators.py
import functools

def ensure_args(min_len, usage):
    def decorator(func):
        @functools.wraps(func)
        async def wrapper(self, message, *args, **kwargs):
            parsed_args = self._parse_args(message)
            if len(parsed_args) < min_len:
                await self._reply_html(
                    message,
                    f"参数不足,请参考用法:\n<code>{usage}</code>"
                )
                return
            return await func(self, message, parsed_args, *args, **kwargs)
        return wrapper
    return decorator

然后更新您的命令文件以导入它:

from decorators import ensure_args

@ensure_args(1, "/register_amount <人数>")
async def register_amount(self, message: Message, args: list[str]):
    ...

这种分离使命令中的核心业务逻辑免受深度嵌套的影响,从而使代码审查和调试更容易,而不会改变功能。

Original comment in English

issue (complexity): Consider moving the argument validation decorator to a separate helper module for better code organization and readability.

You might reduce the extra nesting (caused by the inline decorator) by extracting the decorator into a separate helper module. That way, the command functions remain focused and the control flow clearer. For example, create a separate file (decorators.py):

# decorators.py
import functools

def ensure_args(min_len, usage):
    def decorator(func):
        @functools.wraps(func)
        async def wrapper(self, message, *args, **kwargs):
            parsed_args = self._parse_args(message)
            if len(parsed_args) < min_len:
                await self._reply_html(
                    message,
                    f"参数不足,请参考用法:\n<code>{usage}</code>"
                )
                return
            return await func(self, message, parsed_args, *args, **kwargs)
        return wrapper
    return decorator

Then update your command file to import it:

from decorators import ensure_args

@ensure_args(1, "/register_amount <人数>")
async def register_amount(self, message: Message, args: list[str]):
    ...

This separation keeps the core business logic in your commands free from deep nesting, making code review and debugging easier without altering functionality.

@akaBoyLovesToCode
Copy link
Contributor Author

不太懂为什么上一个pr的4个commits也在

@akaBoyLovesToCode
Copy link
Contributor Author

本次pr实际上为最新的3个commits

@akaBoyLovesToCode
Copy link
Contributor Author

我明天研究下重新pr吧…

@akaBoyLovesToCode
Copy link
Contributor Author

你看下改动有啥问题没

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.

1 participant