Implemented bot endpoint with DB requests and other tweaks
This commit is contained in:
84
app/routers/bot.py
Normal file
84
app/routers/bot.py
Normal file
@@ -0,0 +1,84 @@
|
||||
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__)
|
||||
|
||||
|
||||
@bot_bp.route("/", methods=['GET'])
|
||||
async def get_online_bots_route():
|
||||
"""API endpoint to list bots (by name) currently online."""
|
||||
return jsonify(list(current_app.active_clients.keys()))
|
||||
|
||||
|
||||
@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]
|
||||
|
||||
# --- 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}")
|
||||
|
||||
|
||||
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 in current_app.active_clients:
|
||||
if client.active_token == target_token:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# query_params = dict(request.args)
|
||||
|
||||
# systems = await current_app.sys_db_h.find_systems(query_params)
|
||||
Reference in New Issue
Block a user