[V3] Predicate Utility #1985

Merged
Redjumpman merged 2 commits from V3/develop into V3/feature/predicates 2018-08-06 11:36:58 +02:00
Redjumpman commented 2018-08-06 00:55:39 +02:00 (Migrated from github.com)

Type

  • Bugfix
  • Enhancement
  • New feature

Description of the changes

I often find myself and other cog creators having to write a bunch of boiler plate checks either through functions or lambdas for multiple cogs that need waiting events. Specifically, for when you need to validate a response. Suppose the following scenario:

# Common boilerplate check
def confirm(m):
    return m.author == ctx.author and m.content.lower() in ('yes', 'y', 'no', 'n')

try:
    response = await ctx.bot.wait_for('message', timeout=30, check=confirm)
except asyncio.TimeoutError:
    return await ctx.send('Response timed out')

Because ctx is often tightly coupled in these scenarios, you may find yourself writing simple predicates like the above confirm function or an equivalent lambda over and over across multiple commands or cogs.

Enter the new Predicates core utility module! This solves the problem with reusable predicates. Take the following example into consideration:

from redbot.core import commands
from redbot.core.utils.predicates import Predicate

class CogExample:
    # setup code
    @commands.command()
    async def example(self, ctx):
        await ctx.send("Please set a new welcome message.")
        
        try:
            welcome_message = await self.handler(ctx)
        except asycnio.TimeoutError:
            await ctx.send("Response timed out.")
        except RuntimeError:
            await ctx.send("Cancelled setting a new welcome message.")
        # rest of your code

    async def handler(self, ctx):
        check = Predicate(ctx.author, length=2000)
        message = await ctx.bot.wait_for('message', timeout=30, check=check.length_under)
        await ctx.send("Are you sure you wish to change your message?")
        choice = await ctx.bot.wait_for('message', timeout=30, check=check.confirm)
        if choice.content.lower() in ('y', 'yes'):
            return message.content
        else:
            raise RuntimeError

In the above code, we bypass having to write two separate checks by using Predicate. The Predicate class comes with the following methods:

  • same - sender and message author are the same
  • confirm - message is yes, y, no, or no
  • valid_int - message is an integer
  • valid_float - message is a float
  • positive - message is a positive integer
  • valid_role - message is the same as a role on the server
  • has_role - message is a role the name of a role the sender has
  • equal - message is equal to a set value
  • greater - message is a integer or float that is greater than a set value
  • less - message is a integer or float that is less than a set value
  • member - message is the name of a member on the server.
  • length_less - message has a length that is less than the the predicate's set length
  • length_greater - message has a length that is greater than the the predicate's set length
  • contained - message is a part of the predicate's set collection.

Note: All methods require that the sender and the message author be the same.

