Skip to content

Deployment part edited#1

Open
Pranay5463 wants to merge 27 commits into
Pranay5463:alphafrom
UsergeTeam:alpha
Open

Deployment part edited#1
Pranay5463 wants to merge 27 commits into
Pranay5463:alphafrom
UsergeTeam:alpha

Conversation

@Pranay5463

@Pranay5463 Pranay5463 commented Apr 30, 2022

Copy link
Copy Markdown
Owner

Edited Deployment part

Summary by CodeRabbit

  • Documentation
    • Updated URLs in the documentation for enhanced security and accuracy.
  • New Features
    • Upgraded dependencies to improve functionality and compatibility.
    • Introduced new initialization parameters for better customization and in-memory operations.
    • Enhanced message handling and logging for improved user interaction and feedback.
    • Added support for Pyrogram enums in various methods for more precise type handling.
  • Refactor
    • Improved internal logic and method naming for clarity and consistency across the codebase.
    • Enhanced error handling and logging functionalities for better debuggability.
    • Optimized code structure for readability and maintenance, including the use of enums for type safety.
  • Bug Fixes
    • Fixed variable naming and method calls related to message handling for consistency.
    • Adjusted datetime handling in message scheduling for accuracy.
  • Chores
    • Updated the version to reflect the latest changes and improvements.

SpEcHiDe and others added 27 commits April 30, 2022 15:51
* 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 ...
@coderabbitai

coderabbitai Bot commented Feb 22, 2024

Copy link
Copy Markdown

Walkthrough

The 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

Files Change Summary
README.md Updated URLs from http:// to https:// for enhanced security.
min_loader.txt, userge/versions.py Updated numerical values and version increment.
requirements.txt Upgraded pyrogram version for improved functionality.
userge/core/client.py, .../core/types/new/channel_logger.py, .../new/conversation.py, .../raw/command.py, .../raw/filter.py Introduced additional parameters and updated method names, variable names, and logic to align with new standards and functionalities.
userge/core/ext/raw_client.py, .../methods/chats/send_read_acknowledge.py, .../methods/messages/edit_message_text.py, .../messages/send_as_file.py, .../messages/send_message.py, .../types/bound/message.py Renamed methods, updated parameter types, and refined logic for better clarity and efficiency.
userge/core/methods/decorators/raw_decorator.py, .../methods/messages/send_message.py, .../plugins/builtin/executor/__main__.py, .../builtin/help/__main__.py, .../builtin/loader/__main__.py, .../builtin/sudo/__main__.py, .../builtin/system/__main__.py, .../builtin/tools/__main__.py, userge/utils/progress.py, .../utils/tools.py Enhanced error handling, logging, formatting, and asyncio handling. Adjusted imports and logic to utilize enums from pyrogram and improved method calls for efficiency and readability.
userge/sys_tools.py Introduced caching mechanism for environment variables.

