paper-dynasty-discord/utilities/autocomplete.py
2025-10-08 14:45:41 -05:00

102 lines
2.6 KiB
Python

"""
Autocomplete Utilities
Shared autocomplete functions for Discord slash commands.
"""
from typing import List
import discord
from discord import app_commands
from api_calls import db_get
from helpers import player_desc
async def cardset_autocomplete(
interaction: discord.Interaction,
current: str
) -> List[app_commands.Choice[str]]:
"""
Autocomplete for cardset names using fuzzy search.
Args:
interaction: Discord interaction object
current: Current input from user
Returns:
List of cardset name choices matching the current input
"""
if len(current) < 1:
return []
try:
# Search for cardsets using the /cardsets/search endpoint
search_results = await db_get(
'cardsets/search',
params=[('q', current), ('limit', 25)],
timeout=5
)
if not search_results or search_results.get('count', 0) == 0:
return []
# Get cardsets from search results
cardsets = search_results.get('cardsets', [])
# Create choices with cardset names
choices = [
app_commands.Choice(name=cardset['name'], value=cardset['name'])
for cardset in cardsets
if cardset.get('name')
]
return choices
except Exception:
# Silently fail on autocomplete errors to avoid disrupting user experience
return []
async def player_autocomplete(
interaction: discord.Interaction,
current: str
) -> List[app_commands.Choice[str]]:
"""
Autocomplete for player names using fuzzy search.
Args:
interaction: Discord interaction object
current: Current input from user
Returns:
List of player name choices matching the current input
"""
if len(current) < 2:
return []
try:
# Search for players using the /players/search endpoint
search_results = await db_get(
'players/search',
params=[('q', current), ('limit', 25), ('short_output', True), ('unique_names', True)],
timeout=5
)
if not search_results or search_results.get('count', 0) == 0:
return []
# Get players from search results
players = search_results.get('players', [])
# Create choices with player names
choices = [
app_commands.Choice(name=player['p_name'], value=player['p_name'])
for player in players
if player.get('p_name')
]
return choices
except Exception:
# Silently fail on autocomplete errors to avoid disrupting user experience
return []