Skip to content

Commit

Permalink
feat: Add API
Browse files Browse the repository at this point in the history
  • Loading branch information
seriaati committed Jun 5, 2024
1 parent 0e63371 commit a80492b
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 5 deletions.
52 changes: 52 additions & 0 deletions hoyo_buddy/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import asyncio
from typing import TYPE_CHECKING

import discord
from aiohttp import web
from loguru import logger

if TYPE_CHECKING:
from .bot.bot import HoyoBuddy


class BotAPI:
def __init__(self, bot: "HoyoBuddy") -> None:
self._bot = bot

async def index(self, _: web.Request) -> web.Response:
return web.json_response({"status": "ok"})

async def commands(self, request: web.Request) -> web.Response:
locale_value = request.query.get("locale")
locale = (
discord.Locale(locale_value)
if locale_value is not None
else discord.Locale.american_english
)
commands = self._bot.get_all_commands(locale)
return web.json_response(commands)

async def run(self, port: int = 7824) -> None:
await self._bot.wait_until_ready()

logger.info(f"Starting API server on port {port}...")

app = web.Application()
app.add_routes([web.get("/", self.index), web.get("/commands", self.commands)])

runner = web.AppRunner(app)
await runner.setup()

site = web.TCPSite(runner, "localhost", port)
await site.start()
logger.info("API server started")

try:
await asyncio.Future()
except asyncio.CancelledError:
logger.info("API server shutting down...")
await site.stop()
await app.shutdown()
await app.cleanup()
await runner.shutdown()
await runner.cleanup()
22 changes: 22 additions & 0 deletions hoyo_buddy/bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,28 @@ async def on_command_error(
return
return await super().on_command_error(context, exception)

def get_all_commands(self, locale: discord.Locale) -> dict[str, str]:
result: dict[str, str] = {}
for cog in self.cogs.values():
for command in cog.walk_app_commands():
desc = (
LocaleStr(
command._locale_description.message,
**command._locale_description.extras,
)
if command._locale_description is not None
else command.description
)
translated_desc = self.translator.translate(desc, locale)
name = (
f"/{cog.__cog_name__} {command.name}"
if isinstance(cog, commands.GroupCog)
else f"/{command.name}"
)
result[name] = translated_desc

return result

async def close(self) -> None:
logger.info("Bot shutting down...")
if self.env != "dev":
Expand Down
2 changes: 1 addition & 1 deletion hoyo_buddy/bot/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ async def fetch_source_strings() -> None:
logger.info("Fetching translations...")
start = time.time()
await asyncio.to_thread(tx.fetch_translations)
logger.info("Fetched translations in %.2f seconds", time.time() - start)
logger.info(f"Fetched translations in {time.time() - start:.2f} seconds")

async def push_source_strings(self) -> None:
if not self._not_translated:
Expand Down
3 changes: 1 addition & 2 deletions hoyo_buddy/web_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ async def run(self, port: int = 5000) -> None:
logger.info("Web server started")

try:
while True:
await asyncio.sleep(1)
await asyncio.Future()
except asyncio.CancelledError:
logger.info("Web server shutting down...")
await site.stop()
Expand Down
10 changes: 8 additions & 2 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from sentry_sdk.integrations.aiohttp import AioHttpIntegration
from sentry_sdk.integrations.loguru import LoguruIntegration

from hoyo_buddy.api import BotAPI
from hoyo_buddy.bot.bot import HoyoBuddy
from hoyo_buddy.bot.translator import Translator
from hoyo_buddy.db.pgsql import Database
Expand Down Expand Up @@ -68,9 +69,14 @@ async def main() -> None:
with contextlib.suppress(
KeyboardInterrupt, asyncio.CancelledError, aiohttp.http_websocket.WebSocketError
):
server = GeetestWebServer(translator=translator)
geetest_server = GeetestWebServer(translator=translator)
api_server = BotAPI(bot)

tasks: set[asyncio.Task] = set()
task = asyncio.create_task(server.run())
task = asyncio.create_task(geetest_server.run())
tasks.add(task)
task.add_done_callback(tasks.discard)
task = asyncio.create_task(api_server.run())
tasks.add(task)
task.add_done_callback(tasks.discard)

Expand Down

0 comments on commit a80492b

Please sign in to comment.