### Type - [ ] Bugfix - [x] Enhancement - [ ] New feature ### Description of the changes I often find myself and other cog creators having to write a bunch of boiler plate checks either through functions or lambdas for multiple cogs that need [waiting events](https://discordpy.readthedocs.io/en/rewrite/migrating.html#waiting-for-events). Specifically, for when you need to validate a response. Suppose the following scenario: ```py # Common boilerplate check def confirm(m): return m.author == ctx.author and m.content.lower() in ('yes', 'y', 'no', 'n') try: response = await ctx.bot.wait_for('message', timeout=30, check=confirm) except asyncio.TimeoutError: return await ctx.send('Response timed out') ``` Because `ctx` is often tightly coupled in these scenarios, you may find yourself writing simple predicates like the above `confirm` function or an equivalent lambda over and over across multiple commands or cogs. Enter the new Predicates core utility module! This solves the problem with reusable predicates. Take the following example into consideration: ```py from redbot.core import commands from redbot.core.utils.predicates import Predicate class CogExample: # setup code @commands.command() async def example(self, ctx): await ctx.send("Please set a new welcome message.") try: welcome_message = await self.handler(ctx) except asycnio.TimeoutError: await ctx.send("Response timed out.") except RuntimeError: await ctx.send("Cancelled setting a new welcome message.") # rest of your code async def handler(self, ctx): check = Predicate(ctx.author, length=2000) message = await ctx.bot.wait_for('message', timeout=30, check=check.length_under) await ctx.send("Are you sure you wish to change your message?") choice = await ctx.bot.wait_for('message', timeout=30, check=check.confirm) if choice.content.lower() in ('y', 'yes'): return message.content else: raise RuntimeError ``` In the above code, we bypass having to write **two** separate checks by using Predicate. The Predicate class comes with the following methods: * same - sender and message author are the same * confirm - message is `yes`, `y`, `no`, or `no` * valid_int - message is an integer * valid_float - message is a float * positive - message is a positive integer * valid_role - message is the same as a role on the server * has_role - message is a role the name of a role the sender has * equal - message is equal to a set value * greater - message is a integer or float that is greater than a set value * less - message is a integer or float that is less than a set value * member - message is the name of a member on the server. * length_less - message has a length that is less than the the predicate's set length * length_greater - message has a length that is greater than the the predicate's set length * contained - message is a part of the predicate's set collection. Note: All methods require that the sender and the message author be the same.
Twentysix26 (Migrated from github.com) reviewed 2018-08-06 00:55:39 +02:00
calebj (Migrated from github.com) requested changes 2018-08-06 01:16:01 +02:00
calebj (Migrated from github.com) left a comment

I think has_role, valid_role, and member should support names and IDs. Also, I want to see a channels predicate, a cancel option, the ability to ignore case in contained, the ability to capture multiple items (consume-all, split on spaces or commas), and a way to capture the matched object(s).

I think `has_role`, `valid_role`, and `member` should support names *and* IDs. Also, I *want* to see a `channels` predicate, a `cancel` option, the ability to ignore case in `contained`, the ability to capture multiple items (consume-all, split on spaces or commas), and a way to capture the matched object(s).
Redjumpman commented 2018-08-06 01:53:00 +02:00 (Migrated from github.com)

@calebj Those are some good points. I'll look into adding them to the module. Thank you for the feedback.

@calebj Those are some good points. I'll look into adding them to the module. Thank you for the feedback.
Tobotimus commented 2018-08-06 03:04:08 +02:00 (Migrated from github.com)

👍 This is awesome! This is just a suggestion of mine that could cut down on lines used and perhaps increase usability and extensibility:

  • Simply have ctx as an attribute to the predicate since we might add more checks which need more context
  • Use classmethods to instantiate the Predicate object and return the requested function in one single expression.

Take your example in the header of this PR. With above suggestions implemented, it could look like this:

from redbot.core import commands
from redbot.core.utils.predicates import Predicate

class CogExample:
    # setup code
    @commands.command()
    async def example(self, ctx):
        await ctx.send("Please set a new welcome message.")
        
        try:
            welcome_message = await self.handler(ctx)
        except asycnio.TimeoutError:
            await ctx.send("Response timed out.")
        except RuntimeError:
            await ctx.send("Cancelled setting a new welcome message.")
        # rest of your code

    async def handler(self, ctx):
        message = await ctx.bot.wait_for('message', timeout=30, check=Predicate.length_under(ctx, length=2000))
        await ctx.send("Are you sure you wish to change your message?")
        choice = await ctx.bot.wait_for('message', timeout=30, check=Predicate.confirm(ctx))
        if choice.content.lower() in ('y', 'yes'):
            return message.content
        else:
            raise RuntimeError

The proposed classmethods could return the Predicate object itself but modify its __call__ to match the requested predicate function.

Also I think most message predicates ought to check for ctx.channel == m.channel, otherwise the bot could unexpectedly pick up responses in other channels.

@calebj has some good suggestions too.

I really like this initiative! In fact I think (in another PR) we could add a ReactionPredicate to compliment this one. Perhaps in the interest of future-proofing the naming scheme, this could be renamed to MessagePredicate? Let me know if you have any qualms or queries.

