From ef9b7336319b548d63aab8f7a1c789ef46d40bb9 Mon Sep 17 00:00:00 2001 From: Qubasa Date: Thu, 13 Jun 2024 18:45:36 +0200 Subject: [PATCH] matrix-bot: Add argparse add mautrix --- pkgs/matrix-bot/bin/bot | 12 +++ pkgs/matrix-bot/default.nix | 4 +- pkgs/matrix-bot/flake-module.nix | 1 - pkgs/matrix-bot/matrix_bot/__init__.py | 4 + pkgs/matrix-bot/matrix_bot/__main__.py | 4 + pkgs/matrix-bot/matrix_bot/custom_logger.py | 97 +++++++++++++++++++++ pkgs/matrix-bot/matrix_bot/main.py | 35 +++++++- 7 files changed, 153 insertions(+), 4 deletions(-) create mode 100755 pkgs/matrix-bot/bin/bot create mode 100644 pkgs/matrix-bot/matrix_bot/custom_logger.py diff --git a/pkgs/matrix-bot/bin/bot b/pkgs/matrix-bot/bin/bot new file mode 100755 index 00000000..7d09bcc9 --- /dev/null +++ b/pkgs/matrix-bot/bin/bot @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import os +import sys + +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +) + +from matrix_bot import main # NOQA + +if __name__ == "__main__": + main() diff --git a/pkgs/matrix-bot/default.nix b/pkgs/matrix-bot/default.nix index 0fda206a..61b3a9be 100644 --- a/pkgs/matrix-bot/default.nix +++ b/pkgs/matrix-bot/default.nix @@ -1,10 +1,10 @@ -{ python3, setuptools, ... }: +{ python3, setuptools, mautrix, ... }: let pythonDependencies = [ - + mautrix ]; runtimeDependencies = [ ]; diff --git a/pkgs/matrix-bot/flake-module.nix b/pkgs/matrix-bot/flake-module.nix index 0dd2b86c..f7b15f7f 100644 --- a/pkgs/matrix-bot/flake-module.nix +++ b/pkgs/matrix-bot/flake-module.nix @@ -7,7 +7,6 @@ devShells.matrix-bot = pkgs.callPackage ./shell.nix { inherit (self'.packages) matrix-bot; }; packages = { matrix-bot = pkgs.python3.pkgs.callPackage ./default.nix { }; - default = self'.packages.matrix-bot; }; checks = { }; diff --git a/pkgs/matrix-bot/matrix_bot/__init__.py b/pkgs/matrix-bot/matrix_bot/__init__.py index e69de29b..b727ca63 100644 --- a/pkgs/matrix-bot/matrix_bot/__init__.py +++ b/pkgs/matrix-bot/matrix_bot/__init__.py @@ -0,0 +1,4 @@ +from .main import main + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pkgs/matrix-bot/matrix_bot/__main__.py b/pkgs/matrix-bot/matrix_bot/__main__.py index e69de29b..b727ca63 100644 --- a/pkgs/matrix-bot/matrix_bot/__main__.py +++ b/pkgs/matrix-bot/matrix_bot/__main__.py @@ -0,0 +1,4 @@ +from .main import main + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pkgs/matrix-bot/matrix_bot/custom_logger.py b/pkgs/matrix-bot/matrix_bot/custom_logger.py new file mode 100644 index 00000000..4bd2b3cd --- /dev/null +++ b/pkgs/matrix-bot/matrix_bot/custom_logger.py @@ -0,0 +1,97 @@ +import inspect +import logging +from collections.abc import Callable +from pathlib import Path +from typing import Any + +grey = "\x1b[38;20m" +yellow = "\x1b[33;20m" +red = "\x1b[31;20m" +bold_red = "\x1b[31;1m" +green = "\u001b[32m" +blue = "\u001b[34m" + + +def get_formatter(color: str) -> Callable[[logging.LogRecord, bool], logging.Formatter]: + def myformatter( + record: logging.LogRecord, with_location: bool + ) -> logging.Formatter: + reset = "\x1b[0m" + + try: + filepath = Path(record.pathname).resolve() + filepath = Path("~", filepath.relative_to(Path.home())) + except Exception: + filepath = Path(record.pathname) + + if not with_location: + return logging.Formatter(f"{color}%(levelname)s{reset}: %(message)s") + + return logging.Formatter( + f"{color}%(levelname)s{reset}: %(message)s\nLocation: {filepath}:%(lineno)d::%(funcName)s\n" + ) + + return myformatter + + +FORMATTER = { + logging.DEBUG: get_formatter(blue), + logging.INFO: get_formatter(green), + logging.WARNING: get_formatter(yellow), + logging.ERROR: get_formatter(red), + logging.CRITICAL: get_formatter(bold_red), +} + + +class CustomFormatter(logging.Formatter): + def __init__(self, log_locations: bool) -> None: + super().__init__() + self.log_locations = log_locations + + def format(self, record: logging.LogRecord) -> str: + return FORMATTER[record.levelno](record, self.log_locations).format(record) + + +class ThreadFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + return FORMATTER[record.levelno](record, False).format(record) + + +def get_caller() -> str: + frame = inspect.currentframe() + if frame is None: + return "unknown" + caller_frame = frame.f_back + if caller_frame is None: + return "unknown" + caller_frame = caller_frame.f_back + if caller_frame is None: + return "unknown" + frame_info = inspect.getframeinfo(caller_frame) + + try: + filepath = Path(frame_info.filename).resolve() + filepath = Path("~", filepath.relative_to(Path.home())) + except Exception: + filepath = Path(frame_info.filename) + + ret = f"{filepath}:{frame_info.lineno}::{frame_info.function}" + return ret + + +def setup_logging(level: Any, root_log_name: str = __name__.split(".")[0]) -> None: + # Get the root logger and set its level + main_logger = logging.getLogger(root_log_name) + main_logger.setLevel(level) + + # Create and add the default handler + default_handler = logging.StreamHandler() + + # Create and add your custom handler + default_handler.setLevel(level) + default_handler.setFormatter(CustomFormatter(str(level) == str(logging.DEBUG))) + main_logger.addHandler(default_handler) + + # Set logging level for other modules used by this module + logging.getLogger("asyncio").setLevel(logging.INFO) + logging.getLogger("httpx").setLevel(level=logging.WARNING) diff --git a/pkgs/matrix-bot/matrix_bot/main.py b/pkgs/matrix-bot/matrix_bot/main.py index bffa1502..63df1908 100644 --- a/pkgs/matrix-bot/matrix_bot/main.py +++ b/pkgs/matrix-bot/matrix_bot/main.py @@ -1,3 +1,36 @@ +import argparse +import logging +import sys +from matrix_bot.custom_logger import setup_logging + +log = logging.getLogger(__name__) + + +def create_parser(prog: str | None = None) -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog=prog, + description="A gitea bot for matrix", + formatter_class=argparse.RawTextHelpFormatter, + ) + + parser.add_argument( + "--debug", + help="Enable debug logging", + action="store_true", + default=False, + ) + + return parser def main(): - print("Hello, world!") \ No newline at end of file + parser = create_parser() + args = parser.parse_args() + + if len(sys.argv) == 1: + parser.print_help() + + if args.debug: + setup_logging(logging.DEBUG, root_log_name=__name__.split(".")[0]) + log.debug("Debug log activated") + else: + setup_logging(logging.INFO, root_log_name=__name__.split(".")[0]) \ No newline at end of file