as_plugin.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import logging
  2. import inspect
  3. from ...messaging import RollbotResponse, RollbotFailure, RollbotFailureException
  4. from ..base import RollbotPlugin
  5. from .arg_wiring import get_converters
  6. def as_plugin(command):
  7. if isinstance(command, str):
  8. command_name = command
  9. else:
  10. command_name = command.__name__
  11. def init_standin(self, bot, logger=logging.getLogger(__name__)):
  12. RollbotPlugin.__init__(self, command_name, bot, logger=logger)
  13. def decorator(fn):
  14. sig = inspect.signature(fn)
  15. try:
  16. converters = get_converters(sig.parameters, fn.__annotations__)
  17. except ValueError as ve:
  18. raise ValueError(f"Illegal argument name {str(ve)} in decorated plugin {command_name}")
  19. def on_command_standin(self, db, msg):
  20. try:
  21. res = fn(*[c(self, db, msg) for c in converters])
  22. except RollbotFailureException as rfe:
  23. res = rfe.failure
  24. if res is None:
  25. return RollbotResponse(msg, respond=False)
  26. elif isinstance(res, RollbotResponse):
  27. return res
  28. elif isinstance(res, RollbotFailure):
  29. return RollbotResponse(msg, failure=res, debugging=res.get_debugging())
  30. else:
  31. return RollbotResponse(msg, txt=str(res))
  32. return type(
  33. f"AutoGenerated`{command_name}`Command",
  34. (RollbotPlugin,),
  35. dict(
  36. __init__=init_standin,
  37. on_command=on_command_standin,
  38. )
  39. )
  40. if isinstance(command, str):
  41. return decorator
  42. else:
  43. return decorator(command)