Compare commits

..

5 Commits

4 changed files with 133 additions and 88 deletions

64
main.py
View File

@ -6,6 +6,7 @@ import json
import sys
import os
import threading
import importlib
# global variables
STOP_REQUESTED = False
@ -41,7 +42,7 @@ class ModuleV1:
try:
exec(self.predefine)
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
def process(self, msg):
@ -52,9 +53,27 @@ class ModuleV1:
exec(self.code)
return self.RESPONCE
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 ""
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
class ModuleControlUnit:
@ -103,30 +122,13 @@ class ModuleControlUnit:
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))
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):
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:
elif meta["version"] == 2:
if "index_file" in meta:
index_file = meta["index_file"]
else:
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:
enabled = meta["start_on_boot"]
else:
@ -137,13 +139,15 @@ class ModuleControlUnit:
else:
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:
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:
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
#class MessageQueue:
@ -168,6 +172,12 @@ def queue_processor():
if len(command) >= 2 and command[0] == "module":
if command[1] == "reload":
print("[INFO] Module reloading triggered by a command")
# properly reload all v2 modules
for mod in mcu.modules:
if mod.version == 2:
importlib.reload(mod.obj)
del mcu.modules[:]
mcu.reload_modules()
@ -177,11 +187,11 @@ def queue_processor():
# modules are used in here
for mod in mcu.modules:
if mod.enabled:
if mod.version == 1:
if mod.version == 1 or mod.version == 2:
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)
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
del message_queue[0]

View File

@ -5,6 +5,7 @@ import json
import sys
import os
import threading
import importlib
from telegram import Message, Chat
@ -42,7 +43,7 @@ class ModuleV1:
try:
exec(self.predefine)
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
def process(self, msg):
@ -53,10 +54,29 @@ class ModuleV1:
exec(self.code)
return self.RESPONCE
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 ""
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
class ModuleControlUnit:
def __init__(self):
@ -104,30 +124,13 @@ class ModuleControlUnit:
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))
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):
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:
elif meta["version"] == 2:
if "index_file" in meta:
index_file = meta["index_file"]
else:
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:
enabled = meta["start_on_boot"]
else:
@ -138,13 +141,16 @@ class ModuleControlUnit:
else:
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:
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:
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
#class MessageQueue:
@ -169,6 +175,12 @@ def queue_processor():
if len(command) >= 2 and command[0] == "module":
if command[1] == "reload":
print("[INFO] Module reloading triggered by a command")
# properly reload all v2 modules
for mod in mcu.modules:
if mod.version == 2:
importlib.reload(mod.obj)
del mcu.modules[:]
mcu.reload_modules()
@ -178,10 +190,10 @@ def queue_processor():
# modules are used in here
for mod in mcu.modules:
if mod.enabled:
if mod.version == 1:
if mod.version == 1 or mod.version == 2:
responce = mod.process(msg)
if len(responce) > 0:
print("Responded using module {} ({}) with text: {}".format(mod.path, mod.alias, responce))
if responce:
print(f"Responded using module {mod.path} ({mod.alias}) with text: {responce}")
break
del message_queue[0]
@ -190,6 +202,7 @@ def queue_processor():
break
else:
time.sleep(1)
except Exception as e:
print("[ERROR] queue_processor: current message queue: {}".format(message_queue))
print("[ERROR] queue_processor: error while processing message, trying to delete it...")

View File

@ -0,0 +1,16 @@
class Counter:
def __init__(self):
self.counter = 0
def call_count(self):
self.counter += 1
return self.counter
c = Counter()
def get_num():
return c.call_count()
def process(message, path):
if message.text == "!v2-testing":
return f"Testing successful - call number {get_num()}"

View File

@ -0,0 +1,6 @@
{
"version": 2,
"index_file": "index.py",
"start_on_boot": true,
"alias": "module-v2-example"
}