From 25ccce20c1437c5efe2622923ec3f44ff21e8833 Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 20:57:42 +0100 Subject: [PATCH 1/2] Report guilds to the hub from a lightbulb extension --- README.md | 4 +- pyproject.toml | 2 +- src/librebots/kit/ext/__init__.py | 1 + src/librebots/kit/ext/guilds.py | 72 +++++++++++++ tests/guild_fakes.py | 89 +++++++++++++++ tests/test_ext_guilds.py | 173 ++++++++++++++++++++++++++++++ tests/test_guilds.py | 88 +-------------- uv.lock | 42 +++++++- 8 files changed, 381 insertions(+), 90 deletions(-) create mode 100644 src/librebots/kit/ext/__init__.py create mode 100644 src/librebots/kit/ext/guilds.py create mode 100644 tests/guild_fakes.py create mode 100644 tests/test_ext_guilds.py diff --git a/README.md b/README.md index bcee29b..5a7175d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Libre Bots kit -The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations, UI -helpers, guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code, +The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations, +guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code, and nothing in it runs unless the bot names it. ```sh diff --git a/pyproject.toml b/pyproject.toml index f4072bd..fba3f8a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ requires-python = ">=3.12" dependencies = [ "fluent-runtime>=0.4.0", "hikari>=2.6.0", - "hikari-lightbulb>=3.2.7", + "hikari-lightbulb[crontrigger]>=3.2.7", "hikari-risa>=1.3.0", "librebots-hub>=0.1.1", "msgspec>=0.22.0", diff --git a/src/librebots/kit/ext/__init__.py b/src/librebots/kit/ext/__init__.py new file mode 100644 index 0000000..9d48db4 --- /dev/null +++ b/src/librebots/kit/ext/__init__.py @@ -0,0 +1 @@ +from __future__ import annotations diff --git a/src/librebots/kit/ext/guilds.py b/src/librebots/kit/ext/guilds.py new file mode 100644 index 0000000..1b9e6fd --- /dev/null +++ b/src/librebots/kit/ext/guilds.py @@ -0,0 +1,72 @@ +"""Reports joins and leaves to the hub, and syncs a shard's guilds when it opens a session and daily at 04:00 UTC. + +Needs a `GuildReporter` in lightbulb's dependency injection. +""" + +from __future__ import annotations + +import logging +from collections.abc import Collection + +import hikari +import lightbulb + +from librebots.kit.guilds import GuildReporter +from librebots.kit.hub import HubError + +__all__ = ["loader"] + +_LOGGER = logging.getLogger(__name__) + +loader = lightbulb.Loader() + + +@loader.listener(hikari.GuildJoinEvent) +async def _report_join(event: hikari.GuildJoinEvent, reporter: GuildReporter = lightbulb.di.INJECTED) -> None: + guild = event.guild + try: + await reporter.joined(guild.id, preferred_locale=str(guild.preferred_locale), member_count=guild.member_count) + except HubError as exc: + _LOGGER.warning("Could not report joining guild %s, the next sync will: %s", guild.id, exc) + + +@loader.listener(hikari.GuildLeaveEvent) +async def _report_leave(event: hikari.GuildLeaveEvent, reporter: GuildReporter = lightbulb.di.INJECTED) -> None: + try: + await reporter.left(event.guild_id) + except HubError as exc: + _LOGGER.warning("Could not report leaving guild %s, the next sync will: %s", event.guild_id, exc) + + +@loader.listener(hikari.ShardReadyEvent) +async def _sync_shard( + event: hikari.ShardReadyEvent, + reporter: GuildReporter = lightbulb.di.INJECTED, + rest: hikari.api.RESTClient = lightbulb.di.INJECTED, +) -> None: + await _sync(reporter, rest, [event.shard.id], event.shard.shard_count) + + +async def _sync_own_shards( + bot: hikari.GatewayBot = lightbulb.di.INJECTED, + reporter: GuildReporter = lightbulb.di.INJECTED, + rest: hikari.api.RESTClient = lightbulb.di.INJECTED, +) -> None: + await _sync(reporter, rest, bot.shards.keys(), bot.shard_count) + + +# Registered without the decorator so the tests can call the function itself. +# With lightbulb's default of one failure, a single error would stop the daily sync until the next restart. +loader.task(lightbulb.crontrigger("0 4 * * *"), max_failures=-1)(_sync_own_shards) + + +async def _sync( + reporter: GuildReporter, rest: hikari.api.RESTClient, shard_ids: Collection[int], shard_count: int +) -> None: + shards = sorted(shard_ids) + try: + result = await reporter.sync(rest, shards, shard_count) + except HubError as exc: + _LOGGER.warning("Could not sync the guilds of shards %s: %s", shards, exc) + return + _LOGGER.info("Synced the guilds of shards %s: %d joined, %d left", shards, result.joined, result.left) diff --git a/tests/guild_fakes.py b/tests/guild_fakes.py new file mode 100644 index 0000000..4593348 --- /dev/null +++ b/tests/guild_fakes.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Awaitable +from unittest.mock import create_autospec + +import grpc +import grpc.aio +import hikari +from librebots.hub.v1 import guilds_pb2, guilds_pb2_grpc + +type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] + + +def on_shard(shard: int, nth: int = 1, count: int = 4) -> int: + return (count * nth + shard) << 22 + + +class FakeGuilds(guilds_pb2_grpc.GuildServiceServicer): + def __init__(self) -> None: + self.log: list[str] = [] + self.joined: list[guilds_pb2.GuildJoinedRequest] = [] + self.synced: list[guilds_pb2.SyncGuildsRequest] = [] + self.attempts: list[str] = [] + self.failing: set[str] = set() + self.stalled: set[str] = set() + self.stall_started = asyncio.Event() + self._never = asyncio.Event() + + async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: + self.attempts.append(name) + if name in self.failing: + await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") + if name in self.stalled: + self.stall_started.set() + await self._never.wait() + + async def GuildJoined( + self, + request: guilds_pb2.GuildJoinedRequest, + context: Context[guilds_pb2.GuildJoinedRequest, guilds_pb2.GuildJoinedResponse], + ) -> guilds_pb2.GuildJoinedResponse: + await self._check("joined", context) + self.log.append(f"joined {request.guild_id}") + self.joined.append(request) + return guilds_pb2.GuildJoinedResponse(settings=guilds_pb2.GuildSettings(guild_id=request.guild_id, locale="de")) + + async def GuildLeft( + self, + request: guilds_pb2.GuildLeftRequest, + context: Context[guilds_pb2.GuildLeftRequest, guilds_pb2.GuildLeftResponse], + ) -> guilds_pb2.GuildLeftResponse: + await self._check("left", context) + self.log.append(f"left {request.guild_id}") + return guilds_pb2.GuildLeftResponse() + + async def SyncGuilds( + self, + request: guilds_pb2.SyncGuildsRequest, + context: Context[guilds_pb2.SyncGuildsRequest, guilds_pb2.SyncGuildsResponse], + ) -> guilds_pb2.SyncGuildsResponse: + await self._check("sync", context) + self.log.append(f"sync {','.join(str(guild.guild_id) for guild in request.guilds)}") + self.synced.append(request) + return guilds_pb2.SyncGuildsResponse(joined=1, left=2) + + +def own_guild(guild_id: int, members: int = 1) -> hikari.OwnGuild: + guild = create_autospec(hikari.OwnGuild, instance=True) + guild.id = hikari.Snowflake(guild_id) + guild.approximate_member_count = members + return guild + + +class Listing: + def __init__(self, guilds: list[hikari.OwnGuild]) -> None: + self.guilds = guilds + self.started = asyncio.Event() + self.proceed = asyncio.Event() + self.proceed.set() + rest = create_autospec(hikari.api.RESTClient, instance=True) + rest.fetch_my_guilds.side_effect = self._guilds + self.rest: hikari.api.RESTClient = rest + + async def _guilds(self) -> AsyncIterator[hikari.OwnGuild]: + self.started.set() + await self.proceed.wait() + for guild in self.guilds: + yield guild diff --git a/tests/test_ext_guilds.py b/tests/test_ext_guilds.py new file mode 100644 index 0000000..394ce78 --- /dev/null +++ b/tests/test_ext_guilds.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import logging +from collections.abc import AsyncGenerator, Callable, Coroutine +from typing import Any +from unittest.mock import create_autospec + +import hikari +import lightbulb +import pytest +from guild_fakes import FakeGuilds, Listing, on_shard, own_guild +from hub_server import serving +from librebots.hub.v1 import guilds_pb2_grpc +from librebots.hub.v1.shards_pb2 import ShardSet + +from librebots.kit import GuildReporter +from librebots.kit.ext import guilds + +EXTENSION = "librebots.kit.ext.guilds" + +type Listener = Callable[[Any], Coroutine[Any, Any, None]] + + +@pytest.fixture +async def running() -> AsyncGenerator[tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds]]: + # The fake answers only the calls guild reporting makes. + fake = FakeGuilds() # pyright: ignore[reportAbstractUsage] + async with serving(lambda server: guilds_pb2_grpc.add_GuildServiceServicer_to_server(fake, server)) as hub: + bot = hikari.GatewayBot("MTIzNDU2Nzg5MDEyMzQ1Njc4.x.y", banner=None) + client = lightbulb.client_from_app(bot) + client.di.registry_for(lightbulb.di.Contexts.DEFAULT).register_value(GuildReporter, GuildReporter(hub)) + await client.load_extensions(EXTENSION) + yield bot, client, fake + await client.unload_extensions(EXTENSION) + + +def listener(bot: hikari.GatewayBot, event_type: type[hikari.Event]) -> Listener: + (callback,) = bot.event_manager.get_listeners(event_type) + return callback + + +def provide[T](client: lightbulb.Client, typ: type[T], value: T) -> None: + client.di.registry_for(lightbulb.di.Contexts.DEFAULT).register_value(typ, value) + + +def join_event(guild_id: int, locale: hikari.Locale, members: int | None) -> hikari.GuildJoinEvent: + guild = create_autospec(hikari.GatewayGuild, instance=True) + guild.id = hikari.Snowflake(guild_id) + guild.preferred_locale = locale + guild.member_count = members + event = create_autospec(hikari.GuildJoinEvent, instance=True) + event.guild = guild + return event + + +def leave_event(guild_id: int) -> hikari.GuildLeaveEvent: + event = create_autospec(hikari.GuildLeaveEvent, instance=True) + event.guild_id = hikari.Snowflake(guild_id) + return event + + +def ready_event(shard_id: int, shard_count: int) -> hikari.ShardReadyEvent: + shard = create_autospec(hikari.api.GatewayShard, instance=True) + shard.id = shard_id + shard.shard_count = shard_count + event = create_autospec(hikari.ShardReadyEvent, instance=True) + event.shard = shard + return event + + +def sharded_bot(shard_ids: list[int], shard_count: int) -> hikari.GatewayBot: + bot = create_autospec(hikari.GatewayBot, instance=True) + bot.shards = {shard_id: create_autospec(hikari.api.GatewayShard, instance=True) for shard_id in shard_ids} + bot.shard_count = shard_count + return bot + + +def guilds_on_every_shard() -> Listing: + return Listing([own_guild(on_shard(shard), members=shard + 1) for shard in range(4)]) + + +@pytest.mark.parametrize("event_type", [hikari.GuildJoinEvent, hikari.GuildLeaveEvent, hikari.ShardReadyEvent]) +async def test_listens_once_loaded( + running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], event_type: type[hikari.Event] +) -> None: + assert listener(running[0], event_type) + + +async def test_reports_a_join_with_the_language_and_member_count( + running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], +) -> None: + bot, _, fake = running + + await listener(bot, hikari.GuildJoinEvent)(join_event(on_shard(1), hikari.Locale.DE, 42)) + + request = fake.joined[0] + assert (request.guild_id, request.preferred_locale, request.member_count) == (on_shard(1), "de", 42) + + +async def test_reports_a_leave(running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds]) -> None: + bot, _, fake = running + + await listener(bot, hikari.GuildLeaveEvent)(leave_event(on_shard(3))) + + assert fake.log == [f"left {on_shard(3)}"] + + +@pytest.mark.parametrize( + ("call", "event_type", "event"), + [ + ("joined", hikari.GuildJoinEvent, join_event(on_shard(0), hikari.Locale.EN_US, 1)), + ("left", hikari.GuildLeaveEvent, leave_event(on_shard(0))), + ], +) +async def test_logs_a_report_the_hub_fails( + running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], + caplog: pytest.LogCaptureFixture, + call: str, + event_type: type[hikari.Event], + event: hikari.Event, +) -> None: + bot, _, fake = running + fake.failing.add(call) + + with caplog.at_level(logging.WARNING, logger=guilds.__name__): + await listener(bot, event_type)(event) + + assert str(on_shard(0)) in caplog.text + assert "UNAVAILABLE" in caplog.text + + +async def test_syncs_the_shard_of_a_new_session( + running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], caplog: pytest.LogCaptureFixture +) -> None: + bot, client, fake = running + provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest) + + with caplog.at_level(logging.INFO, logger=guilds.__name__): + await listener(bot, hikari.ShardReadyEvent)(ready_event(2, 4)) + + request = fake.synced[0] + assert request.shards == ShardSet(shard_ids=[2], shard_count=4) + assert [guild.guild_id for guild in request.guilds] == [on_shard(2)] + assert "1 joined, 2 left" in caplog.text + + +async def test_logs_a_sync_the_hub_fails( + running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], caplog: pytest.LogCaptureFixture +) -> None: + bot, client, fake = running + provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest) + fake.failing.add("sync") + + with caplog.at_level(logging.WARNING, logger=guilds.__name__): + await listener(bot, hikari.ShardReadyEvent)(ready_event(2, 4)) + + assert "shards [2]" in caplog.text + assert "UNAVAILABLE" in caplog.text + + +async def test_syncs_every_own_shard_once_a_day( + running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], +) -> None: + _, client, fake = running + provide(client, hikari.GatewayBot, sharded_bot([0, 2], 4)) + provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest) + + async with client.di.enter_context(lightbulb.di.Contexts.DEFAULT): + await lightbulb.di.with_di(guilds._sync_own_shards)() # pyright: ignore[reportPrivateUsage] + + request = fake.synced[0] + assert request.shards == ShardSet(shard_ids=[0, 2], shard_count=4) + assert [guild.guild_id for guild in request.guilds] == [on_shard(0), on_shard(2)] diff --git a/tests/test_guilds.py b/tests/test_guilds.py index 4548b41..35f6544 100644 --- a/tests/test_guilds.py +++ b/tests/test_guilds.py @@ -2,97 +2,15 @@ import asyncio import logging -from collections.abc import AsyncGenerator, AsyncIterator, Awaitable -from unittest.mock import create_autospec +from collections.abc import AsyncGenerator, AsyncIterator -import grpc -import grpc.aio -import hikari import pytest +from guild_fakes import FakeGuilds, Listing, on_shard, own_guild from hub_server import serving -from librebots.hub.v1 import guilds_pb2, guilds_pb2_grpc +from librebots.hub.v1 import guilds_pb2_grpc from librebots.kit import GuildReporter, Hub, HubError, SyncResult -type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] - - -def on_shard(shard: int, nth: int = 1, count: int = 4) -> int: - return (count * nth + shard) << 22 - - -class FakeGuilds(guilds_pb2_grpc.GuildServiceServicer): - def __init__(self) -> None: - self.log: list[str] = [] - self.joined: list[guilds_pb2.GuildJoinedRequest] = [] - self.synced: list[guilds_pb2.SyncGuildsRequest] = [] - self.attempts: list[str] = [] - self.failing: set[str] = set() - self.stalled: set[str] = set() - self.stall_started = asyncio.Event() - self._never = asyncio.Event() - - async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: - self.attempts.append(name) - if name in self.failing: - await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") - if name in self.stalled: - self.stall_started.set() - await self._never.wait() - - async def GuildJoined( - self, - request: guilds_pb2.GuildJoinedRequest, - context: Context[guilds_pb2.GuildJoinedRequest, guilds_pb2.GuildJoinedResponse], - ) -> guilds_pb2.GuildJoinedResponse: - await self._check("joined", context) - self.log.append(f"joined {request.guild_id}") - self.joined.append(request) - return guilds_pb2.GuildJoinedResponse(settings=guilds_pb2.GuildSettings(guild_id=request.guild_id, locale="de")) - - async def GuildLeft( - self, - request: guilds_pb2.GuildLeftRequest, - context: Context[guilds_pb2.GuildLeftRequest, guilds_pb2.GuildLeftResponse], - ) -> guilds_pb2.GuildLeftResponse: - await self._check("left", context) - self.log.append(f"left {request.guild_id}") - return guilds_pb2.GuildLeftResponse() - - async def SyncGuilds( - self, - request: guilds_pb2.SyncGuildsRequest, - context: Context[guilds_pb2.SyncGuildsRequest, guilds_pb2.SyncGuildsResponse], - ) -> guilds_pb2.SyncGuildsResponse: - await self._check("sync", context) - self.log.append(f"sync {','.join(str(guild.guild_id) for guild in request.guilds)}") - self.synced.append(request) - return guilds_pb2.SyncGuildsResponse(joined=1, left=2) - - -def own_guild(guild_id: int, members: int = 1) -> hikari.OwnGuild: - guild = create_autospec(hikari.OwnGuild, instance=True) - guild.id = hikari.Snowflake(guild_id) - guild.approximate_member_count = members - return guild - - -class Listing: - def __init__(self, guilds: list[hikari.OwnGuild]) -> None: - self.guilds = guilds - self.started = asyncio.Event() - self.proceed = asyncio.Event() - self.proceed.set() - rest = create_autospec(hikari.api.RESTClient, instance=True) - rest.fetch_my_guilds.side_effect = self._guilds - self.rest: hikari.api.RESTClient = rest - - async def _guilds(self) -> AsyncIterator[hikari.OwnGuild]: - self.started.set() - await self.proceed.wait() - for guild in self.guilds: - yield guild - @pytest.fixture async def hub() -> AsyncGenerator[tuple[Hub, FakeGuilds]]: diff --git a/uv.lock b/uv.lock index 12ce01b..432035a 100644 --- a/uv.lock +++ b/uv.lock @@ -223,6 +223,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/7a/78d8612ca315c47b4cdd702cf50fd84aa1f22c492eec4fde74c9b41ff4b1/confspec-0.1.0-py3-none-any.whl", hash = "sha256:57d7ce15d424708962fb7bf0077c162fbdb209468fb2620ecf69d22989c6bd75", size = 18768, upload-time = "2026-07-13T09:26:20.002Z" }, ] +[[package]] +name = "croniter" +version = "6.2.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/37/57/2e2a65aee2a70483cb28e2b7e15a072d00a523207593b44400d4717bb100/croniter-6.2.4.tar.gz", hash = "sha256:fc124f751b1b04805c2a04b061898b436b45ab2320b045e1e052ea895de65189", size = 166267, upload-time = "2026-07-10T09:52:59.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cd/ba/d678e5bd329646ca51d3c92addbc77804e86d21f4b6b6a027218e6abb010/croniter-6.2.4-py3-none-any.whl", hash = "sha256:8ef3d544107a5c05a150a2d78f8bf5a8eb9c5c4d93405a736b824109574e3f4d", size = 46677, upload-time = "2026-07-10T09:52:58.425Z" }, +] + [[package]] name = "fluent-runtime" version = "0.4.0" @@ -434,6 +446,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2d/1f/0f51a040f27df9829d86ab7578d35c745ad92664607ace1b777876749696/hikari_lightbulb-3.2.7-py3-none-any.whl", hash = "sha256:ce9167af5819c0689870d427266626d776286be94df463c9976b54e99cc459f4", size = 104641, upload-time = "2026-11-10T20:52:12.783Z" }, ] +[package.optional-dependencies] +crontrigger = [ + { name = "croniter" }, +] + [[package]] name = "hikari-risa" version = "1.3.0" @@ -487,7 +504,7 @@ source = { editable = "." } dependencies = [ { name = "fluent-runtime" }, { name = "hikari" }, - { name = "hikari-lightbulb" }, + { name = "hikari-lightbulb", extra = ["crontrigger"] }, { name = "hikari-risa" }, { name = "librebots-hub" }, { name = "msgspec" }, @@ -506,7 +523,7 @@ dev = [ requires-dist = [ { name = "fluent-runtime", specifier = ">=0.4.0" }, { name = "hikari", specifier = ">=2.6.0" }, - { name = "hikari-lightbulb", specifier = ">=3.2.7" }, + { name = "hikari-lightbulb", extras = ["crontrigger"], specifier = ">=3.2.7" }, { name = "hikari-risa", specifier = ">=1.3.0" }, { name = "librebots-hub", specifier = ">=0.1.1" }, { name = "msgspec", specifier = ">=0.22.0" }, @@ -941,6 +958,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/27/2d/e600d8f47597a803641704aba367c7266cd621f86561ec36da9888f160ec/pytest_asyncio-1.5.0-py3-none-any.whl", hash = "sha256:557f255ee03cc84f84a8d5f438bc9c6e0f714bf86970ae743c7ecb5a38d7e07d", size = 17215, upload-time = "2026-11-12T16:35:48.446Z" }, ] +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + [[package]] name = "pytz" version = "2026.6" @@ -993,6 +1022,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + [[package]] name = "yarl" version = "1.25.1" From 552bd4b6392eff5cd08f55b4b30cf5f73a36b579 Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 22:07:06 +0100 Subject: [PATCH 2/2] Make the daily guild sync public and keep event types in the test listener --- src/librebots/kit/ext/guilds.py | 12 ++++++++---- tests/test_ext_guilds.py | 9 ++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/librebots/kit/ext/guilds.py b/src/librebots/kit/ext/guilds.py index 1b9e6fd..5c7db14 100644 --- a/src/librebots/kit/ext/guilds.py +++ b/src/librebots/kit/ext/guilds.py @@ -14,7 +14,7 @@ from librebots.kit.guilds import GuildReporter from librebots.kit.hub import HubError -__all__ = ["loader"] +__all__ = ["loader", "sync_own_shards"] _LOGGER = logging.getLogger(__name__) @@ -47,17 +47,21 @@ async def _sync_shard( await _sync(reporter, rest, [event.shard.id], event.shard.shard_count) -async def _sync_own_shards( +@lightbulb.di.with_di +async def sync_own_shards( bot: hikari.GatewayBot = lightbulb.di.INJECTED, reporter: GuildReporter = lightbulb.di.INJECTED, rest: hikari.api.RESTClient = lightbulb.di.INJECTED, ) -> None: + """Sync the guilds of every shard this process runs, as the extension does daily at 04:00 UTC. + + Takes its arguments from lightbulb's dependency injection, so call it from a command, listener or task. + """ await _sync(reporter, rest, bot.shards.keys(), bot.shard_count) -# Registered without the decorator so the tests can call the function itself. # With lightbulb's default of one failure, a single error would stop the daily sync until the next restart. -loader.task(lightbulb.crontrigger("0 4 * * *"), max_failures=-1)(_sync_own_shards) +loader.task(lightbulb.crontrigger("0 4 * * *"), max_failures=-1)(sync_own_shards) async def _sync( diff --git a/tests/test_ext_guilds.py b/tests/test_ext_guilds.py index 394ce78..e951df6 100644 --- a/tests/test_ext_guilds.py +++ b/tests/test_ext_guilds.py @@ -1,8 +1,7 @@ from __future__ import annotations import logging -from collections.abc import AsyncGenerator, Callable, Coroutine -from typing import Any +from collections.abc import AsyncGenerator, Awaitable, Callable from unittest.mock import create_autospec import hikari @@ -18,7 +17,7 @@ EXTENSION = "librebots.kit.ext.guilds" -type Listener = Callable[[Any], Coroutine[Any, Any, None]] +type Listener[E: hikari.Event] = Callable[[E], Awaitable[None]] @pytest.fixture @@ -34,7 +33,7 @@ async def running() -> AsyncGenerator[tuple[hikari.GatewayBot, lightbulb.Client, await client.unload_extensions(EXTENSION) -def listener(bot: hikari.GatewayBot, event_type: type[hikari.Event]) -> Listener: +def listener[E: hikari.Event](bot: hikari.GatewayBot, event_type: type[E]) -> Listener[E]: (callback,) = bot.event_manager.get_listeners(event_type) return callback @@ -166,7 +165,7 @@ async def test_syncs_every_own_shard_once_a_day( provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest) async with client.di.enter_context(lightbulb.di.Contexts.DEFAULT): - await lightbulb.di.with_di(guilds._sync_own_shards)() # pyright: ignore[reportPrivateUsage] + await guilds.sync_own_shards() request = fake.synced[0] assert request.shards == ShardSet(shard_ids=[0, 2], shard_count=4)