Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ lives there.
- **Crafters.** `/crafter <query> [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 <name>` looks up a WoW: Forever achievement and shows its points,
description and category, with autocomplete over the full catalog. `/recipe <name>` looks up a recipe (reusing
`/crafter`'s search) and shows its reagents, crafted item and the guild crafters who know it. `/compare
<character1> <character2>` 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.
- **Auction prices.** `/price <item>` shows an item's lowest current auction price, where it's cheapest, how many
are listed, and its 14-day price range. `/watch <item> <price>` (e.g. `1g20s`, `35s`, `80c`) DMs you when that
item's price drops to or below your target; `/unwatch <item>` removes a watch and `/watches` lists yours. Watches
Expand Down
7 changes: 7 additions & 0 deletions pyrefly-baseline.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
{
"errors": [
{
"column": 15,
"path": "src/sidequest_bot/plugins/achievements.py",
"name": "bad-override",
"concise_description": "Class member `_AchievementMatchSelect.callback` overrides parent class `Select` in an inconsistent manner",
"severity": "error"
},
{
"column": 15,
"path": "src/sidequest_bot/plugins/event_sync.py",
Expand Down
44 changes: 44 additions & 0 deletions src/sidequest_bot/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
from tenacity import AsyncRetrying, before_sleep_log, retry_if_exception, stop_after_attempt, wait_exponential

from sidequest_common.schemas import (
AchievementCategorySchema,
AchievementCategoryTree,
AchievementSchema,
ActivityAck,
AddonSchema,
AnnouncementPosted,
Expand Down Expand Up @@ -57,6 +60,7 @@
PendingAnnouncement,
PendingAnnouncementsPage,
RankSchema,
RecipeDetail,
Recruiting,
RoleMenuCreate,
RoleMenuOptionUpsert,
Expand Down Expand Up @@ -96,6 +100,7 @@
_GROUP_SESSIONS = TypeAdapter(list[GroupSessionSchema])
_XP_GRANTS = TypeAdapter(list[XPGrantResult])
_ADDONS = TypeAdapter(list[AddonSchema])
_ACHIEVEMENT_CATEGORIES = TypeAdapter(list[AchievementCategoryTree])


class ItemSummary(BaseModel):
Expand Down Expand Up @@ -981,6 +986,45 @@ async def get_item(self, item_id: int) -> Item:
data = await self._request("GET", f"/api/items/{item_id}")
return _parse(Item.model_validate, data)

# --- Achievements

async def list_achievement_categories(self) -> list[AchievementCategoryTree]:
"""Every root achievement category with its subcategories (the public ``/api/achievements/categories`` GET).

503 if Battle.net isn't configured or didn't answer.
"""
data = await self._request("GET", "/api/achievements/categories")
return _parse(_ACHIEVEMENT_CATEGORIES.validate_python, data)

async def get_achievement_category(self, category_id: int) -> AchievementCategorySchema:
"""One achievement category and its achievements (the public ``/api/achievements/categories/{id}`` GET).

Raises ``NotFoundError`` for an unknown category, or ``APIError`` (status 503) if Battle.net isn't
configured or didn't answer.
"""
data = await self._request("GET", f"/api/achievements/categories/{category_id}")
return _parse(AchievementCategorySchema.model_validate, data)

async def get_achievement(self, achievement_id: int) -> AchievementSchema:
"""One achievement by its game ID (the public ``/api/achievements/{id}`` GET).

Raises ``NotFoundError`` for an unknown achievement, or ``APIError`` (status 503) if Battle.net isn't
configured or didn't answer.
"""
data = await self._request("GET", f"/api/achievements/{achievement_id}")
return _parse(AchievementSchema.model_validate, data)

# --- Recipes

async def get_recipe(self, recipe_id: int) -> RecipeDetail:
"""One recipe by its Battle.net game ID: what it makes, its reagents, and guild crafters.

The public ``/api/recipes/{id}`` GET. Raises ``NotFoundError`` for an unknown recipe, or ``APIError``
(status 503) if Battle.net isn't configured or didn't answer.
"""
data = await self._request("GET", f"/api/recipes/{recipe_id}")
return _parse(RecipeDetail.model_validate, data)

# --- Auctions

async def get_item_price(self, item_id: int) -> ItemAuctionPrice:
Expand Down
215 changes: 215 additions & 0 deletions src/sidequest_bot/plugins/achievements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
"""Achievement lookup: ``/achievement <name>`` shows a WoW: Forever achievement's points, description and category.

Battle.net's achievement API has no name search, so this cog flattens the category tree (``GET
/api/achievements/categories`` then ``GET /api/achievements/categories/{id}`` for each category) into one list,
cached at module scope for :data:`CACHE_TTL` — the same hour the site itself caches this Battle.net-backed reference
data at the edge (``EDGE_REFERENCE_CACHE`` in the website's ``reference/controllers.py``).
"""

import asyncio
import logging
from datetime import datetime, timedelta
from http import HTTPStatus
from typing import TYPE_CHECKING

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, make_embed, truncate

if TYPE_CHECKING:
from collections.abc import Sequence

from sidequest_bot.api_client import SideQuestAPI
from sidequest_common.schemas import AchievementSchema, AchievementSummary

logger = logging.getLogger(__name__)

ACHIEVEMENT_PAGE_URL = "https://sidequest-guild.com/achievements/detail/?id={achievement_id}"
DESCRIPTION_LIMIT = 4096
MAX_AUTOCOMPLETE_RESULTS = 25
MAX_OTHER_MATCHES = 5
CACHE_TTL = timedelta(hours=1)
"""How long the flattened achievement catalog is cached; matches the site's own edge cache for this data."""
NOT_FOUND_HINT = "Try a shorter word, or pick a suggestion as you type."
UNAVAILABLE_MESSAGE = "Achievement lookup isn't available right now; try again shortly."


def build_achievement_embed(achievement: AchievementSchema) -> discord.Embed:
"""The achievement's name, points, description, category and icon, linking to its site page."""
embed = make_embed(
title=achievement.name,
description=truncate(achievement.description, DESCRIPTION_LIMIT),
color=Colors.SITE_GOLD,
timestamp=False,
)
embed.url = ACHIEVEMENT_PAGE_URL.format(achievement_id=achievement.id)
if achievement.icon_url:
embed.set_thumbnail(url=achievement.icon_url)
embed.add_field(name="Points", value=str(achievement.points))
if achievement.category:
embed.add_field(name="Category", value=achievement.category)
if achievement.reward_description:
embed.add_field(name="Reward", value=truncate(achievement.reward_description), inline=False)
embed.add_field(
name="Site",
value=f"[View on site]({ACHIEVEMENT_PAGE_URL.format(achievement_id=achievement.id)})",
inline=False,
)
return embed


def match_option(match: AchievementSummary) -> discord.SelectOption:
"""One search result as a select option, with its points as the description."""
return discord.SelectOption(label=truncate(match.name, 100), value=str(match.id), description=f"{match.points} pts")


class _AchievementCache:
"""The flattened achievement catalog, rebuilt at most once per :data:`CACHE_TTL`."""

def __init__(self) -> None:
self._achievements: list[AchievementSummary] = []
self._built_at: datetime | None = None
self._lock = asyncio.Lock()

async def get(self, api: SideQuestAPI) -> list[AchievementSummary]:
"""The cached catalog, rebuilding it first if stale or never built."""
async with self._lock:
now = discord.utils.utcnow()
if self._built_at is None or now - self._built_at > CACHE_TTL:
self._achievements = await self._build(api)
self._built_at = now
return self._achievements

@staticmethod
async def _build(api: SideQuestAPI) -> list[AchievementSummary]:
"""Every achievement in every category, fetched concurrently; a category Battle.net can't answer is skipped."""
roots = await api.list_achievement_categories()
category_ids = [root.id for root in roots] + [child.id for root in roots for child in root.children]
pages = await asyncio.gather(
*(api.get_achievement_category(category_id) for category_id in category_ids), return_exceptions=True
)
achievements: list[AchievementSummary] = []
for page in pages:
if isinstance(page, APIError):
continue
if isinstance(page, BaseException):
raise page
achievements.extend(page.achievements)
return achievements


_cache = _AchievementCache()


async def _autocomplete_achievement(
interaction: discord.Interaction[SideQuestBot], current: str
) -> list[app_commands.Choice[str]]:
"""Up to 25 achievements matching ``current``, from the cached catalog; empty if Battle.net can't be reached."""
try:
achievements = await _cache.get(interaction.client.api)
except APIError:
return []
current_fold = current.strip().casefold()
if current_fold:
achievements = [a for a in achievements if current_fold in a.name.casefold()]
return [
app_commands.Choice(name=truncate(f"{a.name} ({a.points} pts)", 100), value=str(a.id))
for a in achievements[:MAX_AUTOCOMPLETE_RESULTS]
]


async def _fetch_achievement_embed(
interaction: discord.Interaction[SideQuestBot], achievement_id: int
) -> discord.Embed | str:
"""The achievement's embed, or a plain-text error if the lookup failed."""
try:
found = await interaction.client.api.get_achievement(achievement_id)
except NotFoundError:
return "That achievement is gone."
except APIError as exc:
if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE:
return UNAVAILABLE_MESSAGE
logger.warning("Achievement lookup failed for %s", achievement_id, exc_info=True)
return "Couldn't look up that achievement right now; try again shortly."
return build_achievement_embed(found)


class _AchievementMatchSelect(discord.ui.Select["AchievementMatchView"]):
"""The select menu itself; its callback swaps the parent view's embed to the chosen achievement."""

def __init__(self, matches: Sequence[AchievementSummary]) -> None:
super().__init__(placeholder="Other matches", options=[match_option(match) for match in matches])

async def callback(self, interaction: discord.Interaction[SideQuestBot]) -> None:
achievement_id = int(self.values[0])
result = await _fetch_achievement_embed(interaction, achievement_id)
if isinstance(result, str):
await interaction.response.send_message(result, ephemeral=True)
return
await interaction.response.edit_message(embed=result, view=self.view)


class AchievementMatchView(discord.ui.View):
"""A select menu of up to :data:`MAX_OTHER_MATCHES` other search matches, swapping the shown embed on pick."""

def __init__(self, matches: Sequence[AchievementSummary]) -> None:
super().__init__(timeout=180)
self._select = _AchievementMatchSelect(matches)
self.add_item(self._select)


class AchievementsCog(commands.Cog):
"""``/achievement`` lookup."""

def __init__(self, bot: SideQuestBot) -> None:
self.bot = bot

@app_commands.command(name="achievement", description="Look up a WoW: Forever achievement.")
@app_commands.describe(name="Achievement name, or pick a suggestion as you type")
@app_commands.autocomplete(name=_autocomplete_achievement)
async def achievement_command(self, interaction: discord.Interaction[SideQuestBot], name: str) -> None:
"""Resolve ``name`` to an achievement id (from autocomplete, or a name search) and show its embed."""
await interaction.response.defer()
if name.isdigit():
result = await _fetch_achievement_embed(interaction, int(name))
if isinstance(result, str):
await interaction.followup.send(result, ephemeral=True)
return
await interaction.followup.send(embed=result)
return
try:
achievements = await _cache.get(self.bot.api)
except APIError as exc:
if exc.status_code == HTTPStatus.SERVICE_UNAVAILABLE:
await interaction.followup.send(UNAVAILABLE_MESSAGE, ephemeral=True)
return
logger.warning("Achievement catalog failed to build", exc_info=True)
await interaction.followup.send(
"Couldn't search achievements right now; try again shortly.", ephemeral=True
)
return
name_fold = name.casefold()
matches = [a for a in achievements if name_fold in a.name.casefold()]
if not matches:
await interaction.followup.send(
f"No achievements found matching **{name}**. {NOT_FOUND_HINT}", ephemeral=True
)
return
best, others = matches[0], matches[1 : 1 + MAX_OTHER_MATCHES]
result = await _fetch_achievement_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=AchievementMatchView(others))
else:
await interaction.followup.send(embed=result)


async def setup(bot: SideQuestBot) -> None:
"""Register the cog."""
await bot.add_cog(AchievementsCog(bot))
Loading
Loading