|
| 1 | +"""Helpers for setting a cooldown on commands.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import random |
| 7 | +import time |
| 8 | +import typing |
| 9 | +import weakref |
| 10 | +from collections.abc import Awaitable, Callable, Hashable, Iterable |
| 11 | +from contextlib import suppress |
| 12 | +from dataclasses import dataclass |
| 13 | + |
| 14 | +import discord |
| 15 | +from discord.ext.commands import CommandError, Context |
| 16 | + |
| 17 | +from botcore.utils import scheduling |
| 18 | +from botcore.utils.function import command_wraps |
| 19 | + |
| 20 | +__all__ = ["CommandOnCooldown", "block_duplicate_invocations", "P", "R"] |
| 21 | + |
| 22 | +_KEYWORD_SEP_SENTINEL = object() |
| 23 | + |
| 24 | +_ArgsList = list[object] |
| 25 | +_HashableArgsTuple = tuple[Hashable, ...] |
| 26 | + |
| 27 | +if typing.TYPE_CHECKING: |
| 28 | + import typing_extensions |
| 29 | + from botcore import BotBase |
| 30 | + |
| 31 | +P = typing.ParamSpec("P") |
| 32 | +"""The command's signature.""" |
| 33 | +R = typing.TypeVar("R") |
| 34 | +"""The command's return value.""" |
| 35 | + |
| 36 | + |
| 37 | +class CommandOnCooldown(CommandError, typing.Generic[P, R]): |
| 38 | + """Raised when a command is invoked while on cooldown.""" |
| 39 | + |
| 40 | + def __init__( |
| 41 | + self, |
| 42 | + message: str | None, |
| 43 | + function: Callable[P, Awaitable[R]], |
| 44 | + /, |
| 45 | + *args: P.args, |
| 46 | + **kwargs: P.kwargs, |
| 47 | + ): |
| 48 | + super().__init__(message, function, args, kwargs) |
| 49 | + self._function = function |
| 50 | + self._args = args |
| 51 | + self._kwargs = kwargs |
| 52 | + |
| 53 | + async def call_without_cooldown(self) -> R: |
| 54 | + """ |
| 55 | + Run the command this cooldown blocked. |
| 56 | +
|
| 57 | + Returns: |
| 58 | + The command's return value. |
| 59 | + """ |
| 60 | + return await self._function(*self._args, **self._kwargs) |
| 61 | + |
| 62 | + |
| 63 | +@dataclass |
| 64 | +class _CooldownItem: |
| 65 | + non_hashable_arguments: _ArgsList |
| 66 | + timeout_timestamp: float |
| 67 | + |
| 68 | + |
| 69 | +@dataclass |
| 70 | +class _SeparatedArguments: |
| 71 | + """Arguments separated into their hashable and non-hashable parts.""" |
| 72 | + |
| 73 | + hashable: _HashableArgsTuple |
| 74 | + non_hashable: _ArgsList |
| 75 | + |
| 76 | + @classmethod |
| 77 | + def from_full_arguments(cls, call_arguments: Iterable[object]) -> typing_extensions.Self: |
| 78 | + """Create a new instance from full call arguments.""" |
| 79 | + hashable = list[Hashable]() |
| 80 | + non_hashable = list[object]() |
| 81 | + |
| 82 | + for item in call_arguments: |
| 83 | + try: |
| 84 | + hash(item) |
| 85 | + except TypeError: |
| 86 | + non_hashable.append(item) |
| 87 | + else: |
| 88 | + hashable.append(item) |
| 89 | + |
| 90 | + return cls(tuple(hashable), non_hashable) |
| 91 | + |
| 92 | + |
| 93 | +class _CommandCooldownManager: |
| 94 | + """ |
| 95 | + Manage invocation cooldowns for a command through the arguments the command is called with. |
| 96 | +
|
| 97 | + Use `set_cooldown` to set a cooldown, |
| 98 | + and `is_on_cooldown` to check for a cooldown for a channel with the given arguments. |
| 99 | + A cooldown lasts for `cooldown_duration` seconds. |
| 100 | + """ |
| 101 | + |
| 102 | + def __init__(self, *, cooldown_duration: float): |
| 103 | + self._cooldowns = dict[tuple[Hashable, _HashableArgsTuple], list[_CooldownItem]]() |
| 104 | + self._cooldown_duration = cooldown_duration |
| 105 | + self.cleanup_task = scheduling.create_task( |
| 106 | + self._periodical_cleanup(random.uniform(0, 10)), |
| 107 | + name="CooldownManager cleanup", |
| 108 | + ) |
| 109 | + weakref.finalize(self, self.cleanup_task.cancel) |
| 110 | + |
| 111 | + def set_cooldown(self, channel: Hashable, call_arguments: Iterable[object]) -> None: |
| 112 | + """Set `call_arguments` arguments on cooldown in `channel`.""" |
| 113 | + timeout_timestamp = time.monotonic() + self._cooldown_duration |
| 114 | + separated_arguments = _SeparatedArguments.from_full_arguments(call_arguments) |
| 115 | + cooldowns_list = self._cooldowns.setdefault( |
| 116 | + (channel, separated_arguments.hashable), |
| 117 | + [], |
| 118 | + ) |
| 119 | + |
| 120 | + for item in cooldowns_list: |
| 121 | + if item.non_hashable_arguments == separated_arguments.non_hashable: |
| 122 | + item.timeout_timestamp = timeout_timestamp |
| 123 | + return |
| 124 | + |
| 125 | + cooldowns_list.append(_CooldownItem(separated_arguments.non_hashable, timeout_timestamp)) |
| 126 | + |
| 127 | + def is_on_cooldown(self, channel: Hashable, call_arguments: Iterable[object]) -> bool: |
| 128 | + """Check whether `call_arguments` is on cooldown in `channel`.""" |
| 129 | + current_time = time.monotonic() |
| 130 | + separated_arguments = _SeparatedArguments.from_full_arguments(call_arguments) |
| 131 | + cooldowns_list = self._cooldowns.get( |
| 132 | + (channel, separated_arguments.hashable), |
| 133 | + [], |
| 134 | + ) |
| 135 | + |
| 136 | + for item in cooldowns_list: |
| 137 | + if item.non_hashable_arguments == separated_arguments.non_hashable: |
| 138 | + return item.timeout_timestamp > current_time |
| 139 | + return False |
| 140 | + |
| 141 | + async def _periodical_cleanup(self, initial_delay: float) -> None: |
| 142 | + """ |
| 143 | + Delete stale items every hour after waiting for `initial_delay`. |
| 144 | +
|
| 145 | + The `initial_delay` ensures cleanups are not running for every command at the same time. |
| 146 | + A strong reference to self is only kept while cleanup is running. |
| 147 | + """ |
| 148 | + weak_self = weakref.ref(self) |
| 149 | + del self |
| 150 | + |
| 151 | + await asyncio.sleep(initial_delay) |
| 152 | + while True: |
| 153 | + await asyncio.sleep(60 * 60) |
| 154 | + weak_self()._delete_stale_items() |
| 155 | + |
| 156 | + def _delete_stale_items(self) -> None: |
| 157 | + """Remove expired items from internal collections.""" |
| 158 | + current_time = time.monotonic() |
| 159 | + |
| 160 | + for key, cooldowns_list in self._cooldowns.copy().items(): |
| 161 | + filtered_cooldowns = [ |
| 162 | + cooldown_item for cooldown_item in cooldowns_list if cooldown_item.timeout_timestamp < current_time |
| 163 | + ] |
| 164 | + |
| 165 | + if not filtered_cooldowns: |
| 166 | + del self._cooldowns[key] |
| 167 | + else: |
| 168 | + self._cooldowns[key] = filtered_cooldowns |
| 169 | + |
| 170 | + |
| 171 | +def _create_argument_tuple(*args: object, **kwargs: object) -> tuple[object, ...]: |
| 172 | + return (*args, _KEYWORD_SEP_SENTINEL, *kwargs.items()) |
| 173 | + |
| 174 | + |
| 175 | +def block_duplicate_invocations( |
| 176 | + *, |
| 177 | + cooldown_duration: float = 5, |
| 178 | + send_notice: bool = False, |
| 179 | + args_preprocessor: Callable[P, Iterable[object]] | None = None, |
| 180 | +) -> Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R]]]: |
| 181 | + """ |
| 182 | + Prevent duplicate invocations of a command with the same arguments in a channel for ``cooldown_duration`` seconds. |
| 183 | +
|
| 184 | + Args: |
| 185 | + cooldown_duration: Length of the cooldown in seconds. |
| 186 | + send_notice: If :obj:`True`, notify the user about the cooldown with a reply. |
| 187 | + args_preprocessor: If specified, this function is called with the args and kwargs the function is called with, |
| 188 | + its return value is then used to check for the cooldown instead of the raw arguments. |
| 189 | +
|
| 190 | + Returns: |
| 191 | + A decorator that adds a wrapper which applies the cooldowns. |
| 192 | +
|
| 193 | + Warning: |
| 194 | + The created wrapper raises :exc:`CommandOnCooldown` when the command is on cooldown. |
| 195 | + """ |
| 196 | + |
| 197 | + def decorator(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: |
| 198 | + mgr = _CommandCooldownManager(cooldown_duration=cooldown_duration) |
| 199 | + |
| 200 | + @command_wraps(func) |
| 201 | + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: |
| 202 | + if args_preprocessor is not None: |
| 203 | + all_args = args_preprocessor(*args, **kwargs) |
| 204 | + else: |
| 205 | + all_args = _create_argument_tuple(*args[2:], **kwargs) # skip self and ctx from the command |
| 206 | + ctx = typing.cast("Context[BotBase]", args[1]) |
| 207 | + |
| 208 | + if not isinstance(ctx.channel, discord.DMChannel): |
| 209 | + if mgr.is_on_cooldown(ctx.channel, all_args): |
| 210 | + if send_notice: |
| 211 | + with suppress(discord.NotFound): |
| 212 | + await ctx.reply("The command is on cooldown with the given arguments.") |
| 213 | + raise CommandOnCooldown(ctx.message.content, func, *args, **kwargs) |
| 214 | + mgr.set_cooldown(ctx.channel, all_args) |
| 215 | + |
| 216 | + return await func(*args, **kwargs) |
| 217 | + |
| 218 | + return wrapper |
| 219 | + |
| 220 | + return decorator |
0 commit comments