diff options
Diffstat (limited to 'bot/utils')
| -rw-r--r-- | bot/utils/__init__.py | 5 | ||||
| -rw-r--r-- | bot/utils/checks.py | 5 | ||||
| -rw-r--r-- | bot/utils/converters.py | 4 | ||||
| -rw-r--r-- | bot/utils/decorators.py | 37 | ||||
| -rw-r--r-- | bot/utils/extensions.py | 3 | ||||
| -rw-r--r-- | bot/utils/pagination.py | 5 | ||||
| -rw-r--r-- | bot/utils/randomization.py | 7 | 
7 files changed, 36 insertions, 30 deletions
| diff --git a/bot/utils/__init__.py b/bot/utils/__init__.py index bef12d25..91682dbc 100644 --- a/bot/utils/__init__.py +++ b/bot/utils/__init__.py @@ -2,8 +2,9 @@ import asyncio  import contextlib  import re  import string +from collections.abc import Iterable  from datetime import datetime -from typing import Iterable, List, Optional +from typing import Optional  import discord  from discord.ext.commands import BadArgument, Context @@ -32,7 +33,7 @@ def resolve_current_month() -> Month:  async def disambiguate(      ctx: Context, -    entries: List[str], +    entries: list[str],      *,      timeout: float = 30,      entries_per_page: int = 20, diff --git a/bot/utils/checks.py b/bot/utils/checks.py index 438ec750..612d1ed6 100644 --- a/bot/utils/checks.py +++ b/bot/utils/checks.py @@ -1,6 +1,7 @@  import datetime  import logging -from typing import Callable, Container, Iterable, Optional +from collections.abc import Container, Iterable +from typing import Callable, Optional  from discord.ext.commands import (      BucketType, @@ -21,7 +22,7 @@ log = logging.getLogger(__name__)  class InWhitelistCheckFailure(CheckFailure):      """Raised when the `in_whitelist` check fails.""" -    def __init__(self, redirect_channel: Optional[int]) -> None: +    def __init__(self, redirect_channel: Optional[int]):          self.redirect_channel = redirect_channel          if redirect_channel: diff --git a/bot/utils/converters.py b/bot/utils/converters.py index fe2c980c..7227a406 100644 --- a/bot/utils/converters.py +++ b/bot/utils/converters.py @@ -1,5 +1,5 @@  from datetime import datetime -from typing import Tuple, Union +from typing import Union  import discord  from discord.ext import commands @@ -23,7 +23,7 @@ class CoordinateConverter(commands.Converter):      """Converter for Coordinates."""      @staticmethod -    async def convert(ctx: commands.Context, coordinate: str) -> Tuple[int, int]: +    async def convert(ctx: commands.Context, coordinate: str) -> tuple[int, int]:          """Take in a coordinate string and turn it into an (x, y) tuple."""          if len(coordinate) not in (2, 3):              raise commands.BadArgument("Invalid co-ordinate provided.") diff --git a/bot/utils/decorators.py b/bot/utils/decorators.py index c0783144..132aaa87 100644 --- a/bot/utils/decorators.py +++ b/bot/utils/decorators.py @@ -2,9 +2,10 @@ import asyncio  import functools  import logging  import random -import typing as t  from asyncio import Lock +from collections.abc import Container  from functools import wraps +from typing import Callable, Optional, Union  from weakref import WeakValueDictionary  from discord import Colour, Embed @@ -32,7 +33,7 @@ class InMonthCheckFailure(CheckFailure):      pass -def seasonal_task(*allowed_months: Month, sleep_time: t.Union[float, int] = ONE_DAY) -> t.Callable: +def seasonal_task(*allowed_months: Month, sleep_time: Union[float, int] = ONE_DAY) -> Callable:      """      Perform the decorated method periodically in `allowed_months`. @@ -44,7 +45,7 @@ def seasonal_task(*allowed_months: Month, sleep_time: t.Union[float, int] = ONE_      The wrapped task is responsible for waiting for the bot to be ready, if necessary.      """ -    def decorator(task_body: t.Callable) -> t.Callable: +    def decorator(task_body: Callable) -> Callable:          @functools.wraps(task_body)          async def decorated_task(*args, **kwargs) -> None:              """Call `task_body` once every `sleep_time` seconds in `allowed_months`.""" @@ -63,13 +64,13 @@ def seasonal_task(*allowed_months: Month, sleep_time: t.Union[float, int] = ONE_      return decorator -def in_month_listener(*allowed_months: Month) -> t.Callable: +def in_month_listener(*allowed_months: Month) -> Callable:      """      Shield a listener from being invoked outside of `allowed_months`.      The check is performed against current UTC month.      """ -    def decorator(listener: t.Callable) -> t.Callable: +    def decorator(listener: Callable) -> Callable:          @functools.wraps(listener)          async def guarded_listener(*args, **kwargs) -> None:              """Wrapped listener will abort if not in allowed month.""" @@ -84,7 +85,7 @@ def in_month_listener(*allowed_months: Month) -> t.Callable:      return decorator -def in_month_command(*allowed_months: Month) -> t.Callable: +def in_month_command(*allowed_months: Month) -> Callable:      """      Check whether the command was invoked in one of `enabled_months`. @@ -106,7 +107,7 @@ def in_month_command(*allowed_months: Month) -> t.Callable:      return commands.check(predicate) -def in_month(*allowed_months: Month) -> t.Callable: +def in_month(*allowed_months: Month) -> Callable:      """      Universal decorator for season-locking commands and listeners alike. @@ -124,7 +125,7 @@ def in_month(*allowed_months: Month) -> t.Callable:      manually set to True - this causes a circumvention of the group's callback      and the seasonal check applied to it.      """ -    def decorator(callable_: t.Callable) -> t.Callable: +    def decorator(callable_: Callable) -> Callable:          # Functions decorated as commands are turned into instances of `Command`          if isinstance(callable_, Command):              logging.debug(f"Command {callable_.qualified_name} will be locked to {human_months(allowed_months)}") @@ -144,7 +145,7 @@ def in_month(*allowed_months: Month) -> t.Callable:      return decorator -def with_role(*role_ids: int) -> t.Callable: +def with_role(*role_ids: int) -> Callable:      """Check to see whether the invoking user has any of the roles specified in role_ids."""      async def predicate(ctx: Context) -> bool:          if not ctx.guild:  # Return False in a DM @@ -167,7 +168,7 @@ def with_role(*role_ids: int) -> t.Callable:      return commands.check(predicate) -def without_role(*role_ids: int) -> t.Callable: +def without_role(*role_ids: int) -> Callable:      """Check whether the invoking user does not have all of the roles specified in role_ids."""      async def predicate(ctx: Context) -> bool:          if not ctx.guild:  # Return False in a DM @@ -187,7 +188,7 @@ def without_role(*role_ids: int) -> t.Callable:      return commands.check(predicate) -def whitelist_check(**default_kwargs: t.Container[int]) -> t.Callable[[Context], bool]: +def whitelist_check(**default_kwargs: Container[int]) -> Callable[[Context], bool]:      """      Checks if a message is sent in a whitelisted context. @@ -222,8 +223,8 @@ def whitelist_check(**default_kwargs: t.Container[int]) -> t.Callable[[Context],                      kwargs[arg] = new_value                  # Merge containers -                elif isinstance(default_value, t.Container): -                    if isinstance(new_value, t.Container): +                elif isinstance(default_value, Container): +                    if isinstance(new_value, Container):                          kwargs[arg] = (*default_value, *new_value)                      else:                          kwargs[arg] = new_value @@ -279,7 +280,7 @@ def whitelist_check(**default_kwargs: t.Container[int]) -> t.Callable[[Context],      return predicate -def whitelist_override(bypass_defaults: bool = False, **kwargs: t.Container[int]) -> t.Callable: +def whitelist_override(bypass_defaults: bool = False, **kwargs: Container[int]) -> Callable:      """      Override global whitelist context, with the kwargs specified. @@ -288,7 +289,7 @@ def whitelist_override(bypass_defaults: bool = False, **kwargs: t.Container[int]      This decorator has to go before (below) below the `command` decorator.      """ -    def inner(func: t.Callable) -> t.Callable: +    def inner(func: Callable) -> Callable:          func.override = kwargs          func.override_reset = bypass_defaults          return func @@ -296,7 +297,7 @@ def whitelist_override(bypass_defaults: bool = False, **kwargs: t.Container[int]      return inner -def locked() -> t.Union[t.Callable, None]: +def locked() -> Optional[Callable]:      """      Allows the user to only run one instance of the decorated command at a time. @@ -304,11 +305,11 @@ def locked() -> t.Union[t.Callable, None]:      This decorator has to go before (below) the `command` decorator.      """ -    def wrap(func: t.Callable) -> t.Union[t.Callable, None]: +    def wrap(func: Callable) -> Optional[Callable]:          func.__locks = WeakValueDictionary()          @wraps(func) -        async def inner(self: t.Callable, ctx: Context, *args, **kwargs) -> t.Union[t.Callable, None]: +        async def inner(self: Callable, ctx: Context, *args, **kwargs) -> Optional[Callable]:              lock = func.__locks.setdefault(ctx.author.id, Lock())              if lock.locked():                  embed = Embed() diff --git a/bot/utils/extensions.py b/bot/utils/extensions.py index cd491c4b..cbb8f15e 100644 --- a/bot/utils/extensions.py +++ b/bot/utils/extensions.py @@ -1,7 +1,8 @@  import importlib  import inspect  import pkgutil -from typing import Iterator, NoReturn +from collections.abc import Iterator +from typing import NoReturn  from discord.ext.commands import Context diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index b1062c09..013ef9e7 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -1,6 +1,7 @@  import asyncio  import logging -from typing import Iterable, List, Optional, Tuple +from collections.abc import Iterable +from typing import Optional  from discord import Embed, Member, Reaction  from discord.abc import User @@ -313,7 +314,7 @@ class ImagePaginator(Paginator):          self.images.append(image)      @classmethod -    async def paginate(cls, pages: List[Tuple[str, str]], ctx: Context, embed: Embed, +    async def paginate(cls, pages: list[tuple[str, str]], ctx: Context, embed: Embed,                         prefix: str = "", suffix: str = "", timeout: int = 300,                         exception_on_empty_embed: bool = False) -> None:          """ diff --git a/bot/utils/randomization.py b/bot/utils/randomization.py index 8f47679a..c9eabbd2 100644 --- a/bot/utils/randomization.py +++ b/bot/utils/randomization.py @@ -1,6 +1,7 @@  import itertools  import random -import typing as t +from collections.abc import Iterable +from typing import Any  class RandomCycle: @@ -10,11 +11,11 @@ class RandomCycle:      The iterable is reshuffled after each full cycle.      """ -    def __init__(self, iterable: t.Iterable) -> None: +    def __init__(self, iterable: Iterable):          self.iterable = list(iterable)          self.index = itertools.cycle(range(len(iterable))) -    def __next__(self) -> t.Any: +    def __next__(self) -> Any:          idx = next(self.index)          if idx == 0: | 
