add support for modules of version 2

This commit is contained in:
dymik739 2023-05-03 21:06:05 +03:00
parent 6e0830362c
commit e12532338d
2 changed files with 99 additions and 88 deletions

58
main.py
View File

@ -6,6 +6,7 @@ import json
import sys import sys
import os import os
import threading import threading
import importlib
# global variables # global variables
STOP_REQUESTED = False STOP_REQUESTED = False
@ -41,7 +42,7 @@ class ModuleV1:
try: try:
exec(self.predefine) exec(self.predefine)
except Exception as e: except Exception as e:
print("[ERROR] module: module \"{}\" ({}) raised exception \"{}\" during predefine stage, disabling it...".format(self.path, self.alias, e)) print("[ERROR] module v1: module \"{}\" ({}) raised exception \"{}\" during predefine stage, disabling it...".format(self.path, self.alias, e))
# running the module # running the module
def process(self, msg): def process(self, msg):
@ -52,9 +53,27 @@ 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: module \"{}\" ({}) raised exception \"{}\"".format(self.path, self.alias, e)) print("[ERROR] module v1: module \"{}\" ({}) raised exception \"{}\"".format(self.path, self.alias, e))
return "" return ""
class ModuleV2:
def __init__(self, path, index_file, enabled, alias):
self.version = 2
self.enabled = enabled
self.alias = alias
self.path = path
self.index_file = index_file[:-3]
self.obj = importlib.import_module((path + self.index_file).replace("/", "."))
# running the module
def process(self, msg):
try:
responce = self.obj.process(msg, self.path)
return responce
except Exception as e:
print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"")
return None
# module control unit # module control unit
class ModuleControlUnit: class ModuleControlUnit:
@ -103,30 +122,13 @@ class ModuleControlUnit:
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("[INFO] reload_modules: successfully loaded {} as {} (start_on_boot: {})".format(folder, alias, enabled))
else:
print("[WARN] reload_modules: module {} requires unsupported version ({} > 1), skipping...".format(folder, meta["version"]))
except Exception as e:
print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(folder, e))
def reload_module(self, folder_name): elif meta["version"] == 2:
try:
meta_raw = readfile("modules/{}/meta.json".format(folder))
if not meta_raw:
print("[WARN] module_loader: no meta.json found in module folder \"{}\"".format(folder_name))
return 1
meta = json.loads( readfile("modules/{}/meta.json".format(folder_name)) )
if "version" in meta:
if meta["version"] == 1:
if "index_file" in meta: if "index_file" in meta:
index_file = meta["index_file"] index_file = meta["index_file"]
else: else:
index_file = "index.py" index_file = "index.py"
code = readfile( "modules/{}/{}".format(folder_name, index_file) )
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_name))
if "start_on_boot" in meta: if "start_on_boot" in meta:
enabled = meta["start_on_boot"] enabled = meta["start_on_boot"]
else: else:
@ -137,13 +139,15 @@ class ModuleControlUnit:
else: else:
alias = None alias = None
self.modules.append( ModuleV1( code, 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("[INFO] reload_modules: successfully loaded {} as {} (start_on_boot: {})".format(folder_name, alias, enabled))
else: else:
print("[WARN] reload_modules: module {} requires unsupported version ({} > 1), skipping...".format(folder_name, meta["version"])) print(f"[WARN] reload_modules: module {folder} requires unsupported version ({meta['version']} > 2), skipping...")
except Exception as e: except Exception as e:
print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(folder_name, e)) print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(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:
@ -177,11 +181,11 @@ def queue_processor():
# modules are used in here # modules are used in here
for mod in mcu.modules: for mod in mcu.modules:
if mod.enabled: if mod.enabled:
if mod.version == 1: if mod.version == 1 or mod.version == 2:
responce = mod.process(msg) responce = mod.process(msg)
if len(responce) > 0: if responce:
updater.bot.send_message(chat_id = msg.chat.id, text = responce, disable_web_page_preview = True) updater.bot.send_message(chat_id = msg.chat.id, text = responce, disable_web_page_preview = True)
print("Responded using module {} ({}) with text: {}".format(mod.path, mod.alias, responce)) print(f"Responded using module {mod.path} ({mod.alias}) with text: {responce}")
break break
del message_queue[0] del message_queue[0]

View File

@ -5,6 +5,7 @@ import json
import sys import sys
import os import os
import threading import threading
import importlib
from telegram import Message, Chat from telegram import Message, Chat
@ -42,7 +43,7 @@ class ModuleV1:
try: try:
exec(self.predefine) exec(self.predefine)
except Exception as e: except Exception as e:
print("[ERROR] module: module \"{}\" ({}) raised exception \"{}\" during predefine stage, disabling it...".format(self.path, self.alias, e)) print("[ERROR] module v1: module \"{}\" ({}) raised exception \"{}\" during predefine stage, disabling it...".format(self.path, self.alias, e))
# running the module # running the module
def process(self, msg): def process(self, msg):
@ -53,10 +54,29 @@ 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: module \"{}\" ({}) raised exception \"{}\"".format(self.path, self.alias, e)) print("[ERROR] module v1: module \"{}\" ({}) raised exception \"{}\"".format(self.path, self.alias, e))
return "" return ""
class ModuleV2:
def __init__(self, path, index_file, enabled, alias):
self.version = 2
self.enabled = enabled
self.alias = alias
self.path = path
self.index_file = index_file[:-3]
self.obj = importlib.import_module((path + self.index_file).replace("/", "."))
# running the module
def process(self, msg):
try:
responce = self.obj.process(msg, self.path)
return responce
except Exception as e:
print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"")
return None
# module control unit # module control unit
class ModuleControlUnit: class ModuleControlUnit:
def __init__(self): def __init__(self):
@ -104,30 +124,13 @@ class ModuleControlUnit:
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("[INFO] reload_modules: successfully loaded {} as {} (start_on_boot: {})".format(folder, alias, enabled))
else:
print("[WARN] reload_modules: module {} requires unsupported version ({} > 1), skipping...".format(folder, meta["version"]))
except Exception as e:
print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(folder, e))
def reload_module(self, folder_name): elif meta["version"] == 2:
try:
meta_raw = readfile("modules/{}/meta.json".format(folder))
if not meta_raw:
print("[WARN] module_loader: no meta.json found in module folder \"{}\"".format(folder_name))
return 1
meta = json.loads( readfile("modules/{}/meta.json".format(folder_name)) )
if "version" in meta:
if meta["version"] == 1:
if "index_file" in meta: if "index_file" in meta:
index_file = meta["index_file"] index_file = meta["index_file"]
else: else:
index_file = "index.py" index_file = "index.py"
code = readfile( "modules/{}/{}".format(folder_name, index_file) )
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_name))
if "start_on_boot" in meta: if "start_on_boot" in meta:
enabled = meta["start_on_boot"] enabled = meta["start_on_boot"]
else: else:
@ -138,13 +141,16 @@ class ModuleControlUnit:
else: else:
alias = None alias = None
self.modules.append( ModuleV1( code, 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("[INFO] reload_modules: successfully loaded {} as {} (start_on_boot: {})".format(folder_name, alias, enabled))
else: else:
print("[WARN] reload_modules: module {} requires unsupported version ({} > 1), skipping...".format(folder_name, meta["version"])) print(f"[WARN] reload_modules: module {folder} requires unsupported version ({meta['version']} > 2), skipping...")
except Exception as e: except Exception as e:
print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(folder_name, e)) print("[ERROR] module_loader: error while loading module \"{}\" ({})".format(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:
@ -178,10 +184,10 @@ def queue_processor():
# modules are used in here # modules are used in here
for mod in mcu.modules: for mod in mcu.modules:
if mod.enabled: if mod.enabled:
if mod.version == 1: if mod.version == 1 or mod.version == 2:
responce = mod.process(msg) responce = mod.process(msg)
if len(responce) > 0: if responce:
print("Responded using module {} ({}) with text: {}".format(mod.path, mod.alias, responce)) print(f"Responded using module {mod.path} ({mod.alias}) with text: {responce}")
break break
del message_queue[0] del message_queue[0]
@ -190,6 +196,7 @@ def queue_processor():
break break
else: else:
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("[ERROR] queue_processor: current message queue: {}".format(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...")