import httpx import json from base_api import BaseAPI from config import Config app_config = Config() class RadioAPIClient(BaseAPI): """ A client wrapper for interacting with the Radio App Server API. Uses httpx for asynchronous HTTP requests. """ def __init__(self, base_url="http://localhost:5000"): """ Initializes the API client. Args: base_url (str): The base URL of the server's API (default is http://localhost:5000). """ super().__init__() self.base_url = base_url # Use an AsyncClient for making asynchronous requests self._client = httpx.AsyncClient() async def get_systems(self): """ Retrieves a summary list of all available radio systems. Returns: list: A list of system summaries (e.g., [{"id": "system_1", "name": "..."}]). """ print(f"Fetching systems from {self.base_url}/systems") return await self._request("GET", "/systems") async def get_system_details(self, system_id: str): """ Retrieves detailed information for a specific system. Args: system_id (str): The unique ID of the system. Returns: dict: The system details. Raises: httpx.HTTPStatusError: If the system is not found (404). """ print(f"Fetching details for system: {system_id} from {self.base_url}/systems/{system_id}") return await self._request("GET", f"/systems/{system_id}") async def list_clients(self): """ Retrieves a list of currently connected client IDs. Returns: list: A list of client IDs (strings). """ print(f"Fetching connected clients from {self.base_url}/clients") return await self._request("GET", "/clients") async def request_token(self): """ Retrieves a discord bot token. Returns: str: A token for the bot to use """ url = "/bots/request_token" print(f"Fetching a token from {self.base_url}{url}") return await self._request("POST", url, json={"client_id":app_conf.client_id}) async def send_command(self, client_id: str, command_name: str, args: list = None): """ Sends a command to a specific client via the server's API. Args: client_id (str): The ID of the target client. command_name (str): The name of the command to execute on the client. args (list, optional): A list of arguments for the command. Defaults to None. Returns: dict: The API response indicating the command status. """ if args is None: args = [] print(f"Sending command '{command_name}' to client {client_id} with args {args} via API") return await self._request( "POST", f"/command/{client_id}/{command_name}", json={"args": args} # API expects args in a JSON body ) # --- Example Usage --- async def example_api_usage(): """Demonstrates how to use the RadioAPIClient.""" # You can specify a different base_url if your server is elsewhere async with RadioAPIClient("http://localhost:5000") as api_client: print("\n--- Getting Channels ---") try: systems_summary = await api_client.get_systems() print("Channels Summary:", systems_summary) except Exception as e: print(f"Error getting systems: {e}") print("\n--- Getting Channel Details (system_1) ---") try: system_details = await api_client.get_system_details("system_1") print("Channel 1 Details:", system_details) except Exception as e: print(f"Error getting system details: {e}") print("\n--- Getting Channel Details (non-existent) ---") try: non_existent_system = await api_client.get_system_details("non_existent_system") print("Non-existent Channel Details:", non_existent_system) # This should not print except httpx.HTTPStatusError as e: print(f"Caught expected error for non-existent system: {e.response.status_code} - {e.response.json()}") except Exception as e: print(f"Error getting non-existent system details: {e}") print("\n--- Listing Connected Clients ---") try: connected_clients = await api_client.list_clients() print("Connected Clients:", connected_clients) # --- Sending a Command (Requires a client to be running with a matching ID) --- if connected_clients: target_client_id = connected_clients[0] # Send to the first connected client print(f"\n--- Sending 'print_message' command to {target_client_id} ---") try: command_response = await api_client.send_command( target_client_id, "print_message", ["Hello from the API wrapper!"] ) print("Command Response:", command_response) except Exception as e: print(f"Error sending command: {e}") print(f"\n--- Sending 'run_task' command to {target_client_id} ---") try: command_response = await api_client.send_command( target_client_id, "run_task", ["api_task_1", 3] # task_id, duration_seconds ) print("Command Response:", command_response) except Exception as e: print(f"Error sending command: {e}") else: print("No clients connected to send commands to.") except Exception as e: print(f"Error listing clients or sending commands: {e}") if __name__ == "__main__": # To run this example: # 1. Ensure the server (server.py) is running. # 2. Ensure at least one client (client.py) is running. # 3. Run this script: python api_client.py asyncio.run(example_api_usage())