from datetime import datetime from typing import Any, Dict, List from zoneinfo import ZoneInfo, available_timezones from bson import ObjectId from discord import AutocompleteContext, OptionChoice from pymongo import ASCENDING from typing_extensions import deprecated from modules.database import col_events, col_stages, col_users async def autocomplete_timezones(ctx: AutocompleteContext) -> List[str]: """Return available timezones""" return sorted(list(available_timezones())) @deprecated("Messages will not be displayed on per-user basis") async def autocomplete_languages(ctx: AutocompleteContext) -> List[str]: """Return locales supported by the bot""" return ctx.bot.locales.keys() async def autocomplete_active_events(ctx: AutocompleteContext) -> List[OptionChoice]: """Return list of active events""" query: Dict[str, Any] = { "ended": None, "ends": {"$gt": datetime.now(tz=ZoneInfo("UTC"))}, "is_cancelled": False, } event_names: List[OptionChoice] = [] async for result in col_events.find(query): event_names.append(OptionChoice(result["name"], str(result["_id"]))) return event_names async def autocomplete_user_available_events(ctx: AutocompleteContext) -> List[OptionChoice]: """Return list of active events user can register in""" return await autocomplete_active_events(ctx) async def autocomplete_user_registered_events(ctx: AutocompleteContext) -> List[OptionChoice]: """Return list of active events user is registered in""" utc_now: datetime = datetime.now(tz=ZoneInfo("UTC")) pipeline: List[Dict[str, Any]] = [ {"$match": {"id": ctx.interaction.user.id}}, { "$lookup": { "from": "events", "let": {"event_ids": "$registered_event_ids"}, "pipeline": [ { "$match": { "$expr": { "$and": [ {"$in": ["$_id", "$$event_ids"]}, {"$eq": ["$ended", None]}, {"$gt": ["$ends", utc_now]}, {"$gt": ["$starts", utc_now]}, {"$eq": ["$is_cancelled", False]}, ] } } } ], "as": "registered_events", } }, {"$match": {"registered_events.0": {"$exists": True}}}, ] event_names: List[OptionChoice] = [] async with await col_users.aggregate(pipeline) as cursor: async for result in cursor: for registered_event in result["registered_events"]: event_names.append(OptionChoice(registered_event["name"], str(registered_event["_id"]))) return event_names async def autocomplete_event_stages(ctx: AutocompleteContext) -> List[OptionChoice]: """Return list of stages of the event""" event_id: str | None = ctx.options["event"] if event_id is None: return [] query: Dict[str, Any] = { "event_id": ObjectId(event_id), } event_stages: List[OptionChoice] = [] async for result in col_stages.find(query).sort([("sequence", ASCENDING)]): event_stages.append( OptionChoice( f"{result['sequence']+1} ({result['question'] if len(result['question']) < 50 else result['question'][:47] + '...'})", str(result["_id"]), ) ) return event_stages