:+1: This is awesome! This is just a suggestion of mine that could cut down on lines used and perhaps increase usability and extensibility: - Simply have `ctx` as an attribute to the predicate since we might add more checks which need more context - Use classmethods to instantiate the `Predicate` object and return the requested function in one single expression. Take your example in the header of this PR. With above suggestions implemented, it could look like this: ```py from redbot.core import commands from redbot.core.utils.predicates import Predicate class CogExample: # setup code @commands.command() async def example(self, ctx): await ctx.send("Please set a new welcome message.") try: welcome_message = await self.handler(ctx) except asycnio.TimeoutError: await ctx.send("Response timed out.") except RuntimeError: await ctx.send("Cancelled setting a new welcome message.") # rest of your code async def handler(self, ctx): message = await ctx.bot.wait_for('message', timeout=30, check=Predicate.length_under(ctx, length=2000)) await ctx.send("Are you sure you wish to change your message?") choice = await ctx.bot.wait_for('message', timeout=30, check=Predicate.confirm(ctx)) if choice.content.lower() in ('y', 'yes'): return message.content else: raise RuntimeError ``` The proposed classmethods could return the Predicate object itself but modify its `__call__` to match the requested predicate function. Also I think most message predicates ought to check for `ctx.channel == m.channel`, otherwise the bot could unexpectedly pick up responses in other channels. @calebj has some good suggestions too. I really like this initiative! In fact I think (in another PR) we could add a `ReactionPredicate` to compliment this one. Perhaps in the interest of future-proofing the naming scheme, this could be renamed to `MessagePredicate`? Let me know if you have any qualms or queries.
Redjumpman commented 2018-08-06 05:35:28 +02:00 (Migrated from github.com)

@Tobotimus These are some awesome suggestions. I'll continue working on this PR and try to implement the things you and caleb brought up. I my original implementation used ctx, instead of requiring a member object, but was worried it might seem as too much. I'm happy to revert that change. I'll also change the naming convention to MessagePredicate or something similar so it's a little more extensible if someone wants to add a new predicate class.

@Tobotimus These are some awesome suggestions. I'll continue working on this PR and try to implement the things you and caleb brought up. I my original implementation used ctx, instead of requiring a member object, but was worried it might seem as too much. I'm happy to revert that change. I'll also change the naming convention to MessagePredicate or something similar so it's a little more extensible if someone wants to add a new predicate class.
Redjumpman commented 2018-08-06 07:59:26 +02:00 (Migrated from github.com)

Changed a few things based on the suggestions:

  • Changed sender from a discord.Member object to ctx.
  • Added a channel check.
  • Combined the same method and channel method into a validator method and applied through-out.
  • valid_role and has_role methods now check for either an id or a name.
  • contained now uses string.lower() when testing for membership in a collection.
  • added a cancelled method (provisional)

I have a concern about allowing for additional arguments, outside of instantiating the class, because the predicate is supposed to only accept on argument (or 2 if using it for reactions). I think that's why I initially off-loaded some of the extra args onto __init__. Although I could be tired and missing something obvious. Anyone is free to take a whack at this if they want to.

Changed a few things based on the suggestions: - Changed sender from a discord.Member object to ctx. - Added a channel check. - Combined the same method and channel method into a validator method and applied through-out. - valid_role and has_role methods now check for either an id or a name. - contained now uses string.lower() when testing for membership in a collection. - added a cancelled method (provisional) I have a concern about allowing for additional arguments, outside of instantiating the class, because the predicate is supposed to only accept on argument (or 2 if using it for reactions). I think that's why I initially off-loaded some of the extra args onto `__init__`. Although I could be tired and missing something obvious. Anyone is free to take a whack at this if they want to.
Tobotimus (Migrated from github.com) approved these changes 2018-08-06 11:32:16 +02:00
Tobotimus (Migrated from github.com) left a comment

Awesome, this is a good start. I'm going to merge this into a feature branch now, since as we can see there are quite a few suggestions for additions and/or changes. Work can continue there :)

Awesome, this is a good start. I'm going to merge this into a feature branch now, since as we can see there are quite a few suggestions for additions and/or changes. Work can continue there :)
Sign in to join this conversation.
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!1985
No description provided.