from django.conf import settings import subprocess, os class Bot: plugin_port = getattr(settings, 'PLUGIN_PORT', None) bot_dir = getattr(settings, 'BOT_DIR', "") if not bot_dir.endswith("/"): bot_dir += "/" def __init__(self, name, asset, executable=None, start=None, stop=None, restart=None, status=None, display=None): self.name = name self.asset = asset self.executable = executable self.start = start if start else self._start self.stop = stop if stop else self._stop self.restart = restart if restart else self._restart self.status = status if status else self._status self.display = display if display else self._display self.dir = "{}/assets/".format(os.path.dirname(os.path.abspath(__file__))) if self.asset else self.bot_dir def _start(self): screen = 'screen -S {0}_{1} -d -m {2} {3}{1}.bot.py' subprocess.run(screen.format(self.plugin_port, self.name, self.executable, self.dir), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _stop(self): subprocess.run('screen -X -S "{0}_{1}" quit'.format(self.plugin_port, self.name), shell=True) def _restart(self): self.stop() self.start() def _status(self): screens = subprocess.getoutput("screen -ls") return True if "{0}_{1}".format(self.plugin_port, self.name) in screens else False def _display(self): return "Started" if self.status() else "Stopped"