Add initial draft of importlib code

This commit is contained in:
minerobber 2019-01-28 23:30:50 +00:00
parent 9aa3f39e9b
commit 95c5edb76b
1 changed files with 29 additions and 2 deletions

31
bot.py
View File

@ -1,8 +1,28 @@
import teambot, sys, traceback, imp, plugin, os
import teambot, sys, traceback, plugin, os
import importlib, importlib.util
BOTOP = "~minerobber@127.0.0.1"
PREFIX = "!"
PLUGIN_MODULES = dict()
PLUGIN_SPECS = dict()
# hacky re-implementation of reload, uses importlib internals and hardcoded stuffs
def reloadModule(modname):
if modname not in PLUGIN_MODULES:
return False
if modname not in sys.modules:
sys.modules[modname]=PLUGIN_MODULES[modname]
# Alright, this needs some explaining.
# When you do importlib.reload, it does some juju magic shist to find the spec and calls importlib._bootstrap._exec.
# When you dynamically import a module it won't do its magic correctly and it'll error.
# Luckily, we can skip all the juju magic since we can just store the spec.
try:
importlib._bootstrap._exec(PLUGIN_SPECS[modname],PLUGIN_MODULES[modname])
except:
print("On reloading `{}`:".format(modname))
traceback.print_exc()
return False
return True
class MinerbotPhoenix(teambot.Handler):
def on_connection_established(self,*args):
@ -14,13 +34,20 @@ class MinerbotPhoenix(teambot.Handler):
bot.handler.load_module(name[:-3],os.path.join("plugins",name))
def load_module(self,modname,path):
if modname in PLUGIN_MODULES:
importlib.reload(PLUGIN_MODULES[modname])
print("{} already imported, reloading".format(modname))
if reloadModule(modname):
print("{} reloaded".format(modname))
else:
print("{} reload errored, skipping".format(modname))
return
try:
print("importing {}".format(modname))
spec = importlib.util.spec_from_file_location(modname,path)
PLUGIN_SPECS[modname]=spec
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
PLUGIN_MODULES[modname]=module
sys.modules[modname]=module
except:
print("Unable to load plugin {}".format(modname))
traceback.print_exc()