import json from quart import Blueprint, jsonify, request, abort, current_app from werkzeug.exceptions import HTTPException from internal.types import ActiveClient from internal.db_wrappers import DiscordIdDbController bot_bp = Blueprint('bot', __name__) # ------- Discord Token Functions @bot_bp.route('/request_token', methods=['POST']) async def request_token_route(): """ API endpoint to request a token for a client. Expects 'client_id' in the JSON request body. """ try: request_data = await request.get_json() if not request_data or 'client_id' not in request_data: abort(400, "Missing 'client_id' in request body.") client_id = request_data['client_id'] print(f"Request received for client_id: {client_id}") # get the available IDs active_d_ids = await current_app.d_id_db_h.find_discord_ids(active_only=True) # init available IDs list avail_ids = [] # Init the selected ID selected_id = None # Check which IDs are currently in use by other bots for d_id in active_d_ids: if not find_token_in_active_clients(d_id.token): avail_ids.append(d_id) if not avail_ids: abort(404, "No available active Discord IDs found.") # --- Logic for selecting a preferred ID based on client_id (TODO) --- selected_id = avail_ids[0] current_app.active_clients[client_id].active_token = selected_id # --- End of logic for selecting a preferred ID --- return jsonify(selected_id.to_dict()) except Exception as e: print(f"Error in request_token_route: {e}") abort(500, f"An internal error occurred: {e}") @bot_bp.route('/tokens/', methods=['GET']) async def get_all_discord_tokens(): """ API endpoint to return all discord IDs """ try: # get the available IDs d_ids = await current_app.d_id_db_h.find_discord_ids(active_only=False) return jsonify([d_id.to_dict() for d_id in d_ids]) except Exception as e: print(f"Error in request_token_route: {e}") abort(500, f"An internal error occurred: {e}") # ------- Util Functions def find_token_in_active_clients(target_token: str) -> bool: """ Checks if a target_token exists in the active_token of any ActiveClient object in a list. Args: clients: A list of ActiveClient objects. target_token: The token string to search for. Returns: True if the token is found in any ActiveClient, False otherwise. """ for client_id in current_app.active_clients: if current_app.active_clients[client_id].active_token == target_token: return True return False # query_params = dict(request.args) # systems = await current_app.sys_db_h.find_systems(query_params)