Add public positive_int and finite_float converters #5969

Merged
AAA3A-AAA3A merged 12 commits from patch-7 into V3/develop 2023-04-17 23:33:44 +02:00
AAA3A-AAA3A commented 2023-01-12 22:02:27 +01:00 (Migrated from github.com)

Description of the changes

Hello,

This PR adds the positive_int and finite_float converters to redbot.core.commands.converter.
Since positive_int is an instance of redbot.core.commands.Range, the appropriate error messages have been added to bot.on_command_error with type commands.RangeError.

Testing was done today in #testing the core server.
Thanks in advance and have a nice day,
AAA3A

Closes #5939

Have the changes in this PR been tested?

Yes

### Description of the changes Hello, This PR adds the `positive_int` and `finite_float` converters to `redbot.core.commands.converter`. Since `positive_int` is an instance of `redbot.core.commands.Range`, the appropriate error messages have been added to `bot.on_command_error` with type `commands.RangeError`. Testing was done today in #testing the core server. Thanks in advance and have a nice day, AAA3A Closes #5939 ### Have the changes in this PR been tested? Yes
Zephyrkul (Migrated from github.com) reviewed 2023-01-12 22:51:39 +01:00
Zephyrkul (Migrated from github.com) commented 2023-01-12 22:51:38 +01:00
if TYPE_CHECKING:
    finite_float = float
else:

    def finite_float(arg: str) -> float:
        """
        This converts a user provided string into a finite float.
        """
        try:
            ret = float(arg)
        except ValueError:
            raise BadArgument(_("`{arg}` is not a number.").format(arg=arg))
        if not math.isfinite(ret):
            raise BadArgument(_("`{arg}` is not a finite number.").format(arg=ret))
        return ret
```suggestion if TYPE_CHECKING: finite_float = float else: def finite_float(arg: str) -> float: """ This converts a user provided string into a finite float. """ try: ret = float(arg) except ValueError: raise BadArgument(_("`{arg}` is not a number.").format(arg=arg)) if not math.isfinite(ret): raise BadArgument(_("`{arg}` is not a finite number.").format(arg=ret)) return ret ```
Kreusada (Migrated from github.com) reviewed 2023-01-13 00:11:03 +01:00
@ -684,9 +684,7 @@ class Cleanup(commands.Cog):
@commands.guild_only()
@commands.mod_or_permissions(manage_messages=True)
Kreusada (Migrated from github.com) commented 2023-01-13 00:08:55 +01:00
    async def cleanup_duplicates(self, ctx: commands.Context, number: positive_int = 50):
```suggestion async def cleanup_duplicates(self, ctx: commands.Context, number: positive_int = 50): ```
Kreusada (Migrated from github.com) commented 2023-01-13 00:09:18 +01:00

You can remove the NewType import now as it is not used anywhere else in this file

You can remove the NewType import now as it is not used anywhere else in this file
Kreusada (Migrated from github.com) requested changes 2023-03-21 20:42:54 +01:00
Kreusada (Migrated from github.com) left a comment

There are a few changes needed for this PR which stood out to me, including part of the implementation which is missing. Could you address these changes, and then re-test them? I will also test them thoroughly when I review your changes again.

There are a few changes needed for this PR which stood out to me, including part of the implementation which is missing. Could you address these changes, and then re-test them? I will also test them thoroughly when I review your changes again.
@ -5,3 +5,3 @@
from importlib.machinery import ModuleSpec
from pathlib import Path
from typing import TYPE_CHECKING, Union, List, Optional
from typing import Union, List, Optional
Kreusada (Migrated from github.com) commented 2023-03-20 22:28:29 +01:00
from typing import Union, List, Optional

TYPE_CHECKING is no longer used inside the cog_manager file, we can remove its import.

