plugins.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import logging
  2. import inspect
  3. from functools import reduce
  4. from .messaging import RollbotResponse
  5. class RollbotPlugin:
  6. def __init__(self, command, bot, logger=logging.getLogger(__name__)):
  7. self.command = command
  8. self.bot = bot
  9. self.logger = logger
  10. self.logger.info(f"Intializing {type(self).__name__} matching {command}")
  11. def on_start(self, db):
  12. self.logger.info(f"No on_start initialization of {type(self).__name__}")
  13. def on_shutdown(self, db):
  14. self.logger.info(f"No on_shutdown de-initialization of {type(self).__name__}")
  15. def on_command(self, db, message):
  16. raise NotImplementedError
  17. @staticmethod
  18. def find_all_plugins():
  19. def get_subclasses(clazz):
  20. s = set(clazz.__subclasses__())
  21. return s | reduce(set.union, (get_subclasses(sc) for sc in s), set())
  22. return get_subclasses(RollbotPlugin)
  23. def as_plugin(command):
  24. if isinstance(command, str):
  25. command_name = command
  26. else:
  27. command_name = command.__name__
  28. def init_standin(self, bot, logger=logging.getLogger(__name__)):
  29. RollbotPlugin.__init__(self, command_name, bot, logger=logger)
  30. def decorator(fn):
  31. sig = inspect.signature(fn)
  32. converters = []
  33. for p in sig.parameters:
  34. if p in ("msg", "message", "_msg"):
  35. converters.append(lambda cmd, db, msg: msg)
  36. elif p in ("db", "database"):
  37. converters.append(lambda cmd, db, msg: db)
  38. elif p in ("log", "logger"):
  39. converters.append(lambda cmd, db, msg: cmd.logger)
  40. elif p in ("bot", "rollbot"):
  41. converters.append(lambda cmd, db, msg: cmd.bot)
  42. elif p.startswith("data") or p.endswith("data") or p in ("group_singleton", "singleton"):
  43. annot = fn.__annotations__.get(p, p)
  44. converters.append(lambda cmd, db, msg, sing_cls=annot: sing_cls.get_or_create(db, msg.group_id))
  45. else:
  46. raise ValueError(f"Illegal argument name {p} in decorated plugin {command_name}")
  47. def on_command_standin(self, db, msg):
  48. res = fn(*[c(self, db, msg) for c in converters])
  49. if isinstance(res, RollbotResponse):
  50. return res
  51. else:
  52. return RollbotResponse(msg, txt=str(res))
  53. return type(
  54. f"AutoGenerated`{command_name}`Command",
  55. (RollbotPlugin,),
  56. dict(
  57. __init__=init_standin,
  58. on_command=on_command_standin,
  59. )
  60. )
  61. if isinstance(command, str):
  62. return decorator
  63. else:
  64. return decorator(command)