"In the realm of code, where rabbits dare to tread,
Changes abound, in the files we've just read.
URLs secure, and versions ascend,
With each line refined, we aim to amend.
🐇💻 Through the digital meadow, we hop with glee,
For in code's evolution, endless possibilities we see."

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?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 6

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 3707286 and ffdd4cc.
Files ignored due to path filters (2)
  • resources/userge.png is excluded by: !**/*.png
  • tea.yaml is 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 pyrogram to 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 delay parameter enhances the flexibility of the progress function. Consider adding documentation to explain its usage and impact.
  • 42-42: Using the value attribute for handling FloodWait exceptions 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_id references to id, improves code readability. Ensure all references are consistently updated across the project.
  • 69-69: Changing the method call from read_history to read_chat_history enhances 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 config from userge, 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.ParseMode for the parse_mode parameter enhances type safety and readability. Ensure that this change is consistently applied wherever parse_mode is used across the project.
  • 101-101: Setting the _client attribute 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 send method to invoke and changing the data parameter to query improves 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 rawfilters with enums and using enums.ChatType for the scope parameter 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 datetime import from the datetime module is appropriate for supporting the new schedule_date parameter type.
  • 34-34: Updating the parse_mode parameter to accept enums.ParseMode instead of a generic object enhances type safety and code readability.
  • 39-39: Changing the schedule_date parameter to expect a datetime.datetime object instead of an integer is a good practice for clarity and correctness in handling date and time values.
  • 121-121: Setting the _client attribute of msg before 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 enums from pyrogram is necessary for the subsequent use of enums.ChatType.CHANNEL in the _outgoing_logic function. 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" with enums.ChatType.CHANNEL in the _outgoing_logic function 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 send with invoke when 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 in userge/plugins/builtin/tools/__main__.py that 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_link now 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 log method, returning msg.id instead of msg.message_id aligns with Pyrogram's updated attribute naming. This change ensures consistency with the library's conventions.
  • 146-146: Similarly, in the store method, assigning msg.id to message_id instead of msg.message_id maintains uniformity across the codebase and aligns with Pyrogram's attribute naming conventions.
userge/core/types/new/conversation.py (3)
  • 22-22: Importing enums from 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_mode in the send_message method to use Optional[enums.ParseMode] is a significant improvement. It ensures type safety and clarity on the method's expected parameters.
  • 164-164: Changing message.message_id to message.id in the forward_message method 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 enums from 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 humanbytes function, 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_shot function 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_entities function 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 UsergeBot class with additional parameters name="usergeBot" and in_memory=True is 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 Userge class initialization now includes a new parameter name='userge' and sets session_string based on config.SESSION_STRING. These changes enhance the clarity and configurability of the userge instance.

  • 323-323: Updating the logging message in the _log_success method 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_exit method 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 pyrogram has been updated to include enums. 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_func has 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 the link attribute of r_m is always available and valid in group contexts to avoid potential errors.
  • 242-243: The _build_decorator function's signature has been updated to accept a union of types.raw.Command and types.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 os is a necessary addition for file handling operations, such as downloading and removing files. This change supports the new functionality added in the input_checker decorator.
  • 26-27: The addition of aiofiles import 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 the input_checker decorator.
  • 46-46: The import of enums from pyrogram is 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.MARKDOWN for parse_mode in the exec_ 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 enums from pyrogram is a good practice for using Pyrogram enums instead of string literals, enhancing code readability and maintainability.
  • 90-93: The reorganization of the triggers assignment 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_mode and disable_web_page_preview arguments in message.edit calls to use enums.ParseMode.HTML and True respectively is a good practice. It leverages the Pyrogram enums for parse_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_mode to enums.ParseMode.HTML and disable_web_page_preview to True in the await msg.reply call 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_buttons function has been enhanced for better readability and maintainability. The use of list comprehensions and the callback_data formatting 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 enums from pyrogram is 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 if var_data is 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 Client initialization in the convert_usermode function with the additional in_memory=True parameter 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 RawClient class in userge/core/ext/raw_client.py shows that it extends the Client class from pyrogram and focuses on handling flood control and rate limiting. It does not explicitly deal with session persistence settings, such as the in_memory parameter. Therefore, the addition of the in_memory=True parameter in userge/plugins/builtin/system/__main__.py is unlikely to affect the behavior of RawClient or 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.

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

Length of output: 5055

* 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.
userge/core/types/bound/message.py (13)
  • 37-44: The constructor of the Message class has been modified to include additional initialization parameters. Ensure that all instances of Message creation throughout the codebase are updated to include these new parameters if necessary. This change enhances customization and control over message instances.
  • 48-57: The parse class method has been updated to handle reply_to_message recursively. 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_MENTION instead 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_file method, the decision to delete the original message based on the delete_message parameter 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 reply method has been significantly updated with additional parameters, including parse_mode, disable_web_page_preview, and protect_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 edit method's enhancements, including the handling of MessageNotModified and 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_edit method 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 err method'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_err method, similar to force_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_file method addresses the issue of MessageTooLong by 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_file method provides flexibility in handling large messages, similar to edit_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_file method 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 delete method, handling MessageDeleteForbidden by 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.

Comment on lines +53 to +57
# is this required?
# user.privileges.can_all = None
# if user.status == enums.ChatMemberStatus.OWNER:
# user.privileges.can_all = True
if user.status in (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 = True

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

Suggested change
# 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 (

Comment on lines +186 to +207

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)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 False

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

Suggested change
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)):

Comment on lines +58 to +72
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment on lines 199 to 245
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment on lines 171 to 195
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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.