1
0
mirror of https://github.com/Eyre-S/Coeur-Morny-Cono-python.git synced 2024-09-27 18:56:20 +08:00

update to coeur1.0.0-RC3.7

This commit is contained in:
A.C.Sukazyo Eyre 2023-05-06 23:44:08 +08:00
parent a716b4f5d8
commit 5180739617
Signed by: Eyre_S
GPG Key ID: C17CE40291207874
8 changed files with 220 additions and 90 deletions

View File

@ -1,7 +1,7 @@
from datetime import datetime from datetime import datetime
import threading import threading
from morny.define import Coeur_Def from morny.morny_system import Coeur_Def
from .log import * from .log import *
if Coeur_Def.is_file_logging() : if Coeur_Def.is_file_logging() :

35
morny/log.py Normal file
View File

@ -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

View File

@ -1,4 +0,0 @@
class MornyCoeur :

69
morny/morny_config.py Normal file
View File

@ -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

View File

@ -3,9 +3,9 @@ import os
class Coeur_Def : class Coeur_Def :
'''Morny Coeur python 程序以及当前的版本的元信息''' '''Morny Coeur python 程序以及当前的版本的元信息'''
VERSION = "0.1.1+coeur0.7.2.1" VERSION = "0.1.2+coeur1.0.0-RC3.7"
CODE = "fuzhou" CODE = "beiping"
TIMETAG = "2209272250" TIMETAG = "2305062342"
def is_file_logging () -> bool : def is_file_logging () -> bool :
return os.getenv ("MORNY_LOGGING_TO_FILE") == "true" return os.getenv ("MORNY_LOGGING_TO_FILE") == "true"

View File

