diff --git a/README.md b/README.md index 20b9f7c..9c59301 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,17 @@ lives there. - **Crafters.** `/crafter [profession]` finds guild characters who know a recipe matching `query`, with their profession, skill and the matching recipes, including characters synced from Battle.net who never ran the addon; `profession` autocompletes from the guild's known professions. -- **Achievements and recipes.** `/achievement ` looks up a WoW: Forever achievement and shows its points, - description and category, with autocomplete over the full catalog. `/recipe ` looks up a recipe (reusing - `/crafter`'s search) and shows its reagents, crafted item and the guild crafters who know it. `/compare - ` is `/who` for two characters side by side: level, class, item level with the lead - highlighted, PvP stats, and a per-slot gear comparison table; autocompletes the same way `/who` does. +- **Achievements, quests and recipes.** `/achievement ` looks up a WoW: Forever achievement and shows its + points, description and category, with autocomplete over the full catalog. `/quest ` looks up a quest and + shows its area, category, level range, rewards, and its place in its chain (earlier quests, the quest itself in + bold, and what it leads to), plus any requirements and quests it excludes; autocompletes as you type. `/recipe + ` looks up a recipe (reusing `/crafter`'s search) and shows its reagents, crafted item and the guild + crafters who know it. `/compare ` is `/who` for two characters side by side: level, + class, item level with the lead highlighted, PvP stats, and a per-slot gear comparison table; autocompletes the + same way `/who` does. `/beast [family]` looks up a tameable beast for hunters and shows its family and a + portrait, with autocomplete over the beast catalog and, for `family`, over its families; the catalog takes a + while to build on the API's first request of either, so autocomplete may show no suggestions for a few seconds + after a deploy. - **Auction prices.** `/price ` shows an item's lowest current auction price, where it's cheapest, how many are listed, and its 14-day price range. `/watch ` (e.g. `1g20s`, `35s`, `80c`) DMs you when that item's price drops to or below your target; `/unwatch ` removes a watch and `/watches` lists yours. Watches diff --git a/pyproject.toml b/pyproject.toml index edd0d71..fe6cad9 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 = "d6ee131b188062fd429222cb01a588daee1243c1", subdirectory = "packages/sidequest-common" } -sidequest-api = { git = "https://github.com/SideQuest-Guild/website", rev = "d6ee131b188062fd429222cb01a588daee1243c1", subdirectory = "api" } +sidequest-common = { git = "https://github.com/SideQuest-Guild/website", rev = "59a86f9575d409ec76f9d24766eeb1acd39dba52", subdirectory = "packages/sidequest-common" } +sidequest-api = { git = "https://github.com/SideQuest-Guild/website", rev = "59a86f9575d409ec76f9d24766eeb1acd39dba52", subdirectory = "api" } [tool.pytest.ini_options] asyncio_mode = "auto" diff --git a/pyrefly-baseline.json b/pyrefly-baseline.json index c920261..bb6e48c 100644 --- a/pyrefly-baseline.json +++ b/pyrefly-baseline.json @@ -7,6 +7,13 @@ "concise_description": "Class member `_AchievementMatchSelect.callback` overrides parent class `Select` in an inconsistent manner", "severity": "error" }, + { + "column": 15, + "path": "src/sidequest_bot/plugins/beasts.py", + "name": "bad-override", + "concise_description": "Class member `_BeastMatchSelect.callback` overrides parent class `Select` in an inconsistent manner", + "severity": "error" + }, { "column": 15, "path": "src/sidequest_bot/plugins/event_sync.py", @@ -168,6 +175,13 @@ "concise_description": "Argument `AppCommand | AutoModRule | Emoji | Guild | GuildChannel | GuildSticker | Invite | Member | Object | PartialIntegration | Role | ScheduledEvent | StageInstance | Thread | User | Webhook | None` is not assignable to parameter `user` with type `Member | User` in function `sidequest_bot.lib.embeds.user_line`", "severity": "error" }, + { + "column": 15, + "path": "src/sidequest_bot/plugins/quests.py", + "name": "bad-override", + "concise_description": "Class member `_QuestMatchSelect.callback` overrides parent class `Select` in an inconsistent manner", + "severity": "error" + }, { "column": 15, "path": "src/sidequest_bot/plugins/role_menus.py", diff --git a/src/sidequest_bot/api_client.py b/src/sidequest_bot/api_client.py index 1a84b4c..0d204b6 100644 --- a/src/sidequest_bot/api_client.py +++ b/src/sidequest_bot/api_client.py @@ -20,6 +20,8 @@ AwayNowReport, BadgeAck, BadgeSyncReport, + BeastFamilySchema, + BeastSchema, ConfirmByDiscordRequest, CouncilLogEntry, CouncilLogKind, @@ -59,6 +61,8 @@ ModCaseUpdate, PendingAnnouncement, PendingAnnouncementsPage, + QuestSchema, + QuestSearchResult, RankSchema, RecipeDetail, Recruiting, @@ -102,6 +106,9 @@ _XP_GRANTS = TypeAdapter(list[XPGrantResult]) _ADDONS = TypeAdapter(list[AddonSchema]) _ACHIEVEMENT_CATEGORIES = TypeAdapter(list[AchievementCategoryTree]) +_QUEST_SEARCH_RESULTS = TypeAdapter(list[QuestSearchResult]) +_BEASTS = TypeAdapter(list[BeastSchema]) +_BEAST_FAMILIES = TypeAdapter(list[BeastFamilySchema]) class ItemSummary(BaseModel): @@ -1021,6 +1028,63 @@ async def get_achievement(self, achievement_id: int) -> AchievementSchema: data = await self._request("GET", f"/api/achievements/{achievement_id}") return _parse(AchievementSchema.model_validate, data) + # --- Quests + + async def search_quests(self, query: str, *, limit: int = 10) -> list[QuestSearchResult]: + """Quests with ``query`` in their title, case-insensitive, best matches first (public ``/api/quests/search``). + + 503 if Battle.net isn't configured or didn't answer. + """ + data = await self._request("GET", "/api/quests/search", params={"q": query, "limit": limit}) + return _parse(_QUEST_SEARCH_RESULTS.validate_python, data) + + async def get_quest(self, quest_id: int) -> QuestSchema: + """One quest by its game ID (the public ``/api/quests/{id}`` GET). + + Raises ``NotFoundError`` for an unknown quest, or ``APIError`` (status 503) if Battle.net isn't configured + or didn't answer. + """ + data = await self._request("GET", f"/api/quests/{quest_id}") + return _parse(QuestSchema.model_validate, data) + + # --- Beasts + + async def search_beasts( + self, query: str | None = None, *, family_id: int | None = None, limit: int | None = None + ) -> list[BeastSchema]: + """Tameable beasts matching ``query`` (a substring, prefix match sorting first), sorted by name. + + The public ``/api/beasts`` GET. The first call per API process builds the whole catalog from Battle.net + media lookups and can take 10-20 seconds; callers on a tight budget (autocomplete) should apply their own + timeout. 503 if Battle.net isn't configured or didn't answer. + """ + params: dict[str, Any] = {} + if query is not None: + params["q"] = query + if family_id is not None: + params["family_id"] = family_id + if limit is not None: + params["limit"] = limit + data = await self._request("GET", "/api/beasts", params=params) + return _parse(_BEASTS.validate_python, data) + + async def get_beast(self, creature_id: int) -> BeastSchema: + """One tameable beast by its Battle.net creature id (the public ``/api/beasts/{id}`` GET). + + Raises ``NotFoundError`` if that creature isn't a tameable beast, or ``APIError`` (status 503) if + Battle.net isn't configured or didn't answer. + """ + data = await self._request("GET", f"/api/beasts/{creature_id}") + return _parse(BeastSchema.model_validate, data) + + async def list_beast_families(self) -> list[BeastFamilySchema]: + """Every beast family among tameable beasts, with its count, sorted by name (public ``/api/beasts/families``). + + 503 if Battle.net isn't configured or didn't answer. + """ + data = await self._request("GET", "/api/beasts/families") + return _parse(_BEAST_FAMILIES.validate_python, data) + # --- Recipes async def get_recipe(self, recipe_id: int) -> RecipeDetail: diff --git a/src/sidequest_bot/plugins/beasts.py b/src/sidequest_bot/plugins/beasts.py new file mode 100644 index 0000000..72cdbcf --- /dev/null +++ b/src/sidequest_bot/plugins/beasts.py @@ -0,0 +1,206 @@ +"""Beast lookup: ``/beast `` shows a tameable WoW: Forever beast's family and portrait, for hunters. + +The website builds its whole tameable-beast catalog (``~800`` Battle.net media lookups) on the first ``/api/beasts`` +call per API process, which can take 10-20 seconds — far past Discord's ~3 second autocomplete budget. Both +autocomplete callbacks below apply their own short timeout and fall back to no suggestions rather than erroring or +stalling; the ``/beast`` command itself, which has no such budget, waits out a slow first call normally. +""" + +import asyncio +import logging +from http import HTTPStatus +from typing import TYPE_CHECKING, cast + +import discord +from discord import app_commands +from discord.ext import commands + +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, link_button, link_view, make_embed, truncate + +if TYPE_CHECKING: + from collections.abc import Sequence + + from sidequest_common.schemas import BeastSchema + +logger = logging.getLogger(__name__) + +BEAST_PAGE_URL = "https://sidequest-guild.com/beasts/" +BEAST_WOWHEAD_URL = "https://www.wowhead.com/forever/npc={creature_id}" +MAX_AUTOCOMPLETE_RESULTS = 25 +MAX_OTHER_MATCHES = 5 +AUTOCOMPLETE_TIMEOUT = 2.5 +"""Seconds an autocomplete callback waits before giving up, safely inside Discord's ~3 second budget.""" +NOT_FOUND_HINT = "Try a shorter word, or pick a suggestion as you type." +UNAVAILABLE_MESSAGE = "Beast lookup isn't available right now; try again shortly." + + +def autocomplete_label(beast: BeastSchema) -> str: + """``name (family)``, or just the name if the beast has no family.""" + return f"{beast.name} ({beast.family})" if beast.family else beast.name + + +def match_option(match: BeastSchema) -> discord.SelectOption: + """One search result as a select option, with its family as the description.""" + return discord.SelectOption( + label=truncate(match.name, 100), + value=str(match.id), + description=truncate(match.family, 100) if match.family else None, + ) + + +def build_beast_embed(beast: BeastSchema) -> discord.Embed: + """The beast's name, family and portrait (no per-beast site page exists to link as the embed's URL).""" + embed = make_embed(title=beast.name, color=Colors.GREEN, timestamp=False) + if beast.family: + embed.add_field(name="Family", value=beast.family) + embed.add_field(name="Tameable by hunters", value="Yes") + if beast.image_url: + embed.set_image(url=beast.image_url) + return embed + + +def beast_link_buttons(creature_id: int) -> list[discord.ui.Button]: + """Beasts page (the same URL for every beast; the page has no per-beast deep link) + Wowhead link buttons.""" + return [ + link_button("Beasts page", BEAST_PAGE_URL), + link_button("Wowhead", BEAST_WOWHEAD_URL.format(creature_id=creature_id)), + ] + + +def beast_link_view(creature_id: int) -> discord.ui.View: + """A view holding just the beast's link buttons, for replies with no other matches to offer.""" + return link_view(*beast_link_buttons(creature_id)) + + +async def _autocomplete_beast( + interaction: discord.Interaction[SideQuestBot], current: str +) -> list[app_commands.Choice[str]]: + """Up to 25 beasts matching ``current``; empty if the catalog isn't built within :data:`AUTOCOMPLETE_TIMEOUT`.""" + try: + results = await asyncio.wait_for( + interaction.client.api.search_beasts(current.strip() or None, limit=MAX_AUTOCOMPLETE_RESULTS), + timeout=AUTOCOMPLETE_TIMEOUT, + ) + except APIError, TimeoutError: + return [] + return [app_commands.Choice(name=truncate(autocomplete_label(r), 100), value=str(r.id)) for r in results] + + +async def _autocomplete_beast_family( + interaction: discord.Interaction[SideQuestBot], current: str +) -> list[app_commands.Choice[str]]: + """Up to 25 beast families matching ``current``; empty if the catalog isn't built within the timeout.""" + try: + families = await asyncio.wait_for(interaction.client.api.list_beast_families(), timeout=AUTOCOMPLETE_TIMEOUT) + except APIError, TimeoutError: + return [] + current_fold = current.strip().casefold() + if current_fold: + families = [f for f in families if current_fold in f.name.casefold()] + return [ + app_commands.Choice(name=truncate(f"{f.name} ({f.count})", 100), value=str(f.id)) + for f in families[:MAX_AUTOCOMPLETE_RESULTS] + ] + + +async def _fetch_beast_embed(interaction: discord.Interaction[SideQuestBot], creature_id: int) -> discord.Embed | str: + """The beast's embed, or a plain-text error if the lookup failed.""" + try: + beast = await interaction.client.api.get_beast(creature_id) + except NotFoundError: + return "That's not a tameable beast." + except APIError as exc: + if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE: + return UNAVAILABLE_MESSAGE + logger.warning("Beast lookup failed for %s", creature_id, exc_info=True) + return "Couldn't look up that beast right now; try again shortly." + return build_beast_embed(beast) + + +class _BeastMatchSelect(discord.ui.Select["BeastMatchView"]): + """The select menu itself; its callback swaps the parent view's embed to the chosen beast.""" + + def __init__(self, matches: Sequence[BeastSchema]) -> None: + super().__init__(placeholder="Other matches", options=[match_option(match) for match in matches]) + + async def callback(self, interaction: discord.Interaction[SideQuestBot]) -> None: + creature_id = int(self.values[0]) + result = await _fetch_beast_embed(interaction, creature_id) + if isinstance(result, str): + await interaction.response.send_message(result, ephemeral=True) + return + view = cast("BeastMatchView", self.view) + view.set_beast(creature_id) + await interaction.response.edit_message(embed=result, view=view) + + +class BeastMatchView(discord.ui.View): + """Link buttons for the shown beast plus a select menu of up to :data:`MAX_OTHER_MATCHES` other matches. + + Picking another match swaps the shown embed and repoints the Wowhead button at it (the Beasts page button + never changes: the page has no per-beast deep link). + """ + + def __init__(self, creature_id: int, matches: Sequence[BeastSchema]) -> None: + super().__init__(timeout=180) + self._page_button, self._wowhead_button = beast_link_buttons(creature_id) + self._select = _BeastMatchSelect(matches) + self.add_item(self._select) + self.add_item(self._page_button) + self.add_item(self._wowhead_button) + + def set_beast(self, creature_id: int) -> None: + """Repoint the Wowhead button at ``creature_id``.""" + self._wowhead_button.url = BEAST_WOWHEAD_URL.format(creature_id=creature_id) + + +class BeastsCog(commands.Cog): + """``/beast`` lookup.""" + + def __init__(self, bot: SideQuestBot) -> None: + self.bot = bot + + @app_commands.command(name="beast", description="Look up a WoW: Forever tameable beast.") + @app_commands.describe(name="Beast name, or pick a suggestion as you type", family="Only beasts in this family") + @app_commands.autocomplete(name=_autocomplete_beast, family=_autocomplete_beast_family) + async def beast_command( + self, interaction: discord.Interaction[SideQuestBot], name: str, family: str | None = None + ) -> None: + """Resolve ``name`` to a creature id (from autocomplete, or a name search) and show its embed.""" + await interaction.response.defer() + if name.isdigit(): + result = await _fetch_beast_embed(interaction, int(name)) + if isinstance(result, str): + await interaction.followup.send(result, ephemeral=True) + return + await interaction.followup.send(embed=result, view=beast_link_view(int(name))) + return + family_id = int(family) if family is not None and family.isdigit() else None + try: + matches = await self.bot.api.search_beasts(name, family_id=family_id, limit=MAX_AUTOCOMPLETE_RESULTS) + except APIError as exc: + if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE: + await interaction.followup.send(UNAVAILABLE_MESSAGE, ephemeral=True) + return + logger.warning("Beast search failed for %r", name, exc_info=True) + await interaction.followup.send("Couldn't search beasts right now; try again shortly.", ephemeral=True) + return + if not matches: + await interaction.followup.send(f"No beasts found matching **{name}**. {NOT_FOUND_HINT}", ephemeral=True) + return + best, others = matches[0], matches[1 : 1 + MAX_OTHER_MATCHES] + result = await _fetch_beast_embed(interaction, best.id) + if isinstance(result, str): + await interaction.followup.send(result, ephemeral=True) + return + if others: + await interaction.followup.send(embed=result, view=BeastMatchView(best.id, others)) + else: + await interaction.followup.send(embed=result, view=beast_link_view(best.id)) + + +async def setup(bot: SideQuestBot) -> None: + """Register the cog.""" + await bot.add_cog(BeastsCog(bot)) diff --git a/src/sidequest_bot/plugins/quests.py b/src/sidequest_bot/plugins/quests.py new file mode 100644 index 0000000..6a9d672 --- /dev/null +++ b/src/sidequest_bot/plugins/quests.py @@ -0,0 +1,280 @@ +"""Quest lookup: ``/quest `` shows a WoW: Forever quest's rewards, requirements and where it sits in its chain. + +The website's quest search (``GET /api/quests/search``) matches any substring of a title, case-insensitive, so +autocomplete calls it live rather than flattening a catalog the way :mod:`sidequest_bot.plugins.achievements` does. +""" + +import logging +from http import HTTPStatus +from typing import TYPE_CHECKING, cast + +import discord +from discord import app_commands +from discord.ext import commands + +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, link_button, link_view, make_embed, truncate +from sidequest_common.schemas import QUEST_SEARCH_LIMIT, QUEST_SEARCH_MIN_LENGTH + +if TYPE_CHECKING: + from collections.abc import Sequence + + from sidequest_common.schemas import QuestRequirementRef, QuestRewardsSchema, QuestSchema, QuestSearchResult + +logger = logging.getLogger(__name__) + +QUEST_PAGE_URL = "https://sidequest-guild.com/quests/detail/?id={quest_id}" +QUEST_WOWHEAD_URL = "https://www.wowhead.com/forever/quest={quest_id}" +DESCRIPTION_LIMIT = 4096 +FIELD_LIMIT = 1024 +MAX_OTHER_MATCHES = 5 +MAX_CHAIN_ENTRIES = 6 +"""Chain entries shown on each side of the current quest before collapsing the rest into a "... N earlier" count.""" +NOT_FOUND_HINT = "Try a shorter word, or pick a suggestion as you type." +UNAVAILABLE_MESSAGE = "Quest lookup isn't available right now; try again shortly." + + +def format_money(copper: int) -> str: + """``copper`` as ``Ng Ss Cc``, matching how the website shows quest rewards.""" + gold, rest = divmod(copper, 10000) + silver, bronze = divmod(rest, 100) + return f"{gold}g {silver}s {bronze}c" + + +def _level_range(min_level: int | None, max_level: int | None) -> str | None: + """``min-max``, or just the one level known; ``None`` if neither is set.""" + if min_level is not None and max_level is not None and min_level != max_level: + return f"{min_level}-{max_level}" + level = min_level if min_level is not None else max_level + return str(level) if level is not None else None + + +def _reward_lines(rewards: QuestRewardsSchema) -> list[str]: + """XP, money, items and reputation a quest grants, one per line.""" + lines: list[str] = [] + if rewards.experience: + lines.append(f"{rewards.experience} XP") + if rewards.money: + lines.append(format_money(rewards.money)) + lines.extend(item.name for item in rewards.items) + lines.extend(f"{'+' if rep.value >= 0 else ''}{rep.value} {rep.faction}" for rep in rewards.reputations) + return lines + + +def _chain_text(quest: QuestSchema) -> str | None: + """``earlier quests → **this quest** → later quests``, collapsing overflow on either side.""" + if not quest.chain and not quest.leads_to: + return None + chain = quest.chain + segments: list[str] = [] + if len(chain) > MAX_CHAIN_ENTRIES: + segments.append(f"… {len(chain) - MAX_CHAIN_ENTRIES} earlier") + chain = chain[-MAX_CHAIN_ENTRIES:] + segments.extend(truncate(ref.title, 80) for ref in chain) + segments.append(f"**{truncate(quest.title, 80)}**") + leads_to = quest.leads_to[:MAX_CHAIN_ENTRIES] + segments.extend(truncate(ref.title, 80) for ref in leads_to) + if len(quest.leads_to) > MAX_CHAIN_ENTRIES: + segments.append(f"… {len(quest.leads_to) - MAX_CHAIN_ENTRIES} more") + return " → ".join(segments) + + +def _requires_text(requires: Sequence[QuestRequirementRef]) -> str | None: + """One line per requirement; quests sharing a ``group`` are joined with "or".""" + if not requires: + return None + lines: list[str] = [] + seen_groups: set[int] = set() + for req in requires: + if req.group is None: + lines.append(req.title) + elif req.group not in seen_groups: + seen_groups.add(req.group) + alts = [other.title for other in requires if other.group == req.group] + lines.append(" or ".join(alts)) + return "\n".join(lines) + + +def build_quest_embed(quest: QuestSchema) -> discord.Embed: + """The quest's area/category/type, level, rewards, chain and requirements, linking to its site page.""" + embed = make_embed( + title=quest.title, + description=truncate(quest.description, DESCRIPTION_LIMIT) if quest.description else None, + color=Colors.GOLD, + timestamp=False, + ) + embed.url = QUEST_PAGE_URL.format(quest_id=quest.id) + + meta = [part for part in (quest.area, quest.category, quest.type) if part] + if meta: + embed.add_field(name="Area / Category / Type", value=" • ".join(meta), inline=False) + + level = _level_range(quest.min_level, quest.max_level) + if level: + embed.add_field(name="Level", value=level) + + repeats = [ + label + for label, flag in (("Daily", quest.is_daily), ("Weekly", quest.is_weekly), ("Repeatable", quest.is_repeatable)) + if flag + ] + if repeats: + embed.add_field(name="Repeats", value=", ".join(dict.fromkeys(repeats))) + + reward_lines = _reward_lines(quest.rewards) + if reward_lines: + embed.add_field(name="Rewards", value=truncate("\n".join(reward_lines), FIELD_LIMIT), inline=False) + + chain_text = _chain_text(quest) + if chain_text: + embed.add_field(name="Chain", value=truncate(chain_text, FIELD_LIMIT), inline=False) + + requires_text = _requires_text(quest.requires) + if requires_text: + embed.add_field(name="Requires", value=truncate(requires_text, FIELD_LIMIT), inline=False) + + if quest.excludes: + excludes_text = "\n".join(ref.title for ref in quest.excludes) + embed.add_field(name="Not available if you've done", value=truncate(excludes_text, FIELD_LIMIT), inline=False) + + return embed + + +def quest_link_buttons(quest_id: int) -> list[discord.ui.Button]: + """Quest page + Wowhead link buttons for one quest.""" + return [ + link_button("Quest page", QUEST_PAGE_URL.format(quest_id=quest_id)), + link_button("Wowhead", QUEST_WOWHEAD_URL.format(quest_id=quest_id)), + ] + + +def quest_link_view(quest_id: int) -> discord.ui.View: + """A view holding just the quest's link buttons, for replies with no other matches to offer.""" + return link_view(*quest_link_buttons(quest_id)) + + +def match_option(match: QuestSearchResult) -> discord.SelectOption: + """One search result as a select option, with its area as the description.""" + return discord.SelectOption( + label=truncate(match.title, 100), + value=str(match.id), + description=truncate(match.area, 100) if match.area else None, + ) + + +def autocomplete_label(result: QuestSearchResult) -> str: + """``title (area)``, or just the title if the quest has no area.""" + return f"{result.title} ({result.area})" if result.area else result.title + + +async def _autocomplete_quest( + interaction: discord.Interaction[SideQuestBot], current: str +) -> list[app_commands.Choice[str]]: + """Up to 25 quests matching ``current``; empty for a query shorter than the API's minimum, or if it failed.""" + current = current.strip() + if len(current) < QUEST_SEARCH_MIN_LENGTH: + return [] + try: + results = await interaction.client.api.search_quests(current, limit=QUEST_SEARCH_LIMIT) + except APIError: + return [] + return [app_commands.Choice(name=truncate(autocomplete_label(r), 100), value=str(r.id)) for r in results] + + +async def _fetch_quest_embed(interaction: discord.Interaction[SideQuestBot], quest_id: int) -> discord.Embed | str: + """The quest's embed, or a plain-text error if the lookup failed.""" + try: + quest = await interaction.client.api.get_quest(quest_id) + except NotFoundError: + return "That quest is gone." + except APIError as exc: + if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE: + return UNAVAILABLE_MESSAGE + logger.warning("Quest lookup failed for %s", quest_id, exc_info=True) + return "Couldn't look up that quest right now; try again shortly." + return build_quest_embed(quest) + + +class _QuestMatchSelect(discord.ui.Select["QuestMatchView"]): + """The select menu itself; its callback swaps the parent view's embed to the chosen quest.""" + + def __init__(self, matches: Sequence[QuestSearchResult]) -> None: + super().__init__(placeholder="Other matches", options=[match_option(match) for match in matches]) + + async def callback(self, interaction: discord.Interaction[SideQuestBot]) -> None: + quest_id = int(self.values[0]) + result = await _fetch_quest_embed(interaction, quest_id) + if isinstance(result, str): + await interaction.response.send_message(result, ephemeral=True) + return + view = cast("QuestMatchView", self.view) + view.set_quest(quest_id) + await interaction.response.edit_message(embed=result, view=view) + + +class QuestMatchView(discord.ui.View): + """Link buttons for the shown quest plus a select menu of up to :data:`MAX_OTHER_MATCHES` other matches. + + Picking another match swaps the shown embed and repoints the link buttons at it. + """ + + def __init__(self, quest_id: int, matches: Sequence[QuestSearchResult]) -> None: + super().__init__(timeout=180) + self._page_button, self._wowhead_button = quest_link_buttons(quest_id) + self._select = _QuestMatchSelect(matches) + self.add_item(self._select) + self.add_item(self._page_button) + self.add_item(self._wowhead_button) + + def set_quest(self, quest_id: int) -> None: + """Repoint the link buttons at ``quest_id``.""" + self._page_button.url = QUEST_PAGE_URL.format(quest_id=quest_id) + self._wowhead_button.url = QUEST_WOWHEAD_URL.format(quest_id=quest_id) + + +class QuestsCog(commands.Cog): + """``/quest`` lookup.""" + + def __init__(self, bot: SideQuestBot) -> None: + self.bot = bot + + @app_commands.command(name="quest", description="Look up a WoW: Forever quest.") + @app_commands.describe(name="Quest name, or pick a suggestion as you type") + @app_commands.autocomplete(name=_autocomplete_quest) + async def quest_command(self, interaction: discord.Interaction[SideQuestBot], name: str) -> None: + """Resolve ``name`` to a quest id (from autocomplete, or a title search) and show its embed.""" + await interaction.response.defer() + if name.isdigit(): + result = await _fetch_quest_embed(interaction, int(name)) + if isinstance(result, str): + await interaction.followup.send(result, ephemeral=True) + return + await interaction.followup.send(embed=result, view=quest_link_view(int(name))) + return + try: + matches = await self.bot.api.search_quests(name, limit=QUEST_SEARCH_LIMIT) + except APIError as exc: + if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE: + await interaction.followup.send(UNAVAILABLE_MESSAGE, ephemeral=True) + return + logger.warning("Quest search failed for %r", name, exc_info=True) + await interaction.followup.send("Couldn't search quests right now; try again shortly.", ephemeral=True) + return + if not matches: + await interaction.followup.send(f"No quests found matching **{name}**. {NOT_FOUND_HINT}", ephemeral=True) + return + best, others = matches[0], matches[1 : 1 + MAX_OTHER_MATCHES] + result = await _fetch_quest_embed(interaction, best.id) + if isinstance(result, str): + await interaction.followup.send(result, ephemeral=True) + return + if others: + await interaction.followup.send(embed=result, view=QuestMatchView(best.id, others)) + else: + await interaction.followup.send(embed=result, view=quest_link_view(best.id)) + + +async def setup(bot: SideQuestBot) -> None: + """Register the cog.""" + await bot.add_cog(QuestsCog(bot)) diff --git a/tests/test_beasts.py b/tests/test_beasts.py new file mode 100644 index 0000000..9ded89c --- /dev/null +++ b/tests/test_beasts.py @@ -0,0 +1,391 @@ +"""Unit tests for the beasts plugin: the embed builder, autocomplete timeouts, ``/beast``, and the match select menu.""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import discord +import pytest + +from sidequest_bot.api_client import APIError, NotFoundError +from sidequest_bot.plugins.beasts import ( + NOT_FOUND_HINT, + UNAVAILABLE_MESSAGE, + BeastMatchView, + BeastsCog, + _autocomplete_beast, + _autocomplete_beast_family, + autocomplete_label, + beast_link_buttons, + beast_link_view, + build_beast_embed, + match_option, +) +from sidequest_common.schemas import BeastFamilySchema, BeastSchema + + +def _beast( + *, + beast_id: int = 1, + name: str = "Ashamane", + family_id: int | None = 10, + family: str | None = "Cat", + image_url: str | None = "https://render.worldofwarcraft.com/npcs/56/beast.jpg", + display_id: int | None = 99, +) -> BeastSchema: + return BeastSchema( + id=beast_id, name=name, family_id=family_id, family=family, image_url=image_url, display_id=display_id + ) + + +def _family(*, family_id: int = 10, name: str = "Cat", count: int = 5) -> BeastFamilySchema: + return BeastFamilySchema(id=family_id, name=name, count=count) + + +def _make_cog(*, api: object | None = None) -> BeastsCog: + cog = BeastsCog.__new__(BeastsCog) + cog.bot = SimpleNamespace(api=api or AsyncMock()) + return cog + + +def _make_interaction(*, api: object | None = None) -> Mock: + interaction = Mock(spec=discord.Interaction) + interaction.response = Mock() + interaction.response.defer = AsyncMock() + interaction.response.send_message = AsyncMock() + interaction.response.edit_message = AsyncMock() + interaction.followup = Mock() + interaction.followup.send = AsyncMock() + interaction.client = SimpleNamespace(api=api or AsyncMock()) + return interaction + + +class TestBuildBeastEmbed: + def test_sets_title_and_color(self) -> None: + embed = build_beast_embed(_beast(name="Ashamane")) + assert embed.title == "Ashamane" + + def test_has_no_url(self) -> None: + """No per-beast site page exists, so the embed shouldn't claim one.""" + embed = build_beast_embed(_beast()) + assert embed.url is None + + def test_family_field(self) -> None: + embed = build_beast_embed(_beast(family="Cat")) + fields = {field.name: field.value for field in embed.fields} + assert fields["Family"] == "Cat" + + def test_omits_family_field_when_unset(self) -> None: + embed = build_beast_embed(_beast(family=None)) + assert "Family" not in [field.name for field in embed.fields] + + def test_tameable_field_always_present(self) -> None: + embed = build_beast_embed(_beast()) + fields = {field.name: field.value for field in embed.fields} + assert fields["Tameable by hunters"] == "Yes" + + def test_sets_image_when_present(self) -> None: + embed = build_beast_embed(_beast(image_url="https://example.test/beast.jpg")) + assert embed.image.url == "https://example.test/beast.jpg" + + def test_no_image_leaves_image_unset(self) -> None: + embed = build_beast_embed(_beast(image_url=None)) + assert embed.image.url is None + + +class TestBeastLinkButtons: + def test_page_and_wowhead_buttons(self) -> None: + page, wowhead = beast_link_buttons(42) + assert page.label == "Beasts page" + assert page.url == "https://sidequest-guild.com/beasts/" + assert wowhead.label == "Wowhead" + assert wowhead.url == "https://www.wowhead.com/forever/npc=42" + + def test_page_url_is_the_same_for_every_beast(self) -> None: + page_a, _ = beast_link_buttons(1) + page_b, _ = beast_link_buttons(2) + assert page_a.url == page_b.url + + +class TestBeastLinkView: + def test_holds_both_link_buttons(self) -> None: + view = beast_link_view(42) + labels = [button.label for button in view.children] + assert labels == ["Beasts page", "Wowhead"] + + +class TestMatchOption: + def test_label_value_and_description(self) -> None: + option = match_option(_beast(beast_id=3, name="Explorer", family="Cat")) + assert option.label == "Explorer" + assert option.value == "3" + assert option.description == "Cat" + + def test_no_family_leaves_description_unset(self) -> None: + option = match_option(_beast(family=None)) + assert option.description is None + + +class TestAutocompleteLabel: + def test_includes_family_when_present(self) -> None: + assert autocomplete_label(_beast(name="Ashamane", family="Cat")) == "Ashamane (Cat)" + + def test_falls_back_to_name_without_family(self) -> None: + assert autocomplete_label(_beast(name="Ashamane", family=None)) == "Ashamane" + + +class TestAutocompleteBeast: + async def test_returns_choices_from_search(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [_beast(beast_id=1, name="Ashamane", family="Cat")] + interaction = _make_interaction(api=api) + + choices = await _autocomplete_beast(interaction, "asha") + + assert [choice.value for choice in choices] == ["1"] + assert choices[0].name == "Ashamane (Cat)" + api.search_beasts.assert_awaited_once_with("asha", limit=25) + + async def test_empty_current_passes_no_query(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [] + interaction = _make_interaction(api=api) + + await _autocomplete_beast(interaction, "") + + api.search_beasts.assert_awaited_once_with(None, limit=25) + + async def test_api_error_returns_empty(self) -> None: + api = AsyncMock() + api.search_beasts.side_effect = APIError(503, "down") + interaction = _make_interaction(api=api) + + assert await _autocomplete_beast(interaction, "asha") == [] + + async def test_slow_catalog_build_times_out_to_empty(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sidequest_bot.plugins.beasts.AUTOCOMPLETE_TIMEOUT", 0.01) + + async def _slow(*_args: object, **_kwargs: object) -> list[BeastSchema]: + await asyncio.sleep(1) + return [_beast()] + + api = AsyncMock() + api.search_beasts.side_effect = _slow + interaction = _make_interaction(api=api) + + choices = await _autocomplete_beast(interaction, "asha") + + assert choices == [] + + +class TestAutocompleteBeastFamily: + async def test_filters_by_substring(self) -> None: + api = AsyncMock() + api.list_beast_families.return_value = [_family(family_id=1, name="Cat"), _family(family_id=2, name="Bear")] + interaction = _make_interaction(api=api) + + choices = await _autocomplete_beast_family(interaction, "cat") + + assert [choice.value for choice in choices] == ["1"] + assert choices[0].name == "Cat (5)" + + async def test_empty_current_returns_everything(self) -> None: + api = AsyncMock() + api.list_beast_families.return_value = [_family(family_id=1, name="Cat")] + interaction = _make_interaction(api=api) + + choices = await _autocomplete_beast_family(interaction, "") + + assert len(choices) == 1 + + async def test_api_error_returns_empty(self) -> None: + api = AsyncMock() + api.list_beast_families.side_effect = APIError(503, "down") + interaction = _make_interaction(api=api) + + assert await _autocomplete_beast_family(interaction, "cat") == [] + + async def test_slow_catalog_build_times_out_to_empty(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sidequest_bot.plugins.beasts.AUTOCOMPLETE_TIMEOUT", 0.01) + + async def _slow() -> list[BeastFamilySchema]: + await asyncio.sleep(1) + return [_family()] + + api = AsyncMock() + api.list_beast_families.side_effect = _slow + interaction = _make_interaction(api=api) + + choices = await _autocomplete_beast_family(interaction, "") + + assert choices == [] + + +class TestBeastCommand: + async def test_digit_name_fetches_directly(self) -> None: + api = AsyncMock() + api.get_beast.return_value = _beast(beast_id=42, name="Ashamane") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "42") + + api.get_beast.assert_awaited_once_with(42) + kwargs = interaction.followup.send.await_args.kwargs + assert kwargs["embed"].title == "Ashamane" + labels = [button.label for button in kwargs["view"].children] + assert labels == ["Beasts page", "Wowhead"] + + async def test_digit_name_not_found(self) -> None: + api = AsyncMock() + api.get_beast.side_effect = NotFoundError(404, "not tameable") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "42") + + interaction.followup.send.assert_awaited_once_with("That's not a tameable beast.", ephemeral=True) + + async def test_digit_name_unavailable(self) -> None: + api = AsyncMock() + api.get_beast.side_effect = APIError(503, "down") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "42") + + interaction.followup.send.assert_awaited_once_with(UNAVAILABLE_MESSAGE, ephemeral=True) + + async def test_name_search_unavailable(self) -> None: + api = AsyncMock() + api.search_beasts.side_effect = APIError(503, "down") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "ashamane") + + interaction.followup.send.assert_awaited_once_with(UNAVAILABLE_MESSAGE, ephemeral=True) + + async def test_name_search_generic_error(self) -> None: + api = AsyncMock() + api.search_beasts.side_effect = APIError(500, "boom") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "ashamane") + + message = interaction.followup.send.await_args.args[0] + assert "try again shortly" in message + + async def test_no_matches_sends_hint(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [] + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "zzznotfound") + + message = interaction.followup.send.await_args.args[0] + assert NOT_FOUND_HINT in message + + async def test_single_match_sends_link_buttons_without_select(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [_beast(beast_id=7, name="Ashamane")] + api.get_beast.return_value = _beast(beast_id=7, name="Ashamane") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "ashamane") + + kwargs = interaction.followup.send.await_args.kwargs + assert kwargs["embed"].title == "Ashamane" + labels = [button.label for button in kwargs["view"].children] + assert labels == ["Beasts page", "Wowhead"] + + async def test_multiple_matches_offers_select_of_others(self) -> None: + api = AsyncMock() + matches = [_beast(beast_id=i, name=f"Beast {i}") for i in range(1, 8)] + api.search_beasts.return_value = matches + api.get_beast.return_value = _beast(beast_id=1, name="Beast 1") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "beast") + + kwargs = interaction.followup.send.await_args.kwargs + view = kwargs["view"] + assert isinstance(view, BeastMatchView) + assert [option.value for option in view._select.options] == ["2", "3", "4", "5", "6"] + + async def test_beast_gone_after_search_reports_not_tameable(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [_beast(beast_id=1, name="Ashamane")] + api.get_beast.side_effect = NotFoundError(404, "not tameable") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "ashamane") + + interaction.followup.send.assert_awaited_once_with("That's not a tameable beast.", ephemeral=True) + + async def test_digit_family_filters_the_search(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [_beast(beast_id=1, name="Ashamane")] + api.get_beast.return_value = _beast(beast_id=1, name="Ashamane") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "ashamane", "10") + + api.search_beasts.assert_awaited_once_with("ashamane", family_id=10, limit=25) + + async def test_non_digit_family_is_ignored(self) -> None: + api = AsyncMock() + api.search_beasts.return_value = [_beast(beast_id=1, name="Ashamane")] + api.get_beast.return_value = _beast(beast_id=1, name="Ashamane") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await BeastsCog.beast_command.callback(cog, interaction, "ashamane", "not-an-id") + + api.search_beasts.assert_awaited_once_with("ashamane", family_id=None, limit=25) + + +class TestBeastMatchView: + def test_options_use_match_names_and_ids(self) -> None: + view = BeastMatchView(1, [_beast(beast_id=1, name="A"), _beast(beast_id=2, name="B")]) + assert [option.label for option in view._select.options] == ["A", "B"] + assert [option.value for option in view._select.options] == ["1", "2"] + + def test_link_buttons_point_at_initial_beast(self) -> None: + view = BeastMatchView(1, [_beast(beast_id=2, name="B")]) + assert view._page_button.url == "https://sidequest-guild.com/beasts/" + assert view._wowhead_button.url == "https://www.wowhead.com/forever/npc=1" + + async def test_select_callback_edits_message_with_chosen_beast(self) -> None: + api = AsyncMock() + api.get_beast.return_value = _beast(beast_id=2, name="B") + view = BeastMatchView(1, [_beast(beast_id=2, name="B")]) + view._select._values = ["2"] + interaction = _make_interaction(api=api) + + await view._select.callback(interaction) + + interaction.response.edit_message.assert_awaited_once() + kwargs = interaction.response.edit_message.await_args.kwargs + assert kwargs["embed"].title == "B" + assert kwargs["view"] is view + assert view._page_button.url == "https://sidequest-guild.com/beasts/" + assert view._wowhead_button.url == "https://www.wowhead.com/forever/npc=2" + + async def test_select_callback_reports_error_ephemerally(self) -> None: + api = AsyncMock() + api.get_beast.side_effect = NotFoundError(404, "not tameable") + view = BeastMatchView(1, [_beast(beast_id=2)]) + view._select._values = ["2"] + interaction = _make_interaction(api=api) + + await view._select.callback(interaction) + + interaction.response.send_message.assert_awaited_once_with("That's not a tameable beast.", ephemeral=True) + interaction.response.edit_message.assert_not_awaited() diff --git a/tests/test_quests.py b/tests/test_quests.py new file mode 100644 index 0000000..1a59a62 --- /dev/null +++ b/tests/test_quests.py @@ -0,0 +1,429 @@ +"""Unit tests for the quests plugin: the embed builder, autocomplete, ``/quest``, and the match select menu.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import discord + +from sidequest_bot.api_client import APIError, NotFoundError +from sidequest_bot.plugins.quests import ( + NOT_FOUND_HINT, + UNAVAILABLE_MESSAGE, + QuestMatchView, + QuestsCog, + _autocomplete_quest, + autocomplete_label, + build_quest_embed, + format_money, + match_option, + quest_link_buttons, + quest_link_view, +) +from sidequest_common.schemas import ( + QuestRef, + QuestReputationReward, + QuestRequirementRef, + QuestRewardItem, + QuestRewardsSchema, + QuestSchema, + QuestSearchResult, +) + + +def _search_result( + *, quest_id: int = 1, title: str = "Call of Water", area: str | None = "Durotar" +) -> QuestSearchResult: + return QuestSearchResult(id=quest_id, title=title, area=area) + + +def _quest( + *, + quest_id: int = 1, + title: str = "Call of Water", + description: str | None = "Bring water to the elder.", + area: str | None = "Durotar", + category: str | None = None, + type: str | None = None, # noqa: A002 - mirrors the schema's field name + min_level: int | None = 5, + max_level: int | None = 5, + is_repeatable: bool = False, + is_daily: bool = False, + is_weekly: bool = False, + rewards: QuestRewardsSchema | None = None, + requires: list[QuestRequirementRef] | None = None, + excludes: list[QuestRef] | None = None, + chain: list[QuestRef] | None = None, + leads_to: list[QuestRef] | None = None, +) -> QuestSchema: + return QuestSchema( + id=quest_id, + title=title, + description=description, + area=area, + category=category, + type=type, + min_level=min_level, + max_level=max_level, + is_repeatable=is_repeatable, + is_daily=is_daily, + is_weekly=is_weekly, + rewards=rewards if rewards is not None else QuestRewardsSchema(), + requires=requires or [], + excludes=excludes or [], + chain=chain or [], + leads_to=leads_to or [], + ) + + +def _make_cog(*, api: object | None = None) -> QuestsCog: + cog = QuestsCog.__new__(QuestsCog) + cog.bot = SimpleNamespace(api=api or AsyncMock()) + return cog + + +def _make_interaction(*, api: object | None = None) -> Mock: + interaction = Mock(spec=discord.Interaction) + interaction.response = Mock() + interaction.response.defer = AsyncMock() + interaction.response.send_message = AsyncMock() + interaction.response.edit_message = AsyncMock() + interaction.followup = Mock() + interaction.followup.send = AsyncMock() + interaction.client = SimpleNamespace(api=api or AsyncMock()) + return interaction + + +class TestFormatMoney: + def test_splits_into_gold_silver_copper(self) -> None: + assert format_money(123456) == "12g 34s 56c" + + def test_zero_is_all_zeros(self) -> None: + assert format_money(0) == "0g 0s 0c" + + +class TestBuildQuestEmbed: + def test_sets_title_color_and_url(self) -> None: + embed = build_quest_embed(_quest(quest_id=42, title="Explorer's Path")) + assert embed.title == "Explorer's Path" + assert embed.url == "https://sidequest-guild.com/quests/detail/?id=42" + + def test_description_is_set(self) -> None: + embed = build_quest_embed(_quest(description="Go forth.")) + assert embed.description == "Go forth." + + def test_no_description_leaves_it_unset(self) -> None: + embed = build_quest_embed(_quest(description=None)) + assert embed.description is None + + def test_area_category_type_field(self) -> None: + embed = build_quest_embed(_quest(area="Durotar", category="Shaman", type="Class")) + fields = {field.name: field.value for field in embed.fields} + assert fields["Area / Category / Type"] == "Durotar • Shaman • Class" + + def test_omits_area_field_when_all_unset(self) -> None: + embed = build_quest_embed(_quest(area=None, category=None, type=None)) + assert "Area / Category / Type" not in [field.name for field in embed.fields] + + def test_level_range_shown_for_differing_levels(self) -> None: + embed = build_quest_embed(_quest(min_level=10, max_level=15)) + fields = {field.name: field.value for field in embed.fields} + assert fields["Level"] == "10-15" + + def test_single_level_shown_without_range(self) -> None: + embed = build_quest_embed(_quest(min_level=10, max_level=10)) + fields = {field.name: field.value for field in embed.fields} + assert fields["Level"] == "10" + + def test_omits_level_when_both_unset(self) -> None: + embed = build_quest_embed(_quest(min_level=None, max_level=None)) + assert "Level" not in [field.name for field in embed.fields] + + def test_daily_and_weekly_flags(self) -> None: + embed = build_quest_embed(_quest(is_daily=True, is_weekly=True)) + fields = {field.name: field.value for field in embed.fields} + assert fields["Repeats"] == "Daily, Weekly" + + def test_omits_repeats_when_none_set(self) -> None: + embed = build_quest_embed(_quest()) + assert "Repeats" not in [field.name for field in embed.fields] + + def test_rewards_field_includes_xp_money_items_and_reputation(self) -> None: + rewards = QuestRewardsSchema( + experience=500, + money=123456, + items=[QuestRewardItem(item_id=1, name="Worn Blade")], + reputations=[QuestReputationReward(faction="Darkspear Trolls", value=10)], + ) + embed = build_quest_embed(_quest(rewards=rewards)) + fields = {field.name: field.value for field in embed.fields} + assert "500 XP" in fields["Rewards"] + assert "12g 34s 56c" in fields["Rewards"] + assert "Worn Blade" in fields["Rewards"] + assert "+10 Darkspear Trolls" in fields["Rewards"] + + def test_omits_rewards_field_when_empty(self) -> None: + embed = build_quest_embed(_quest(rewards=QuestRewardsSchema())) + assert "Rewards" not in [field.name for field in embed.fields] + + def test_chain_field_renders_this_quest_in_bold_between_chain_and_leads_to(self) -> None: + quest = _quest( + title="Call of Water 3", + chain=[QuestRef(id=1, title="Call of Water 1"), QuestRef(id=2, title="Call of Water 2")], + leads_to=[QuestRef(id=4, title="Call of Water 4")], + ) + embed = build_quest_embed(quest) + fields = {field.name: field.value for field in embed.fields} + assert fields["Chain"] == "Call of Water 1 → Call of Water 2 → **Call of Water 3** → Call of Water 4" + + def test_chain_field_collapses_earlier_overflow(self) -> None: + chain = [QuestRef(id=i, title=f"Step {i}") for i in range(1, 10)] + embed = build_quest_embed(_quest(title="Step 10", chain=chain)) + fields = {field.name: field.value for field in embed.fields} + assert fields["Chain"].startswith("… 3 earlier → ") + assert "Step 1 " not in fields["Chain"] + assert fields["Chain"].endswith("**Step 10**") + + def test_chain_field_collapses_leads_to_overflow(self) -> None: + leads_to = [QuestRef(id=i, title=f"Follow {i}") for i in range(1, 10)] + embed = build_quest_embed(_quest(title="Root", leads_to=leads_to)) + fields = {field.name: field.value for field in embed.fields} + assert fields["Chain"].endswith("… 3 more") + + def test_omits_chain_field_when_no_chain_or_leads_to(self) -> None: + embed = build_quest_embed(_quest()) + assert "Chain" not in [field.name for field in embed.fields] + + def test_requires_field_groups_one_of_alternatives(self) -> None: + requires = [ + QuestRequirementRef(id=1, title="Quest A", group=None), + QuestRequirementRef(id=2, title="Quest B", group=1), + QuestRequirementRef(id=3, title="Quest C", group=1), + ] + embed = build_quest_embed(_quest(requires=requires)) + fields = {field.name: field.value for field in embed.fields} + assert fields["Requires"] == "Quest A\nQuest B or Quest C" + + def test_omits_requires_field_when_empty(self) -> None: + embed = build_quest_embed(_quest()) + assert "Requires" not in [field.name for field in embed.fields] + + def test_excludes_field_lists_titles(self) -> None: + embed = build_quest_embed(_quest(excludes=[QuestRef(id=9, title="Opposing Path")])) + fields = {field.name: field.value for field in embed.fields} + assert fields["Not available if you've done"] == "Opposing Path" + + def test_omits_excludes_field_when_empty(self) -> None: + embed = build_quest_embed(_quest()) + assert "Not available if you've done" not in [field.name for field in embed.fields] + + +class TestQuestLinkButtons: + def test_page_and_wowhead_buttons(self) -> None: + page, wowhead = quest_link_buttons(42) + assert page.label == "Quest page" + assert page.url == "https://sidequest-guild.com/quests/detail/?id=42" + assert wowhead.label == "Wowhead" + assert wowhead.url == "https://www.wowhead.com/forever/quest=42" + + +class TestQuestLinkView: + def test_holds_both_link_buttons(self) -> None: + view = quest_link_view(42) + labels = [button.label for button in view.children] + assert labels == ["Quest page", "Wowhead"] + + +class TestMatchOption: + def test_label_value_and_description(self) -> None: + option = match_option(_search_result(quest_id=3, title="Explorer", area="Durotar")) + assert option.label == "Explorer" + assert option.value == "3" + assert option.description == "Durotar" + + def test_no_area_leaves_description_unset(self) -> None: + option = match_option(_search_result(area=None)) + assert option.description is None + + +class TestAutocompleteLabel: + def test_includes_area_when_present(self) -> None: + assert autocomplete_label(_search_result(title="Explorer", area="Durotar")) == "Explorer (Durotar)" + + def test_falls_back_to_title_without_area(self) -> None: + assert autocomplete_label(_search_result(title="Explorer", area=None)) == "Explorer" + + +class TestAutocompleteQuest: + async def test_short_query_returns_nothing_without_calling_the_api(self) -> None: + api = AsyncMock() + interaction = _make_interaction(api=api) + + choices = await _autocomplete_quest(interaction, "a") + + assert choices == [] + api.search_quests.assert_not_called() + + async def test_returns_choices_from_search(self) -> None: + api = AsyncMock() + api.search_quests.return_value = [_search_result(quest_id=1, title="Call of Water", area="Durotar")] + interaction = _make_interaction(api=api) + + choices = await _autocomplete_quest(interaction, "call") + + assert [choice.value for choice in choices] == ["1"] + assert choices[0].name == "Call of Water (Durotar)" + + async def test_api_error_returns_empty(self) -> None: + api = AsyncMock() + api.search_quests.side_effect = APIError(503, "down") + interaction = _make_interaction(api=api) + + assert await _autocomplete_quest(interaction, "call") == [] + + +class TestQuestCommand: + async def test_digit_name_fetches_directly(self) -> None: + api = AsyncMock() + api.get_quest.return_value = _quest(quest_id=42, title="Explorer's Path") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "42") + + api.get_quest.assert_awaited_once_with(42) + kwargs = interaction.followup.send.await_args.kwargs + assert kwargs["embed"].title == "Explorer's Path" + labels = [button.label for button in kwargs["view"].children] + assert labels == ["Quest page", "Wowhead"] + + async def test_digit_name_not_found(self) -> None: + api = AsyncMock() + api.get_quest.side_effect = NotFoundError(404, "gone") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "42") + + interaction.followup.send.assert_awaited_once_with("That quest is gone.", ephemeral=True) + + async def test_digit_name_unavailable(self) -> None: + api = AsyncMock() + api.get_quest.side_effect = APIError(503, "down") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "42") + + interaction.followup.send.assert_awaited_once_with(UNAVAILABLE_MESSAGE, ephemeral=True) + + async def test_name_search_unavailable(self) -> None: + api = AsyncMock() + api.search_quests.side_effect = APIError(503, "down") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "water") + + interaction.followup.send.assert_awaited_once_with(UNAVAILABLE_MESSAGE, ephemeral=True) + + async def test_name_search_generic_error(self) -> None: + api = AsyncMock() + api.search_quests.side_effect = APIError(500, "boom") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "water") + + message = interaction.followup.send.await_args.args[0] + assert "try again shortly" in message + + async def test_no_matches_sends_hint(self) -> None: + api = AsyncMock() + api.search_quests.return_value = [] + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "zzznotfound") + + message = interaction.followup.send.await_args.args[0] + assert NOT_FOUND_HINT in message + + async def test_single_match_sends_link_buttons_without_select(self) -> None: + api = AsyncMock() + api.search_quests.return_value = [_search_result(quest_id=7, title="Explorer")] + api.get_quest.return_value = _quest(quest_id=7, title="Explorer") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "explorer") + + kwargs = interaction.followup.send.await_args.kwargs + assert kwargs["embed"].title == "Explorer" + labels = [button.label for button in kwargs["view"].children] + assert labels == ["Quest page", "Wowhead"] + + async def test_multiple_matches_offers_select_of_others(self) -> None: + api = AsyncMock() + matches = [_search_result(quest_id=i, title=f"Explorer {i}") for i in range(1, 8)] + api.search_quests.return_value = matches + api.get_quest.return_value = _quest(quest_id=1, title="Explorer 1") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "explorer") + + kwargs = interaction.followup.send.await_args.kwargs + view = kwargs["view"] + assert isinstance(view, QuestMatchView) + assert [option.value for option in view._select.options] == ["2", "3", "4", "5", "6"] + + async def test_quest_gone_after_search_reports_gone(self) -> None: + api = AsyncMock() + api.search_quests.return_value = [_search_result(quest_id=1, title="Explorer")] + api.get_quest.side_effect = NotFoundError(404, "gone") + cog = _make_cog(api=api) + interaction = _make_interaction(api=api) + + await QuestsCog.quest_command.callback(cog, interaction, "explorer") + + interaction.followup.send.assert_awaited_once_with("That quest is gone.", ephemeral=True) + + +class TestQuestMatchView: + def test_options_use_match_titles_and_ids(self) -> None: + view = QuestMatchView(1, [_search_result(quest_id=1, title="A"), _search_result(quest_id=2, title="B")]) + assert [option.label for option in view._select.options] == ["A", "B"] + assert [option.value for option in view._select.options] == ["1", "2"] + + def test_link_buttons_point_at_initial_quest(self) -> None: + view = QuestMatchView(1, [_search_result(quest_id=2, title="B")]) + assert view._page_button.url == "https://sidequest-guild.com/quests/detail/?id=1" + assert view._wowhead_button.url == "https://www.wowhead.com/forever/quest=1" + + async def test_select_callback_edits_message_with_chosen_quest(self) -> None: + api = AsyncMock() + api.get_quest.return_value = _quest(quest_id=2, title="B") + view = QuestMatchView(1, [_search_result(quest_id=2, title="B")]) + view._select._values = ["2"] + interaction = _make_interaction(api=api) + + await view._select.callback(interaction) + + interaction.response.edit_message.assert_awaited_once() + kwargs = interaction.response.edit_message.await_args.kwargs + assert kwargs["embed"].title == "B" + assert kwargs["view"] is view + assert view._page_button.url == "https://sidequest-guild.com/quests/detail/?id=2" + assert view._wowhead_button.url == "https://www.wowhead.com/forever/quest=2" + + async def test_select_callback_reports_error_ephemerally(self) -> None: + api = AsyncMock() + api.get_quest.side_effect = NotFoundError(404, "gone") + view = QuestMatchView(1, [_search_result(quest_id=2)]) + view._select._values = ["2"] + interaction = _make_interaction(api=api) + + await view._select.callback(interaction) + + interaction.response.send_message.assert_awaited_once_with("That quest is gone.", ephemeral=True) + interaction.response.edit_message.assert_not_awaited() diff --git a/uv.lock b/uv.lock index 3b84497..cd6d4a7 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=d6ee131b188062fd429222cb01a588daee1243c1#d6ee131b188062fd429222cb01a588daee1243c1" } +source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=api&rev=59a86f9575d409ec76f9d24766eeb1acd39dba52#59a86f9575d409ec76f9d24766eeb1acd39dba52" } 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=d6ee131b188062fd429222cb01a588daee1243c1" }, + { name = "sidequest-common", git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=59a86f9575d409ec76f9d24766eeb1acd39dba52" }, { 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=d6ee131b188062fd429222cb01a588daee1243c1" }, + { name = "sidequest-api", git = "https://github.com/SideQuest-Guild/website?subdirectory=api&rev=59a86f9575d409ec76f9d24766eeb1acd39dba52" }, ] [[package]] name = "sidequest-common" version = "0.1.0" -source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=d6ee131b188062fd429222cb01a588daee1243c1#d6ee131b188062fd429222cb01a588daee1243c1" } +source = { git = "https://github.com/SideQuest-Guild/website?subdirectory=packages%2Fsidequest-common&rev=59a86f9575d409ec76f9d24766eeb1acd39dba52#59a86f9575d409ec76f9d24766eeb1acd39dba52" } dependencies = [ { name = "advanced-alchemy" }, { name = "pydantic" }, @@ -1578,16 +1578,16 @@ wheels = [ [[package]] name = "wow" -version = "0.5.1" +version = "0.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, { name = "httpx" }, { name = "msgspec" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b0/29/813eba9dbb3dff4c43ffc09314a7f7e720fbc5b3976efa5eaaa9b8fc8470/wow-0.5.1.tar.gz", hash = "sha256:822e0bd958c41d5bc33b37fe47813e978fddbbcbd896fe8deb422ca932e6f849", size = 60146, upload-time = "2026-11-11T20:00:42.06Z" } +sdist = { url = "https://files.pythonhosted.org/packages/63/12/8220aadc97225cc5677d61ea3d7f43eef4cd195363e8e9be93f3bda608f7/wow-0.6.0.tar.gz", hash = "sha256:4e7f92d8605a1a8f863926594e0efe2a26e4851a4c07b72c9bc3f8da756f95e2", size = 63669, upload-time = "2026-11-13T19:33:30.697Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/f2/ee438e0fd5b0d6a87ddadf5bc8a1c6ece8f06168607f05d8f91f4743d4bc/wow-0.5.1-py3-none-any.whl", hash = "sha256:7fefdf636628e3e5862998c1db7d549901a4328ccc68470013989dbffbe2311a", size = 90634, upload-time = "2026-11-11T20:00:40.669Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/980458c2ecb7deeffc21f45ff5573a2ade1c1504b8ddb193ed450b1011a8/wow-0.6.0-py3-none-any.whl", hash = "sha256:7125ef011a6f4ba0b1aff228c5b4f5dbcf1085a2ceebe88035ed295f5cbaeee7", size = 100580, upload-time = "2026-11-13T19:33:29.428Z" }, ] [[package]]