commit
aaa
diff --git a/commands/cogs/genshin.py b/commands/cogs/genshin.py
index a92709a..1ccaee8 100644
--- a/commands/cogs/genshin.py
+++ b/commands/cogs/genshin.py
@@ -7,7 +7,7 @@ import hashlib
import io
from pathlib import Path
import re
-from sandrone import mood
+from sandrone import checks, mood
import time
from typing import Any, NamedTuple
from utils import components, genshin_card
@@ -389,6 +389,7 @@ class Genshin(commands.Cog):
description="Look up a Genshin Impact account by UID",
)
@app_commands.describe(uid="The 9–10 digit Genshin UID to look up")
+ @checks.cooldown(2, 30)
@mood.sassy
async def genshin(
self, interaction: discord.Interaction, uid: str
diff --git a/commands/cogs/lookups/github.py b/commands/cogs/lookups/github.py
index b8ad3fa..f7cb76c 100644
--- a/commands/cogs/lookups/github.py
+++ b/commands/cogs/lookups/github.py
@@ -42,6 +42,7 @@ class GitHub(commands.Cog):
username="The GitHub username to fetch information on"
)
@checks.hasPermissions(embed_links=True)
+ @checks.cooldown(3, 30)
@mood.sassy
async def github(
self, interaction: discord.Interaction, username: str
@@ -146,6 +147,7 @@ class GitHub(commands.Cog):
repository="The repository to fetch, as username/repo"
)
@checks.hasPermissions(embed_links=True)
+ @checks.cooldown(3, 30)
@mood.sassy
async def repo(
self, interaction: discord.Interaction, repository: str
diff --git a/commands/cogs/media/pride.py b/commands/cogs/media/pride.py
index 267117d..b68b01d 100644
--- a/commands/cogs/media/pride.py
+++ b/commands/cogs/media/pride.py
@@ -78,6 +78,7 @@ class Pride(commands.Cog):
)
@app_commands.choices(style=prideStyles.options)
@checks.hasPermissions(attach_files=True)
+ @checks.cooldown(2, 30)
@mood.sassy
async def pride(
self,
diff --git a/commands/cogs/media/yt_dlp.py b/commands/cogs/media/yt_dlp.py
index 06237a6..88a8ee6 100644
--- a/commands/cogs/media/yt_dlp.py
+++ b/commands/cogs/media/yt_dlp.py
@@ -5,7 +5,7 @@ from discord.ext import commands
import io
from pathlib import Path
import re
-from sandrone import config, mood
+from sandrone import checks, config, mood
import shutil
from typing import NamedTuple
from urllib.parse import parse_qs, urlsplit
@@ -63,6 +63,7 @@ class YtDlp(commands.Cog):
url="YouTube URL", type="Audio or Video? (defaults to Video)"
)
@app_commands.choices(type=containers.options)
+ @checks.cooldown(1, 60)
@mood.sassy
async def ytDlp(
self,
diff --git a/commands/cogs/tools/translate.py b/commands/cogs/tools/translate.py
index b3baac9..913c693 100644
--- a/commands/cogs/tools/translate.py
+++ b/commands/cogs/tools/translate.py
@@ -4,7 +4,7 @@ import discord
from discord import app_commands
from discord.ext import commands
import re
-from sandrone import mood
+from sandrone import checks, mood
from utils import components
titleBrackets = (("『", "』"), ("《", "》"))
@@ -46,6 +46,7 @@ class Translate(commands.Cog):
@app_commands.autocomplete(
source=languageAutocomplete, to=languageAutocomplete
)
+ @checks.cooldown(2, 30)
@mood.sassy
async def translate(
self,
diff --git a/sandrone/checks.py b/sandrone/checks.py
index 1873509..075585f 100644
--- a/sandrone/checks.py
+++ b/sandrone/checks.py
@@ -1,9 +1,71 @@
import discord
from discord import app_commands
-from sandrone import mood
+import math
+from sandrone import config, mood
from utils import cf, errors
permsAttr = "__sandrone_bot_perms__"
+cooldownAttr = "__sandrone_cooldown__"
+
+# Every command gets this unless it's decorated with its own `cooldown`.
+defaultRate = 3
+defaultPer = 10.0
+
+
+def perUserCooldown(rate: int, per: float):
+ """A per-user cooldown check that owners are never held back by."""
+
+ def factory(
+ interaction: discord.Interaction,
+ ) -> app_commands.Cooldown | None:
+ if interaction.user.id in config.owners:
+ return None
+ return app_commands.Cooldown(rate, per)
+
+ return app_commands.checks.dynamic_cooldown(factory)
+
+
+def cooldown(rate: int, per: float):
+ """Let each user run the command *rate* times every *per* seconds.
+
+ The limit is stashed on the callback so the default cooldown knows to
+ leave the command alone.
+ """
+ check = perUserCooldown(rate, per)
+
+ def decorator(func):
+ target = getattr(func, "callback", func)
+ setattr(target, cooldownAttr, (rate, per))
+ return check(func)
+
+ return decorator
+
+
+def applyDefaultCooldown(
+ command: app_commands.Command | app_commands.ContextMenu,
+) -> None:
+ """Give *command* the default cooldown if it has none of its own.
+
+ Cogs copy their commands but share callbacks, so the default is
+ marked on the command itself, not the callback.
+ """
+ if hasattr(command.callback, cooldownAttr) or hasattr(
+ command, cooldownAttr
+ ):
+ return
+ perUserCooldown(defaultRate, defaultPer)(command)
+ setattr(command, cooldownAttr, (defaultRate, defaultPer))
+
+
+def commandCooldown(
+ command: app_commands.Command | app_commands.ContextMenu,
+) -> tuple[int, float] | None:
+ """The (rate, per) limit *command* runs under, if any."""
+ return getattr(
+ command.callback,
+ cooldownAttr,
+ getattr(command, cooldownAttr, None),
+ )
def hasPermissions(*, guildOnly: bool = False, **perms: bool):
@@ -103,7 +165,7 @@ async def handleAppCommandError(
if isinstance(error, app_commands.CommandOnCooldown):
await respond(
interaction,
- f"Slow down. Try again in {error.retry_after:.0f}s.",
+ f"Slow down. Try again in {math.ceil(error.retry_after)}s.",
)
return
diff --git a/sandrone/client.py b/sandrone/client.py
index 1c33b74..81928e5 100644
--- a/sandrone/client.py
+++ b/sandrone/client.py
@@ -1,10 +1,11 @@
import asyncio
import contextlib
import discord
+from discord import app_commands
from discord.ext import commands
from pathlib import Path
from sandrone import config, website
-from sandrone.checks import handleAppCommandError
+from sandrone.checks import applyDefaultCooldown, handleAppCommandError
import signal
import sys
from utils import cf, downloads, errors, jp_storage
@@ -20,6 +21,23 @@ def discoverExtensions(directory: Path, package: str) -> list[str]:
)
+class Tree(app_commands.CommandTree):
+ """Hands every command the default cooldown as it's added.
+
+ Cogs, /help and hot reloads all come through add_command, so nothing
+ slips past without a limit.
+ """
+
+ def add_command(self, command, /, **kwargs) -> None:
+ if isinstance(command, app_commands.Group):
+ for child in command.walk_commands():
+ if isinstance(child, app_commands.Command):
+ applyDefaultCooldown(child)
+ else:
+ applyDefaultCooldown(command)
+ super().add_command(command, **kwargs)
+
+
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -143,11 +161,11 @@ class Bot(commands.Bot):
await self.tree.sync()
async def applyNameStyle(self) -> None:
- """Set her display name font/effect/colours in every server she's in.
+ """Set her display name font/effect/colours in every server.
- discord.py has no wrapper for these fields yet, so they go straight
- through the raw member-edit route. It's per-guild because bots can't
- style their global profile.
+ discord.py has no wrapper for these fields yet, so they go
+ straight through the raw member-edit route. It's per-guild
+ because bots can't style their global profile.
"""
fields = {
key: value
@@ -165,7 +183,12 @@ class Bot(commands.Bot):
try:
await self.http.edit_my_member(guild.id, **fields)
except discord.HTTPException as e:
- print(cf.red(f"[style] couldn't style my name in {guild.id}: {e}"))
+ print(
+ cf.red(
+ f"[style] couldn't style my name in {guild.id}: "
+ f"{e}"
+ )
+ )
else:
print(cf.yellow(f"[style] name style set in {guild.name}"))
@@ -205,6 +228,7 @@ def createBot() -> Bot:
intents=intents,
activity=activity,
help_command=None,
+ tree_cls=Tree,
)
diff --git a/tests/test_cooldowns.py b/tests/test_cooldowns.py
new file mode 100644
index 0000000..7684ec8
--- /dev/null
+++ b/tests/test_cooldowns.py
@@ -0,0 +1,114 @@
+import asyncio
+import datetime
+import discord
+from discord import app_commands
+import pytest
+from sandrone import checks, config
+from sandrone.client import Tree
+from types import SimpleNamespace
+from typing import Any, cast
+
+strangerId = 1
+
+
+def fakeInteraction(userId: int = strangerId) -> discord.Interaction:
+ return cast(
+ Any,
+ SimpleNamespace(
+ user=SimpleNamespace(id=userId),
+ created_at=datetime.datetime.now(datetime.UTC),
+ ),
+ )
+
+
+def makeCommand(*decorators) -> app_commands.Command:
+ async def callback(interaction: discord.Interaction) -> None:
+ pass
+
+ for decorator in reversed(decorators):
+ callback = decorator(callback)
+ return app_commands.Command(
+ name="thing", description="A thing", callback=callback
+ )
+
+
+def runChecks(
+ command: app_commands.Command, interaction: discord.Interaction
+) -> None:
+ for predicate in command.checks:
+ asyncio.run(discord.utils.maybe_coroutine(predicate, interaction))
+
+
+def test_a_command_with_no_cooldown_gets_the_default() -> None:
+ command = makeCommand()
+ checks.applyDefaultCooldown(command)
+
+ assert len(command.checks) == 1
+ assert checks.commandCooldown(command) == (
+ checks.defaultRate,
+ checks.defaultPer,
+ )
+
+
+def test_the_default_is_only_applied_once() -> None:
+ command = makeCommand()
+ checks.applyDefaultCooldown(command)
+ checks.applyDefaultCooldown(command)
+
+ assert len(command.checks) == 1
+
+
+def test_an_explicit_cooldown_is_left_alone() -> None:
+ command = makeCommand(checks.cooldown(1, 60))
+ checks.applyDefaultCooldown(command)
+
+ assert len(command.checks) == 1
+ assert checks.commandCooldown(command) == (1, 60)
+
+
+def test_a_user_is_stopped_once_they_run_out() -> None:
+ command = makeCommand(checks.cooldown(2, 60))
+ interaction = fakeInteraction()
+
+ runChecks(command, interaction)
+ runChecks(command, interaction)
+ with pytest.raises(app_commands.CommandOnCooldown):
+ runChecks(command, interaction)
+
+
+def test_users_have_their_own_buckets() -> None:
+ command = makeCommand(checks.cooldown(1, 60))
+
+ runChecks(command, fakeInteraction(strangerId))
+ runChecks(command, fakeInteraction(strangerId + 1))
+
+
+def test_owners_are_never_held_back() -> None:
+ command = makeCommand(checks.cooldown(1, 60))
+ owner = fakeInteraction(config.owners[0])
+
+ for _ in range(5):
+ runChecks(command, owner)
+
+
+def test_the_tree_gives_group_children_the_default() -> None:
+ group = app_commands.Group(name="things", description="Things")
+
+ @group.command(name="plain", description="No cooldown of its own")
+ async def plain(interaction: discord.Interaction) -> None:
+ pass
+
+ @group.command(name="slow", description="Has its own cooldown")
+ @checks.cooldown(1, 60)
+ async def slow(interaction: discord.Interaction) -> None:
+ pass
+
+ tree = Tree(discord.Client(intents=discord.Intents.none()))
+ tree.add_command(group)
+
+ assert checks.commandCooldown(plain) == (
+ checks.defaultRate,
+ checks.defaultPer,
+ )
+ assert checks.commandCooldown(slow) == (1, 60)
+ assert len(slow.checks) == 1
diff --git a/utils/genshin_card.py b/utils/genshin_card.py
index 201eb31..2efa27d 100644
--- a/utils/genshin_card.py
+++ b/utils/genshin_card.py
@@ -2,8 +2,8 @@ from __future__ import annotations
from functools import lru_cache
import io
-import re
from PIL import Image, ImageDraw, ImageFont
+import re
from sandrone import config
from typing import Any