diff --git a/cogs/dogesetup/dogesetup.py b/cogs/dogesetup/dogesetup.py index e82404c..22b7916 100644 --- a/cogs/dogesetup/dogesetup.py +++ b/cogs/dogesetup/dogesetup.py @@ -8,7 +8,8 @@ On every start (after Red is ready) this cog: 3. updates the repos and reloads cogs that changed, so a restart picks up new cog versions; 4. enables the manifest's slash commands that aren't enabled yet, and syncs - them to Discord only then (Red asks for syncs to be rare); + with Discord only when one was enabled or their definitions changed + (Red asks for syncs to be rare); then, every ``DOGEBOT_COG_UPDATE_HOURS`` (default 24), updates the repos and reloads cogs that changed again. @@ -20,6 +21,8 @@ checks they still exist before an upgrade. """ import asyncio +import hashlib +import json import logging import os from typing import Any @@ -55,11 +58,16 @@ class DogeSetup(commands.Cog): """Create the cog.""" self.bot = bot self._task: asyncio.Task[None] | None = None + self.config: Any = None hours = float(os.environ.get("DOGEBOT_COG_UPDATE_HOURS", "24")) self.update_interval = hours * 3600 async def cog_load(self) -> None: """Start provisioning once Red is ready.""" + self.config = Config.get_conf( + self, identifier=0xD06E5E7, force_registration=True + ) + self.config.register_global(slash_digest="") self._task = asyncio.create_task(self._run()) async def cog_unload(self) -> None: @@ -172,12 +180,24 @@ class DogeSetup(commands.Cog): log.info("Loaded %s", result["loaded_packages"]) return result - async def enable_slash_commands(self) -> list[str]: - """Enable new manifest slash commands; sync if there were any. + def _slash_digest(self) -> str: + """Hash the manifest's slash commands as Discord sees them.""" + payloads = [] + for name in manifest.SLASH_COMMANDS: + command = self.bot.tree.get_command(name) + if command is not None: + payloads.append(command.to_dict(self.bot.tree)) + text = json.dumps(payloads, sort_keys=True, default=str) + return hashlib.sha256(text.encode()).hexdigest() + async def enable_slash_commands(self) -> list[str]: + """Enable new manifest slash commands; sync when they changed. + + Syncs with Discord only when a command was newly enabled or + the definitions (options, descriptions) differ from the last + sync, which keeps Discord's sync rate limits out of reach. Only commands whose cog is loaded count, so a cog that failed - to load is retried on the next start instead of being marked - enabled without ever being synced. + to load is retried on the next start. """ enabled = (await self.bot.list_enabled_app_commands())["slash"] new = [ @@ -186,14 +206,17 @@ class DogeSetup(commands.Cog): if name not in enabled and self.bot.get_command(name) is not None ] - if not new: - return [] for name in new: await self.bot.enable_app_command(name) - await self.bot.tree.red_check_enabled() + if new: + await self.bot.tree.red_check_enabled() + digest = self._slash_digest() + if not new and digest == await self.config.slash_digest(): + return [] await self.bot.tree.sync() - log.info("Enabled and synced slash commands %s", new) - return new + await self.config.slash_digest.set(digest) + log.info("Synced slash commands (newly enabled: %s)", new) + return new or list(manifest.SLASH_COMMANDS) async def update_cogs(self) -> list[str]: """Update repos, install changed cogs and reload them.""" diff --git a/tests/test_dogesetup.py b/tests/test_dogesetup.py index 68684c2..d4a0f71 100644 --- a/tests/test_dogesetup.py +++ b/tests/test_dogesetup.py @@ -95,6 +95,18 @@ class FakeCore: return {"loaded_packages": list(names)} +class FakeCommand: + """An app command with a payload.""" + + def __init__(self, payload: dict[str, Any]) -> None: + """Remember the payload.""" + self.payload = payload + + def to_dict(self, _tree: object) -> dict[str, Any]: + """Return what Discord would get.""" + return self.payload + + class FakeTree: """Counts syncs.""" @@ -102,6 +114,11 @@ class FakeTree: """Start unsynced.""" self.syncs = 0 self.checked = 0 + self.commands: dict[str, FakeCommand] = {} + + def get_command(self, name: str) -> FakeCommand | None: + """Return an app command.""" + return self.commands.get(name) async def red_check_enabled(self) -> None: """Red re-reads which commands are enabled.""" @@ -143,10 +160,35 @@ class FakeBot: return self.cogs.get(name) +class FakeValue: + """One Config value.""" + + def __init__(self) -> None: + """Start empty.""" + self.value = "" + + async def __call__(self) -> str: + """Read it.""" + return self.value + + async def set(self, value: str) -> None: + """Write it.""" + self.value = value + + +@dataclass +class FakeConfig: + """dogesetup's Config.""" + + slash_digest: FakeValue = field(default_factory=FakeValue) + + def make(installed: list[str], broken: set[str] | None = None) -> DogeSetup: """Return a DogeSetup on a fake bot.""" downloader = FakeDownloader(installed, broken or set()) - return DogeSetup(cast("Red", FakeBot(downloader))) + setup = DogeSetup(cast("Red", FakeBot(downloader))) + setup.config = FakeConfig() + return setup async def test_fresh_install_adds_every_repo_and_cog() -> None: @@ -205,6 +247,9 @@ async def test_slash_commands_enabled_and_synced_once() -> None: setup = make([]) bot = cast("FakeBot", setup.bot) bot.commands = set(manifest.SLASH_COMMANDS) + bot.tree.commands = { + n: FakeCommand({"name": n}) for n in manifest.SLASH_COMMANDS + } assert await setup.enable_slash_commands() == list( manifest.SLASH_COMMANDS ) @@ -214,13 +259,29 @@ async def test_slash_commands_enabled_and_synced_once() -> None: assert bot.tree.syncs == 1 -async def test_slash_commands_of_unloaded_cogs_wait() -> None: - """A command whose cog didn't load is neither enabled nor synced.""" +async def test_changed_definitions_sync_again() -> None: + """A cog update that changes options triggers one more sync.""" setup = make([]) bot = cast("FakeBot", setup.bot) + name = manifest.SLASH_COMMANDS[0] + bot.commands = {name} + bot.tree.commands = {name: FakeCommand({"name": name, "options": []})} + await setup.enable_slash_commands() + bot.tree.commands[name] = FakeCommand( + {"name": name, "options": [{"name": "new"}]} + ) + assert await setup.enable_slash_commands() == [name] + assert bot.tree.syncs == 2 assert await setup.enable_slash_commands() == [] + assert bot.tree.syncs == 2 + + +async def test_slash_commands_of_unloaded_cogs_wait() -> None: + """A command whose cog didn't load isn't enabled.""" + setup = make([]) + bot = cast("FakeBot", setup.bot) + await setup.enable_slash_commands() assert bot.enabled_slash == {} - assert bot.tree.syncs == 0 def test_lavalink_settings_from_env(monkeypatch: pytest.MonkeyPatch) -> None: