This commit is contained in:
2025-02-15 21:09:33 -05:00
parent 60416c493f
commit 39d1ddaffa
22 changed files with 509 additions and 525 deletions

View File

@ -2,22 +2,26 @@
import os
import random
from typing import LiteralString, Optional
from typing import Union, LiteralString
import aiosqlite as sqlite3
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from .constructors import RandMsgRequest
class RandMsg(FastAPI):
"""Random Message Endpoint"""
def __init__(self, app: FastAPI, util, constants): # pylint: disable=super-init-not-called
self.app = app
"""
Random Message Endpoint
"""
def __init__(self, app: FastAPI,
util, constants) -> None: # pylint: disable=super-init-not-called
self.app: FastAPI = app
self.util = util
self.constants = constants
self.endpoint_name = "randmsg"
app.add_api_route(f"/{self.endpoint_name}", self.randmsg_handler, methods=["POST"])
async def randmsg_handler(self, data: RandMsgRequest):
async def randmsg_handler(self, data: RandMsgRequest) -> JSONResponse:
"""
Get a randomly generated message
"""
@ -25,16 +29,16 @@ class RandMsg(FastAPI):
short: bool = data.short if data.short else False
if not short:
db_rand_selected = random.choice([0, 1, 3])
db_rand_selected: int = random.choice([0, 1, 3])
else:
db_rand_selected = 9
title_attr = "Unknown"
title_attr: str = "Unknown"
match db_rand_selected:
case 0:
randmsg_db_path = os.path.join("/usr/local/share",
randmsg_db_path: Union[str, LiteralString] = os.path.join("/usr/local/share",
"sqlite_dbs", "qajoke.db") # For qajoke db
db_query = "SELECT id, ('<b>Q:</b> ' || question || '<br/><b>A:</b> ' \
db_query: str = "SELECT id, ('<b>Q:</b> ' || question || '<br/><b>A:</b> ' \
|| answer) FROM jokes ORDER BY RANDOM() LIMIT 1" # For qajoke db
title_attr = "QA Joke DB"
case 1 | 9:
@ -74,23 +78,16 @@ class RandMsg(FastAPI):
db_query = """SELECT id, (title || "<br>" || body) FROM jokes \
WHERE score >= 10000 ORDER BY RANDOM() LIMIT 1"""
title_attr = "r/jokes DB"
case 6:
randmsg_db_path = os.path.join("/usr/local/share",
"sqlite_dbs",
"donnies.db") # Donnies DB
random.seed()
twilight_or_mice: str = random.choice(["twilight", "mice"])
db_query = f"SELECT id, text FROM {twilight_or_mice} ORDER BY RANDOM() LIMIT 1"
title_attr = "Donnies DB"
async with sqlite3.connect(database=randmsg_db_path, timeout=1) as _db:
async with await _db.execute(db_query) as _cursor:
result = await _cursor.fetchone()
result: sqlite3.Row = await _cursor.fetchone()
(result_id, result_msg) = result
result_msg = result_msg.strip()
return {
"id": result_id,
"msg": result_msg,
'title': title_attr
}
return JSONResponse(content=
{
"id": result_id,
"msg": result_msg,
"title": title_attr,
})