|
1
|
|
|
# Copyright Pincer 2021-Present |
|
|
|
|
|
|
2
|
|
|
# Full MIT License can be found in `LICENSE` at the project root. |
|
3
|
|
|
from abc import ABC, abstractmethod |
|
4
|
|
|
from enum import Enum, auto |
|
5
|
|
|
from typing import Dict, Any, Optional |
|
6
|
|
|
|
|
7
|
|
|
from .context import Context |
|
8
|
|
|
from ..utils.slidingwindow import SlidingWindow |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
class ThrottleScope(Enum): |
|
12
|
|
|
""" |
|
13
|
|
|
On what the cooldown should be set/on what should the cooldown be |
|
14
|
|
|
set. |
|
15
|
|
|
|
|
16
|
|
|
:param GUILD: |
|
17
|
|
|
The cooldown is per guild. |
|
18
|
|
|
|
|
19
|
|
|
:param CHANNEL: |
|
20
|
|
|
The cooldown is per channel. |
|
21
|
|
|
|
|
22
|
|
|
:param USER: |
|
23
|
|
|
The cooldown is per user. |
|
24
|
|
|
|
|
25
|
|
|
:param GLOBAL: |
|
26
|
|
|
The cooldown is global. |
|
27
|
|
|
""" |
|
28
|
|
|
GUILD = auto() |
|
29
|
|
|
CHANNEL = auto() |
|
30
|
|
|
USER = auto() |
|
31
|
|
|
GLOBAL = auto() |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
class ThrottleInterface(ABC): |
|
|
|
|
|
|
35
|
|
|
@abstractmethod |
|
36
|
|
|
def __init__(self, client, **kwargs): |
|
37
|
|
|
""" |
|
38
|
|
|
Initializes a throttler. |
|
39
|
|
|
|
|
40
|
|
|
:param client: |
|
41
|
|
|
The current connected client, aka your bot. |
|
42
|
|
|
|
|
43
|
|
|
:param kwargs: |
|
44
|
|
|
Optional extra arguments. |
|
45
|
|
|
""" |
|
46
|
|
|
self.client = client |
|
47
|
|
|
|
|
48
|
|
|
@abstractmethod |
|
49
|
|
|
async def handle(self, ctx: Context, **kwargs): |
|
50
|
|
|
""" |
|
51
|
|
|
Handles a context. This method is executed before the command is. |
|
52
|
|
|
|
|
53
|
|
|
:param ctx: |
|
54
|
|
|
The context of the command. |
|
55
|
|
|
|
|
56
|
|
|
:param kwargs: |
|
57
|
|
|
The extra kwargs passed for the cooldown. |
|
58
|
|
|
""" |
|
59
|
|
|
raise NotImplementedError |
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
class DefaultThrottleHandler(ThrottleInterface, ABC): |
|
|
|
|
|
|
63
|
|
|
default_throttle_type = ThrottleScope.GLOBAL |
|
64
|
|
|
throttle: Dict[Any, SlidingWindow] = {} |
|
65
|
|
|
|
|
66
|
|
|
__throttle_scopes = { |
|
67
|
|
|
ThrottleScope.GLOBAL: None, |
|
68
|
|
|
ThrottleScope.GUILD: "guild.id", |
|
69
|
|
|
ThrottleScope.CHANNEL: "channel.id", |
|
70
|
|
|
ThrottleScope.USER: "author.id" |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
def get_key_from_scope( |
|
|
|
|
|
|
74
|
|
|
self, |
|
75
|
|
|
ctx: Context, |
|
|
|
|
|
|
76
|
|
|
scope: ThrottleScope |
|
|
|
|
|
|
77
|
|
|
) -> Optional[int]: |
|
78
|
|
|
""" |
|
79
|
|
|
Retrieve the the appropriate key from the context through the |
|
80
|
|
|
throttle scope. |
|
81
|
|
|
""" |
|
82
|
|
|
... |
|
83
|
|
|
|
|
84
|
|
|
async def handle(self, ctx: Context, **kwargs): |
|
85
|
|
|
... |
|
86
|
|
|
|