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

Compare commits

...

2 Commits

Author SHA1 Message Date
b8ec9169ab
use pyssage as logging backend 2023-05-11 20:40:32 +08:00
5180739617
update to coeur1.0.0-RC3.7 2023-05-06 23:44:08 +08:00
11 changed files with 200 additions and 157 deletions

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Coeur-Morny-Cono-python
todo...

View File

@ -1,26 +0,0 @@
import time
class LogLevel:
def __init__(self, level:float, name:str) :
self.level = level
self.name = name
# def level (self) -> float : return self.level
# def name (self) -> str : return self.name
class LogLevels:
trace:LogLevel = LogLevel(-1, "TRAC")
debug:LogLevel = LogLevel(0.1, "DBUG")
info:LogLevel = LogLevel(0, "INFO")
warn:LogLevel = LogLevel(0.5, "WARN")
error:LogLevel = LogLevel(1, "ERRO")
fatal:LogLevel = LogLevel(10, "FTAL")
null:LogLevel = LogLevel(0, "NULL")
class Log:
def __init__ (self, message:str, level:LogLevel) :
self.timestamp = time.time_ns()
self.level = level
self.message = message
# def timestamp (self) -> int : return self.timestamp
# def level (self) -> LogLevel : return self.level
# def message (self) -> str : return self.message

View File

@ -1,31 +0,0 @@
from datetime import datetime
import threading
from morny.define import Coeur_Def
from .log import *
if Coeur_Def.is_file_logging() :
log_file_archive = open(f"./logs/{time.strftime('%Y-%m-%d-%H:%M:%S.log', time.localtime())}", "x")
log_file = open("./log__latest.log", "a")
def output (message:Log) :
echo = format_message(message)
print(echo)
if Coeur_Def.is_file_logging() :
log_file.write(echo+"\n")
log_file_archive.write(echo+"\n")
def format_message (log:Log) -> str :
origins = log.message.split("\n")
message = ""
message += f"[{datetime.fromtimestamp(log.timestamp/1000/1000/1000).strftime('%Y-%m-%d/%H:%M:%S:%f')}]" + \
f"[{threading.current_thread().name }]"
promptNewLine = "'"*len(message)
message += f"[{log.level.name}]{origins[0]}"
for i in range(len(origins)-1) :
message += f"\n{promptNewLine}[{log.level.name}]{origins[i+1]}"
return message

View File

@ -1,10 +0,0 @@
from logger.log import Log, LogLevels
from logger.log_appender import output
def trace (msg:str) : output(Log(msg, LogLevels.trace))
def debug (msg:str) : output(Log(msg, LogLevels.debug))
def info (msg:str) : output(Log(msg, LogLevels.info))
def warn(msg:str) : output(Log(msg, LogLevels.warn))
def error (msg:str) : output(Log(msg, LogLevels.error))
def fatal (msg:str) : output(Log(msg, LogLevels.fatal))

21
morny/log.py Normal file
View File

@ -0,0 +1,21 @@
from pyssage.components.restrictions import RestrictionToLog, LevelRestriction
from pyssage.appender import ConsoleAppender
from pyssage.formatter import SimpleFormatter
from pyssage.log.log import levels
from pyssage.logger import Logger
restriction: RestrictionToLog = LevelRestriction(levels.INFO)
logger: Logger = Logger(ConsoleAppender(SimpleFormatter()))
logger.restrictions.append(restriction)
def set_debug_mode(mode: bool):
if mode:
restriction.min_level = levels.ALL
else:
restriction.min_level = levels.INFO
def is_debug_mode () -> bool:
return restriction.min_level < levels.INFO

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 :
'''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"

View File

@ -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;
_unknownArgs: list[str] = []
while (__i < len(sys.argv)) :
i = 1;
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 (log.is_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 :
<unavailable_in_python_implementation>
- rw.time :
{Coeur_Def.TIMETAG} [UTC+8]"""
); exit()
if _printmode_version :
logger.info(strm(
f"Morny Cono Version",
f"- version :",
f" {Coeur_Def.VERSION} {Coeur_Def.CODE.upper()}",
f"- md5hash :",
f" <unavailable_in_python_implementation>",
f"- rw.time :",
f" {Coeur_Def.TIMETAG} [UTC+8]",
));
exit()
if showWelcome : info(morny_hello_text())
if welcomeEchoMode : 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 <token> set by EnvVar ${propTokenKey}")
if (key == None) :
info("Parameter required has no value:\n --token.")
exit()
if (_propToken != None) :
logger.info(f"Parameter <token> set by EnvVar ${_propToken_key}")
threading.current_thread().name = thread_morny_init
#todo call coeur main
#todo: call coeur main

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

@ -0,0 +1,7 @@
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

View File

@ -1,14 +1,17 @@
[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 <sukazyo@outlook.com>"]
readme = "README.md"
packages = [{include = "morny_coeur_python"}]
packages = [
{include = "morny"}
]
[tool.poetry.dependencies]
python = "^3.10"
python-telegram-bot = "^13.14"
pyssage = { git = "https://github.com/suk-ws/pyssage", tag="0.1.0" }
[build-system]