@ -1,9 +1,14 @@
import os import os
import sys import sys
import threading import threading
from morny.define import Coeur_Def from morny.util.str import strm
from logger.logger import *
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_hello import morny_hello_text
from morny.morny_config import MornyConfigPrototype
thread_morny_init = "morny-init" thread_morny_init = "morny-init"
prop_name_token_tg_key = "TELEGRAM_BOT_API_TOKEN" 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 # Todo: set startup time
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
## ##
## ##
## 从命令行与环境变量读取启动参数值 ## 从命令行与环境变量读取启动参数值
__i = 1;
i = 1; _unknownArgs: list[str] = []
while (i < len(sys.argv)) : 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" : case "--outdated-block" | "-ob" :
outdatedBlock = True _config.eventIgnoreOutdated = True
i+=1;continue __i+=1;continue
case "--no-hello" | "-hf" | "--quiet" | "-q" : case "--no-hello" | "-hf" | "--quiet" | "-q" :
showWelcome = False _showHello = False
i+=1;continue __i+=1;continue
case "--only-hello" | "-ho" | "-o" | "-hi" : case "--only-hello" | "-ho" | "-o" | "-hi" :
welcomeEchoMode = True _printmode_hello = True
i+=1;continue __i+=1;continue
case "--version" | "-v" : case "--version" | "-v" :
versionEchoMode = True _printmode_version = True
i+=1;continue __i+=1;continue
case "--token" | "-t" : case "--token" | "-t" :
i+=1; key = sys.argv[i] __i+=1; _config.telegram_bot_key = sys.argv[__i]
i+=1;continue __i+=1;continue
case "--username" | "-u" : case "--username" | "-u" :
i+=1; username = sys.argv[i] __i+=1; _config.telegram_bot_username = sys.argv[__i]
i+=1;continue __i+=1;continue
case "--master" | "-mm" : case "--master" | "-mm" :
i+=1; master = int(sys.argv[i]) __i+=1; _config.trusted_master = int(sys.argv[__i])
i+=1;continue __i+=1;continue
case "--trusted-chat" | "-trs" : case "--trusted-chat" | "-trs" :
i+=1; trustedChat = int(sys.argv[i]) __i+=1; _config.trusted_master = int(sys.argv[__i])
i+=1;continue __i+=1;continue
case "--trusted-reader-dinner" | "-trsd" : case "--trusted-reader-dinner" | "-trsd" :
i+=1; trustedReadersOfDinner.add(int(sys.argv[i])) __i+=1; _config.trusted_dinnerReaders.add(int(sys.argv[__i]))
i+=1;continue __i+=1;continue
case "--auto-cmd" | "-cmd" | "-c" : case "--auto-cmd" | "-cmd" | "-c" :
autoCmdList = True _config.commandRefresh_onLogin = True
autoCmdRemove = True _config.commandRefresh_onLogout = True
i+=1;continue __i+=1;continue
case "--auto-cmd-list" | "-ca" : case "--auto-cmd-list" | "-ca" :
autoCmdList = True _config.commandRefresh_onLogin = True
i+=1;continue __i+=1;continue
case "--auto-cmd-remove" | "-cr" : case "--auto-cmd-remove" | "-cr" :
autoCmdRemove = True _config.commandRefresh_onLogout = True
i+=1;continue __i+=1;continue
case "--api" | "-a" : case "--api" | "-a" :
i+=1; api = sys.argv[i] __i+=1; _config.telegram_botApi_server = sys.argv[__i]
i+=1;continue __i+=1;continue
case "--api-files" | "files-api" | "-af" : case "--api-files" | "files-api" | "-af" :
i+=1; api4File = sys.argv[i] __i+=1; _config.telegram_botApi_server4File = sys.argv[__i]
i+=1;continue __i+=1;continue
warn(f"Can't understand arg to some meaning :\n {sys.argv[i]}") _unknownArgs.append(sys.argv[__i])
i+=1 __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 值''' '''从系统环境变量设置的 bot token 值'''
propToken:str|None = None _propToken:str|None = None
'''表明 bot token 值的来源是哪个系统环境变量''' '''表明 bot token 值的来源是哪个系统环境变量'''
propTokenKey:str|None = None _propToken_key:str|None = None
for __key in [prop_name_token_tg_key, prop_name_token_morny_key] :
for iKey in [prop_name_token_tg_key, prop_name_token_morny_key] : if (os.getenv(__key) != None) :
if (os.getenv(iKey) != None) : _propToken = os.getenv(__key)
propToken = os.getenv(iKey) _propToken_key = __key
propTokenKey = iKey
## ##
## ##
## 启动参数的检查和处理 ## 启动参数的检查和处理
if versionEchoMode : if _printmode_version :
info(f"""Morny Cono Version logger.info(strm(
- version : f"Morny Cono Version",
{Coeur_Def.VERSION} {Coeur_Def.CODE.upper()} f"- version :",
- md5hash : f" {Coeur_Def.VERSION} {Coeur_Def.CODE.upper()}",
<unavailable_in_python_implementation> f"- md5hash :",
- rw.time : f" <unavailable_in_python_implementation>",
{Coeur_Def.TIMETAG} [UTC+8]""" f"- rw.time :",
); exit() f" {Coeur_Def.TIMETAG} [UTC+8]",
));
if showWelcome : info(morny_hello_text()) exit()
if welcomeEchoMode : exit()
info(f"""morny/server_main.py Executed >>> logger.info(strm(
- version {Coeur_Def.VERSION} [{Coeur_Def.TIMETAG}] f"morny/server_main.py Executed >>>",
- Morny {Coeur_Def.CODE.upper()}""") f"- version {Coeur_Def.VERSION} [{Coeur_Def.TIMETAG}]",
f"- Morny {Coeur_Def.CODE.upper()}",
))
## ##
## ##
## Coeur 参数检查以及正式呼叫主程序 ## Coeur 参数检查以及正式呼叫主程序
if (propToken != None) : if (_propToken != None) :
key = propToken logger.info(f"Parameter <token> set by EnvVar ${_propToken_key}")
info(f"Parameter <token> set by EnvVar ${propTokenKey}")
if (key == None) :
info("Parameter required has no value:\n --token.")
exit()
threading.current_thread().name = thread_morny_init threading.current_thread().name = thread_morny_init
#todo call coeur main
#todo: call coeur main

19
morny/util/str.py Normal file
View File

@ -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"
))

View File

@ -1,6 +1,6 @@
[tool.poetry] [tool.poetry]
name = "morny-coeur-python" 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" description = "A Coeur-Morny-Cono rewrite by python3"
authors = ["Eyre_S <sukazyo@outlook.com>"] authors = ["Eyre_S <sukazyo@outlook.com>"]
readme = "README.md" readme = "README.md"