Deployment part edited#1
Conversation
* Add support to eval from .py and .txt file Reopened #313 * import `os` * 🤔🤔 * Remove useless code * Update __main__.py * ....... * typo * remove duplications + async read * bug fixes Co-authored-by: rking32 <sljohnwick@gmail.com>
Co-authored-by: yuno74 <92328346+yuno74@users.noreply.github.com>
* fix conditions * update to pyrogram v2 * fixes * fix conditions * pep8 * pep8 * Update raw_client.py * some minor things Co-authored-by: None <52490534+rking32@users.noreply.github.com> Co-authored-by: rking32 <sljohnwick@gmail.com>
* Fix deepsource * Update tools.py * Update tools.py Noobs everywhere
* Delete multiple sudo cmds from sudo at once * Fix pep8😁 * Pep8 * Typos * use delete_many() * Pep8🤦 * Now seems good * Typo😅 * Typo King 👑 * minor tweaks
* add syntax highlighting * fix f-string error * typo
* Fix deepsource [`consider-using-f-string`] * Update channel_logger.py * Update channel_logger.py Co-authored-by: None <52490534+rking32@users.noreply.github.com>
* deepsource * deepsource
* Make bash as default shell on unix * Forgot the walrus eyes ...
WalkthroughThe overall update enhances security, improves functionality, and modernizes code standards across various components of the project. Key changes include URL updates for enhanced security, numerical and version upgrades for better functionality, and significant code refinements in methods, classes, and plugins to align with updated libraries and coding practices. The update reflects a comprehensive effort to maintain the project's relevance and efficiency in the face of evolving technological standards. Changes
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (invoked as PR comments)
Additionally, you can add CodeRabbit Configration File (
|
There was a problem hiding this comment.
Review Status
Actionable comments generated: 6
Configuration used: CodeRabbit UI
Files ignored due to path filters (2)
resources/userge.pngis excluded by:!**/*.pngtea.yamlis excluded by:!**/*.yaml
Files selected for processing (25)
- README.md (1 hunks)
- min_loader.txt (1 hunks)
- requirements.txt (1 hunks)
- userge/core/client.py (7 hunks)
- userge/core/ext/raw_client.py (3 hunks)
- userge/core/methods/chats/send_read_acknowledge.py (1 hunks)
- userge/core/methods/decorators/raw_decorator.py (11 hunks)
- userge/core/methods/messages/edit_message_text.py (4 hunks)
- userge/core/methods/messages/send_as_file.py (1 hunks)
- userge/core/methods/messages/send_message.py (5 hunks)
- userge/core/types/bound/message.py (26 hunks)
- userge/core/types/new/channel_logger.py (3 hunks)
- userge/core/types/new/conversation.py (4 hunks)
- userge/core/types/raw/command.py (2 hunks)
- userge/core/types/raw/filter.py (4 hunks)
- userge/plugins/builtin/executor/main.py (14 hunks)
- userge/plugins/builtin/help/main.py (12 hunks)
- userge/plugins/builtin/loader/main.py (12 hunks)
- userge/plugins/builtin/sudo/main.py (2 hunks)
- userge/plugins/builtin/system/main.py (4 hunks)
- userge/plugins/builtin/tools/main.py (1 hunks)
- userge/sys_tools.py (3 hunks)
- userge/utils/progress.py (4 hunks)
- userge/utils/tools.py (7 hunks)
- userge/versions.py (1 hunks)
Files skipped from review due to trivial changes (3)
- min_loader.txt
- userge/plugins/builtin/loader/main.py
- userge/versions.py
Additional comments: 66
requirements.txt (1)
- 4-4: The upgrade of
pyrogramto version 2.0.58 is a significant update that likely introduces new features and bug fixes. Ensure compatibility with the existing codebase and perform thorough testing to catch any potential breaking changes.userge/utils/progress.py (2)
- 29-29: The addition of an optional
delayparameter enhances the flexibility of theprogressfunction. Consider adding documentation to explain its usage and impact.- 42-42: Using the
valueattribute for handlingFloodWaitexceptions is a direct approach. Ensure this change is thoroughly tested to handle rate-limiting scenarios effectively.userge/core/methods/chats/send_read_acknowledge.py (2)
- 57-59: Updating variable names to more descriptive ones, such as changing
message_idreferences toid, improves code readability. Ensure all references are consistently updated across the project.- 69-69: Changing the method call from
read_historytoread_chat_historyenhances clarity. Verify that this change is reflected wherever the method is invoked to maintain consistency.userge/sys_tools.py (1)
- 19-19: Introducing a caching mechanism for environment variables is a good practice for performance optimization. Consider adding comments to explain how the cache is managed and ensure proper cache invalidation if necessary.
userge/core/methods/messages/send_as_file.py (1)
- 19-19: Removing unused imports, such as
configfromuserge, is a good practice for maintaining clean code. Ensure that this change does not impact the module's functionality.README.md (1)
- 52-54: Updating URLs to use HTTPS in the documentation and deployment sections enhances security. Verify the accessibility of the updated URLs to ensure they are correct and accessible.
userge/core/methods/messages/edit_message_text.py (2)
- 32-32: Using
enums.ParseModefor theparse_modeparameter enhances type safety and readability. Ensure that this change is consistently applied whereverparse_modeis used across the project.- 101-101: Setting the
_clientattribute before deletion is an important fix. Consider adding comments to explain its necessity for future maintainability.userge/core/ext/raw_client.py (1)
- 45-47: Renaming the
sendmethod toinvokeand changing thedataparameter toqueryimproves naming clarity. Ensure that all references to these are consistently updated throughout the project.userge/core/types/raw/filter.py (1)
- 15-15: Replacing the import of
rawfilterswithenumsand usingenums.ChatTypefor thescopeparameter enhances type safety and readability. Ensure that the use of enumerated types is consistently applied and understood throughout the project.userge/core/methods/messages/send_message.py (4)
- 15-15: The addition of the
datetimeimport from thedatetimemodule is appropriate for supporting the newschedule_dateparameter type.- 34-34: Updating the
parse_modeparameter to acceptenums.ParseModeinstead of a generic object enhances type safety and code readability.- 39-39: Changing the
schedule_dateparameter to expect adatetime.datetimeobject instead of an integer is a good practice for clarity and correctness in handling date and time values.- 121-121: Setting the
_clientattribute ofmsgbefore deleting the message is a logical step to ensure that the message object is properly associated with the client. However, it's important to ensure that this does not introduce any side effects or dependencies that could affect the message deletion process.Verification successful
--- <!--Monologue: [observations] The script output indicates that the `_client` attribute is set in two places within the message handling code: `send_message.py` and `edit_message_text.py`. This suggests that setting the `_client` attribute is a practice used in multiple parts of the message handling process, not just an isolated case. [decomposition] Given this information, the verification task can be broken down into: 1. Understanding the purpose of setting the `_client` attribute in these contexts. 2. Determining if this practice is consistent and if it's designed to facilitate certain operations within the message handling process. 3. Assessing if setting the `_client` attribute just before message deletion (as in `send_message.py`) aligns with its usage in other parts of the code, such as `edit_message_text.py`. [analysis] The fact that the `_client` attribute is explicitly set in both message sending and editing suggests that it's an important part of the message lifecycle management within the library. This could imply that setting the `_client` attribute is intended to ensure that message objects are fully integrated with their client context, potentially for operations like editing or deleting messages. Given the limited scope of the search results, it's not clear if there are specific side effects associated with setting the `_client` attribute, but the consistency in its usage suggests that it's a standard practice rather than a potential source of issues. [actions] To conclude, the verification process should focus on the consistency and intended purpose of setting the `_client` attribute. Since the search did not reveal any direct evidence of side effects or issues caused by this practice, and given its consistent application, it seems reasonable to conclude that setting the `_client` attribute is a standard and necessary part of the message handling process in this library. --> Setting the `_client` attribute in `msg` objects within the message handling code, as observed in both `send_message.py` and `edit_message_text.py`, appears to be a consistent practice designed to ensure that message objects are properly associated with their client context. This consistency suggests that it is a standard part of the message lifecycle management within the library, rather than a source of potential side effects or issues. Therefore, the original review comment concern about introducing side effects or dependencies that could affect the message deletion process does not find evidence of issues based on the current analysis of the codebase. </details> <details> <summary>Scripts Executed</summary> The following scripts were executed for the analysis: --- Script: ```shell #!/bin/bash # Verify if setting the _client attribute introduces any side effects in message handling. # This script is a placeholder for the verification process and should be adapted to the specific verification needs. echo "Verify if setting the _client attribute introduces any side effects in message handling."Length of output: 186
Script:
#!/bin/bash # Search for references to the `_client` attribute within the message handling and deletion code. rg "_client" userge/core/methods/messages/Length of output: 221
userge/core/types/raw/command.py (2)
- 16-16: Importing
enumsfrompyrogramis necessary for the subsequent use ofenums.ChatType.CHANNELin the_outgoing_logicfunction. This change aligns with the PR's objective to enhance code readability and maintainability by using enums instead of string literals.- 99-99: Replacing the string literal
"channel"withenums.ChatType.CHANNELin the_outgoing_logicfunction is a good practice for code maintainability and readability. It leverages the type safety and clarity provided by enums.userge/plugins/builtin/tools/__main__.py (1)
- 124-124: Replacing
sendwithinvokewhen interacting with the client to ping the Telegram servers is consistent with the PR's objective to refine code functionality. This change likely reflects an update in the underlying library or a decision to use a more descriptive method name. Ensure that this change is reflected across all similar usages in the project for consistency.Verification successful
The verification process has revealed that the
.send(method does not appear in the provided output, indicating it might no longer be used in the context similar to the one under review. The.invoke(method, however, is found in three occurrences within the codebase, including the one inuserge/plugins/builtin/tools/__main__.pythat was part of the original review comment. This suggests that the change from.send(to.invoke(has been applied, at least in some parts of the project. Given the information available, it seems that the change is consistent with the project's direction, although a comprehensive review of all method usages would require a deeper analysis of the project's structure and documentation.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify if the change from `send` to `invoke` is consistently applied across the project. echo "Verify if the change from `send` to `invoke` is consistently applied across the project."Length of output: 322
Script:
#!/bin/bash # Search for occurrences of `.send(` and `.invoke(` in the codebase to verify the change consistency. echo "Searching for .send( occurrences:" rg "\.send\(" echo -e "\nSearching for .invoke( occurrences:" rg "\.invoke\("Length of output: 477
userge/core/types/new/channel_logger.py (3)
- 53-54: The method
get_linknow constructs the link using an f-string and returns it formatted within an HTML anchor tag. This change enhances readability and ensures the link is directly usable in HTML contexts.- 81-81: In the
logmethod, returningmsg.idinstead ofmsg.message_idaligns with Pyrogram's updated attribute naming. This change ensures consistency with the library's conventions.- 146-146: Similarly, in the
storemethod, assigningmsg.idtomessage_idinstead ofmsg.message_idmaintains uniformity across the codebase and aligns with Pyrogram's attribute naming conventions.userge/core/types/new/conversation.py (3)
- 22-22: Importing
enumsfrom Pyrogram at the beginning of the file is a good practice. It allows for using enum types throughout the file, which enhances code readability and type safety.- 116-116: Updating the type hint for
parse_modein thesend_messagemethod to useOptional[enums.ParseMode]is a significant improvement. It ensures type safety and clarity on the method's expected parameters.- 164-164: Changing
message.message_idtomessage.idin theforward_messagemethod aligns with Pyrogram's attribute naming conventions. This change ensures consistency and clarity in accessing message IDs.userge/utils/tools.py (4)
- 19-19: Importing
enumsfrom Pyrogram at the beginning of the file is a good practice. It allows for using enum types throughout the file, enhancing code readability and type safety.- 108-117: The formatting improvements in the
humanbytesfunction, specifically the alignment of dictionary elements, enhance readability and maintainability. This change makes it easier to understand the mapping between power and its corresponding unit.- 151-154: Enhancing logging messages in the
take_screen_shotfunction provides more context about the operation being performed. This change improves the clarity of logs, making it easier to debug and understand the process.- 225-253: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [217-241]
Updating the
extract_entitiesfunction to use Pyrogram enums for specifying message entity types improves code clarity and type safety. This change ensures that the function's behavior is more predictable and aligns with best practices.userge/core/client.py (4)
- 240-242: Initializing the
UsergeBotclass with additional parametersname="usergeBot"andin_memory=Trueis a good practice. It provides more context about the bot instance and optimizes memory usage by using in-memory storage.- 266-277: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [255-270]
The
Usergeclass initialization now includes a new parametername='userge'and setssession_stringbased onconfig.SESSION_STRING. These changes enhance the clarity and configurability of the userge instance.
- 323-323: Updating the logging message in the
_log_successmethod for formatting enhances readability. It ensures that the success message is clearly distinguishable in logs.- 327-327: Similarly, updating the logging message in the
_log_exitmethod for formatting improves readability. It clearly indicates the process of exiting Userge in logs.userge/core/methods/decorators/raw_decorator.py (3)
- 20-20: The import statement for
pyrogramhas been updated to includeenums. This change is positive as it enhances code readability and maintainability by using enums instead of string literals.- 107-110: The error handling in
_raise_funchas been refined to differentiate between private chats and groups when sending error messages. This is a good practice as it enhances user experience by providing context-appropriate responses. However, ensure that thelinkattribute ofr_mis always available and valid in group contexts to avoid potential errors.- 242-243: The
_build_decoratorfunction's signature has been updated to accept a union oftypes.raw.Commandandtypes.raw.Filter. This change likely enhances the flexibility of the decorator, allowing it to handle different types of filters more effectively. Ensure that all usages of this decorator throughout the codebase have been updated to align with this change.userge/plugins/builtin/executor/__main__.py (4)
- 14-14: The import of
osis a necessary addition for file handling operations, such as downloading and removing files. This change supports the new functionality added in theinput_checkerdecorator.- 26-27: The addition of
aiofilesimport is crucial for asynchronous file operations, which is a good practice for non-blocking I/O operations in an async environment. This change supports the asynchronous reading of files in theinput_checkerdecorator.- 46-46: The import of
enumsfrompyrogramis used to enhance code readability and maintainability by utilizing enums for parse modes instead of string literals. This is a good practice.- 105-105: The update to use
enums.ParseMode.MARKDOWNforparse_modein theexec_function is a good practice, as it uses the enum provided by Pyrogram instead of a string literal, enhancing code readability and maintainability.userge/plugins/builtin/help/__main__.py (9)
- 15-15: The addition of
enumsfrompyrogramis a good practice for using Pyrogram enums instead of string literals, enhancing code readability and maintainability.- 90-93: The reorganization of the
triggersassignment improves readability by grouping related items together. This change makes it easier to understand the triggers used in the command parsing logic.- 112-115: Updating the
parse_modeanddisable_web_page_previewarguments inmessage.editcalls to useenums.ParseMode.HTMLandTruerespectively is a good practice. It leverages the Pyrogram enums forparse_mode, which enhances code readability and maintainability, and the explicit disabling of web page previews can improve the user experience by preventing unnecessary previews from being shown.- 138-139: The use of decorators for permission checks (
@check_owner) before executing bot commands is a good security practice. It ensures that only the bot owner can interact with these commands, reducing the risk of unauthorized access or misuse.- 159-159: The explicit setting of
parse_modetoenums.ParseMode.HTMLanddisable_web_page_previewtoTruein theawait msg.replycall is consistent with best practices for enhancing message formatting and user experience.- 161-163: The regex pattern used in
filters.regex(pattern=r"\((.+)\)(next|prev)\((\d+)\)")for navigating between pages is well-constructed. It captures the necessary groups for determining the current position, the action (next or previous), and the page number, which is crucial for pagination logic.- 301-304: The button creation logic in
parse_buttonsfunction has been enhanced for better readability and maintainability. The use of list comprehensions and thecallback_dataformatting are clear and concise, making the code easier to understand and maintain.- 347-350: The dynamic update of the preferred client button (
"🔩 Preferred Client : {cur_clnt}") based on the current client mode is a user-friendly feature. It provides clear feedback to the user about the current mode and allows easy switching, enhancing the bot's usability.- 512-512: The handling of inline queries and the dynamic creation of inline query results, including error handling with a support button, is well-implemented. It enhances the bot's interactivity and provides a helpful user interface for troubleshooting.
userge/plugins/builtin/system/__main__.py (4)
- 15-15: The addition of
enumsfrompyrogramis a good practice for enhancing code readability and maintainability by using enums instead of string literals. This change aligns with the PR's objective of refining code functionality.- 173-173: The modification in the
delvar_function to check ifvar_datais not present before proceeding with deletion is a logical improvement. It ensures that an attempt to delete a non-existent variable is handled gracefully, providing feedback to the user.- 359-362: The update to the
Clientinitialization in theconvert_usermodefunction with the additionalin_memory=Trueparameter is a thoughtful addition. This parameter likely contributes to performance improvements by avoiding unnecessary disk I/O operations for temporary sessions. However, ensure that this change aligns with the overall application's session management strategy and does not introduce unintended side effects.Verification successful
The investigation into the
RawClientclass inuserge/core/ext/raw_client.pyshows that it extends theClientclass from pyrogram and focuses on handling flood control and rate limiting. It does not explicitly deal with session persistence settings, such as thein_memoryparameter. Therefore, the addition of thein_memory=Trueparameter inuserge/plugins/builtin/system/__main__.pyis unlikely to affect the behavior ofRawClientor other parts of the application in terms of session management. Based on the provided context, there's no evidence to suggest that the change conflicts with the application's session management strategy or introduces unintended side effects related to session persistence.* 417-417: Replacing `["code"]` with `[enums.MessageEntityType.CODE]` in the `convert_botmode` function is an excellent example of using Pyrogram enums for better code clarity. This change not only makes the code more readable but also reduces the likelihood of errors due to typos in string literals.Scripts Executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify if other parts of the application rely on persisted sessions that might be affected by this change. grep -R "Client(" .Length of output: 251
Script:
#!/bin/bash # Investigate the usage of Client in userge/core/ext/raw_client.py, focusing on session management aspects. cat ./userge/core/ext/raw_client.pyLength of output: 5055
userge/core/types/bound/message.py (13)
- 37-44: The constructor of the
Messageclass has been modified to include additional initialization parameters. Ensure that all instances ofMessagecreation throughout the codebase are updated to include these new parameters if necessary. This change enhances customization and control over message instances.- 48-57: The
parseclass method has been updated to handlereply_to_messagerecursively. This is a logical enhancement for parsing nested reply messages. However, ensure that this recursive parsing does not introduce infinite loops or excessive recursion depth in cases where messages are heavily nested.- 144-144: The use of Pyrogram enums for
MessageEntityType.TEXT_MENTIONinstead of string literals is a good practice for enhancing code readability and maintainability. This change aligns with the overall objective of using enums across the project.- 295-296: In the
reply_as_filemethod, the decision to delete the original message based on thedelete_messageparameter is a useful feature for managing chat cleanliness, especially when sending large outputs as files. However, ensure that this behavior is clearly documented and that callers of this method are aware that the original message may be deleted.- 311-321: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [314-363]
The
replymethod has been significantly updated with additional parameters, includingparse_mode,disable_web_page_preview, andprotect_content. These enhancements provide more control over how messages are sent. It's important to verify that all calls to this method have been reviewed to ensure they pass the correct arguments according to the new signature.
- 426-432: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [408-456]
The
editmethod's enhancements, including the handling ofMessageNotModifiedand other exceptions, improve the robustness of message editing operations. The fallback to reply in case of certain exceptions is a thoughtful addition but ensure that this behavior is intended and documented, as it changes the flow of interaction in the chat.
- 481-487: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [484-507]
The
force_editmethod introduces a fallback mechanism for editing messages, which is a useful feature for handling permissions-related errors gracefully. However, ensure that this method's behavior is consistent with the user's expectations and that it doesn't inadvertently expose or alter the intended message flow.
- 548-554: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [551-576]
The
errmethod's implementation, which allows sending error messages with an optional command info button, is a user-friendly feature. The conditional logic for showing help and handling bot usernames is well-implemented. Ensure that the error handling and user feedback mechanisms are thoroughly tested, especially in scenarios where inline bot results are used.
- 651-659: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [654-679]
The
force_errmethod, similar toforce_edit, provides a robust way to handle errors by attempting to edit and falling back to reply if necessary. This method enhances the error feedback mechanism. As with other methods that have fallback behaviors, ensure that this approach aligns with the intended user experience and is documented.
- 761-767: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [764-794]
The
edit_or_send_as_filemethod addresses the issue ofMessageTooLongby falling back to sending the content as a file. This is a clever solution for handling large messages that exceed Telegram's limits. Ensure that the transition between editing and sending as a file is seamless from the user's perspective and that any potential file size limits are also considered.
- 832-838: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [835-872]
The
reply_or_send_as_filemethod provides flexibility in handling large messages, similar toedit_or_send_as_file. This method enhances the bot's ability to manage message sizes effectively. As with other methods that offer fallback options, thorough testing is recommended to ensure the feature works as expected under various conditions.
- 923-929: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [926-953]
The
force_edit_or_send_as_filemethod combines the functionalities of force editing and handling large messages by sending them as files if necessary. This comprehensive approach to message handling ensures that the bot can adapt to different scenarios effectively. Ensure that the implementation details are well-documented and that users are aware of how the bot will behave in scenarios where editing is not possible.
- 923-929: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [926-953]
In the
deletemethod, handlingMessageDeleteForbiddenby optionally allowing sudo users to bypass this restriction is a thoughtful addition. However, ensure that this behavior is clearly communicated to users and that it aligns with the security and privacy expectations of the bot's functionality.
| # is this required? | ||
| # user.privileges.can_all = None | ||
| # if user.status == enums.ChatMemberStatus.OWNER: | ||
| # user.privileges.can_all = True | ||
| if user.status in ( |
There was a problem hiding this comment.
The commented-out code regarding user privileges seems to be left intentionally for reference or future use. However, leaving commented-out code can clutter the codebase. It's generally a good practice to remove such code or provide a clear comment on why it's retained.
- # is this required?
- # user.privileges.can_all = None
- # if user.status == enums.ChatMemberStatus.OWNER:
- # user.privileges.can_all = TrueConsider removing these lines if they are no longer needed, or add a more descriptive comment explaining their purpose.
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.
| # is this required? | |
| # user.privileges.can_all = None | |
| # if user.status == enums.ChatMemberStatus.OWNER: | |
| # user.privileges.can_all = True | |
| if user.status in ( | |
| if user.status in ( |
|
|
||
| if flt.check_change_info_perm and not ( | ||
| (user.can_all or user.can_change_info) and bot.can_change_info): | ||
| (user.privileges and bot.privileges) and ( | ||
| user.privileges.can_change_info and bot.privileges.can_change_info)): | ||
| return False | ||
| if flt.check_edit_perm and not ( | ||
| (user.can_all or user.can_edit_messages) and bot.can_edit_messages): | ||
| if flt.check_edit_perm and not ((user.privileges and bot.privileges) and ( | ||
| user.privileges.can_edit_messages and bot.privileges.can_edit_messages)): | ||
| return False | ||
| if flt.check_delete_perm and not ( | ||
| (user.can_all or user.can_delete_messages) and bot.can_delete_messages): | ||
| if flt.check_delete_perm and not ((user.privileges and bot.privileges) and ( | ||
| user.privileges.can_delete_messages and bot.privileges.can_delete_messages)): | ||
| return False | ||
| if flt.check_restrict_perm and not ( | ||
| (user.can_all or user.can_restrict_members) and bot.can_restrict_members): | ||
| if flt.check_restrict_perm and not ((user.privileges and bot.privileges) and ( | ||
| user.privileges.can_restrict_members and bot.privileges.can_restrict_members)): | ||
| return False | ||
| if flt.check_promote_perm and not ( | ||
| (user.can_all or user.can_promote_members) and bot.can_promote_members): | ||
| if flt.check_promote_perm and not ((user.privileges and bot.privileges) and ( | ||
| user.privileges.can_promote_members and bot.privileges.can_promote_members)): | ||
| return False | ||
| if flt.check_invite_perm and not ( | ||
| (user.can_all or user.can_invite_users) and bot.can_invite_users): | ||
| if flt.check_invite_perm and not ((user.privileges and bot.privileges) and ( | ||
| user.privileges.can_invite_users and bot.privileges.can_invite_users)): | ||
| return False | ||
| if flt.check_pin_perm and not ( | ||
| (user.can_all or user.can_pin_messages) and bot.can_pin_messages): | ||
| if flt.check_pin_perm and not ((user.privileges and bot.privileges) and ( | ||
| user.privileges.can_pin_messages and bot.privileges.can_pin_messages)): |
There was a problem hiding this comment.
The permission checks in _both_have_perm function are comprehensive and ensure that both the user and the bot have the required permissions before proceeding. This is crucial for maintaining the integrity and security of bot operations within chats. However, consider adding error handling for cases where user.privileges or bot.privileges might be None, to prevent attribute access errors.
+ if user.privileges is None or bot.privileges is None:
+ return FalseInsert this check before the permission checks to ensure robust error handling.
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.
| if flt.check_change_info_perm and not ( | |
| (user.can_all or user.can_change_info) and bot.can_change_info): | |
| (user.privileges and bot.privileges) and ( | |
| user.privileges.can_change_info and bot.privileges.can_change_info)): | |
| return False | |
| if flt.check_edit_perm and not ( | |
| (user.can_all or user.can_edit_messages) and bot.can_edit_messages): | |
| if flt.check_edit_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_edit_messages and bot.privileges.can_edit_messages)): | |
| return False | |
| if flt.check_delete_perm and not ( | |
| (user.can_all or user.can_delete_messages) and bot.can_delete_messages): | |
| if flt.check_delete_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_delete_messages and bot.privileges.can_delete_messages)): | |
| return False | |
| if flt.check_restrict_perm and not ( | |
| (user.can_all or user.can_restrict_members) and bot.can_restrict_members): | |
| if flt.check_restrict_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_restrict_members and bot.privileges.can_restrict_members)): | |
| return False | |
| if flt.check_promote_perm and not ( | |
| (user.can_all or user.can_promote_members) and bot.can_promote_members): | |
| if flt.check_promote_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_promote_members and bot.privileges.can_promote_members)): | |
| return False | |
| if flt.check_invite_perm and not ( | |
| (user.can_all or user.can_invite_users) and bot.can_invite_users): | |
| if flt.check_invite_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_invite_users and bot.privileges.can_invite_users)): | |
| return False | |
| if flt.check_pin_perm and not ( | |
| (user.can_all or user.can_pin_messages) and bot.can_pin_messages): | |
| if flt.check_pin_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_pin_messages and bot.privileges.can_pin_messages)): | |
| if user.privileges is None or bot.privileges is None: | |
| return False | |
| if flt.check_change_info_perm and not ( | |
| (user.privileges and bot.privileges) and ( | |
| user.privileges.can_change_info and bot.privileges.can_change_info)): | |
| return False | |
| if flt.check_edit_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_edit_messages and bot.privileges.can_edit_messages)): | |
| return False | |
| if flt.check_delete_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_delete_messages and bot.privileges.can_delete_messages)): | |
| return False | |
| if flt.check_restrict_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_restrict_members and bot.privileges.can_restrict_members)): | |
| return False | |
| if flt.check_promote_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_promote_members and bot.privileges.can_promote_members)): | |
| return False | |
| if flt.check_invite_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_invite_users and bot.privileges.can_invite_users)): | |
| return False | |
| if flt.check_pin_perm and not ((user.privileges and bot.privileges) and ( | |
| user.privileges.can_pin_messages and bot.privileges.can_pin_messages)): |
| if not message.input_str: | ||
| if (func.__name__ == "eval_" | ||
| and replied and replied.document | ||
| and replied.document.file_name.endswith(('.txt', '.py')) | ||
| and replied.document.file_size <= 2097152): | ||
|
|
||
| dl_loc = await replied.download() | ||
| async with aiofiles.open(dl_loc) as jv: | ||
| message.text += " " + await jv.read() | ||
| os.remove(dl_loc) | ||
| message.flags.update({'file': True}) | ||
| else: | ||
| await message.err("No Command Found!") | ||
| return | ||
|
|
There was a problem hiding this comment.
The logic in the input_checker decorator has been enhanced to handle file downloads and processing. This is a significant improvement, allowing the execution of code from files attached to messages. However, ensure that file size and type checks are sufficient to prevent potential security risks, such as executing malicious code or handling excessively large files.
Consider adding more explicit checks on the file type and content before execution to enhance security.
| async def _callback(output: Optional[str], errored: bool): | ||
| final = "" | ||
| if not silent_mode: | ||
| final += f"**>** ```{cmd}```\n\n" | ||
| final += "**>**" + (replied.link if is_file else f"```python\n{cmd}```") + "\n\n" | ||
| if isinstance(output, str): | ||
| output = output.strip() | ||
| if output == '': | ||
| output = None | ||
| if output is not None: | ||
| final += f"**>>** ```{output}```" | ||
| if errored and message.chat.type in ("group", "supergroup", "channel"): | ||
| final += f"**>>** ```python\n{output}```" | ||
| if errored and message.chat.type in ( | ||
| enums.ChatType.GROUP, | ||
| enums.ChatType.SUPERGROUP, | ||
| enums.ChatType.CHANNEL): | ||
| msg_id = await CHANNEL.log(final) | ||
| await msg.edit(f"**Logs**: {CHANNEL.get_link(msg_id)}") | ||
| elif final: | ||
| await msg.edit_or_send_as_file(text=final, | ||
| as_raw=as_raw, | ||
| parse_mode='md', | ||
| parse_mode=enums.ParseMode.MARKDOWN, | ||
| disable_web_page_preview=True, | ||
| filename="eval.txt", | ||
| caption=cmd) | ||
| else: | ||
| await msg.delete() | ||
|
|
||
| msg = message | ||
| replied = message.reply_to_message | ||
| if (replied and replied.from_user | ||
| and replied.from_user.is_self and isinstance(replied.text, Str) | ||
| and str(replied.text.html).startswith("<b>></b> <pre>")): | ||
| msg = replied | ||
|
|
||
| await msg.edit("`Executing eval ...`", parse_mode='md') | ||
|
|
||
| _g, _l = _context( | ||
| context_type, userge=userge, message=message, replied=message.reply_to_message) | ||
| _g, _l = _context(context_type, userge=userge, | ||
| message=message, replied=message.reply_to_message) | ||
| l_d = {} | ||
| try: | ||
| exec(_wrap_code(cmd, _l.keys()), _g, l_d) # nosec pylint: disable=W0122 | ||
| # nosec pylint: disable=W0122 | ||
| exec(_wrap_code(cmd, _l.keys()), _g, l_d) | ||
| except Exception: # pylint: disable=broad-except | ||
| _g[_KEY] = _l | ||
| await _callback(traceback.format_exc(), True) | ||
| return | ||
|
|
||
| future = asyncio.get_running_loop().create_future() | ||
| pool.submit_thread(_run_coro, future, l_d['__aexec'](*_l.values()), _callback) | ||
| pool.submit_thread( | ||
| _run_coro, | ||
| future, | ||
| l_d['__aexec']( | ||
| *_l.values()), | ||
| _callback) | ||
| hint = cmd.split('\n')[0] | ||
| _EVAL_TASKS[future] = hint[:25] + "..." if len(hint) > 25 else hint | ||
|
|
There was a problem hiding this comment.
📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [187-218]
The enhancements in the eval_ function, including handling flags and tasks more efficiently, are commendable. Using enums for parse modes and improving the output formatting contribute to a better user experience and code maintainability. However, ensure that the execution environment for the evaluated code is securely sandboxed to prevent potential security risks.
Consider adding more explicit security measures or sandboxing techniques to ensure that evaluated code cannot access or modify sensitive parts of the bot's environment or the host system.
| out_data = f"{output}<pre>{t_obj.output}</pre>\n{prefix}" | ||
| await message.edit_or_send_as_file( | ||
| out_data, as_raw=as_raw, parse_mode='html', filename="term.txt", caption=cmd) | ||
| out_data, as_raw=as_raw, parse_mode=enums.ParseMode.HTML, filename="term.txt", caption=cmd) |
There was a problem hiding this comment.
The improvements in the term_ function for better output handling and parsing are beneficial. Using HTML parse mode for formatting terminal command outputs enhances the readability of the output. Ensure that the command execution environment is secure and that user inputs are properly sanitized to prevent command injection vulnerabilities.
Consider adding explicit input validation or sanitization to prevent potential security risks associated with executing shell commands based on user input.
| if not cmd: | ||
| await message.err('input not found!') | ||
| return | ||
| if cmd not in sudo.COMMANDS: | ||
| await message.edit(f"cmd : `{cmd}` not in **SUDO**!", del_in=5) | ||
| else: | ||
| sudo.COMMANDS.remove(cmd) | ||
| await asyncio.gather( | ||
| SUDO_CMDS_COLLECTION.delete_one({'_id': cmd}), | ||
| message.edit(f"cmd : `{cmd}` removed from **SUDO**!", del_in=5, log=__name__)) | ||
| NOT_IN_SUDO = [] | ||
| IS_REMOVED = [] | ||
| for ncmd in cmd.split(" "): | ||
| if ncmd not in sudo.COMMANDS: | ||
| NOT_IN_SUDO.append(ncmd) | ||
| else: | ||
| sudo.COMMANDS.remove(ncmd) | ||
| IS_REMOVED.append(ncmd) | ||
| if IS_REMOVED: | ||
| await SUDO_CMDS_COLLECTION.delete_many({'_id': {'$in': IS_REMOVED}}) | ||
| await message.edit( | ||
| f"cmds : `{' '.join(IS_REMOVED)}` removed from **SUDO**!", | ||
| del_in=5, log=__name__) | ||
| if NOT_IN_SUDO and not IS_REMOVED: | ||
| await message.edit( | ||
| f"cmds : `{' '.join(NOT_IN_SUDO)}` not in **SUDO**!", del_in=5) | ||
| elif NOT_IN_SUDO: | ||
| await message.reply_text( | ||
| f"cmds : `{' '.join(NOT_IN_SUDO)}` not in **SUDO**!", del_in=5) | ||
|
|
||
|
|
||
| @userge.on_cmd("vscmd", about={'header': "view sudo cmds"}, allow_channels=False) |
There was a problem hiding this comment.
📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [160-191]
Enhancing the del_sudo_cmd function to handle multiple command deletions at once and providing feedback on which commands were successfully removed and which were not found in the sudo commands list is a significant improvement. It improves the user experience by allowing batch operations and clear feedback. However, ensure that the command names are properly sanitized and validated to prevent any unintended behavior.
Consider adding input validation to ensure that the command names provided for deletion are valid and do not contain any special characters that could lead to unintended behavior.
Edited Deployment part
Summary by CodeRabbit