Minor changes.
This commit is contained in:
parent
efac73776f
commit
72c5b0b4a9
62
main.py
62
main.py
|
@ -11,16 +11,18 @@ import importlib
|
||||||
# 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):
|
||||||
|
@ -42,7 +44,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):
|
||||||
|
@ -53,9 +56,10 @@ 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 ""
|
||||||
|
|
||||||
|
|
||||||
class ModuleV2:
|
class ModuleV2:
|
||||||
def __init__(self, path, index_file, enabled, alias):
|
def __init__(self, path, index_file, enabled, alias):
|
||||||
self.version = 2
|
self.version = 2
|
||||||
|
@ -68,8 +72,8 @@ class ModuleV2:
|
||||||
# running the module
|
# running the module
|
||||||
def process(self, msg):
|
def process(self, msg):
|
||||||
try:
|
try:
|
||||||
responce = self.obj.process(msg, self.path)
|
response = self.obj.process(msg, self.path)
|
||||||
return responce
|
return response
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"")
|
print(f"[ERROR] module v2: module \"{self.path}\" ({self.alias}) raised exception \"{e}\"")
|
||||||
return None
|
return None
|
||||||
|
@ -88,7 +92,7 @@ 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 )
|
||||||
|
@ -103,7 +107,7 @@ class ModuleControlUnit:
|
||||||
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("[WARN] reload_modules: module {} does not have any code, skipping...".format(folder))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if "start_on_boot" in meta:
|
if "start_on_boot" in meta:
|
||||||
enabled = meta["start_on_boot"]
|
enabled = meta["start_on_boot"]
|
||||||
else:
|
else:
|
||||||
|
@ -119,9 +123,10 @@ class ModuleControlUnit:
|
||||||
else:
|
else:
|
||||||
predefine = False
|
predefine = False
|
||||||
|
|
||||||
self.modules.append( ModuleV1( "modules/{}/".format(folder), code, enabled, alias, predefine ) )
|
self.modules.append(ModuleV1(f"modules/{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:
|
||||||
|
@ -141,19 +146,15 @@ 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
|
|
||||||
#class MessageQueue:
|
|
||||||
# def __init__(self):
|
|
||||||
# print("[INFO] Initializing the message queue...")
|
|
||||||
# self.queue = []
|
|
||||||
|
|
||||||
|
|
||||||
# synchronous message processor
|
# synchronous message processor
|
||||||
|
@ -163,12 +164,12 @@ def queue_processor():
|
||||||
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:
|
||||||
if msg["text"][0] == "$":
|
if msg["text"][0] == "$":
|
||||||
command = msg["text"][1:].split(" ")
|
command = msg["text"][1:].split(" ")
|
||||||
|
|
||||||
if len(command) >= 2 and command[0] == "module":
|
if len(command) >= 2 and command[0] == "module":
|
||||||
if command[1] == "reload":
|
if command[1] == "reload":
|
||||||
print("[INFO] Module reloading triggered by a command")
|
print("[INFO] Module reloading triggered by a command")
|
||||||
|
@ -180,20 +181,21 @@ def queue_processor():
|
||||||
|
|
||||||
del mcu.modules[:]
|
del mcu.modules[:]
|
||||||
mcu.reload_modules()
|
mcu.reload_modules()
|
||||||
|
|
||||||
del message_queue[0]
|
del message_queue[0]
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 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 or mod.version == 2:
|
if mod.version == 1 or mod.version == 2:
|
||||||
responce = mod.process(msg)
|
responce = mod.process(msg)
|
||||||
if responce:
|
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(f"Responded using module {mod.path} ({mod.alias}) with text: {responce}")
|
print(f"Responded using module {mod.path} ({mod.alias}) with text: {responce}")
|
||||||
break
|
break
|
||||||
|
|
||||||
del message_queue[0]
|
del message_queue[0]
|
||||||
|
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
@ -202,8 +204,8 @@ def queue_processor():
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
except Exception as e:
|
except Exception:
|
||||||
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]
|
||||||
|
@ -216,7 +218,7 @@ def queue_processor():
|
||||||
|
|
||||||
# telegram bot processor
|
# telegram bot processor
|
||||||
def message_handler(update, context):
|
def message_handler(update, context):
|
||||||
print("[DEBUG] Received new message") # just for testing
|
print("[DEBUG] Received new message") # just for testing
|
||||||
message_queue.append(update.message)
|
message_queue.append(update.message)
|
||||||
|
|
||||||
|
|
||||||
|
@ -229,7 +231,7 @@ 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()
|
||||||
|
|
||||||
|
|
||||||
|
@ -241,7 +243,7 @@ if not TOKEN:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# connect to Telegram servers
|
# connect to Telegram servers
|
||||||
updater = Updater(TOKEN, use_context = True)
|
updater = Updater(TOKEN, use_context=True)
|
||||||
dispatcher = updater.dispatcher
|
dispatcher = updater.dispatcher
|
||||||
|
|
||||||
# assign the handler for messages
|
# assign the handler for messages
|
||||||
|
|
|
@ -45,8 +45,8 @@ class ModuleV1:
|
||||||
try:
|
try:
|
||||||
exec(self.predefine)
|
exec(self.predefine)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{e}\""
|
print(f"[ERROR] module v1: module \"{self.path}\" ({self.alias}) raised exception \"{e}\" "
|
||||||
f" during predefine stage, disabling it...")
|
f"during predefine stage, disabling it...")
|
||||||
|
|
||||||
# running the module
|
# running the module
|
||||||
def process(self, msg):
|
def process(self, msg):
|
||||||
|
@ -124,7 +124,7 @@ class ModuleControlUnit:
|
||||||
else:
|
else:
|
||||||
predefine = False
|
predefine = False
|
||||||
|
|
||||||
self.modules.append(ModuleV1("modules/{}/".format(folder), code, enabled, alias, predefine))
|
self.modules.append(ModuleV1(f"modules/{folder}/", code, enabled, alias, predefine))
|
||||||
|
|
||||||
print(f"[INFO] reload_modules: successfully loaded {folder} as {alias} "
|
print(f"[INFO] reload_modules: successfully loaded {folder} as {alias} "
|
||||||
f"(start_on_boot: {enabled})")
|
f"(start_on_boot: {enabled})")
|
||||||
|
|
Loading…
Reference in New Issue