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
13 changes: 13 additions & 0 deletions src/sidequest_bot/lib/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,16 @@ def user_line(user: discord.Member | discord.User) -> str:
def truncate(text: str, limit: int = 1024) -> str:
"""Trim ``text`` to fit an embed field (default 1024 chars)."""
return text if len(text) <= limit else text[: limit - 1] + "…"


def link_button(label: str, url: str) -> discord.ui.Button:
"""A link-style button; needs no callback, so it works in views with any timeout, including none."""
return discord.ui.Button(style=discord.ButtonStyle.link, label=label, url=url)


def link_view(*buttons: discord.ui.Button, timeout: float | None = None) -> discord.ui.View:
"""A view holding only link buttons, in order."""
view = discord.ui.View(timeout=timeout)
for button in buttons:
view.add_item(button)
return view
48 changes: 35 additions & 13 deletions src/sidequest_bot/plugins/achievements.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
import logging
from datetime import datetime, timedelta
from http import HTTPStatus
from typing import TYPE_CHECKING
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, make_embed, truncate
from sidequest_bot.lib.embeds import Colors, link_button, link_view, make_embed, truncate

if TYPE_CHECKING:
from collections.abc import Sequence
Expand All @@ -29,6 +29,7 @@
logger = logging.getLogger(__name__)

ACHIEVEMENT_PAGE_URL = "https://sidequest-guild.com/achievements/detail/?id={achievement_id}"
ACHIEVEMENT_WOWHEAD_URL = "https://www.wowhead.com/forever/achievement={achievement_id}"
DESCRIPTION_LIMIT = 4096
MAX_AUTOCOMPLETE_RESULTS = 25
MAX_OTHER_MATCHES = 5
Expand All @@ -54,14 +55,22 @@ def build_achievement_embed(achievement: AchievementSchema) -> discord.Embed:
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 achievement_link_buttons(achievement_id: int) -> list[discord.ui.Button]:
"""Site + Wowhead link buttons for one achievement."""
return [
link_button("Site", ACHIEVEMENT_PAGE_URL.format(achievement_id=achievement_id)),
link_button("Wowhead", ACHIEVEMENT_WOWHEAD_URL.format(achievement_id=achievement_id)),
]


