1+ import pathlib
12from contextlib import asynccontextmanager
23from typing import cast
34from urllib .parse import urlparse
45
56import uvicorn
67import uvicorn .server
78from colorama import Fore
8- from discord .ext .commands import Bot
9- from fastapi import FastAPI
9+ from fastapi import APIRouter , FastAPI
1010from starlette .routing import Route
1111
12+ from bot .main import ActBot
1213from utils .log import LOG_CONFIG , logger
13- from utils .misc import text_block
14-
15- from .routes import add_routes
14+ from utils .misc import import_classes , text_block
1615
1716log = logger (__name__ )
1817
2120# * ACT API
2221# ----------------------------------------------------------------------------------------------------
2322class ActApi (FastAPI ):
24- def __init__ (self , bot : Bot | None = None , url = "" , * args , ** kwargs ):
23+ def __init__ (self , bot : "ActBot | None" = None , url = "" , * args , ** kwargs ):
2524 @asynccontextmanager
2625 async def lifespan (self : ActApi ):
2726 try :
@@ -47,8 +46,7 @@ async def lifespan(self: ActApi):
4746 log_config = LOG_CONFIG ,
4847 )
4948 )
50- if bot :
51- add_routes (self , bot )
49+ self .load_routers ()
5250
5351 # ----------------------------------------------------------------------------------------------------
5452
@@ -71,6 +69,29 @@ def info_text(self):
7169
7270 # ----------------------------------------------------------------------------------------------------
7371
72+ def load_routers (self ):
73+ router_classes = import_classes (
74+ f"{ pathlib .Path (__file__ ).parent } /routers" , APIRouter
75+ )
76+ log .loading ("Loading routers..." )
77+ loaded_routers_count = 0
78+ for router_class in router_classes :
79+ try :
80+ router : APIRouter = router_class (self .bot )
81+ self .include_router (router )
82+ log .info (
83+ f"{ router .__class__ .__name__ } router loaded from { router .__module__ } module."
84+ )
85+ loaded_routers_count += 1
86+ except Exception as e :
87+ log .error (
88+ f"Error loading { router_class .__class__ .__name__ } router from { router_class .__module__ } module:\t " ,
89+ e ,
90+ )
91+ log .success (f"{ loaded_routers_count } /{ len (router_classes )} routers loaded." )
92+
93+ # ----------------------------------------------------------------------------------------------------
94+
7495 async def open (self ):
7596 log .loading (f"API server opening..." )
7697 await self .server .serve ()
0 commit comments