Edited according to PEP8 and added f-strings.

This commit is contained in:
Rhinemann 2023-05-08 09:59:07 +03:00
parent 1f9212c033
commit 7bca26e07c
1 changed files with 28 additions and 23 deletions

View File

@ -12,16 +12,18 @@ from telegram import Message, Chat
# global variables # global variables
STOP_REQUESTED = False STOP_REQUESTED = False
# some functions that increase readability of the code # some functions that increase readability of the code
def readfile(filename): def readfile(filename):
try: try:
return codecs.open(filename, encoding = "utf-8").read() return codecs.open(filename, encoding="utf-8").read()
except FileNotFoundError: except FileNotFoundError:
return False return False
except Exception as e: except Exception as e:
print( "[ERROR] Unexpected error occured in readfile() ({0})".format(e) ) print(f"[ERROR] Unexpected error occurred in readfile() ({e})")
return False return False
# module object classes # module object classes
class ModuleV1: class ModuleV1:
def __init__(self, path, code, enabled, alias, predefine): def __init__(self, path, code, enabled, alias, predefine):
@ -43,7 +45,8 @@ class ModuleV1:
try: try:
exec(self.predefine) exec(self.predefine)
except Exception as e: except Exception as e:
print("[ERROR] module v1: module \"{}\" ({}) raised exception \"{}\" during predefine stage, disabling it...".format(self.path, self.alias, e)) print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{e}\""
f" during predefine stage, disabling it...")
# running the module # running the module
def process(self, msg): def process(self, msg):
@ -54,7 +57,7 @@ class ModuleV1:
exec(self.code) exec(self.code)
return self.RESPONCE return self.RESPONCE
except Exception as e: except Exception as e:
print("[ERROR] module v1: module \"{}\" ({}) raised exception \"{}\"".format(self.path, self.alias, e)) print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"")
return "" return ""
@ -90,10 +93,10 @@ class ModuleControlUnit:
try: try:
meta_raw = readfile("modules/{}/meta.json".format(folder)) meta_raw = readfile("modules/{}/meta.json".format(folder))
if not meta_raw: if not meta_raw:
print("[WARN] module_loader: no meta.json found in module folder \"{}\"".format(folder)) print(f"[WARN] module_loader: no meta.json found in module folder \"{folder}\"")
continue continue
meta = json.loads( meta_raw ) meta = json.loads(meta_raw)
if "version" in meta: if "version" in meta:
if meta["version"] == 1: if meta["version"] == 1:
if "index_file" in meta: if "index_file" in meta:
@ -101,9 +104,9 @@ class ModuleControlUnit:
else: else:
index_file = "index.py" index_file = "index.py"
code = readfile( "modules/{}/{}".format(folder, index_file) ) code = readfile("modules/{}/{}".format(folder, index_file))
if not code: # False both when readfile() returns False and when the code string is empty if not code: # False both when readfile() returns False and when the code string is empty
print("[WARN] reload_modules: module {} does not have any code, skipping...".format(folder)) print(f"[WARN] reload_modules: module {folder} does not have any code, skipping...")
continue continue
if "start_on_boot" in meta: if "start_on_boot" in meta:
@ -121,9 +124,10 @@ class ModuleControlUnit:
else: else:
predefine = False predefine = False
self.modules.append( ModuleV1( "modules/{}/".format(folder), code, enabled, alias, predefine ) ) self.modules.append(ModuleV1("modules/{}/".format(folder), code, enabled, alias, predefine))
print("[INFO] reload_modules: successfully loaded {} as {} (start_on_boot: {})".format(folder, alias, enabled)) print(f"[INFO] reload_modules: successfully loaded {folder} as {alias} "
f"(start_on_boot: {enabled})")
elif meta["version"] == 2: elif meta["version"] == 2:
if "index_file" in meta: if "index_file" in meta:
@ -143,17 +147,19 @@ class ModuleControlUnit:
self.modules.append(ModuleV2(f"modules/{folder}/", index_file, enabled, alias)) self.modules.append(ModuleV2(f"modules/{folder}/", index_file, enabled, alias))
print(f"[INFO] reload_modules: successfully loaded {folder} as {alias} (start_on_boot: {enabled})") print(f"[INFO] reload_modules: successfully loaded {folder} as {alias} "
f"(start_on_boot: {enabled})")
else: else:
print(f"[WARN] reload_modules: module {folder} requires unsupported version ({meta['version']} > 2), skipping...") print(f"[WARN] reload_modules: module {folder} requires unsupported version "
f"({meta['version']} > 2), skipping...")
except Exception as e: except Exception as e:
print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(folder, e)) print(f"[ERROR] module_loader: error while loading module \"{folder}\" ({e})")
# message queue object to go back to synchronous message processing # message queue object to go back to synchronous message processing
#class MessageQueue: # class MessageQueue:
# def __init__(self): # def __init__(self):
# print("[INFO] Initializing the message queue...") # print("[INFO] Initializing the message queue...")
# self.queue = [] # self.queue = []
@ -165,7 +171,7 @@ def queue_processor():
try: try:
if len(message_queue) > 0: if len(message_queue) > 0:
msg = message_queue[0] msg = message_queue[0]
print("[DEBUG] queue_processor: {}".format(msg)) # debug print("[DEBUG] queue_processor: {}".format(msg)) # debug
# check for control commands # check for control commands
if msg["chat"]["id"] == 575246355: if msg["chat"]["id"] == 575246355:
@ -204,7 +210,7 @@ def queue_processor():
time.sleep(1) time.sleep(1)
except Exception as e: except Exception as e:
print("[ERROR] queue_processor: current message queue: {}".format(message_queue)) print(f"[ERROR] queue_processor: current message queue: {message_queue}")
print("[ERROR] queue_processor: error while processing message, trying to delete it...") print("[ERROR] queue_processor: error while processing message, trying to delete it...")
try: try:
del message_queue[0] del message_queue[0]
@ -224,10 +230,9 @@ message_queue = []
mcu = ModuleControlUnit() mcu = ModuleControlUnit()
processor_thread = threading.Thread( target = queue_processor, args = [] ) processor_thread = threading.Thread(target=queue_processor, args=[])
processor_thread.start() processor_thread.start()
print("Enter testing messages one by one, end with an empty line") print("Enter testing messages one by one, end with an empty line")
while True: while True:
@ -235,4 +240,4 @@ while True:
if len(new_msg) == 0: if len(new_msg) == 0:
break break
message_queue.append(Message(9, round(time.time()), Chat(575246355, 'supergroup'), text = new_msg)) message_queue.append(Message(9, round(time.time()), Chat(575246355, 'supergroup'), text=new_msg))