discordbot/run_unified_api.py
2025-06-05 21:31:06 -06:00

66 lines
2.0 KiB
Python

import os
import sys
import threading
import uvicorn
from dotenv import load_dotenv
# Add the api_service directory to the Python path
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "api_service"))
# Add the discordbot directory to the Python path (for settings_manager)
discordbot_path = os.path.dirname(__file__)
if discordbot_path not in sys.path:
sys.path.append(discordbot_path)
# Load environment variables
load_dotenv()
# Get configuration from environment variables
api_host = os.getenv("API_HOST", "0.0.0.0")
api_port = int(os.getenv("API_PORT", "8001"))
# SSL is now handled by a reverse proxy, so we don't configure it here.
def run_unified_api():
"""Run the unified API service (dual-stack IPv4+IPv6)"""
import threading
def run_uvicorn(bind_host):
print(f"Starting unified API service on {bind_host}:{api_port} (HTTP only)")
uvicorn.run(
"api_service.api_server:app",
host=bind_host,
port=api_port,
log_level="debug",
)
try:
# Use threading instead of multiprocessing to avoid pickling issues
threads = []
# Only run on IPv4 for now to avoid conflicts
for bind_host in ["127.0.0.1"]: # Removed "::1" to simplify
t = threading.Thread(target=run_uvicorn, args=(bind_host,))
t.daemon = True
t.start()
threads.append(t)
# Don't join threads here - let them run in the background
print(f"API service started on {api_port}")
except Exception as e:
print(f"Error starting unified API service: {e}")
def start_api_in_thread():
"""Start the unified API service in a separate thread"""
api_thread = threading.Thread(target=run_unified_api)
api_thread.daemon = True
api_thread.start()
print("Unified API service started in background thread")
return api_thread
if __name__ == "__main__":
# Run the API directly if this script is executed
run_unified_api()