From 518073961741e11084c13c6e0e2ceaf52d6c90f7 Mon Sep 17 00:00:00 2001 From: Eyre_S Date: Sat, 6 May 2023 23:44:08 +0800 Subject: [PATCH] update to coeur1.0.0-RC3.7 --- logger/log_appender.py | 2 +- morny/log.py | 35 ++++++ morny/morny_coeur.py | 4 - morny/morny_config.py | 69 +++++++++++ morny/{define.py => morny_system.py} | 6 +- morny/server_main.py | 173 ++++++++++++++------------- morny/util/str.py | 19 +++ pyproject.toml | 2 +- 8 files changed, 220 insertions(+), 90 deletions(-) create mode 100644 morny/log.py delete mode 100644 morny/morny_coeur.py create mode 100644 morny/morny_config.py rename morny/{define.py => morny_system.py} (70%) create mode 100644 morny/util/str.py diff --git a/logger/log_appender.py b/logger/log_appender.py index 21e6cda..eeced27 100644 --- a/logger/log_appender.py +++ b/logger/log_appender.py @@ -1,7 +1,7 @@ from datetime import datetime import threading -from morny.define import Coeur_Def +from morny.morny_system import Coeur_Def from .log import * if Coeur_Def.is_file_logging() : diff --git a/morny/log.py b/morny/log.py new file mode 100644 index 0000000..9f46faa --- /dev/null +++ b/morny/log.py @@ -0,0 +1,35 @@ +from logger import logger as logger_impl + +class logger: + + debug_mode: bool = False + + @staticmethod + def trace (msg: str): + if (logger.debug_mode): + logger_impl.trace(msg) + + @staticmethod + def debug (msg: str): + if (logger.debug_mode): + logger_impl.debug(msg) + + @staticmethod + def info (msg: str): + logger_impl.info(msg) + + @staticmethod + def warn (msg: str): + logger_impl.warn(msg) + + @staticmethod + def error (msg: str): + logger_impl.error(msg) + + @staticmethod + def fatal (msg: str): + logger_impl.fatal(msg) + + +def set_debug_mode(mode: bool): + logger.debug_mode = mode diff --git a/morny/morny_coeur.py b/morny/morny_coeur.py deleted file mode 100644 index c8de17f..0000000 --- a/morny/morny_coeur.py +++ /dev/null @@ -1,4 +0,0 @@ -class MornyCoeur : - - - \ No newline at end of file diff --git a/morny/morny_config.py b/morny/morny_config.py new file mode 100644 index 0000000..6d588c4 --- /dev/null +++ b/morny/morny_config.py @@ -0,0 +1,69 @@ +PROP_TOKEN_KEY_DEFAULT: str = "TELEGRAM_BOT_API_TOKEN" +PROP_MORNY_TOKEN_KEY: str = "MORNY_TG_TOKEN" + +PROP_TOKEN_KEYS: list[str] = [PROP_TOKEN_KEY_DEFAULT, PROP_MORNY_TOKEN_KEY] + +class MornyConfigPrototype: + def __init__(self): + + self.telegram_botApi_server: str|None = None + self.telegram_botApi_server4File: str|None = None + self.telegram_bot_key: str|None = None + self.telegram_bot_username: str|None = None + + self.eventIgnoreOutdated: bool = False + self.eventOutdatedTimestamp: int = -1 + + self.commandRefresh_onLogin: bool = False + self.commandRefresh_onLogout: bool = False + + self.trusted_master: int = 793274677 + self.trusted_chat: int = -1001541451710 + + self.trusted_dinnerReaders: set[int] = set[int]() + self.dinner_chatId: int = -1001707106392 + + self.reportTo_chatId: int = -1001650050443 + + self.medicationNotify_toChat_id: int = -1001729016815 + self.medicationNotify_useTimezone = 0 #todo: type + self.medicationNotify_atHour: set[int] = set[int]() + + +class MornyConfig: + + class CheckError(Exception): + def __init__(self, failure_at: str, request: str): + self.failure_at = failure_at + + def __init__(self, prototype: MornyConfigPrototype): + + if (prototype.telegram_bot_key == None): raise MornyConfig.CheckError("telegram_bot_key", "not None.") + self.telegram_botApi_server: str|None = prototype.telegram_botApi_server + self.telegram_botApi_server4File: str|None = prototype.telegram_botApi_server4File + self.telegram_bot_key: str = prototype.telegram_bot_key + self.telegram_bot_username: str|None = prototype.telegram_bot_username + + if (prototype.eventOutdatedTimestamp < 1): raise MornyConfig.CheckError("eventOutdatedTimestamp", "bigger than 1") + self.eventIgnoreOutdated: bool = prototype.eventIgnoreOutdated + self.eventOutdatedTimestamp: int = prototype.eventOutdatedTimestamp + + self.commandRefresh_onLogin: bool = prototype.commandRefresh_onLogin + self.commandRefresh_onLogout: bool = prototype.commandRefresh_onLogout + + self.trusted_master: int = prototype.trusted_master + self.trusted_chat: int = prototype.trusted_chat + + self.trusted_dinnerReaders: set[int] = prototype.trusted_dinnerReaders + self.dinner_chatId: int = prototype.dinner_chatId + + self.reportTo_chatId: int = prototype.reportTo_chatId + + for i in prototype.medicationNotify_atHour: + if (i > 23 or i < 0): + raise MornyConfig.CheckError(f"medicationNotify_atHour value {i}", "must a vaild hour number(0-23)") + self.medicationNotify_toChat_id: int = prototype.medicationNotify_toChat_id + self.medicationNotify_useTimezone = prototype.medicationNotify_useTimezone + self.medicationNotify_atHour: set[int] = prototype.medicationNotify_atHour + + diff --git a/morny/define.py b/morny/morny_system.py similarity index 70% rename from morny/define.py rename to morny/morny_system.py index ee0de4e..ce5dd55 100644 --- a/morny/define.py +++ b/morny/morny_system.py @@ -3,9 +3,9 @@ import os class Coeur_Def : '''Morny Coeur python 程序以及当前的版本的元信息''' - VERSION = "0.1.1+coeur0.7.2.1" - CODE = "fuzhou" - TIMETAG = "2209272250" + VERSION = "0.1.2+coeur1.0.0-RC3.7" + CODE = "beiping" + TIMETAG = "2305062342" def is_file_logging () -> bool : return os.getenv ("MORNY_LOGGING_TO_FILE") == "true" diff --git a/morny/server_main.py b/morny/server_main.py index 0364f8a..2673716 100644 --- a/morny/server_main.py +++ b/morny/server_main.py @@ -1,9 +1,14 @@ import os import sys import threading -from morny.define import Coeur_Def -from logger.logger import * +from morny.util.str import strm + +from morny.morny_system import Coeur_Def +from morny import log +from morny.log import logger from morny.morny_hello import morny_hello_text +from morny.morny_config import MornyConfigPrototype + thread_morny_init = "morny-init" prop_name_token_tg_key = "TELEGRAM_BOT_API_TOKEN" @@ -14,120 +19,126 @@ def main(): ## ## ## 启动参数的声明 + _config: MornyConfigPrototype = MornyConfigPrototype() + _printmode_version: bool = False + _printmode_hello: bool = False + _showHello: bool = True - versionEchoMode:bool = False - welcomeEchoMode:bool = False - showWelcome:bool = True - key:str|None = None - username:str|None = None; - outdatedBlock:bool = False - master:int = 793274677 - trustedReadersOfDinner:set = set() - trustedChat:int = -1001541451710 - autoCmdList:bool = False - autoCmdRemove:bool = False - api:str|None = None - api4File:str|None = None - + # Todo: set startup time ## ## ## 从命令行与环境变量读取启动参数值 - - i = 1; - while (i < len(sys.argv)) : + __i = 1; + _unknownArgs: list[str] = [] + while (__i < len(sys.argv)) : - if (sys.argv[i].startswith("-")): + if (sys.argv[__i].startswith("-")): - match sys.argv[i] : + match sys.argv[__i] : + case "-d" | "--dbg", "--debug": + log.set_debug_mode(True) + __i+=1;continue case "--outdated-block" | "-ob" : - outdatedBlock = True - i+=1;continue + _config.eventIgnoreOutdated = True + __i+=1;continue case "--no-hello" | "-hf" | "--quiet" | "-q" : - showWelcome = False - i+=1;continue + _showHello = False + __i+=1;continue case "--only-hello" | "-ho" | "-o" | "-hi" : - welcomeEchoMode = True - i+=1;continue + _printmode_hello = True + __i+=1;continue case "--version" | "-v" : - versionEchoMode = True - i+=1;continue + _printmode_version = True + __i+=1;continue case "--token" | "-t" : - i+=1; key = sys.argv[i] - i+=1;continue + __i+=1; _config.telegram_bot_key = sys.argv[__i] + __i+=1;continue case "--username" | "-u" : - i+=1; username = sys.argv[i] - i+=1;continue + __i+=1; _config.telegram_bot_username = sys.argv[__i] + __i+=1;continue case "--master" | "-mm" : - i+=1; master = int(sys.argv[i]) - i+=1;continue + __i+=1; _config.trusted_master = int(sys.argv[__i]) + __i+=1;continue case "--trusted-chat" | "-trs" : - i+=1; trustedChat = int(sys.argv[i]) - i+=1;continue + __i+=1; _config.trusted_master = int(sys.argv[__i]) + __i+=1;continue case "--trusted-reader-dinner" | "-trsd" : - i+=1; trustedReadersOfDinner.add(int(sys.argv[i])) - i+=1;continue + __i+=1; _config.trusted_dinnerReaders.add(int(sys.argv[__i])) + __i+=1;continue case "--auto-cmd" | "-cmd" | "-c" : - autoCmdList = True - autoCmdRemove = True - i+=1;continue + _config.commandRefresh_onLogin = True + _config.commandRefresh_onLogout = True + __i+=1;continue case "--auto-cmd-list" | "-ca" : - autoCmdList = True - i+=1;continue + _config.commandRefresh_onLogin = True + __i+=1;continue case "--auto-cmd-remove" | "-cr" : - autoCmdRemove = True - i+=1;continue + _config.commandRefresh_onLogout = True + __i+=1;continue case "--api" | "-a" : - i+=1; api = sys.argv[i] - i+=1;continue + __i+=1; _config.telegram_botApi_server = sys.argv[__i] + __i+=1;continue case "--api-files" | "files-api" | "-af" : - i+=1; api4File = sys.argv[i] - i+=1;continue + __i+=1; _config.telegram_botApi_server4File = sys.argv[__i] + __i+=1;continue - warn(f"Can't understand arg to some meaning :\n {sys.argv[i]}") - i+=1 + _unknownArgs.append(sys.argv[__i]) + __i+=1 + if (_showHello): + logger.info(morny_hello_text()) + if (_printmode_hello): + exit(0) + + if (_unknownArgs.count != 0): + logger.warn("Can't understand arg to some meaning :") + for __arg in _unknownArgs: + logger.warn(f" {__arg}") + + if (logger.debug_mode): + logger.warn("Debug log output enabled.\n It may lower your performance, make sure that you are not in production environment.") + logger.debug("Debug log output enabled.") + '''从系统环境变量设置的 bot token 值''' - propToken:str|None = None + _propToken:str|None = None '''表明 bot token 值的来源是哪个系统环境变量''' - propTokenKey:str|None = None - - for iKey in [prop_name_token_tg_key, prop_name_token_morny_key] : - if (os.getenv(iKey) != None) : - propToken = os.getenv(iKey) - propTokenKey = iKey + _propToken_key:str|None = None + for __key in [prop_name_token_tg_key, prop_name_token_morny_key] : + if (os.getenv(__key) != None) : + _propToken = os.getenv(__key) + _propToken_key = __key ## ## ## 启动参数的检查和处理 - if versionEchoMode : - info(f"""Morny Cono Version - - version : - {Coeur_Def.VERSION} {Coeur_Def.CODE.upper()} - - md5hash : - - - rw.time : - {Coeur_Def.TIMETAG} [UTC+8]""" - ); exit() - - if showWelcome : info(morny_hello_text()) - if welcomeEchoMode : exit() + if _printmode_version : + logger.info(strm( + f"Morny Cono Version", + f"- version :", + f" {Coeur_Def.VERSION} {Coeur_Def.CODE.upper()}", + f"- md5hash :", + f" ", + f"- rw.time :", + f" {Coeur_Def.TIMETAG} [UTC+8]", + )); + exit() - info(f"""morny/server_main.py Executed >>> - - version {Coeur_Def.VERSION} [{Coeur_Def.TIMETAG}] - - Morny {Coeur_Def.CODE.upper()}""") + logger.info(strm( + f"morny/server_main.py Executed >>>", + f"- version {Coeur_Def.VERSION} [{Coeur_Def.TIMETAG}]", + f"- Morny {Coeur_Def.CODE.upper()}", + )) ## ## ## Coeur 参数检查以及正式呼叫主程序 - if (propToken != None) : - key = propToken - info(f"Parameter set by EnvVar ${propTokenKey}") - if (key == None) : - info("Parameter required has no value:\n --token.") - exit() + if (_propToken != None) : + logger.info(f"Parameter set by EnvVar ${_propToken_key}") + threading.current_thread().name = thread_morny_init - #todo call coeur main + + #todo: call coeur main diff --git a/morny/util/str.py b/morny/util/str.py new file mode 100644 index 0000000..9417a49 --- /dev/null +++ b/morny/util/str.py @@ -0,0 +1,19 @@ +def strm(*strs: str) -> str: + output: str = "" + for i in range(len(strs)-1): + output += strs[i] + output += "\n" + output += strs[len(strs)-1] + return output + +# test for this +if __name__ == "__main__": + + print(strm( + "Aaa", + " bbb", + " ccc", + "Xxx", + " yyy" + )) + \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 2269d91..a9bf125 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "morny-coeur-python" -version = "0.1.1+coeur0.7.2.1" +version = "0.1.2+coeur1.0.0-RC3.7" description = "A Coeur-Morny-Cono rewrite by python3" authors = ["Eyre_S "] readme = "README.md"