File size: 1,937 Bytes
be3de43 edcbd4b be3de43 7edeafb be3de43 7edeafb be3de43 162a5cd be3de43 162a5cd be3de43 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import importlib
import os
from typing import Dict
import git
REPO_PATH = "student_bots"
class BotCache:
"""
Stores and updates bot modules from a git repo
"""
def __init__(self):
self.bots = self._load_bots()
def update(self) -> Dict[str, type]:
"""
Update and return bot dictionary
Returns:
Dict[str, type]: maps bot names to bot classes
"""
self.bots = self._load_bots()
return self.bots
@staticmethod
def _load_bots() -> Dict[str, type]:
print("Refreshing bots")
BotCache._refresh_files()
python_files = [f[:-3] for f in os.listdir(REPO_PATH)
if f.endswith(".py")]
all_classes = []
for py in python_files:
# import
mod = __import__('.'.join([REPO_PATH, py]), fromlist=[py])
# reload
importlib.reload(mod)
# get classes
classes = [getattr(mod, x) for x in dir(mod)
if isinstance(getattr(mod, x), type)]
all_classes.extend(classes)
bots = {}
error_num = 0
for cls in all_classes:
try:
bots[cls.get_name()] = cls
except:
try:
bots[cls().get_name()] = cls
except:
bots[f"Error fetching name {error_num}"] = cls
error_num += 1
return bots
@staticmethod
def _refresh_files():
if os.path.exists(REPO_PATH):
repo = git.Repo(REPO_PATH)
origin = repo.remotes.origin
origin.pull()
else:
pat_token = os.environ["GITHUB_PAT_TOKEN"]
username = os.environ["GITHUB_USERNAME"]
repo = os.environ["GITHUB_REPO"]
git.Repo.clone_from(f"https://{pat_token}@github.com/{username}/{repo}.git", REPO_PATH)
|