Praxis_Bot/channel_points/channelPoints_loader.py
2021-04-25 20:59:28 -04:00

80 lines
3.0 KiB
Python

import importlib
import importlib.util
import inspect
import os
import sys
from typing import Dict
from channel_points.channelPoints_base import AbstractChannelPoints
#New
def load_rewards(channelPointsType: AbstractChannelPoints.ChannelPointsType) -> Dict[str, AbstractChannelPoints]:
print(" -Loading ", channelPointsType ," ChannelPointRewards...\n")
channelPointRewards = compile_and_load(channelPointsType)
return channelPointRewards
#New
def compile_and_load_file(path: str, channelPointsType: AbstractChannelPoints.ChannelPointsType):
module_name = os.path.split(path)[1].replace(".py", "")
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.load_module(module_name)
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and name.startswith("ChannelPointReward"):
channelPointReward_inst = obj()
if channelPointsType == channelPointReward_inst.get_ChannelPointRewardType():
print(" ---Successfully loaded %s: %s" % (channelPointsType, channelPointReward_inst.get_ChannelPointRewardType()))
return channelPointReward_inst.get_ChannelPointRewardType(), channelPointReward_inst
elif channelPointsType != channelPointReward_inst.get_ChannelPointRewardType():
print(" -%s ChannelPointsType did not match: %s for: %s" % (channelPointReward_inst.get_ChannelPointRewardType(), channelPointsType, channelPointReward_inst.get_ChannelPointRewardName()))
return "", None
#New
def compile_and_load(ChannelPointsRewardType: AbstractChannelPoints.ChannelPointsType) -> Dict[str, AbstractChannelPoints]:
dic = {}
implementations = get_implementations_dir()
for dirName, subdirList, fileList in os.walk(implementations):
for file in fileList:
name = os.path.join(dirName, file)
print("compiling: %s" % name)
name, reward = compile_and_load_file(name, ChannelPointsRewardType)
if reward is not None and reward.ChannelPointRewardType is ChannelPointsRewardType:
dic[name] = reward
break
return dic
def get_base_dir() -> str:
cwd = os.getcwd()
split = os.path.split(cwd)
current = split[len(split) - 1]
if current == 'channel_points':
return check_dir(cwd)
elif current == 'Praxis_Bot' or current == 'Praxis':
return check_dir(os.path.join(cwd, "channel_points"))
else:
print("could not find working directory for Praxis_Bot/channel_points")
raise Exception
def get_implementations_dir() -> str:
return check_dir(os.path.join(get_base_dir(), "implemented"))
def get_compiled_dir() -> str:
return check_dir(os.path.join(get_base_dir(), "compiled"))
def check_dir(path: str) -> str:
if not os.path.exists(path):
os.mkdir(path, 0x777)
return path
if __name__ == "__main__":
rewards = load_rewards()