1"""Typed HTTP client for the SideQuest API. The only way the bot talks to the API."""
2
3import logging
4from datetime import date, datetime
5from http import HTTPStatus
6from typing import TYPE_CHECKING, Any, Literal, Self
7from uuid import UUID
8
9import httpx
10from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError
11from tenacity import AsyncRetrying, before_sleep_log, retry_if_exception, stop_after_attempt, wait_exponential
12
13from sidequest_common.schemas import (
14 AchievementCategorySchema,
15 AchievementCategoryTree,
16 AchievementSchema,
17 ActivityAck,
18 AddonSchema,
19 AnnouncementPosted,
20 AwayNowReport,
21 BadgeAck,
22 BadgeSyncReport,
23 BeastFamilySchema,
24 BeastSchema,
25 ConfirmByDiscordRequest,
26 CouncilLogEntry,
27 CouncilLogKind,
28 CouncilLogPage,
29 CouncilPostedBody,
30 DiscordEventReconcile,
31 DiscordEventState,
32 DiscordInterestReport,
33 DiscordLiveReport,
34 DiscordPushAck,
35 DiscordRosterConfirmRequest,
36 DiscordSyncPending,
37 EventSummary,
38 GroupPresenceReport,
39 GroupSessionClose,
40 GroupSessionCreate,
41 GroupSessionSchema,
42 GroupSessionUpdate,
43 GroupTranscriptPurge,
44 GuildConfigSchema,
45 GuildConfigUpdate,
46 GuildCrafters,
47 GuildRoleIn,
48 GuildRolesReplace,
49 LeaderboardPage,
50 LevelRoleSchema,
51 LevelRoleUpsert,
52 MarketReport,
53 MarketReportKind,
54 MemberLevelSchema,
55 MemberLink,
56 MemberListing,
57 MemberProfileIn,
58 MemberProfilesReplace,
59 MessageBackfill,
60 MessageBackfillResult,
61 ModCaseCreate,
62 ModCaseSchema,
63 ModCaseUpdate,
64 PendingAnnouncement,
65 PendingAnnouncementsPage,
66 QuestSchema,
67 QuestSearchResult,
68 RankSchema,
69 RecipeDetail,
70 Recruiting,
71 RecruitShoutoutAck,
72 RoleMenuCreate,
73 RoleMenuOptionUpsert,
74 RoleMenuSchema,
75 RoleMenuUpdate,
76 RoleResetCandidate,
77 SetXPRequest,
78 Signup,
79 SignupByDiscord,
80 SignupNoticeAck,
81 SignupNoticesPage,
82 SignupUpsert,
83 VoicePresenceReport,
84 VoiceXPRequest,
85 WeeklyBoardEvent,
86 WeeklyBoardMessage,
87 XPActivityReport,
88 XPAwardResult,
89 XPGrantResult,
90)
91
92if TYPE_CHECKING:
93 from collections.abc import Callable, Sequence
94 from types import TracebackType
95
96logger = logging.getLogger(__name__)
97
98API_KEY_HEADER = "X-API-Key"
99
100_LEVEL_ROLES = TypeAdapter(list[LevelRoleSchema])
101_CASES = TypeAdapter(list[ModCaseSchema])
102_ROLE_MENUS = TypeAdapter(list[RoleMenuSchema])
103_EVENTS = TypeAdapter(list[EventSummary])
104_MEMBER_LINKS = TypeAdapter(list[MemberLink])
105_ROLE_RESETS = TypeAdapter(list[RoleResetCandidate])
106_WEEKLY_BOARD_EVENTS = TypeAdapter(list[WeeklyBoardEvent])
107_GROUP_SESSIONS = TypeAdapter(list[GroupSessionSchema])
108_XP_GRANTS = TypeAdapter(list[XPGrantResult])
109_ADDONS = TypeAdapter(list[AddonSchema])
110_ACHIEVEMENT_CATEGORIES = TypeAdapter(list[AchievementCategoryTree])
111_QUEST_SEARCH_RESULTS = TypeAdapter(list[QuestSearchResult])
112_BEASTS = TypeAdapter(list[BeastSchema])
113_BEAST_FAMILIES = TypeAdapter(list[BeastFamilySchema])
114
115
[docs]
116class ItemSummary(BaseModel):
117 """One item in a search result (``GET /api/items``); no icon or tooltip.
118
119 Mirrors the website's ``ItemSearchResult`` by hand: the item schemas aren't in the ``sidequest-common`` pin yet.
120 """
121
122 item_id: int
123 name: str
124 quality: str = Field(description="Battle.net's quality constant, such as `EPIC`.")
125 quality_name: str = Field(description="The quality as the game shows it, such as `Epic`.")
126 inventory_type: str = Field(description="Battle.net's slot constant, such as `TWOHWEAPON`.")
127 inventory_type_name: str = Field(description="The slot as the game shows it, such as `Two-Hand`.")
128 item_level: int
129 required_level: int
130
131
[docs]
132class ItemSearchPage(BaseModel):
133 """One page of item search results (``GET /api/items``). Mirrors the website's ``ItemSearchPage`` by hand."""
134
135 page: int
136 page_count: int
137 results: list[ItemSummary]
138
139
[docs]
140class Item(BaseModel):
141 """An item with its tooltip (``GET /api/items/{item_id}``). Mirrors the website's ``ItemSchema`` by hand."""
142
143 item_id: int
144 name: str
145 quality: str = Field(description="Battle.net's quality constant, such as `EPIC`.")
146 quality_name: str = Field(description="The quality as the game shows it, such as `Epic`.")
147 item_class: str
148 item_subclass: str
149 inventory_type: str = Field(description="Battle.net's slot constant, such as `TWOHWEAPON`.")
150 inventory_type_name: str = Field(description="The slot as the game shows it, such as `Two-Hand`.")
151 item_level: int
152 required_level: int
153 sell_price: int = Field(description="What a vendor pays, in copper.")
154 is_equippable: bool
155 icon_url: str | None
156 tooltip: list[str] = Field(description="The tooltip's text lines in order, below the item's name.")
157
158
[docs]
159class RosterSyncReport(BaseModel):
160 """``POST /api/guilds/{id}/characters/sync``.
161
162 Mirrors the website's ``RosterSyncReport`` by hand: phase 3's character schemas aren't in the
163 ``sidequest-common`` pin yet.
164 """
165
166 members: int
167 joined: list[str]
168 left: list[str]
169 profiles_refreshed: int
170 characters_linked: int
171 members_confirmed: int = 0
172 """Members newly confirmed on the guild roster because one of their Battle.net characters is in it."""
173
174
[docs]
175class CharacterGearItem(BaseModel):
176 """One equipped item, as shown in ``/who``'s gear field.
177
178 Mirrors a subset of the website's ``CharacterGear`` by hand: phase 4's character schemas aren't in the
179 ``sidequest-common`` pin yet.
180 """
181
182 slot_name: str
183 name: str
184 item_level: int | None
185
186
[docs]
187class CharacterHunterPet(BaseModel):
188 """One of a hunter's tamed pets, as shown in ``/who``'s Pets field.
189
190 Mirrors the website's ``CharacterHunterPet`` by hand: phase 4's character schemas aren't in the
191 ``sidequest-common`` pin yet. ``creature`` is the tamed beast's species name (e.g. "Great Goretusk").
192 """
193
194 name: str
195 level: int
196 creature: str
197 creature_id: int
198 active: bool = False
199
200
[docs]
201class CharacterSheet(BaseModel):
202 """The subset of the website's ``CharacterSheet`` this bot shows: the gear list and any hunter pets.
203
204 ``hunter_pets`` defaults empty so the bot works against a site that hasn't deployed it yet.
205 """
206
207 gear: list[CharacterGearItem]
208 hunter_pets: list[CharacterHunterPet] = Field(default_factory=list)
209
210
[docs]
211class CharacterSummary(BaseModel):
212 """A character's Battle.net summary (``GET /api/characters/`` or ``GET /api/characters/?q=``).
213
214 Mirrors the website's ``CharacterSummary`` by hand: phase 4's character schemas aren't in the
215 ``sidequest-common`` pin yet. ``profile_found`` is false while Battle.net has no profile for the character; the
216 summary then holds only what the guild roster says.
217 """
218
219 model_config = ConfigDict(populate_by_name=True)
220
221 slug: str
222 name: str
223 surname: str
224 level: int
225 wow_class: str | None = Field(default=None, alias="class")
226 race: str | None = None
227 faction: str | None = None
228 guild_name: str | None = None
229 guild_slug: str | None = None
230 in_roster: bool
231 guild_rank: int | None = None
232 rank_name: str | None = None
233 item_level: int | None = None
234 spec: str | None = None
235 achievement_points: int | None = None
236 honorable_kills: int | None = None
237 pvp_rank: int | None = None
238 last_login_at: datetime | None = None
239 profile_found: bool
240 fetched_at: datetime | None = None
241
242
[docs]
243class CharacterPage(CharacterSummary):
244 """A character's summary plus its sheet (``GET /api/characters/{slug}``).
245
246 ``sheet`` is ``None`` while Battle.net has no profile for the character.
247 """
248
249 sheet: CharacterSheet | None = None
250
251
[docs]
252class CharacterMilestone(BaseModel):
253 """A roster character reaching level 40 or 60 (``GET .../characters/milestones/pending``).
254
255 Mirrors the website's ``CharacterMilestoneSchema`` by hand: phase 4's milestone schema isn't in the
256 ``sidequest-common`` pin yet.
257 """
258
259 model_config = ConfigDict(populate_by_name=True)
260
261 id: UUID
262 slug: str
263 name: str
264 surname: str
265 wow_class: str | None = Field(default=None, alias="class")
266 level: int
267 reached_at: datetime
268 posted_at: datetime | None = None
269
270
[docs]
271class MilestonePosted(BaseModel):
272 """Body for ``POST .../characters/milestones/{id}/posted``: the Discord message the bot posted."""
273
274 discord_message_id: int | None = None
275
276
277_CHARACTER_SUMMARIES = TypeAdapter(list[CharacterSummary])
278_PENDING_MILESTONES = TypeAdapter(list[CharacterMilestone])
279
280AUCTION_TREND_DAYS = 14
281"""Days of daily price history ``get_item_price`` returns in ``trend`` (``sidequest-common`` ``AUCTION_TREND_DAYS``)."""
282MAX_AUCTION_WATCHES = 25
283"""Per-member cap on auction watches (``sidequest-common`` ``MAX_AUCTION_WATCHES``); upsert returns 409 past it."""
284
285
[docs]
286class AuctionHousePrice(BaseModel):
287 """One auction house's current price for an item.
288
289 Mirrors the website's ``AuctionHousePrice`` by hand: the auctions schemas aren't in the ``sidequest-common``
290 pin yet.
291 """
292
293 house_id: int
294 house_name: str
295 unit_price: int
296 quantity: int
297 listings: int
298 updated_at: datetime
299
300
[docs]
301class AuctionTrendPoint(BaseModel):
302 """One day's lowest price in a 14-day trend. Mirrors the website's ``AuctionTrendPoint`` by hand."""
303
304 day: date
305 unit_price: int
306
307
[docs]
308class ItemAuctionPrice(BaseModel):
309 """``GET /api/auctions/prices/{item_id}``: an item's current price across every faction house, plus trend.
310
311 Mirrors the website's ``ItemAuctionPrice`` by hand. ``unit_price`` is the lowest across houses, ``None`` when
312 nobody lists the item.
313 """
314
315 item_id: int
316 unit_price: int | None
317 quantity_total: int
318 houses: list[AuctionHousePrice]
319 trend: list[AuctionTrendPoint]
320 updated_at: datetime | None
321
322
[docs]
323class AuctionSyncHouse(BaseModel):
324 """One house's counts from an auction sync. Mirrors the website's ``AuctionSyncHouse`` by hand."""
325
326 house_id: int
327 house_name: str
328 auctions: int
329 commodities: int
330
331
[docs]
332class AuctionSyncReport(BaseModel):
333 """``POST /api/guilds/{id}/auctions/sync``. Mirrors the website's ``AuctionSyncReport`` by hand."""
334
335 houses: list[AuctionSyncHouse]
336 items_priced: int
337 alerts_queued: int
338
339
[docs]
340class AuctionWatch(BaseModel):
341 """A member's price watch on one item. Mirrors the website's ``AuctionWatch`` by hand."""
342
343 id: UUID
344 item_id: int
345 item_name: str | None
346 icon_url: str | None
347 max_unit_price: int
348 current_unit_price: int | None
349 created_at: datetime
350 last_alerted_at: datetime | None
351
352
[docs]
353class AuctionWatchCreate(BaseModel):
354 """Body for ``POST .../auction-watches``: upserts by ``item_id``. Mirrors ``AuctionWatchCreate`` by hand."""
355
356 item_id: int = Field(gt=0)
357 max_unit_price: int = Field(ge=1, le=10_000_000_000)
358
359
[docs]
360class AuctionAlertSchema(BaseModel):
361 """A queued price alert, ready to DM. Mirrors the website's ``AuctionAlertSchema`` by hand."""
362
363 id: UUID
364 discord_user_id: int
365 member_name: str
366 item_id: int
367 item_name: str | None
368 icon_url: str | None
369 unit_price: int
370 max_unit_price: int
371 quantity: int
372 house_name: str
373 created_at: datetime
374
375
376_AUCTION_WATCHES = TypeAdapter(list[AuctionWatch])
377_AUCTION_ALERTS = TypeAdapter(list[AuctionAlertSchema])
378
379SIM_SLOTS = (
380 "head",
381 "neck",
382 "shoulder",
383 "back",
384 "chest",
385 "wrist",
386 "hands",
387 "waist",
388 "legs",
389 "feet",
390 "finger1",
391 "finger2",
392 "trinket1",
393 "trinket2",
394 "main_hand",
395 "off_hand",
396 "ranged",
397)
398"""Every gear slot the sim understands, matching the website's ``SimItem.slot`` literal."""
399
400SIM_MOBS = ("humanoid", "undead", "beast", "demon", "dragonkin", "elemental", "giant", "mechanical")
401"""Every mob type the sim understands, matching the website's ``SimItem``/``SimRequest`` ``mobs`` literal."""
402
403MAX_SIM_SWAPS = 6
404MAX_SIM_WEARING = 17
405MAX_QUEUED_SIMS_PER_MEMBER = 3
406"""Jobs queued or running at once per ``requested_by`` before the API answers 409 (``sidequest-common`` constant)."""
407
408
[docs]
409class SimItem(BaseModel):
410 """One item to try or correct a baseline with.
411
412 Mirrors the website's ``SimItem`` by hand: the sim schemas aren't in the ``sidequest-common`` pin yet.
413 ``item`` is a numeric item id, a Wowhead URL containing ``item=ID``, or an item name (case-insensitive,
414 resolved against the sim's item database); the bot never resolves it itself.
415 """
416
417 item: str
418 slot: str | None = None
419 enchant: str | None = None
420 suffix: str | None = None
421
422
[docs]
423class SimRequest(BaseModel):
424 """Body for ``POST /api/guilds/{id}/sims``. Mirrors the website's ``SimRequest`` by hand."""
425
426 character: str
427 swaps: list[SimItem] = Field(min_length=1, max_length=MAX_SIM_SWAPS)
428 wearing: list[SimItem] = Field(default_factory=list, max_length=MAX_SIM_WEARING)
429 spec: str | None = None
430 talents: str | None = None
431 targets: list[int] = Field(default_factory=lambda: [1, 4])
432 mobs: list[str] = Field(default_factory=lambda: ["humanoid"])
433 duration: int = 90
434 requested_by: str | None = None
435
436
437SimJobStatus = Literal["queued", "running", "done", "failed"]
438
439
[docs]
440class SimMetrics(BaseModel):
441 """One set of per-run metrics. Mirrors the website's ``SimMetrics`` by hand."""
442
443 dps: float | None = None
444 tps: float | None = None
445 dtps: float | None = None
446 hps: float | None = None
447
448
[docs]
449class SimRow(BaseModel):
450 """One target-count/mob combination's baseline vs swapped metrics. Mirrors ``SimRow`` by hand."""
451
452 targets: int
453 mob: str
454 baseline: SimMetrics
455 swapped: SimMetrics
456 delta_pct: SimMetrics
457 noise: list[str] = Field(default_factory=list)
458
459
[docs]
460class SimResultItem(BaseModel):
461 """One side of a gear change: ``None`` on ``from_item`` means the slot was empty.
462
463 Mirrors the website's (unnamed, inlined) item-change schema by hand.
464 """
465
466 id: int
467 name: str
468
469
[docs]
470class SimChange(BaseModel):
471 """One slot's before/after item in a comparison.
472
473 Mirrors the website's (unnamed, inlined) change schema by hand.
474 """
475
476 slot: str
477 from_item: SimResultItem | None = None
478 to_item: SimResultItem
479
480
[docs]
481class SimComparison(BaseModel):
482 """One full gear-change scenario (all swaps applied, or one possible slot for an unslotted ring/trinket swap).
483
484 Mirrors the website's ``SimComparison`` by hand.
485 """
486
487 label: str
488 changes: list[SimChange]
489 rows: list[SimRow]
490
491
[docs]
492class SimResult(BaseModel):
493 """A finished sim's full output. Mirrors the website's ``SimResult`` by hand."""
494
495 character: str
496 class_name: str
497 spec: str
498 role: Literal["tank", "healer", "dps"]
499 level: int
500 gear_fetched_at: datetime | None = None
501 iterations: int
502 duration: int
503 comparisons: list[SimComparison]
504 notes: list[str] = Field(default_factory=list)
505
506
[docs]
507class SimJob(BaseModel):
508 """``POST``/``GET /api/guilds/{id}/sims(/{id})``. Mirrors the website's ``SimJob`` by hand."""
509
510 id: UUID
511 status: SimJobStatus
512 position: int | None = None
513 error: str | None = None
514 result: SimResult | None = None
515 created_at: datetime
516
517
518class APIError(Exception):
519 """The API returned an error response, or couldn't be reached. Every client failure is an APIError."""
520
521 def __init__(self, status_code: int, detail: str) -> None:
522 super().__init__(f"API error {status_code}: {detail}")
523 self.status_code = status_code
524 self.detail = detail
525
526
527class NotFoundError(APIError):
528 """The API returned 404."""
529
530
531class APIUnavailableError(APIError):
532 """The API couldn't be reached (connection/timeout) after retries. Reported as status 503."""
533
534
535class APIResponseShapeError(APIError):
536 """The API answered, but not in the shape this bot expects: usually the other half of a rolling deploy.
537
538 Raised as an APIError (status 502) so every caller's existing APIError handling covers it; a bare pydantic
539 ValidationError escaping a discord.py ``tasks.loop`` would stop that loop until the bot restarts.
540 """
541
542
543def _parse[T](validate: Callable[[object], T], data: object) -> T:
544 """Validate an API response with ``validate``, turning a schema mismatch into :class:`APIResponseShapeError`."""
545 try:
546 return validate(data)
547 except ValidationError as exc:
548 detail = f"unexpected response shape ({exc.error_count()} error(s)): {exc.errors()[0]['loc']}"
549 raise APIResponseShapeError(HTTPStatus.BAD_GATEWAY, detail) from exc
550
551
552def _is_retryable(exc: BaseException) -> bool:
553 """Idempotent requests: retry any transport error or 5xx."""
554 if isinstance(exc, httpx.TransportError):
555 return True
556 return isinstance(exc, APIError) and exc.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR
557
558
559def _never_sent(exc: BaseException) -> bool:
560 """Non-idempotent requests (POST): retry only if the request never reached the server."""
561 return isinstance(exc, httpx.ConnectError | httpx.ConnectTimeout)
562
563
564def _retrying(predicate: Callable[[BaseException], bool]) -> AsyncRetrying:
565 return AsyncRetrying(
566 retry=retry_if_exception(predicate),
567 stop=stop_after_attempt(3),
568 wait=wait_exponential(multiplier=0.5, max=4),
569 before_sleep=before_sleep_log(logger, logging.WARNING),
570 reraise=True,
571 )
572
573
[docs]
574class SideQuestAPI:
575 """Async client for the SideQuest API.
576
577 Retries 3x with backoff: idempotent methods on transport errors/5xx, POST only when the connection never opened
578 (so a case or XP award is never recorded twice). 4xx is never retried.
579
580 Pass ``client`` to reuse an existing ``httpx.AsyncClient`` (tests pass Litestar's ``AsyncTestClient``).
581 """
582
583 def __init__(self, base_url: str, api_key: str, *, client: httpx.AsyncClient | None = None) -> None:
584 self._owns_client = client is None
585 self._client = client or httpx.AsyncClient(base_url=base_url, timeout=10.0)
586 self._headers = {API_KEY_HEADER: api_key}
587
[docs]
588 async def aclose(self) -> None:
589 """Close the underlying HTTP client if this instance created it."""
590 if self._owns_client:
591 await self._client.aclose()
592
593 async def __aenter__(self) -> Self:
594 return self
595
596 async def __aexit__(
597 self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
598 ) -> None:
599 await self.aclose()
600
601 async def _request(
602 self,
603 method: str,
604 path: str,
605 *,
606 body: BaseModel | None = None,
607 params: dict[str, Any] | None = None,
608 exclude_unset: bool = False,
609 ) -> Any:
610 json = body.model_dump(mode="json", exclude_unset=exclude_unset) if body is not None else None
611 retrying = _retrying(_never_sent if method == "POST" else _is_retryable)
612 try:
613 return await retrying(self._send, method, path, json=json, params=params)
614 except httpx.TransportError as exc:
615 raise APIUnavailableError(HTTPStatus.SERVICE_UNAVAILABLE, f"API unreachable: {exc!r}") from exc
616
617 async def _send(self, method: str, path: str, *, json: Any, params: dict[str, Any] | None) -> Any:
618 response = await self._client.request(method, path, json=json, params=params, headers=self._headers)
619 if response.status_code == HTTPStatus.NO_CONTENT:
620 return None
621 if response.is_error:
622 try:
623 detail = str(response.json().get("detail", response.text))
624 except ValueError:
625 detail = response.text
626 error_cls = NotFoundError if response.status_code == HTTPStatus.NOT_FOUND else APIError
627 raise error_cls(response.status_code, detail)
628 return response.json()
629
630 @staticmethod
631 def _guild(guild_id: int) -> str:
632 return f"/api/guilds/{guild_id}"
633
634 # --- Guild config
635
[docs]
636 async def get_guild_config(self, guild_id: int) -> GuildConfigSchema:
637 """Config for ``guild_id`` (created with defaults on first access)."""
638 data = await self._request("GET", f"{self._guild(guild_id)}/config")
639 return _parse(GuildConfigSchema.model_validate, data)
640
[docs]
641 async def update_guild_config(self, guild_id: int, changes: GuildConfigUpdate) -> GuildConfigSchema:
642 """Apply only the fields set on ``changes``."""
643 data = await self._request("PATCH", f"{self._guild(guild_id)}/config", body=changes, exclude_unset=True)
644 return _parse(GuildConfigSchema.model_validate, data)
645
646 # --- Loot council
647
[docs]
648 async def pending_council_log(self, guild_id: int) -> list[CouncilLogEntry]:
649 """Council decisions and voids not yet posted, oldest first (max 25, raises ``NotFoundError`` otherwise)."""
650 data = await self._request("GET", f"{self._guild(guild_id)}/loot/council/pending")
651 return _parse(CouncilLogPage.model_validate, data).items
652
[docs]
653 async def ack_council_log(self, guild_id: int, loot_id: UUID, kind: CouncilLogKind) -> None:
654 """Confirm ``loot_id``'s ``kind`` posted; ``pending_council_log`` stops reporting it."""
655 body = CouncilPostedBody(kind=kind)
656 await self._request("POST", f"{self._guild(guild_id)}/loot/council/{loot_id}/posted", body=body)
657
658 # --- Member links
659
[docs]
660 async def list_member_links(self, guild_id: int) -> list[MemberLink]:
661 """Every signed-in member of ``guild_id``, and whether they've also linked Battle.net."""
662 data = await self._request("GET", f"{self._guild(guild_id)}/member-links")
663 return _parse(_MEMBER_LINKS.validate_python, data)
664
[docs]
665 async def mark_character_nick(self, guild_id: int, discord_id: int) -> None:
666 """Record the bot's one character-nickname call for ``discord_id``; it never renames them again."""
667 await self._request("POST", f"{self._guild(guild_id)}/member-links/{discord_id}/character-nick")
668
[docs]
669 async def confirm_discord_member(
670 self, guild_id: int, discord_id: int, request: DiscordRosterConfirmRequest
671 ) -> MemberLink:
672 """**Confirm in guild**: confirm a Discord-only member on the roster.
673
674 Creates their ``Member`` row from ``request.profile`` if they have none, else refreshes it.
675 """
676 data = await self._request(
677 "PUT", f"{self._guild(guild_id)}/discord-members/{discord_id}/roster-confirmation", body=request
678 )
679 return _parse(MemberLink.model_validate, data)
680
681 # --- Away
682
[docs]
683 async def get_away_now(self, guild_id: int) -> list[int]:
684 """Discord ids of members marked away today (America/Chicago)."""
685 data = await self._request("GET", f"{self._guild(guild_id)}/away-now")
686 return _parse(AwayNowReport.model_validate, data).discord_ids
687
688 # --- Leveling
689
[docs]
690 async def award_xp(self, guild_id: int, user_id: int) -> XPAwardResult:
691 """Award one message's worth of XP (API enforces cooldown and amount)."""
692 data = await self._request("POST", f"{self._guild(guild_id)}/members/{user_id}/xp")
693 return _parse(XPAwardResult.model_validate, data)
694
[docs]
695 async def set_xp(self, guild_id: int, user_id: int, xp: int) -> MemberLevelSchema:
696 """Overwrite a member's XP total; level is recomputed."""
697 data = await self._request("PUT", f"{self._guild(guild_id)}/members/{user_id}/xp", body=SetXPRequest(xp=xp))
698 return _parse(MemberLevelSchema.model_validate, data)
699
[docs]
700 async def grant_voice_xp(self, guild_id: int, request: VoiceXPRequest) -> list[XPGrantResult]:
701 """Voice XP for members the bot found eligible this minute."""
702 data = await self._request("POST", f"{self._guild(guild_id)}/xp/voice", body=request)
703 return _parse(_XP_GRANTS.validate_python, data)
704
[docs]
705 async def sync_activity_xp(self, guild_id: int) -> XPActivityReport:
706 """Pay any newly earned event and #lfg group XP (idempotent; safe to poll)."""
707 data = await self._request("POST", f"{self._guild(guild_id)}/xp/activity")
708 return _parse(XPActivityReport.model_validate, data)
709
[docs]
710 async def backfill_messages(self, guild_id: int, request: MessageBackfill) -> MessageBackfillResult:
711 """Push message counts read once from channel history (idempotent; keeps ``max(existing, reported)``)."""
712 data = await self._request("PUT", f"{self._guild(guild_id)}/activity/messages", body=request)
713 return _parse(MessageBackfillResult.model_validate, data)
714
[docs]
715 async def get_rank(self, guild_id: int, user_id: int) -> RankSchema:
716 """A member's rank; members without XP get ``rank=None`` and zeros."""
717 data = await self._request("GET", f"{self._guild(guild_id)}/members/{user_id}/rank")
718 return _parse(RankSchema.model_validate, data)
719
[docs]
720 async def get_leaderboard(self, guild_id: int, *, limit: int = 10, offset: int = 0) -> LeaderboardPage:
721 """Highest XP first."""
722 data = await self._request(
723 "GET", f"{self._guild(guild_id)}/leaderboard", params={"limit": limit, "offset": offset}
724 )
725 return _parse(LeaderboardPage.model_validate, data)
726
[docs]
727 async def list_level_roles(self, guild_id: int) -> list[LevelRoleSchema]:
728 """Level rewards, lowest level first."""
729 return _parse(_LEVEL_ROLES.validate_python, await self._request("GET", f"{self._guild(guild_id)}/level-roles"))
730
[docs]
731 async def set_level_role(self, guild_id: int, level: int, role_id: int) -> LevelRoleSchema:
732 """Grant ``role_id`` at ``level`` (replaces any existing reward for that level)."""
733 data = await self._request(
734 "PUT", f"{self._guild(guild_id)}/level-roles/{level}", body=LevelRoleUpsert(role_id=role_id)
735 )
736 return _parse(LevelRoleSchema.model_validate, data)
737
[docs]
738 async def delete_level_role(self, guild_id: int, level: int) -> None:
739 """Remove the reward at ``level``. Raises NotFoundError if none."""
740 await self._request("DELETE", f"{self._guild(guild_id)}/level-roles/{level}")
741
742 # --- Moderation cases
743
[docs]
744 async def create_case(self, guild_id: int, case: ModCaseCreate) -> ModCaseSchema:
745 """Record a moderation action; the API assigns the case number."""
746 return _parse(
747 ModCaseSchema.model_validate, await self._request("POST", f"{self._guild(guild_id)}/cases", body=case)
748 )
749
[docs]
750 async def list_cases(
751 self, guild_id: int, *, user_id: int | None = None, limit: int = 25, offset: int = 0
752 ) -> list[ModCaseSchema]:
753 """Newest first, optionally only for ``user_id``."""
754 params: dict[str, Any] = {"limit": limit, "offset": offset}
755 if user_id is not None:
756 params["user_id"] = user_id
757 return _parse(
758 _CASES.validate_python, await self._request("GET", f"{self._guild(guild_id)}/cases", params=params)
759 )
760
[docs]
761 async def get_case(self, guild_id: int, case_number: int) -> ModCaseSchema:
762 """One case. Raises NotFoundError if missing."""
763 data = await self._request("GET", f"{self._guild(guild_id)}/cases/{case_number}")
764 return _parse(ModCaseSchema.model_validate, data)
765
[docs]
766 async def update_case(self, guild_id: int, case_number: int, changes: ModCaseUpdate) -> ModCaseSchema:
767 """Edit a case: its reason or handler, or a report's status, closing note or thread. Only set fields go."""
768 data = await self._request(
769 "PATCH", f"{self._guild(guild_id)}/cases/{case_number}", body=changes, exclude_unset=True
770 )
771 return _parse(ModCaseSchema.model_validate, data)
772
773 # --- Role menus
774
779
783
788
795
799
808
813
814 # --- Event sync
815
[docs]
816 async def get_pending_event_sync(self, guild_id: int) -> DiscordSyncPending:
817 """Pushes and deletions the bot should apply to Discord now."""
818 data = await self._request("GET", f"{self._guild(guild_id)}/event-sync")
819 return _parse(DiscordSyncPending.model_validate, data)
820
[docs]
821 async def ack_event_push(self, guild_id: int, event_id: UUID, ack: DiscordPushAck) -> None:
822 """Confirm ``ack.push_hash`` was applied (or skipped) for ``event_id``."""
823 await self._request("POST", f"{self._guild(guild_id)}/event-sync/{event_id}/ack", body=ack)
824
[docs]
825 async def report_discord_event(self, guild_id: int, state: DiscordEventState) -> None:
826 """Report that Discord now holds ``state`` for one event (created, edited, or read off the gateway)."""
827 await self._request("POST", f"{self._guild(guild_id)}/event-sync/events", body=state)
828
[docs]
829 async def report_discord_event_deleted(self, guild_id: int, event_id: int) -> None:
830 """Report that ``event_id`` was deleted in Discord."""
831 await self._request("DELETE", f"{self._guild(guild_id)}/event-sync/events/{event_id}")
832
[docs]
833 async def delete_event_sync_tombstone(self, guild_id: int, event_id: int) -> None:
834 """Clear the tombstone for ``event_id`` after deleting it in Discord."""
835 await self._request("DELETE", f"{self._guild(guild_id)}/event-sync/tombstones/{event_id}")
836
[docs]
837 async def reconcile_event_sync(self, guild_id: int, reconcile: DiscordEventReconcile) -> None:
838 """Report every scheduled event currently in the guild."""
839 await self._request("POST", f"{self._guild(guild_id)}/event-sync/reconcile", body=reconcile)
840
[docs]
841 async def report_event_interest(self, guild_id: int, discord_event_id: int, report: DiscordInterestReport) -> None:
842 """Replace the interested-user set for the guild event linked to ``discord_event_id``; no-op if unlinked."""
843 await self._request("PUT", f"{self._guild(guild_id)}/event-sync/interest/{discord_event_id}", body=report)
844
[docs]
845 async def ack_event_activity(self, guild_id: int, ids: list[UUID]) -> None:
846 """Confirm these sign-up activity rows were posted in their event's forum thread."""
847 await self._request("POST", f"{self._guild(guild_id)}/event-sync/activity/ack", body=ActivityAck(ids=ids))
848
[docs]
849 async def ack_recruit_shoutouts(self, guild_id: int, ids: list[UUID]) -> None:
850 """Confirm these recruit shout-out rows were posted (or undeliverable) in their drive's forum thread."""
851 await self._request(
852 "POST", f"{self._guild(guild_id)}/event-sync/recruit-shoutouts/ack", body=RecruitShoutoutAck(ids=ids)
853 )
854
[docs]
855 async def get_event_signup_by_discord(self, guild_id: int, event_id: UUID, discord_id: int) -> SignupByDiscord:
856 """A member's current signup for ``event_id`` plus their most recent character/class/role, by Discord id.
857
858 Raises ``NotFoundError`` if ``discord_id`` has never signed in on the site, or ``event_id`` doesn't exist.
859 """
860 data = await self._request("GET", f"{self._guild(guild_id)}/events/{event_id}/signups/by-discord/{discord_id}")
861 return _parse(SignupByDiscord.model_validate, data)
862
[docs]
863 async def upsert_event_signup_by_discord(
864 self, guild_id: int, event_id: UUID, discord_id: int, data: SignupUpsert
865 ) -> Signup:
866 """Create or replace a member's signup for ``event_id``, by Discord id (Discord's sign-up buttons).
867
868 Raises ``NotFoundError`` if ``discord_id`` has never signed in. The caller is responsible for handling a
869 409 (event not scheduled) or 400 (role kind missing character/class/role) ``APIError``.
870 """
871 response = await self._request(
872 "PUT", f"{self._guild(guild_id)}/events/{event_id}/signups/by-discord/{discord_id}", body=data
873 )
874 return _parse(Signup.model_validate, response)
875
[docs]
876 async def list_upcoming_events(self) -> list[EventSummary]:
877 """Upcoming guild events, soonest first (the public ``/api/events`` list; also materializes repeats)."""
878 data = await self._request("GET", "/api/events", params={"when": "upcoming"})
879 return _parse(_EVENTS.validate_python, data)
880
[docs]
881 async def get_event(self, event_id: UUID) -> EventSummary:
882 """One event's headline fields (kind, title, ...), via the public ``/api/events/{id}`` GET.
883
884 Raises ``NotFoundError`` if ``event_id`` is unknown. The response is actually ``EventDetail`` (a superset
885 of ``EventSummary``, e.g. with the roster); validating as ``EventSummary`` keeps callers that only need the
886 headline fields decoupled from that extra shape.
887 """
888 data = await self._request("GET", f"/api/events/{event_id}")
889 return _parse(EventSummary.model_validate, data)
890
[docs]
891 async def get_recruiting(self) -> Recruiting:
892 """What roles and classes the guild is recruiting for (the public ``/api/recruiting`` GET)."""
893 data = await self._request("GET", "/api/recruiting")
894 return _parse(Recruiting.model_validate, data)
895
[docs]
896 async def list_addons(self) -> list[AddonSchema]:
897 """Every recommended addon, by name (the public ``/api/addons`` GET)."""
898 data = await self._request("GET", "/api/addons")
899 return _parse(_ADDONS.validate_python, data)
900
[docs]
901 async def list_weekly_board_events(self, guild_id: int, start: datetime, end: datetime) -> list[WeeklyBoardEvent]:
902 """Scheduled events starting in ``[start, end)``, soonest first, with their forum thread id and sign-ups."""
903 data = await self._request(
904 "GET",
905 f"{self._guild(guild_id)}/weekly-board/events",
906 params={"start": start.isoformat(), "end": end.isoformat()},
907 )
908 return _parse(_WEEKLY_BOARD_EVENTS.validate_python, data)
909
[docs]
910 async def set_weekly_board_message(self, guild_id: int, event_id: UUID, message: WeeklyBoardMessage) -> None:
911 """Record ``message`` as ``event_id``'s weekly-board card, so the event sync keeps its sign-ups current."""
912 await self._request("PUT", f"{self._guild(guild_id)}/weekly-board/events/{event_id}/message", body=message)
913
914 # --- Live status
915
[docs]
916 async def report_discord_live(self, guild_id: int, report: DiscordLiveReport) -> None:
917 """Push the current voice/presence snapshot for ``guild_id``."""
918 await self._request("PUT", f"{self._guild(guild_id)}/live", body=report)
919
[docs]
920 async def put_guild_roles(self, guild_id: int, roles: list[GuildRoleIn]) -> None:
921 """Replace ``guild_id``'s full role set (excluding ``@everyone``, dropped by the caller)."""
922 await self._request("PUT", f"{self._guild(guild_id)}/roles", body=GuildRolesReplace(roles=roles))
923
924 # --- Attendance
925
[docs]
926 async def report_voice_presence(self, guild_id: int, report: VoicePresenceReport) -> None:
927 """Push cumulative voice minutes per member for one event so far.
928
929 Idempotent: the API keeps ``max(stored, reported)`` per member, so a repeated or restart-reset push never
930 lowers the stored total.
931 """
932 await self._request("PUT", f"{self._guild(guild_id)}/attendance/voice", body=report)
933
[docs]
934 async def get_voice_presence(self, guild_id: int, event_id: UUID) -> VoicePresenceReport:
935 """Currently stored cumulative voice minutes per member for ``event_id``, to resume tracking after a restart."""
936 data = await self._request("GET", f"{self._guild(guild_id)}/attendance/voice/{event_id}")
937 return _parse(VoicePresenceReport.model_validate, data)
938
[docs]
939 async def put_member_profiles(
940 self, guild_id: int, profiles: list[MemberProfileIn], departed_ids: list[int]
941 ) -> None:
942 """Push linked members' current Discord profiles and report linked members who've left."""
943 await self._request(
944 "PUT",
945 f"{self._guild(guild_id)}/member-profiles",
946 body=MemberProfilesReplace(profiles=profiles, departed_ids=departed_ids),
947 )
948
949 # --- Signup notices
950
[docs]
951 async def list_signup_notices(self, guild_id: int) -> SignupNoticesPage:
952 """Members needing a new notice posted, and posted notices whose message is now stale."""
953 data = await self._request("GET", f"{self._guild(guild_id)}/signup-notices")
954 return _parse(SignupNoticesPage.model_validate, data)
955
[docs]
956 async def ack_signup_notice(self, guild_id: int, member_id: int, ack: SignupNoticeAck) -> None:
957 """Confirm the bot's message for ``member_id`` now reflects their current roster state."""
958 await self._request("POST", f"{self._guild(guild_id)}/signup-notices/{member_id}/ack", body=ack)
959
[docs]
960 async def confirm_roster_from_notice(
961 self, guild_id: int, member_id: int, request: ConfirmByDiscordRequest
962 ) -> MemberListing:
963 """Confirm site member ``member_id`` on the roster, with the acting GM identified by Discord id."""
964 data = await self._request(
965 "PUT", f"{self._guild(guild_id)}/signup-notices/{member_id}/roster-confirmation", body=request
966 )
967 return _parse(MemberListing.model_validate, data)
968
[docs]
969 async def unconfirm_roster_from_notice(
970 self, guild_id: int, member_id: int, request: ConfirmByDiscordRequest
971 ) -> MemberListing:
972 """Clear site member ``member_id``'s roster confirmation, with the acting GM identified by Discord id."""
973 data = await self._request(
974 "DELETE", f"{self._guild(guild_id)}/signup-notices/{member_id}/roster-confirmation", body=request
975 )
976 return _parse(MemberListing.model_validate, data)
977
978 # --- Role resets
979
[docs]
980 async def list_role_resets(self, guild_id: int) -> list[RoleResetCandidate]:
981 """Pending Discord role resets owed after a site account deletion, oldest first, capped at 50."""
982 data = await self._request("GET", f"{self._guild(guild_id)}/role-resets")
983 return _parse(_ROLE_RESETS.validate_python, data)
984
[docs]
985 async def ack_role_reset(self, guild_id: int, reset_id: UUID) -> None:
986 """Confirm the bot stripped this member's roles (or found them no longer in the guild)."""
987 await self._request("POST", f"{self._guild(guild_id)}/role-resets/{reset_id}/ack")
988
989 # --- Badges
990
[docs]
991 async def sync_badges(self, guild_id: int) -> BadgeSyncReport:
992 """Recompute every member's badges, award newly earned ones, and report role state + new announcements."""
993 data = await self._request("GET", f"{self._guild(guild_id)}/badges/sync")
994 return _parse(BadgeSyncReport.model_validate, data)
995
[docs]
996 async def ack_badge(self, guild_id: int, ack: BadgeAck) -> None:
997 """Confirm one member's badge announcement posted, so ``sync_badges`` stops reporting it as pending."""
998 await self._request("POST", f"{self._guild(guild_id)}/badges/ack", body=ack)
999
1000 # --- Characters
1001
[docs]
1002 async def search_characters(self, query: str | None = None) -> list[CharacterSummary]:
1003 """The guild roster (``query=None``), or up to 25 stored characters matching ``query``, roster first.
1004
1005 ``query`` needs 2+ characters (the public ``/api/characters/`` GET's ``q``).
1006 """
1007 params: dict[str, Any] = {}
1008 if query is not None:
1009 params["q"] = query
1010 data = await self._request("GET", "/api/characters/", params=params)
1011 return _parse(_CHARACTER_SUMMARIES.validate_python, data)
1012
[docs]
1013 async def get_character(self, slug: str) -> CharacterPage:
1014 """One character by its ``name-surname`` slug (the public ``/api/characters/{slug}`` GET).
1015
1016 Raises ``NotFoundError`` if Battle.net has no such character, or ``APIError`` (status 503) if Battle.net
1017 didn't answer and the character was never stored.
1018 """
1019 data = await self._request("GET", f"/api/characters/{slug}")
1020 return _parse(CharacterPage.model_validate, data)
1021
[docs]
1022 async def sync_roster(self, guild_id: int) -> RosterSyncReport:
1023 """Reconcile the website's character roster with the guild's current Discord/addon data.
1024
1025 Refreshes up to 8 stale Battle.net profiles per call; safe to call repeatedly. Raises ``NotFoundError`` for
1026 a non-site ``guild_id``, or ``APIError`` (status 503) if Battle.net is unconfigured or down.
1027 """
1028 data = await self._request("POST", f"{self._guild(guild_id)}/characters/sync")
1029 return _parse(RosterSyncReport.model_validate, data)
1030
[docs]
1031 async def get_crafters(
1032 self, guild_id: int, *, q: str | None = None, profession: str | None = None
1033 ) -> GuildCrafters:
1034 """Characters that know a recipe matching ``q`` (recipe or profession substring) / ``profession``.
1035
1036 Same semantics as the member route (``GET /api/guild/crafters``), but keyed by ``guild_id`` for the bot.
1037 Raises ``NotFoundError`` for a non-site ``guild_id``, or if the site hasn't deployed this route yet.
1038 """
1039 params: dict[str, Any] = {}
1040 if q is not None:
1041 params["q"] = q
1042 if profession is not None:
1043 params["profession"] = profession
1044 data = await self._request("GET", f"{self._guild(guild_id)}/crafters", params=params)
1045 return _parse(GuildCrafters.model_validate, data)
1046
1047 # --- Character milestones
1048
[docs]
1049 async def list_pending_milestones(self, guild_id: int) -> list[CharacterMilestone]:
1050 """Level 40/60 milestones not yet posted to Discord, oldest first.
1051
1052 Raises ``NotFoundError`` for a non-site ``guild_id``.
1053 """
1054 data = await self._request("GET", f"{self._guild(guild_id)}/characters/milestones/pending")
1055 return _parse(_PENDING_MILESTONES.validate_python, data)
1056
[docs]
1057 async def mark_milestone_posted(self, guild_id: int, milestone_id: UUID, message_id: int | None) -> None:
1058 """Record that ``milestone_id`` posted to Discord as ``message_id``.
1059
1060 Raises ``NotFoundError`` for an unknown milestone or a non-site ``guild_id``.
1061 """
1062 await self._request(
1063 "POST",
1064 f"{self._guild(guild_id)}/characters/milestones/{milestone_id}/posted",
1065 body=MilestonePosted(discord_message_id=message_id),
1066 )
1067
1068 # --- Guild hub announcements
1069
[docs]
1070 async def list_pending_announcements(self, guild_id: int) -> list[PendingAnnouncement]:
1071 """Discord-queued announcements not yet posted, oldest first."""
1072 data = await self._request("GET", f"{self._guild(guild_id)}/announcements/pending")
1073 return _parse(PendingAnnouncementsPage.model_validate, data).items
1074
[docs]
1075 async def mark_announcement_posted(self, guild_id: int, announcement_id: UUID, message_id: int) -> None:
1076 """Record that ``announcement_id`` posted to Discord as ``message_id``."""
1077 await self._request(
1078 "POST",
1079 f"{self._guild(guild_id)}/announcements/{announcement_id}/posted",
1080 body=AnnouncementPosted(message_id=message_id),
1081 )
1082
1083 # --- Group voice (LFG)
1084
[docs]
1085 async def create_group(self, guild_id: int, create: GroupSessionCreate) -> GroupSessionSchema:
1086 """Record a group channel the bot just created. Raises ``APIError`` (409) if the channel already has one."""
1087 data = await self._request("POST", f"{self._guild(guild_id)}/groups", body=create)
1088 return _parse(GroupSessionSchema.model_validate, data)
1089
[docs]
1090 async def list_open_groups(self, guild_id: int) -> list[GroupSessionSchema]:
1091 """Every group session with no ``ended_at`` yet, oldest first, so a restarted bot can resume counters."""
1092 data = await self._request("GET", f"{self._guild(guild_id)}/groups/open")
1093 return _parse(_GROUP_SESSIONS.validate_python, data)
1094
[docs]
1095 async def get_group(self, guild_id: int, session_id: UUID) -> GroupSessionSchema:
1096 """One group session. Raises ``NotFoundError`` if unknown."""
1097 data = await self._request("GET", f"{self._guild(guild_id)}/groups/{session_id}")
1098 return _parse(GroupSessionSchema.model_validate, data)
1099
[docs]
1100 async def update_group(self, guild_id: int, session_id: UUID, changes: GroupSessionUpdate) -> GroupSessionSchema:
1101 """Apply only the fields set on ``changes``; ``channel_name=None`` is ignored, never clears it."""
1102 data = await self._request(
1103 "PATCH", f"{self._guild(guild_id)}/groups/{session_id}", body=changes, exclude_unset=True
1104 )
1105 return _parse(GroupSessionSchema.model_validate, data)
1106
[docs]
1107 async def report_group_presence(self, guild_id: int, session_id: UUID, report: GroupPresenceReport) -> None:
1108 """Push cumulative per-member and per-pair minutes so far; the API keeps ``max(stored, reported)``."""
1109 await self._request("PUT", f"{self._guild(guild_id)}/groups/{session_id}/presence", body=report)
1110
[docs]
1111 async def close_group(self, guild_id: int, session_id: UUID, close: GroupSessionClose) -> None:
1112 """End a group session with final presence and transcript. Idempotent: closing twice merges presence only."""
1113 await self._request("POST", f"{self._guild(guild_id)}/groups/{session_id}/close", body=close)
1114
[docs]
1115 async def purge_group_transcripts(self, guild_id: int) -> GroupTranscriptPurge:
1116 """Delete transcripts of sessions ended more than the retention window ago. Called once a day."""
1117 data = await self._request("POST", f"{self._guild(guild_id)}/groups/purge")
1118 return _parse(GroupTranscriptPurge.model_validate, data)
1119
1120 # --- Items
1121
[docs]
1122 async def search_items(
1123 self, query: str, *, page: int = 1, qualities: Sequence[str] = (), slot: str | None = None
1124 ) -> ItemSearchPage:
1125 """Items with a whole word of ``query`` in their name (the public ``/api/items`` GET).
1126
1127 Battle.net matches English word stems (``bless`` finds Blessed, ``thund`` finds nothing); search on submit,
1128 never as-you-type. 503 if Battle.net isn't configured or didn't answer.
1129 """
1130 params: dict[str, Any] = {"q": query, "page": page}
1131 if qualities:
1132 params["quality"] = list(qualities)
1133 if slot is not None:
1134 params["slot"] = slot
1135 data = await self._request("GET", "/api/items", params=params)
1136 return _parse(ItemSearchPage.model_validate, data)
1137
[docs]
1138 async def get_item(self, item_id: int) -> Item:
1139 """One item with its tooltip (the public ``/api/items/{id}`` GET).
1140
1141 Raises ``NotFoundError`` for an unknown item, or ``APIError`` (status 503) if Battle.net isn't configured
1142 or didn't answer.
1143 """
1144 data = await self._request("GET", f"/api/items/{item_id}")
1145 return _parse(Item.model_validate, data)
1146
1147 # --- Achievements
1148
[docs]
1149 async def list_achievement_categories(self) -> list[AchievementCategoryTree]:
1150 """Every root achievement category with its subcategories (the public ``/api/achievements/categories`` GET).
1151
1152 503 if Battle.net isn't configured or didn't answer.
1153 """
1154 data = await self._request("GET", "/api/achievements/categories")
1155 return _parse(_ACHIEVEMENT_CATEGORIES.validate_python, data)
1156
[docs]
1157 async def get_achievement_category(self, category_id: int) -> AchievementCategorySchema:
1158 """One achievement category and its achievements (the public ``/api/achievements/categories/{id}`` GET).
1159
1160 Raises ``NotFoundError`` for an unknown category, or ``APIError`` (status 503) if Battle.net isn't
1161 configured or didn't answer.
1162 """
1163 data = await self._request("GET", f"/api/achievements/categories/{category_id}")
1164 return _parse(AchievementCategorySchema.model_validate, data)
1165
[docs]
1166 async def get_achievement(self, achievement_id: int) -> AchievementSchema:
1167 """One achievement by its game ID (the public ``/api/achievements/{id}`` GET).
1168
1169 Raises ``NotFoundError`` for an unknown achievement, or ``APIError`` (status 503) if Battle.net isn't
1170 configured or didn't answer.
1171 """
1172 data = await self._request("GET", f"/api/achievements/{achievement_id}")
1173 return _parse(AchievementSchema.model_validate, data)
1174
1175 # --- Quests
1176
[docs]
1177 async def search_quests(self, query: str, *, limit: int = 10) -> list[QuestSearchResult]:
1178 """Quests with ``query`` in their title, case-insensitive, best matches first (public ``/api/quests/search``).
1179
1180 503 if Battle.net isn't configured or didn't answer.
1181 """
1182 data = await self._request("GET", "/api/quests/search", params={"q": query, "limit": limit})
1183 return _parse(_QUEST_SEARCH_RESULTS.validate_python, data)
1184
[docs]
1185 async def get_quest(self, quest_id: int) -> QuestSchema:
1186 """One quest by its game ID (the public ``/api/quests/{id}`` GET).
1187
1188 Raises ``NotFoundError`` for an unknown quest, or ``APIError`` (status 503) if Battle.net isn't configured
1189 or didn't answer.
1190 """
1191 data = await self._request("GET", f"/api/quests/{quest_id}")
1192 return _parse(QuestSchema.model_validate, data)
1193
1194 # --- Beasts
1195
[docs]
1196 async def search_beasts(
1197 self, query: str | None = None, *, family_id: int | None = None, limit: int | None = None
1198 ) -> list[BeastSchema]:
1199 """Tameable beasts matching ``query`` (a substring, prefix match sorting first), sorted by name.
1200
1201 The public ``/api/beasts`` GET. The first call per API process builds the whole catalog from Battle.net
1202 media lookups and can take 10-20 seconds; callers on a tight budget (autocomplete) should apply their own
1203 timeout. 503 if Battle.net isn't configured or didn't answer.
1204 """
1205 params: dict[str, Any] = {}
1206 if query is not None:
1207 params["q"] = query
1208 if family_id is not None:
1209 params["family_id"] = family_id
1210 if limit is not None:
1211 params["limit"] = limit
1212 data = await self._request("GET", "/api/beasts", params=params)
1213 return _parse(_BEASTS.validate_python, data)
1214
[docs]
1215 async def get_beast(self, creature_id: int) -> BeastSchema:
1216 """One tameable beast by its Battle.net creature id (the public ``/api/beasts/{id}`` GET).
1217
1218 Raises ``NotFoundError`` if that creature isn't a tameable beast, or ``APIError`` (status 503) if
1219 Battle.net isn't configured or didn't answer.
1220 """
1221 data = await self._request("GET", f"/api/beasts/{creature_id}")
1222 return _parse(BeastSchema.model_validate, data)
1223
[docs]
1224 async def list_beast_families(self) -> list[BeastFamilySchema]:
1225 """Every beast family among tameable beasts, with its count, sorted by name (public ``/api/beasts/families``).
1226
1227 503 if Battle.net isn't configured or didn't answer.
1228 """
1229 data = await self._request("GET", "/api/beasts/families")
1230 return _parse(_BEAST_FAMILIES.validate_python, data)
1231
1232 # --- Recipes
1233
[docs]
1234 async def get_recipe(self, recipe_id: int) -> RecipeDetail:
1235 """One recipe by its Battle.net game ID: what it makes, its reagents, and guild crafters.
1236
1237 The public ``/api/recipes/{id}`` GET. Raises ``NotFoundError`` for an unknown recipe, or ``APIError``
1238 (status 503) if Battle.net isn't configured or didn't answer.
1239 """
1240 data = await self._request("GET", f"/api/recipes/{recipe_id}")
1241 return _parse(RecipeDetail.model_validate, data)
1242
1243 # --- Auctions
1244
[docs]
1245 async def get_item_price(self, item_id: int) -> ItemAuctionPrice:
1246 """``item_id``'s current lowest price across the faction's houses, plus a 14-day trend (public).
1247
1248 Always 200, even for an unknown or unlisted item (``unit_price`` is ``None``, ``houses``/``trend`` empty).
1249 """
1250 data = await self._request("GET", f"/api/auctions/prices/{item_id}")
1251 return _parse(ItemAuctionPrice.model_validate, data)
1252
[docs]
1253 async def sync_auctions(self, guild_id: int) -> AuctionSyncReport:
1254 """Fetch the faction's auction houses, rebuild prices, update history, and queue new alerts.
1255
1256 Raises ``NotFoundError`` for a non-site ``guild_id``, or ``APIError`` (status 503) if Battle.net didn't
1257 answer.
1258 """
1259 data = await self._request("POST", f"{self._guild(guild_id)}/auctions/sync")
1260 return _parse(AuctionSyncReport.model_validate, data)
1261
[docs]
1262 async def pending_auction_alerts(self, guild_id: int) -> list[AuctionAlertSchema]:
1263 """Queued price alerts not yet sent, oldest first. Raises ``NotFoundError`` for a non-site ``guild_id``."""
1264 data = await self._request("GET", f"{self._guild(guild_id)}/auctions/alerts/pending")
1265 return _parse(_AUCTION_ALERTS.validate_python, data)
1266
[docs]
1267 async def ack_auction_alert(self, guild_id: int, alert_id: UUID) -> None:
1268 """Confirm ``alert_id`` was sent (or couldn't be), so ``pending_auction_alerts`` stops reporting it."""
1269 await self._request("POST", f"{self._guild(guild_id)}/auctions/alerts/{alert_id}/sent")
1270
[docs]
1271 async def list_auction_watches(self, guild_id: int, user_id: int) -> list[AuctionWatch]:
1272 """``user_id``'s price watches. Raises ``NotFoundError`` if their Discord account isn't linked."""
1273 data = await self._request("GET", f"{self._guild(guild_id)}/members/{user_id}/auction-watches")
1274 return _parse(_AUCTION_WATCHES.validate_python, data)
1275
[docs]
1276 async def upsert_auction_watch(self, guild_id: int, user_id: int, watch: AuctionWatchCreate) -> AuctionWatch:
1277 """Add or replace ``user_id``'s watch on ``watch.item_id``.
1278
1279 Raises ``NotFoundError`` if their Discord account isn't linked, or ``APIError`` (status 409) at
1280 :data:`MAX_AUCTION_WATCHES` new watches.
1281 """
1282 data = await self._request("POST", f"{self._guild(guild_id)}/members/{user_id}/auction-watches", body=watch)
1283 return _parse(AuctionWatch.model_validate, data)
1284
[docs]
1285 async def delete_auction_watch(self, guild_id: int, user_id: int, item_id: int) -> None:
1286 """Remove ``user_id``'s watch on ``item_id``.
1287
1288 Raises ``NotFoundError`` if their Discord account isn't linked, or if they have no watch on that item.
1289 """
1290 await self._request("DELETE", f"{self._guild(guild_id)}/members/{user_id}/auction-watches/{item_id}")
1291
1292 # --- Sim jobs
1293
[docs]
1294 async def create_sim_job(self, guild_id: int, request: SimRequest) -> SimJob:
1295 """Queue a gear-swap sim (``POST .../sims``); 202 while it's queued.
1296
1297 Raises ``APIError`` (400) for an unresolvable character/item/spec, or (429) past
1298 :data:`MAX_QUEUED_SIMS_PER_MEMBER` queued/running jobs for ``request.requested_by``.
1299 """
1300 data = await self._request("POST", f"{self._guild(guild_id)}/sims", body=request)
1301 return _parse(SimJob.model_validate, data)
1302
[docs]
1303 async def get_sim_job(self, guild_id: int, job_id: UUID) -> SimJob:
1304 """Poll one sim job's current status/result. Raises ``NotFoundError`` for an unknown job."""
1305 data = await self._request("GET", f"{self._guild(guild_id)}/sims/{job_id}")
1306 return _parse(SimJob.model_validate, data)
1307
1308 # --- Market report
1309
[docs]
1310 async def get_market_report(self, guild_id: int, *, kind: MarketReportKind = "daily") -> MarketReport | None:
1311 """The guild's current ``kind`` market report, or ``None`` before the first auction house feed (404)."""
1312 try:
1313 data = await self._request("GET", f"{self._guild(guild_id)}/market-report", params={"kind": kind})
1314 except NotFoundError:
1315 return None
1316 return _parse(MarketReport.model_validate, data)