```suggestion from typing import Union, List, Optional ``` `TYPE_CHECKING` is no longer used inside the cog_manager file, we can remove its import.
@ -242,2 +240,4 @@
if error.send_cmd_help:
await ctx.send_help()
elif isinstance(error, commands.RangeError):
if isinstance(error.value, int):
Kreusada (Migrated from github.com) commented 2023-03-21 17:47:31 +01:00
                        "Provided value `{value}` for argument `{parameter_name}` must be a string with a length of no more than {maximum}."
                    )
                elif error.minimum is not None and error.maximum is None:
                    message = _(
                        "Provided value `{value}` for argument `{parameter_name}` must be a string with a length of no less than {minimum}."
                    )
                elif error.maximum is not None and error.minimum is not None:
                    message = _(
                        "Provided value `{value}` for argument `{parameter_name}` must be a string with a length of between {minimum} and {maximum}."

These strings should be changed for when the Range annotation is str, because a "string no more than [...]" isn't grammatically fitting. I've made a suggestion but feel free to improvise if you have a better idea.

```suggestion "Provided value `{value}` for argument `{parameter_name}` must be a string with a length of no more than {maximum}." ) elif error.minimum is not None and error.maximum is None: message = _( "Provided value `{value}` for argument `{parameter_name}` must be a string with a length of no less than {minimum}." ) elif error.maximum is not None and error.minimum is not None: message = _( "Provided value `{value}` for argument `{parameter_name}` must be a string with a length of between {minimum} and {maximum}." ``` These strings should be changed for when the Range annotation is `str`, because a "string no more than [...]" isn't grammatically fitting. I've made a suggestion but feel free to improvise if you have a better idea.
Kreusada (Migrated from github.com) commented 2023-03-21 18:18:50 +01:00

Why are we doing this? It makes the response looks very absurd. Can the error value itself not be formatted here?
image

Why are we doing this? It makes the response looks very absurd. Can the error value itself not be formatted here? ![image](https://user-images.githubusercontent.com/67752638/226689999-5e5f1751-4405-4295-95b3-96cdfa98e553.png)
Kreusada (Migrated from github.com) commented 2023-03-21 20:26:17 +01:00
        elif isinstance(error, commands.RangeError):
```suggestion elif isinstance(error, commands.RangeError): ```
Kreusada (Migrated from github.com) commented 2023-03-21 17:54:27 +01:00

You haven't handled when the converter annotation is str here. That means the code will fall past this section and UnboundLocalError will be raised because message isn't defined. You should add a condition here which accounts for when the converter annotation is a string. You should emulate the behaviour you defined above for when RangeError is raised. You should also take into account my grammatical comments I made above, and ensure that stays consistent in his handling of the converter error.

I suggest using an else block here instead of an additional elif, as we only need to account for three types (str, float, int).

You can test these changes by creating a command which uses a str annotation in the Range converter. For example:

@commands.command()
async def test(ctx, arg: dpy_commands.converter.Range[str, None, 5]):
    await ctx.tick()

# [p]test helloworld

Currently, this raises an implicit error which looks like this:

image

You haven't handled when the converter annotation is `str` here. That means the code will fall past this section and UnboundLocalError will be raised because `message` isn't defined. You should add a condition here which accounts for when the converter annotation is a string. You should emulate the behaviour you defined above for when RangeError is raised. You should also take into account my grammatical comments I made above, and ensure that stays consistent in his handling of the converter error. I suggest using an else block here instead of an additional elif, as we only need to account for three types (str, float, int). You can test these changes by creating a command which uses a `str` annotation in the Range converter. For example: ```py @commands.command() async def test(ctx, arg: dpy_commands.converter.Range[str, None, 5]): await ctx.tick() # [p]test helloworld ``` Currently, this raises an implicit error which looks like this: ![image](https://user-images.githubusercontent.com/67752638/226474946-7371d7e9-3265-4d48-95f1-42607bc7bbfe.png)
AAA3A-AAA3A commented 2023-03-21 23:13:47 +01:00 (Migrated from github.com)

Hello,
Thank you for your review of this PR.
All requested changes have been pushed.
Thanks in advance,
AAA3A

Hello, Thank you for your review of this PR. All requested changes have been pushed. Thanks in advance, AAA3A
AAA3A-AAA3A commented 2023-03-26 19:24:48 +02:00 (Migrated from github.com)

After #6002 was merged, to fix an error on the local clone of my Red fork, I force push the commits. I had forgotten to save the redbot.core.commands.converter file, so I lost it. I just made the changes again.

After #6002 was merged, to fix an error on the local clone of my Red fork, I force push the commits. I had forgotten to save the `redbot.core.commands.converter` file, so I lost it. I just made the changes again.
Kreusada (Migrated from github.com) reviewed 2023-04-02 22:37:20 +02:00
Kreusada (Migrated from github.com) left a comment

You should update redbot/core/commands/__init__.py, importing both finite_float and positive_int respectively. You should also add these two converter names to redbot.core.commands.converter.__all__.

You should update `redbot/core/commands/__init__.py`, importing both `finite_float` and `positive_int` respectively. You should also add these two converter names to `redbot.core.commands.converter.__all__`.
AAA3A-AAA3A commented 2023-04-02 22:39:20 +02:00 (Migrated from github.com)

You should update redbot/core/commands/__init__.py, importing both finite_float and positive_int respectively. You should also add these two converter names to redbot.core.commands.converter.__all__.

Ah, I had thought of adding them to redbot.core.commands, but I thought it was a bad idea. I'll do it tomorrow.

> You should update `redbot/core/commands/__init__.py`, importing both `finite_float` and `positive_int` respectively. You should also add these two converter names to `redbot.core.commands.converter.__all__`. Ah, I had thought of adding them to `redbot.core.commands`, but I thought it was a bad idea. I'll do it tomorrow.
Kreusada (Migrated from github.com) requested changes 2023-04-15 00:46:43 +02:00
Kreusada (Migrated from github.com) left a comment

There are still changes that are needed before this can be approved and merged. Have a look at the review comments, and test your changes afterwards if you can. Should be good to go if those changes are made correctly.

There are still changes that are needed before this can be approved and merged. Have a look at the review comments, and test your changes afterwards if you can. Should be good to go if those changes are made correctly.
@ -241,10 +239,112 @@ def init_events(bot, cli_flags):
await ctx.send(msg)
Kreusada (Migrated from github.com) commented 2023-04-15 00:26:59 +02:00

Whilst this check makes sense, if the converter minimum were to be 1, and the user passes "0" to the converter, the message would still ask for a positive integer despite zero being a positive integer. Is the == 1 check really needed?

image

Whilst this check makes sense, if the converter minimum were to be 1, and the user passes "0" to the converter, the message would still ask for a positive integer despite zero being a positive integer. Is the `== 1` check really needed? ![image](https://user-images.githubusercontent.com/67752638/232164954-13ddfffd-4b4b-457a-923b-a9cb4572729a.png)
Kreusada (Migrated from github.com) commented 2023-04-15 00:34:09 +02:00
                            "Argument `{parameter_name}` must be an integer no less than {minimum}."

Here, we check if the converter's max is None, so it will always read "no less than None", instead of our desired result. It just requires changing this part of the string in the suggestion.

```suggestion "Argument `{parameter_name}` must be an integer no less than {minimum}." ``` Here, we check if the converter's max is None, so it will always read "no less than None", instead of our desired result. It just requires changing this part of the string in the suggestion.
Kreusada (Migrated from github.com) commented 2023-04-15 00:36:18 +02:00
                elif converter.annotation is str:
```suggestion elif converter.annotation is str: ```
Kreusada (Migrated from github.com) commented 2023-04-15 00:37:06 +02:00

Please apply the above comment to here aswell.

Please apply the above comment to here aswell.
Kreusada (Migrated from github.com) commented 2023-04-15 00:37:38 +02:00
                            "Argument `{parameter_name}` must be a number no less than {minimum}."
```suggestion "Argument `{parameter_name}` must be a number no less than {minimum}." ```
Kreusada (Migrated from github.com) commented 2023-04-15 00:41:27 +02:00
            elif isinstance(error.value, str):
```suggestion elif isinstance(error.value, str): ```
Kreusada (Migrated from github.com) commented 2023-04-15 00:42:11 +02:00

Whilst this check makes sense, if the minimum were to be 1, and "0" is passed to the converter, the message would still ask for a positive integer despite zero being a positive integer. Is the == 1 check really needed?

Whilst this check makes sense, if the minimum were to be 1, and "0" is passed to the converter, the message would still ask for a positive integer despite zero being a positive integer. Is the `== 1` check really needed?
Kreusada (Migrated from github.com) commented 2023-04-15 00:42:58 +02:00
                        "Argument `{parameter_name}` must be an integer no less than {minimum}."
```suggestion "Argument `{parameter_name}` must be an integer no less than {minimum}." ```
Kreusada (Migrated from github.com) approved these changes 2023-04-17 23:33:13 +02:00
Kreusada (Migrated from github.com) left a comment

Thanks for working on this, looks all set now 🎉

Thanks for working on this, looks all set now 🎉
Sign in to join this conversation.
No reviewers
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Mrcoolgamer11/Red-DiscordBot!5969
No description provided.