def achievement_link_view(achievement_id: int) -> discord.ui.View:
"""A view holding just the achievement's link buttons, for replies with no other matches to offer."""
return link_view(*achievement_link_buttons(achievement_id))


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")
Expand Down Expand Up @@ -150,16 +159,29 @@ async def callback(self, interaction: discord.Interaction[SideQuestBot]) -> None
if isinstance(result, str):
await interaction.response.send_message(result, ephemeral=True)
return
await interaction.response.edit_message(embed=result, view=self.view)
view = cast("AchievementMatchView", self.view)
view.set_achievement(achievement_id)
await interaction.response.edit_message(embed=result, view=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."""
"""Link buttons for the shown achievement plus a select menu of up to :data:`MAX_OTHER_MATCHES` other matches.

def __init__(self, matches: Sequence[AchievementSummary]) -> None:
Picking another match swaps the shown embed and repoints the link buttons at it.
"""

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

def set_achievement(self, achievement_id: int) -> None:
"""Repoint the link buttons at ``achievement_id``."""
self._site_button.url = ACHIEVEMENT_PAGE_URL.format(achievement_id=achievement_id)
self._wowhead_button.url = ACHIEVEMENT_WOWHEAD_URL.format(achievement_id=achievement_id)


class AchievementsCog(commands.Cog):
Expand All @@ -179,7 +201,7 @@ async def achievement_command(self, interaction: discord.Interaction[SideQuestBo
if isinstance(result, str):
await interaction.followup.send(result, ephemeral=True)
return
await interaction.followup.send(embed=result)
await interaction.followup.send(embed=result, view=achievement_link_view(int(name)))
return
try:
achievements = await _cache.get(self.bot.api)
Expand All @@ -205,9 +227,9 @@ async def achievement_command(self, interaction: discord.Interaction[SideQuestBo
await interaction.followup.send(result, ephemeral=True)
return
if others:
await interaction.followup.send(embed=result, view=AchievementMatchView(others))
await interaction.followup.send(embed=result, view=AchievementMatchView(best.id, others))
else:
await interaction.followup.send(embed=result)
await interaction.followup.send(embed=result, view=achievement_link_view(best.id))


async def setup(bot: SideQuestBot) -> None:
Expand Down
16 changes: 9 additions & 7 deletions src/sidequest_bot/plugins/auctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
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
from sidequest_bot.lib.embeds import Colors, link_button, link_view, make_embed, truncate
from sidequest_bot.plugins.items import ITEM_PAGE_URL, item_quality_color

if TYPE_CHECKING:
Expand Down Expand Up @@ -94,11 +94,8 @@ def format_price(copper: int) -> str:
def build_alert_embed(alert: AuctionAlertSchema) -> discord.Embed:
"""DM embed for one price alert: item name/link, price vs the member's max, quantity and house."""
name = alert.item_name or f"Item {alert.item_id}"
embed = make_embed(
title=f"{name} is on sale",
description=f"[View on the site]({ITEM_PAGE_URL.format(item_id=alert.item_id)})",
color=Colors.GOLD,
)
embed = make_embed(title=f"{name} is on sale", color=Colors.GOLD)
embed.url = ITEM_PAGE_URL.format(item_id=alert.item_id)
if alert.icon_url:
embed.set_thumbnail(url=alert.icon_url)
embed.add_field(
Expand All @@ -109,6 +106,11 @@ def build_alert_embed(alert: AuctionAlertSchema) -> discord.Embed:
return embed


def build_alert_view(alert: AuctionAlertSchema) -> discord.ui.View:
"""A view holding the DM's "View on the site" link button."""
return link_view(link_button("View on the site", ITEM_PAGE_URL.format(item_id=alert.item_id)))


def build_price_embed(item: Item, price: ItemAuctionPrice) -> discord.Embed:
"""``/price``'s embed: lowest price and where, total listed, per-house lines, and the 14-day low/high."""
embed = make_embed(title=item.name, color=item_quality_color(item.quality))
Expand Down Expand Up @@ -227,7 +229,7 @@ async def _send_alert(self, guild: discord.Guild, alert: AuctionAlertSchema) ->
logger.info("Could not find Discord user %s for auction alert %s", alert.discord_user_id, alert.id)
else:
try:
await user.send(embed=build_alert_embed(alert))
await user.send(embed=build_alert_embed(alert), view=build_alert_view(alert))
except discord.Forbidden:
logger.info("Could not DM auction alert to %s: DMs are closed", alert.discord_user_id)
except discord.HTTPException:
Expand Down
19 changes: 11 additions & 8 deletions src/sidequest_bot/plugins/badges.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from sidequest_bot.api_client import APIError, NotFoundError
from sidequest_bot.bot import SideQuestBot # noqa: TC001 # discord.py evaluates app-command annotations at runtime
from sidequest_bot.lib.embeds import Colors, make_embed
from sidequest_bot.lib.embeds import Colors, link_button, link_view, make_embed
from sidequest_bot.lib.roles import grant_block_reason
from sidequest_common.schemas import BadgeAck, GuildConfigUpdate
from sidequest_common.schemas.badges import BADGE_LIST, BADGES, BadgeDefinition
Expand Down Expand Up @@ -95,8 +95,8 @@ def badge_grant_reason(badge_id: str) -> str:
return f"Earned {name} on sidequest-guild.com"


def build_badge_embed(announcement: PendingBadgeAnnouncement, profile_url: str, *, with_icon: bool) -> discord.Embed:
"""Gold embed for one newly earned badge, with a link to the Hall of Heroes.
def build_badge_embed(announcement: PendingBadgeAnnouncement, *, with_icon: bool) -> discord.Embed:
"""Gold embed for one newly earned badge.

``with_icon``: the badge's image rides along as an attachment and shows as the thumbnail; otherwise the
definition's emoji leads the title.
Expand All @@ -110,10 +110,14 @@ def build_badge_embed(announcement: PendingBadgeAnnouncement, profile_url: str,
)
if with_icon:
embed.set_thumbnail(url=f"attachment://{BADGE_ICON_FILENAME}")
embed.add_field(name="Hall of Heroes", value=f"[View the Hall of Heroes]({profile_url})", inline=False)
return embed


def build_badge_view(profile_url: str) -> discord.ui.View:
"""A view holding the announcement's "Hall of Heroes" link button."""
return link_view(link_button("Hall of Heroes", profile_url))


async def create_badge_role(guild: discord.Guild, badge: BadgeDefinition) -> discord.Role | None:
"""Create ``badge``'s Discord role: not hoisted, not mentionable, colored per the badge definition.

Expand Down Expand Up @@ -290,14 +294,13 @@ async def _announce_one(
self, guild: discord.Guild, channel: discord.TextChannel, announcement: PendingBadgeAnnouncement
) -> bool:
icon = badge_icon(announcement.badge_id)
embed = build_badge_embed(
announcement, hall_of_heroes_url(_web_settings().BASE_URL), with_icon=icon is not None
)
embed = build_badge_embed(announcement, with_icon=icon is not None)
view = build_badge_view(hall_of_heroes_url(_web_settings().BASE_URL))
mention_target = guild.get_member(announcement.discord_id) or discord.Object(id=announcement.discord_id)
allowed = discord.AllowedMentions(users=[mention_target])
files = [discord.File(io.BytesIO(icon), BADGE_ICON_FILENAME)] if icon is not None else []
try:
await channel.send(embed=embed, files=files, allowed_mentions=allowed)
await channel.send(embed=embed, view=view, files=files, allowed_mentions=allowed)
except discord.HTTPException:
logger.warning(
"Failed to post badge announcement for %s in guild %s",
Expand Down
10 changes: 7 additions & 3 deletions src/sidequest_bot/plugins/characters.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from sidequest_bot.api_client import APIError, CharacterPage, CharacterSummary, 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
from sidequest_bot.lib.embeds import Colors, link_button, link_view, make_embed, truncate

if TYPE_CHECKING:
from collections.abc import Sequence
Expand Down Expand Up @@ -161,10 +161,14 @@ def build_character_embed(character: CharacterPage) -> discord.Embed:
embed.add_field(name="Gear", value=build_gear_field(character.sheet.gear), inline=False)
if character.sheet is not None and character.sheet.hunter_pets:
embed.add_field(name="Pets", value=build_pets_field(character.sheet.hunter_pets), inline=False)
embed.add_field(name="Armory", value=f"[View on Armory]({ARMORY_URL.format(slug=character.slug)})", inline=False)
return embed


def character_link_view(slug: str) -> discord.ui.View:
"""A view holding the character's Armory link button."""
return link_view(link_button("View on Armory", ARMORY_URL.format(slug=slug)))


class CharactersCog(commands.Cog):
"""``/who`` character lookup."""

Expand Down Expand Up @@ -195,7 +199,7 @@ async def who_command(self, interaction: discord.Interaction[SideQuestBot], char
"Couldn't look up that character right now; try again shortly.", ephemeral=True
)
return
await interaction.followup.send(embed=build_character_embed(page))
await interaction.followup.send(embed=build_character_embed(page), view=character_link_view(page.slug))


async def setup(bot: SideQuestBot) -> None:
Expand Down
48 changes: 34 additions & 14 deletions src/sidequest_bot/plugins/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
import logging
import re
from http import HTTPStatus
from typing import TYPE_CHECKING
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, Item, ItemSummary, 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
from sidequest_bot.lib.embeds import Colors, link_button, link_view, make_embed, truncate

if TYPE_CHECKING:
from collections.abc import Sequence
Expand Down Expand Up @@ -66,15 +66,22 @@ def build_item_embed(item: Item) -> discord.Embed:
)
if item.icon_url:
embed.set_thumbnail(url=item.icon_url)
embed.add_field(
name="Links",
value=f"[Item page]({ITEM_PAGE_URL.format(item_id=item.item_id)}) • "
f"[Wowhead]({WOWHEAD_URL.format(item_id=item.item_id)})",
inline=False,
)
return embed


def item_link_buttons(item_id: int) -> list[discord.ui.Button]:
"""Item page + Wowhead link buttons for one item."""
return [
link_button("Item page", ITEM_PAGE_URL.format(item_id=item_id)),
link_button("Wowhead", WOWHEAD_URL.format(item_id=item_id)),
]


def item_link_view(item_id: int) -> discord.ui.View:
"""A view holding just the item's link buttons, for replies with no other matches to offer."""
return link_view(*item_link_buttons(item_id))


def match_option(match: ItemSummary) -> discord.SelectOption:
"""One search result as a select option, with quality/slot/ilvl as its description."""
return discord.SelectOption(
Expand Down Expand Up @@ -110,16 +117,29 @@ async def callback(self, interaction: discord.Interaction[SideQuestBot]) -> None
if isinstance(result, str):
await interaction.response.send_message(result, ephemeral=True)
return
await interaction.response.edit_message(embed=result, view=self.view)
view = cast("ItemMatchView", self.view)
view.set_item(item_id)
await interaction.response.edit_message(embed=result, view=view)


class ItemMatchView(discord.ui.View):
"""A select menu of up to :data:`MAX_OTHER_MATCHES` other search matches, swapping the shown embed on pick."""
"""Link buttons for the shown item plus a select menu of up to :data:`MAX_OTHER_MATCHES` other matches.

def __init__(self, matches: Sequence[ItemSummary]) -> None:
Picking another match swaps the shown embed and repoints the link buttons at it.
"""

def __init__(self, item_id: int, matches: Sequence[ItemSummary]) -> None:
super().__init__(timeout=180)
self._item_page_button, self._wowhead_button = item_link_buttons(item_id)
self._select = _ItemMatchSelect(matches)
self.add_item(self._select)
self.add_item(self._item_page_button)
self.add_item(self._wowhead_button)

def set_item(self, item_id: int) -> None:
"""Repoint the link buttons at ``item_id``."""
self._item_page_button.url = ITEM_PAGE_URL.format(item_id=item_id)
self._wowhead_button.url = WOWHEAD_URL.format(item_id=item_id)


class ItemsCog(commands.Cog):
Expand Down Expand Up @@ -151,9 +171,9 @@ async def item_command(self, interaction: discord.Interaction[SideQuestBot], nam
await interaction.followup.send(result, ephemeral=True)
return
if others:
await interaction.followup.send(embed=result, view=ItemMatchView(others))
await interaction.followup.send(embed=result, view=ItemMatchView(best.item_id, others))
else:
await interaction.followup.send(embed=result)
await interaction.followup.send(embed=result, view=item_link_view(best.item_id))

@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
Expand All @@ -176,7 +196,7 @@ async def on_message(self, message: discord.Message) -> None:
logger.warning("Item link unfurl failed for %s", item_id, exc_info=True)
continue
try:
await message.channel.send(embed=build_item_embed(item))
await message.channel.send(embed=build_item_embed(item), view=item_link_view(item_id))
except discord.HTTPException:
logger.warning("Failed to post item unfurl for %s in channel %s", item_id, message.channel.id)

Expand Down
Loading
Loading