diff --git a/README.md b/README.md index 1410546..93b8b43 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,11 @@ lives there. up as people sign up. A week with no events gets no cards. - **WoW: Forever news.** Every five minutes the bot checks Blizzard's own forum posts about WoW: Forever and Wowhead's WoW: Forever news, and posts each new one in the feed channel with a link to the full post. +- **Addons.** `#addons`, right below `#rules`, lists the community addons the guild recommends for WoW: Forever, + grouped by who they're for (required for raids, suggested for raids, everyone, leveling, PvP), with a link to the + full catalog on the website. The bot creates the channel the first time it has addons to show, keeps it read-only + like `#rules`, and edits its own posts every ten minutes to stay in step with the website without ever reposting + unchanged content. - **Class halls.** Pick a class in `#choose-your-class` and you join that class's post in `#class-halls`. - **Group voice.** `#lfg` has one button per kind (Dungeon, Raid, World Boss, Leveling, PvP, Hangout). Click one and a voice channel opens right away, with a Join link and an **Add details** button to name it, add a note, flag diff --git a/pyproject.toml b/pyproject.toml index f7bb004..4767d86 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,8 +36,8 @@ dev = [ ] [tool.uv.sources] -sidequest-common = { git = "https://github.com/SideQuest-Guild/website", rev = "9b37db6351643f218573abd223188cdf9dec2bbd", subdirectory = "packages/sidequest-common" } -sidequest-api = { git = "https://github.com/SideQuest-Guild/website", rev = "9b37db6351643f218573abd223188cdf9dec2bbd", subdirectory = "api" } +sidequest-common = { git = "https://github.com/SideQuest-Guild/website", rev = "ca6be8049dc9c29357b829588c5c7feb97aaa7f1", subdirectory = "packages/sidequest-common" } +sidequest-api = { git = "https://github.com/SideQuest-Guild/website", rev = "ca6be8049dc9c29357b829588c5c7feb97aaa7f1", subdirectory = "api" } [tool.pytest.ini_options] asyncio_mode = "auto" diff --git a/src/sidequest_bot/api_client.py b/src/sidequest_bot/api_client.py index 4332dae..6fe3b9d 100644 --- a/src/sidequest_bot/api_client.py +++ b/src/sidequest_bot/api_client.py @@ -12,6 +12,7 @@ from sidequest_common.schemas import ( ActivityAck, + AddonSchema, AnnouncementPosted, AwayNowReport, BadgeAck, @@ -92,6 +93,7 @@ _WEEKLY_BOARD_EVENTS = TypeAdapter(list[WeeklyBoardEvent]) _GROUP_SESSIONS = TypeAdapter(list[GroupSessionSchema]) _XP_GRANTS = TypeAdapter(list[XPGrantResult]) +_ADDONS = TypeAdapter(list[AddonSchema]) class ItemSummary(BaseModel): @@ -694,6 +696,11 @@ async def get_recruiting(self) -> Recruiting: data = await self._request("GET", "/api/recruiting") return _parse(Recruiting.model_validate, data) + async def list_addons(self) -> list[AddonSchema]: + """Every recommended addon, by name (the public ``/api/addons`` GET).""" + data = await self._request("GET", "/api/addons") + return _parse(_ADDONS.validate_python, data) + async def list_weekly_board_events(self, guild_id: int, start: datetime, end: datetime) -> list[WeeklyBoardEvent]: """Scheduled events starting in ``[start, end)``, soonest first, with their forum thread id and sign-ups.""" data = await self._request( diff --git a/src/sidequest_bot/plugins/addons_channel.py b/src/sidequest_bot/plugins/addons_channel.py new file mode 100644 index 0000000..6c3aeb8 --- /dev/null +++ b/src/sidequest_bot/plugins/addons_channel.py @@ -0,0 +1,221 @@ +"""Read-only ``#addons`` channel: the addons the guild requires and suggests, grouped by category. + +Every ten minutes the bot fetches the catalog from the API and keeps ``#addons`` in the site guild (``WEB_GUILD_ID``) +in sync: creates the channel below ``#rules`` with the same visibility the first time, then edits, posts or deletes +its own messages so the channel always mirrors the current catalog without reposting unchanged content. +""" + +import logging +from functools import lru_cache +from typing import TYPE_CHECKING, Any, Final + +import discord +from discord.ext import commands, tasks + +from sidequest_bot.api_client import APIError, NotFoundError +from sidequest_bot.bot import SideQuestBot # noqa: TC001 # discord.py evaluates app-command annotations at runtime +from sidequest_bot.lib.embeds import Colors, make_embed +from sidequest_common.schemas import ADDON_CATEGORY_LABELS, AddonCategory +from sidequest_common.settings import WebSettings + +if TYPE_CHECKING: + from collections.abc import Sequence + + from sidequest_common.schemas import AddonSchema + +logger = logging.getLogger(__name__) + +CHECK_INTERVAL_MINUTES = 10 +CHANNEL_NAME = "addons" +RULES_CHANNEL_NAME = "rules" +HISTORY_LIMIT = 50 +"""How many of the channel's own recent messages are read back to sync against; the catalog is far smaller.""" +DESCRIPTION_LIMIT: Final = 4096 +"""Discord's hard cap on an embed's ``description``.""" + + +@lru_cache(maxsize=1) +def _web_settings() -> WebSettings: + """``WebSettings`` (``WEB_*`` env vars), shared with the API: ``GUILD_ID`` and ``BASE_URL`` for the addons link.""" + return WebSettings() + + +def find_text_channel(guild: discord.Guild, name: str) -> discord.TextChannel | None: + """The one text channel called ``name`` anywhere in ``guild``, or ``None``.""" + for channel in guild.channels: + if isinstance(channel, discord.TextChannel) and channel.name.casefold() == name.casefold(): + return channel + return None + + +def _channel_topic(base_url: str) -> str: + return f"Addons the guild recommends for WoW: Forever. Kept in step with {base_url}/addons/." + + +def build_intro(base_url: str) -> str: + """Plain-words explanation of the channel, posted as the first message. + + The link sits in ``<>`` so Discord adds no preview embed, which would make the intro never match on the next sync. + """ + return ( + "Addons for WoW: Forever, grouped by who they're for. Run the **Required for raids** ones on raid nights; " + f"the rest are suggestions. The same list, with versions, is at <{base_url}/addons/>." + ) + + +def _addon_line(addon: AddonSchema) -> str: + return f"**[{addon.name}]({addon.download_url})**: {addon.summary}" + + +def _pack_lines(lines: Sequence[str], limit: int = DESCRIPTION_LIMIT) -> list[str]: + """Greedily pack ``lines`` into newline-joined chunks no longer than ``limit`` characters.""" + chunks: list[str] = [] + current: list[str] = [] + current_len = 0 + for line in lines: + added = len(line) + (1 if current else 0) + if current and current_len + added > limit: + chunks.append("\n".join(current)) + current = [line] + current_len = len(line) + else: + current.append(line) + current_len += added + if current: + chunks.append("\n".join(current)) + return chunks or [""] + + +class RenderedPost: + """One message to sync: either plain ``content`` (the intro) or a single category ``embed``, never both.""" + + __slots__ = ("content", "embed") + + def __init__(self, *, content: str | None = None, embed: discord.Embed | None = None) -> None: + self.content = content + self.embed = embed + + +def render_posts(addons: Sequence[AddonSchema], base_url: str) -> list[RenderedPost]: + """The intro message, then one embed per non-empty category (in enum order, split if it would overflow). + + Within a category, guild-made addons sort first, then alphabetically. + """ + posts = [RenderedPost(content=build_intro(base_url))] + for category in AddonCategory: + group = [addon for addon in addons if addon.category == category] + if not group: + continue + ordered = sorted(group, key=lambda addon: (addon.origin != "guild", addon.name.casefold())) + lines = [_addon_line(addon) for addon in ordered] + for chunk in _pack_lines(lines): + embed = make_embed(ADDON_CATEGORY_LABELS[category], chunk, color=Colors.SITE_GOLD, timestamp=False) + posts.append(RenderedPost(embed=embed)) + return posts + + +def _embed_key(embed: discord.Embed) -> tuple[str | None, str | None, int | None]: + """What the bot sets on a category embed, compared field by field: Discord may add keys of its own to a sent one.""" + return embed.title, embed.description, embed.colour.value if embed.colour is not None else None + + +def _post_matches(message: discord.Message, post: RenderedPost) -> bool: + """Whether ``message`` already shows ``post``'s content and embed, so editing it would be a no-op.""" + content_matches = (message.content or "") == (post.content or "") + desired_embeds = [_embed_key(post.embed)] if post.embed is not None else [] + return content_matches and [_embed_key(embed) for embed in message.embeds] == desired_embeds + + +class AddonsChannelCog(commands.Cog): + """Keeps the site guild's ``#addons`` channel in sync with the API's addon catalog.""" + + def __init__(self, bot: SideQuestBot) -> None: + self.bot = bot + self._check_loop.start() + + async def cog_unload(self) -> None: + """Stop the check loop when the cog is unloaded.""" + self._check_loop.cancel() + + @tasks.loop(minutes=CHECK_INTERVAL_MINUTES) + async def _check_loop(self) -> None: + guild = self.bot.get_guild(_web_settings().GUILD_ID) + if guild is None: + return + try: + addons = await self.bot.api.list_addons() + except NotFoundError: + # The addons endpoint may not exist yet on an old API pod mid-rollout; retry next tick. + logger.info("Addons endpoint not available yet; retrying next tick") + return + except APIError: + # Must not escape: an unhandled exception stops a tasks.loop for good. Retried next tick. + logger.warning("Failed to fetch addons", exc_info=True) + return + if not addons: + # Nothing to show yet; leave whatever is already in the channel alone. + return + try: + await self._sync_guild(guild, addons) + except discord.HTTPException: + logger.warning("Failed to sync #%s in guild %s", CHANNEL_NAME, guild.id, exc_info=True) + + @_check_loop.before_loop + async def _before_check_loop(self) -> None: + await self.bot.wait_until_ready() + + async def _sync_guild(self, guild: discord.Guild, addons: Sequence[AddonSchema]) -> None: + channel = await self._ensure_channel(guild) + if channel is None: + return + await self._sync_messages(channel, addons) + + async def _ensure_channel(self, guild: discord.Guild) -> discord.TextChannel | None: + """The existing ``#addons`` channel, or a new one placed right below ``#rules`` with its overwrites.""" + existing = find_text_channel(guild, CHANNEL_NAME) + if existing is not None: + return existing + rules = find_text_channel(guild, RULES_CHANNEL_NAME) + if rules is None: + logger.warning("No #%s channel in guild %s; can't place #%s", RULES_CHANNEL_NAME, guild.id, CHANNEL_NAME) + return None + channel = await guild.create_text_channel( + CHANNEL_NAME, + overwrites=dict(rules.overwrites), + topic=_channel_topic(_web_settings().BASE_URL), + reason="Auto-created to list recommended addons, visible like #rules", + ) + await channel.move(after=rules) + return channel + + async def _sync_messages(self, channel: discord.TextChannel, addons: Sequence[AddonSchema]) -> None: + """Edit, post or delete the channel's own messages so they match ``addons``, touching nothing else.""" + me = self.bot.user + if me is None: + return + posts = render_posts(addons, _web_settings().BASE_URL) + existing = [ + message + async for message in channel.history(limit=HISTORY_LIMIT, oldest_first=True) + if message.author.id == me.id + ] + for index, post in enumerate(posts): + if index < len(existing): + if not _post_matches(existing[index], post): + await existing[index].edit( + content=post.content, embed=post.embed, allowed_mentions=discord.AllowedMentions.none() + ) + else: + send_kwargs: dict[str, Any] = {"allowed_mentions": discord.AllowedMentions.none()} + if post.content is not None: + send_kwargs["content"] = post.content + if post.embed is not None: + send_kwargs["embed"] = post.embed + await channel.send(**send_kwargs) + for surplus in existing[len(posts) :]: + await surplus.delete() + + +async def setup(bot: SideQuestBot) -> None: + """Register the cog.""" + await bot.add_cog(AddonsChannelCog(bot)) diff --git a/tests/fakes.py b/tests/fakes.py index a381bb3..79f638d 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -4,7 +4,8 @@ setting permissions and adding roles change the fake's state, so a check after a plan runs sees what Discord would. """ -from collections.abc import Iterable +import functools +from collections.abc import AsyncIterator, Iterable from itertools import count from typing import Any from unittest.mock import AsyncMock, MagicMock @@ -13,6 +14,9 @@ _ids = count(900_000) +BOT_USER_ID = 999_999_999 +"""The fake server's own bot account id. ``channel.send()``'s messages carry it as ``message.author.id``; a cog +under test usually needs ``cog.bot.user = SimpleNamespace(id=BOT_USER_ID, bot=True)`` to recognize its own posts.""" ChannelSpec = type[discord.abc.GuildChannel] @@ -30,6 +34,68 @@ def make_role(role_id: int, name: str, *, permissions: discord.Permissions | Non return role +def _bot_author() -> MagicMock: + author = MagicMock(spec=discord.ClientUser) + author.id = BOT_USER_ID + author.bot = True + return author + + +async def _edit_message(message: MagicMock, **edit_kwargs: Any) -> None: + if "content" in edit_kwargs: + message.content = edit_kwargs["content"] + if "embeds" in edit_kwargs: + message.embeds = edit_kwargs["embeds"] or [] + elif "embed" in edit_kwargs: + message.embeds = [edit_kwargs["embed"]] if edit_kwargs["embed"] else [] + + +async def _delete_message(channel: MagicMock, message: MagicMock) -> None: + if message in channel.messages: + channel.messages.remove(message) + + +async def _channel_send(channel: MagicMock, content: str | None = None, **kwargs: Any) -> MagicMock: + embeds = kwargs.get("embeds") or ([kwargs["embed"]] if kwargs.get("embed") else []) + message = MagicMock(spec=discord.Message) + message.id = next(_ids) + message.author = _bot_author() + message.content = content + message.embeds = embeds + message.jump_url = f"https://discord.com/channels/1/{channel.id}/{message.id}" + message.edit = AsyncMock(side_effect=functools.partial(_edit_message, message)) + message.delete = AsyncMock(side_effect=functools.partial(_delete_message, channel, message)) + channel.messages.append(message) + return message + + +async def _channel_history( + channel: MagicMock, *, limit: int | None = None, oldest_first: bool | None = None, **_kwargs: Any +) -> AsyncIterator[MagicMock]: + items = list(channel.messages) if oldest_first else list(reversed(channel.messages)) + if limit is not None: + items = items[:limit] + for message in items: + yield message + + +async def _move_channel(channel: MagicMock, *, after: MagicMock | None = None, **_kwargs: Any) -> None: + siblings = channel.guild.channels + if channel in siblings: + siblings.remove(channel) + if after is None: + siblings.insert(0, channel) + else: + siblings.insert(siblings.index(after) + 1, channel) + + +async def _channel_set_permissions( + channel: MagicMock, target: Any, *, overwrite: discord.PermissionOverwrite, **_kwargs: Any +) -> None: + channel.overwrites[target] = overwrite + channel.permissions_synced = False + + def make_channel( spec: ChannelSpec, channel_id: int, @@ -38,31 +104,27 @@ def make_channel( *, category: MagicMock | None = None, ) -> MagicMock: - """A channel or category. With ``overwrites=None`` in a category, it is synced to the category's access.""" + """A channel or category. With ``overwrites=None`` in a category, it is synced to the category's access. + + ``.guild`` starts ``None``; ``make_guild`` and its ``create_*`` methods set it, which ``.move()`` needs. + """ channel = MagicMock(spec=spec) channel.id = channel_id channel.name = name channel.mention = f"<#{channel_id}>" channel.category = category channel.category_id = category.id if category is not None else None + channel.guild = None channel.overwrites = ( dict(category.overwrites) if overwrites is None and category is not None else (overwrites or {}) ) channel.permissions_synced = category is not None and channel.overwrites == category.overwrites channel.overwrites_for.side_effect = lambda target: channel.overwrites.get(target, discord.PermissionOverwrite()) - - async def set_permissions(target: Any, *, overwrite: discord.PermissionOverwrite, **_kwargs: Any) -> None: - channel.overwrites[target] = overwrite - channel.permissions_synced = False - - async def send(content: str, **_kwargs: Any) -> MagicMock: - message = MagicMock(spec=discord.Message) - message.content = content - message.jump_url = f"https://discord.com/channels/1/{channel_id}/{next(_ids)}" - return message - - channel.set_permissions = AsyncMock(side_effect=set_permissions) - channel.send = AsyncMock(side_effect=send) + channel.messages: list[MagicMock] = [] + channel.set_permissions = AsyncMock(side_effect=functools.partial(_channel_set_permissions, channel)) + channel.send = AsyncMock(side_effect=functools.partial(_channel_send, channel)) + channel.history = lambda **kwargs: _channel_history(channel, **kwargs) + channel.move = AsyncMock(side_effect=functools.partial(_move_channel, channel)) return channel @@ -112,6 +174,8 @@ def by_category() -> list[tuple[MagicMock | None, list[MagicMock]]]: guild.by_category.side_effect = by_category for member in members: member.guild = guild + for channel in channels: + channel.guild = guild async def create_role(**kwargs: Any) -> MagicMock: role = make_role(next(_ids), kwargs["name"], permissions=kwargs.get("permissions")) @@ -125,6 +189,7 @@ async def create(name: str, **kwargs: Any) -> MagicMock: spec, next(_ids), name, dict(kwargs.get("overwrites") or {}), category=kwargs.get("category") ) channel.created_with = kwargs + channel.guild = guild guild.channels.append(channel) return channel diff --git a/tests/test_addons_channel.py b/tests/test_addons_channel.py new file mode 100644 index 0000000..a6f75a0 --- /dev/null +++ b/tests/test_addons_channel.py @@ -0,0 +1,220 @@ +"""Unit tests for the #addons channel plugin: rendering, channel placement, and message sync.""" + +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import AsyncMock +from uuid import uuid4 + +import discord +import pytest + +from sidequest_bot.api_client import APIError, NotFoundError +from sidequest_bot.plugins import addons_channel +from sidequest_bot.plugins.addons_channel import ( + AddonsChannelCog, + build_intro, + find_text_channel, + render_posts, +) +from sidequest_common.schemas import ADDON_CATEGORY_LABELS, AddonCategory, AddonOrigin, AddonSchema +from sidequest_common.settings import WebSettings +from tests import fakes +from tests.fakes import named, sidequest_server + +BASE_URL = "https://sidequest-guild.com" + + +def _addon(**overrides: object) -> AddonSchema: + base: dict[str, object] = { + "id": uuid4(), + "slug": "addon", + "name": "Addon", + "summary": "Does a thing.", + "version": "1.0", + "download_url": "https://example.com/addon", + "homepage_url": None, + "origin": AddonOrigin.COMMUNITY, + "category": AddonCategory.GENERAL, + "updated_at": datetime(2026, 1, 1, tzinfo=UTC), + } + base.update(overrides) + return AddonSchema.model_validate(base) + + +def _web_settings(guild_id: int) -> WebSettings: + return WebSettings(_env_file=None, GUILD_ID=guild_id, BASE_URL=BASE_URL) + + +def _make_cog(*, api: object, guild: object) -> AddonsChannelCog: + cog = AddonsChannelCog.__new__(AddonsChannelCog) + cog.bot = SimpleNamespace( + api=api, + user=SimpleNamespace(id=fakes.BOT_USER_ID), + get_guild=lambda gid: guild if gid == guild.id else None, + ) + return cog + + +class TestFindTextChannel: + def test_finds_by_name_anywhere_in_the_guild(self) -> None: + guild = sidequest_server() + assert find_text_channel(guild, "rules") is named(guild.channels, "rules") + + def test_missing_channel_is_none(self) -> None: + guild = sidequest_server() + assert find_text_channel(guild, "addons") is None + + +class TestRenderPosts: + def test_categories_in_contract_order_guild_made_first(self) -> None: + addons = [ + _addon(name="Zebra", category=AddonCategory.RAID, origin=AddonOrigin.COMMUNITY), + _addon(name="Alpha", category=AddonCategory.RAID, origin=AddonOrigin.GUILD), + _addon(name="Leveler", category=AddonCategory.LEVELING, origin=AddonOrigin.COMMUNITY), + ] + posts = render_posts(addons, BASE_URL) + assert posts[0].content == build_intro(BASE_URL) + assert posts[0].embed is None + # RAID precedes LEVELING in AddonCategory's declaration order; RAID_REQUIRED and GENERAL/PVP are empty. + assert posts[1].embed is not None + assert posts[1].embed.title == ADDON_CATEGORY_LABELS[AddonCategory.RAID] + assert posts[1].embed.description.splitlines() == [ + "**[Alpha](https://example.com/addon)**: Does a thing.", + "**[Zebra](https://example.com/addon)**: Does a thing.", + ] + assert posts[2].embed is not None + assert posts[2].embed.title == ADDON_CATEGORY_LABELS[AddonCategory.LEVELING] + assert len(posts) == 3 + + def test_skips_empty_categories(self) -> None: + posts = render_posts([_addon(category=AddonCategory.PVP)], BASE_URL) + assert len(posts) == 2 + assert posts[1].embed is not None + assert posts[1].embed.title == ADDON_CATEGORY_LABELS[AddonCategory.PVP] + + +class TestCheckLoop: + async def test_creates_addons_channel_below_rules_with_rules_overwrites( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + guild = sidequest_server() + rules = named(guild.channels, "rules") + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + api = AsyncMock() + api.list_addons.return_value = [_addon(category=AddonCategory.GENERAL)] + cog = _make_cog(api=api, guild=guild) + + await cog._check_loop.coro(cog) + + channel = named(guild.channels, "addons") + assert channel.created_with["overwrites"] == rules.overwrites + assert channel.created_with["overwrites"] is not rules.overwrites + assert guild.channels.index(channel) == guild.channels.index(rules) + 1 + + async def test_does_nothing_outside_the_site_guild(self, monkeypatch: pytest.MonkeyPatch) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id + 1)) + api = AsyncMock() + cog = _make_cog(api=api, guild=guild) + + await cog._check_loop.coro(cog) + + api.list_addons.assert_not_called() + assert find_text_channel(guild, "addons") is None + + async def test_second_tick_with_unchanged_addons_sends_or_edits_nothing( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + api = AsyncMock() + api.list_addons.return_value = [_addon(name="Alpha", category=AddonCategory.GENERAL)] + cog = _make_cog(api=api, guild=guild) + await cog._check_loop.coro(cog) + channel = named(guild.channels, "addons") + channel.send.reset_mock() + + await cog._check_loop.coro(cog) + + channel.send.assert_not_called() + for message in channel.messages: + message.edit.assert_not_called() + + async def test_changed_summary_edits_only_that_message(self, monkeypatch: pytest.MonkeyPatch) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + alpha = _addon(name="Alpha", category=AddonCategory.GENERAL, summary="Old summary.") + beta = _addon(name="Beta", category=AddonCategory.PVP, summary="Other summary.") + api = AsyncMock() + api.list_addons.return_value = [alpha, beta] + cog = _make_cog(api=api, guild=guild) + await cog._check_loop.coro(cog) + channel = named(guild.channels, "addons") + intro_msg, general_msg, pvp_msg = channel.messages + + api.list_addons.return_value = [ + _addon(name="Alpha", category=AddonCategory.GENERAL, summary="New summary!"), + beta, + ] + await cog._check_loop.coro(cog) + + intro_msg.edit.assert_not_called() + general_msg.edit.assert_awaited_once() + pvp_msg.edit.assert_not_called() + assert "New summary!" in general_msg.embeds[0].description + + async def test_posts_never_ping(self, monkeypatch: pytest.MonkeyPatch) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + api = AsyncMock() + api.list_addons.return_value = [_addon(category=AddonCategory.RAID)] + cog = _make_cog(api=api, guild=guild) + + await cog._check_loop.coro(cog) + + channel = named(guild.channels, "addons") + none_mentions = discord.AllowedMentions.none().to_dict() + for call in channel.send.await_args_list: + assert call.kwargs["allowed_mentions"].to_dict() == none_mentions + + async def test_empty_addon_list_leaves_the_channel_untouched(self, monkeypatch: pytest.MonkeyPatch) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + api = AsyncMock() + api.list_addons.return_value = [_addon(category=AddonCategory.GENERAL)] + cog = _make_cog(api=api, guild=guild) + await cog._check_loop.coro(cog) + channel = named(guild.channels, "addons") + message_count = len(channel.messages) + channel.send.reset_mock() + + api.list_addons.return_value = [] + await cog._check_loop.coro(cog) + + channel.send.assert_not_called() + assert len(channel.messages) == message_count + + async def test_not_found_does_not_crash_the_loop_and_retries_next_tick( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + api = AsyncMock() + api.list_addons.side_effect = [NotFoundError(404, "not found"), [_addon(category=AddonCategory.GENERAL)]] + cog = _make_cog(api=api, guild=guild) + + await cog._check_loop.coro(cog) + assert find_text_channel(guild, "addons") is None + await cog._check_loop.coro(cog) + + assert api.list_addons.await_count == 2 + assert find_text_channel(guild, "addons") is not None + + async def test_api_error_does_not_crash_the_loop(self, monkeypatch: pytest.MonkeyPatch) -> None: + guild = sidequest_server() + monkeypatch.setattr(addons_channel, "_web_settings", lambda: _web_settings(guild.id)) + api = AsyncMock() + api.list_addons.side_effect = APIError(500, "boom") + cog = _make_cog(api=api, guild=guild) + + await cog._check_loop.coro(cog) # must not raise diff --git a/uv.lock b/uv.lock index f51db23..f635fa1 100644 --- a/uv.lock +++ b/uv.lock @@ -1248,7 +1248,7 @@ wheels = [ [[package]] name = "sidequest-api" version = "0.1.0" -source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=api&rev=9b37db6351643f218573abd223188cdf9dec2bbd#9b37db6351643f218573abd223188cdf9dec2bbd" } +source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=api&rev=ca6be8049dc9c29357b829588c5c7feb97aaa7f1#ca6be8049dc9c29357b829588c5c7feb97aaa7f1" } dependencies = [ { name = "advanced-alchemy", extra = ["uuid"] }, { name = "alembic" }, @@ -1297,7 +1297,7 @@ requires-dist = [ { name = "httpx", specifier = ">=0.28" }, { name = "pydantic", specifier = ">=2.14" }, { name = "pydantic-settings", specifier = ">=2.16" }, - { name = "sidequest-common", git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=9b37db6351643f218573abd223188cdf9dec2bbd" }, + { name = "sidequest-common", git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=ca6be8049dc9c29357b829588c5c7feb97aaa7f1" }, { name = "tenacity", specifier = ">=9.2" }, ] @@ -1311,13 +1311,13 @@ dev = [ { name = "pytest-socket", specifier = ">=0.7" }, { name = "respx", specifier = ">=0.23" }, { name = "ruff", specifier = ">=0.17" }, - { name = "sidequest-api", git = "https://github.com/SideQuest-Guild/website?subdirectory=api&rev=9b37db6351643f218573abd223188cdf9dec2bbd" }, + { name = "sidequest-api", git = "https://github.com/SideQuest-Guild/website?subdirectory=api&rev=ca6be8049dc9c29357b829588c5c7feb97aaa7f1" }, ] [[package]] name = "sidequest-common" version = "0.1.0" -source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=9b37db6351643f218573abd223188cdf9dec2bbd#9b37db6351643f218573abd223188cdf9dec2bbd" } +source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=ca6be8049dc9c29357b829588c5c7feb97aaa7f1#ca6be8049dc9c29357b829588c5c7feb97aaa7f1" } dependencies = [ { name = "advanced-alchemy" }, { name = "pydantic" },