style: enforce PEP8 compliance and update documentation structure#23
style: enforce PEP8 compliance and update documentation structure#23akaBoyLovesToCode wants to merge 7 commits intoembyplus:mainfrom akaBoyLovesToCode:readme
Conversation
- 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
… to CONTRIBUTING.md
文件级别变更
提示和命令与 Sourcery 互动
自定义您的体验访问您的 仪表板 以:
获得帮助Original review guide in EnglishReviewer's Guide by SourceryThis 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 Updated class diagram for CommandHandlerclassDiagram
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."
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
嘿 @Qubbby - 我已经审查了你的更改 - 这里有一些反馈:
总体评论:
- 考虑使用
ruff format自动应用格式更改,而不是手动更改代码。 - 新的装饰器
@ensure_args看起来是减少样板代码的好方法。
这是我在审查期间查看的内容
- 🟡 一般问题:发现 3 个问题
- 🟢 安全性:一切看起来都很好
- 🟡 测试:发现 2 个问题
- 🟡 复杂性:发现 1 个问题
- 🟢 文档:一切看起来都很好
帮助我更有用!请点击每个评论上的 👍 或 👎,我将使用反馈来改进您的评论。
Original comment in English
Hey @Qubbby - I've reviewed your changes - here's some feedback:
Overall Comments:
- Consider using
ruff formatto automatically apply formatting changes instead of manually changing the code. - The new decorator
@ensure_argslooks 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
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( |
There was a problem hiding this comment.
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.
| # Initialize logger | ||
| logger = logging.getLogger(__name__) | ||
| console_handler = logging.StreamHandler() | ||
| console_handler.setLevel(logging.INFO) | ||
| logger.addHandler(console_handler) |
There was a problem hiding this comment.
suggestion (bug_risk): 多个日志处理程序可能会导致重复的日志消息。
app.py 中的日志配置现在同时添加了控制台处理程序和文件处理程序,并且 _init_logger() 添加了额外的处理程序。请确保重复初始化不会无意中注册重复的处理程序,这将导致重复的日志输出。
| # 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.
| # 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" /> |
There was a problem hiding this comment.
issue (typo): 错别字:"pre-commit" 中缺少空格
在徽章链接中的 "pre" 和 "commit" 之间添加一个空格。
| <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.
| <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 | ||
| ``` |
There was a problem hiding this comment.
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.
| ### Integration Tests | ||
|
|
||
| Continuous integration with [Sourcery-ai](https://sourcery.ai//). |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 decoratorThen 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.
|
不太懂为什么上一个pr的4个commits也在 |
|
本次pr实际上为最新的3个commits |
|
我明天研究下重新pr吧… |
|
你看下改动有啥问题没 |
This PR introduces the following changes:
Ruff Configuration Update:
Documentation Filename Update:
readme.mdfile in order to rename it with an uppercase filename.README and Contribution Guide Refactor:
README.mdfor better clarity.CONTRIBUTING.mdfile 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函数中的错误处理和日志记录。parse_iso8601和parse_timestamp_to_normal_date函数中的错误处理。user_in_group_on_filter和admin_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_until和register_amount函数以改进输入验证。ban_emby和unban_emby函数以改进错误处理和用户反馈。select_line函数以更优雅地处理缺少的路由器列表。new_code和new_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_ban和emby_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_code和create_whitelist_code函数以处理用户权限。emby_ban_info函数以提高代码清晰度。idle函数以提高代码清晰度。stop函数以提高代码清晰度。create_database_if_not_exists函数以提高代码清晰度。_init_db函数以提高代码清晰度。_init_logger函数以改进日志记录配置。_init_tz函数以改进错误处理。setup_bot函数以提高代码清晰度。fetch_group_members函数以提高代码清晰度。main函数以提高代码清晰度和日志记录。文档:
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_argsmethod to use a decorator. Improve logging and error handling throughout the project.Enhancements:
ensure_argsmethod to use a decorator for checking command arguments, simplifying command functions._parse_argsmethod to handle command arguments more efficiently._send_errormethod to provide more informative error messages.get_user_telegram_idfunction.parse_iso8601andparse_timestamp_to_normal_datefunctions.user_in_group_on_filterandadmin_user_on_filterfunctions to handle channel members.emby_user_on_filterfunction to improve error handling.Usermodel to include atelegram_namefield and improve thecheck_use_redeem_codemethod.InviteCodemodel to use clearer naming conventions.Configmodel to use clearer naming conventions.BotClientinitialization to simplify the process.fetch_group_membersfunction to handle multiple group IDs.CommandHandlerinitialization to improve dependency injection.group_member_change_handlerfunction to handle member changes more efficiently.handle_callback_queryfunction to improve error handling and user feedback.countfunction to handle missing data more gracefully.register_untilandregister_amountfunctions to improve input validation.ban_embyandunban_embyfunctions to improve error handling and user feedback.select_linefunction to handle missing router list more gracefully.new_codeandnew_whitelist_codefunctions to handle message replies more efficiently.reset_emby_passwordfunction to improve error handling and user feedback.infofunction to display ban information more clearly.use_codefunction to handle different invitation code types more effectively.create_userfunction to improve error handling and user feedback.help_commandfunction to provide more comprehensive help information.setup_commandsfunction to improve command registration.mainfunction to improve logging and initialization.get_or_create_user_by_telegram_idfunction to handle missing usernames.must_get_emby_userfunction to provide more specific error messages._emby_create_userfunction to handle Emby API errors more effectively.emby_create_userfunction to handle registration permissions more accurately._check_register_permissionfunction to handle expired registration times.redeem_codefunction to prevent race conditions.reset_passwordfunction to improve error handling.emby_banandemby_unbanfunctions to handle admin permissions.set_emby_configfunction to handle admin permissions.update_user_routerfunction to improve type handling.get_router_listfunction to handle missing Emby user information.parse_argsfunction to handle empty arguments.create_user,info,use_code,reset_emby_password,new_code,new_whitelist_code,ban_emby,unban_emby,register_until,register_amountcommand functions to use the newensure_argsdecorator.first_or_create_emby_configfunction to ensure config initialization.emby_infofunction to handle missing Emby user data.get_user_routerfunction to handle missing Emby user data.update_user_routerfunction to handle missing Emby user data.get_router_listfunction to handle missing Emby user data.call_apifunction to handle API key authorization.query_all_route,query_user_route, andupdate_user_routefunctions to handle API errors.get_user,create_user,ban_user,set_default_policy,update_user_policy,reset_user_password,set_user_password,check_emby_site, andcountfunctions to handle API errors.gen_default_passwd,gen_register_code, andgen_whitelist_codefunctions to improve code clarity.create_invite_codeandcreate_whitelist_codefunctions to handle user permissions.emby_ban_infofunction to improve code clarity.idlefunction to improve code clarity.stopfunction to improve code clarity.create_database_if_not_existsfunction to improve code clarity._init_dbfunction to improve code clarity._init_loggerfunction to improve logging configuration._init_tzfunction to improve error handling.setup_botfunction to improve code clarity.fetch_group_membersfunction to improve code clarity.mainfunction to improve code clarity and logging.Documentation: