diff options
| author | 2020-03-15 16:33:27 +0100 | |
|---|---|---|
| committer | 2020-03-15 16:33:27 +0100 | |
| commit | 066436def1471ba22f1d67958e17f7d52a1ca80d (patch) | |
| tree | 3d82efb9dbac70126dd227034b386a98c20f140c /bot/decorators.py | |
| parent | Deseasonify: improve `in_month` command check (diff) | |
Deseasonify: add listener decorator for season locking
A guarded listener will abort if the triggering event happens outside
of `allowed_months`. This provides a convenient way of season-locking
listeners without having to write guards directly within their bodies.
Diffstat (limited to 'bot/decorators.py')
| -rw-r--r-- | bot/decorators.py | 22 | 
1 files changed, 22 insertions, 0 deletions
| diff --git a/bot/decorators.py b/bot/decorators.py index f031d404..2520679a 100644 --- a/bot/decorators.py +++ b/bot/decorators.py @@ -1,3 +1,4 @@ +import functools  import logging  import random  import typing @@ -27,6 +28,27 @@ class InMonthCheckFailure(CheckFailure):      pass +def in_month_listener(*allowed_months: Month) -> typing.Callable: +    """ +    Shield a listener from being invoked outside of `allowed_months`. + +    The check is performed against current UTC month. +    """ +    def decorator(listener: typing.Callable) -> typing.Callable: +        @functools.wraps(listener) +        async def guarded_listener(*args, **kwargs) -> None: +            """Wrapped listener will abort if not in allowed month.""" +            current_month = Month(datetime.utcnow().month) + +            if current_month in allowed_months: +                # Propagate return value although it should always be None +                return await listener(*args, **kwargs) +            else: +                log.debug(f"Guarded {listener.__qualname__} from invoking in {current_month.name}") +        return guarded_listener +    return decorator + +  def in_month(*allowed_months: Month) -> typing.Callable:      """      Check whether the command was invoked in one of `enabled_months`. | 
