nonsensebot/app/main.py

58 lines
1.7 KiB
Python
Raw Normal View History

2024-07-28 03:59:19 +01:00
import sys
import niobot
import tomllib
import platform
import logging
import tortoise
from pathlib import Path
log = logging.getLogger(__name__)
with open("config.toml", "rb") as fd:
config = tomllib.load(fd)
(store := (Path.cwd() / "store")).mkdir(parents=True, exist_ok=True)
class TortoiseIntegratedBot(niobot.NioBot):
async def start(self, **kwargs):
url = config["database"].get("uri")
if not url:
log.critical("No database URI specified in config.toml - using ephemeral sqlite.")
url = "sqlite://:memory:"
sys.path.extend(("..", "."))
await tortoise.Tortoise.init(db_url=url, modules={"models": ["app.models"]})
await tortoise.Tortoise.generate_schemas()
for file in (Path(__file__).parent / "./modules").glob("*.py"):
if file.name.startswith("__"):
log.warning("Skipping loading %s - dunder file.", file)
name = "app.modules." + file.name[:-3]
try:
log.info("Loading %s...", name)
bot.mount_module(name)
except Exception:
log.error("Failed to load %s!", name, exc_info=True)
else:
log.info("Loaded %s.", name)
await super().start(**kwargs)
bot = TortoiseIntegratedBot(
homeserver=config["bot"]["homeserver"],
user_id=config["bot"]["user_id"],
device_id=config["bot"].get("device_id", platform.node()),
store_path=str(store.resolve()),
command_prefix="h!",
owner_id=config["bot"].get("owner_id", "@nex:nexy7574.co.uk"),
)
bot.cfg = config
@bot.on_event("ready")
async def on_ready(_):
log.info("Bot has logged in.")