[V3 Utils] Predicate Utility #1986

Merged
Tobotimus merged 2 commits from V3/feature/predicates into V3/develop 2018-10-06 00:15:26 +02:00
Tobotimus commented 2018-08-06 11:46:56 +02:00 (Migrated from github.com)

Type

  • New Feature

Tasks

  • Reaction equivalent to MessagePredicate
  • (maybe) Use of @classmethods for instantiation
  • Unit tests
  • Documentation
    ... probably more to be added

Description of the changes

(PR Description copied from #1985, originally written by @Redjumpman)

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 - New Feature ### Tasks - [x] Reaction equivalent to `MessagePredicate` - [x] (maybe) Use of `@classmethod`s for instantiation - [ ] Unit tests - [x] Documentation *... probably more to be added* ### Description of the changes *(PR Description copied from #1985, originally written by @Redjumpman)* 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.
palmtree5 (Migrated from github.com) reviewed 2018-08-06 11:46:56 +02:00
tekulvw (Migrated from github.com) reviewed 2018-08-06 11:46:56 +02:00
Twentysix26 (Migrated from github.com) reviewed 2018-08-06 11:46:56 +02:00
mikeshardmind commented 2018-08-10 16:41:25 +02:00 (Migrated from github.com)

I'd like a mixed listener that allows for waiting for a reaction or message meeting criteria, but this is going to require working with socket_raw_recieve, I'll write something for this later. and it shouldnt hold up the initial work on this PR being merged if I dont have it ready by the time this is ready for review.

I'd like a mixed listener that allows for waiting for a reaction or message meeting criteria, but this is going to require working with `socket_raw_recieve`, I'll write something for this later. and it shouldnt hold up the initial work on this PR being merged if I dont have it ready by the time this is ready for review.
Tobotimus commented 2018-10-02 08:38:24 +02:00 (Migrated from github.com)

About to rebase+force push this PR branch.

About to rebase+force push this PR branch.
Tobotimus commented 2018-10-06 00:09:44 +02:00 (Migrated from github.com)

Just want to post this for the record, the header of this PR is out of date and should not be used as a guide for this feature; see the documentation after this PR is merged for details 😃

Just want to post this for the record, the header of this PR is out of date and should not be used as a guide for this feature; see the documentation after this PR is merged for details :smiley:
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!1986
No description provided.