rollbot.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import logging
  2. import time
  3. from command_system import RollbotResponse, RollbotFailure, as_plugin
  4. def lift_response(call, response):
  5. @as_plugin(call)
  6. def response_func(db, msg):
  7. return RollbotResponse(msg, txt=response)
  8. return response_func
  9. class Rollbot:
  10. def __init__(self, logger=logging.getLogger(__name__), plugin_classes={}, aliases={}, responses={}, sleep_time=0.0, session_factory=None, callback=None):
  11. self.logger = logger
  12. self.session_factory = session_factory or (lambda: None)
  13. self.post_callback = callback or (lambda txt, gid: self.logger.info(f"Responding to {gid} with {txt}"))
  14. self.commands = {}
  15. self.to_start = set()
  16. self.to_stop = set()
  17. self.logger.info("Loading command plugins")
  18. for plugin_class in plugin_classes:
  19. plugin_instance = plugin_class(self, logger=logger)
  20. if plugin_instance.command in self.commands:
  21. self.logger.error(f"Duplicate command word '{plugin_instance.command}'")
  22. raise ValueError(f"Duplicate command word '{plugin_instance.command}'")
  23. self.commands[plugin_instance.command] = plugin_instance
  24. if "on_start" in plugin_class.__dict__:
  25. self.to_start.add(plugin_instance)
  26. if "on_shutdown" in plugin_class.__dict__:
  27. self.to_stop.add(plugin_instance)
  28. self.logger.info(f"Finished loading plugins, {len(self.commands)} commands found")
  29. self.logger.info("Loading simple responses")
  30. for cmd, response in responses.items():
  31. if cmd in self.commands:
  32. self.logger.error(f"Duplicate command word '{cmd}'")
  33. raise ValueError(f"Duplicate command word '{cmd}'")
  34. self.commands[cmd] = lift_response(cmd, response)(self, logger=logger)
  35. self.logger.info(f"Finished loading simple responses, {len(self.commands)} total commands available")
  36. self.logger.info("Loading aliases")
  37. for alias, cmd in aliases.items():
  38. if cmd not in self.commands:
  39. self.logger.error(f"Missing aliased command word '{cmd}'")
  40. raise ValueError(f"Missing aliased command word '{cmd}'")
  41. if alias in self.commands:
  42. self.logger.error(f"Duplicate command word '{alias}'")
  43. raise ValueError(f"Duplicate command word '{alias}'")
  44. self.commands[alias] = self.commands[cmd]
  45. self.logger.info(f"Finished loading aliases, {len(self.commands)} total commands + aliases available")
  46. self.sleep_time = sleep_time
  47. def start_plugins(self):
  48. self.logger.info("Starting plugins")
  49. with self.session_factory() as session:
  50. for cmd in self.to_start:
  51. cmd.on_start(session)
  52. self.logger.info("Finished starting plugins")
  53. def shutdown_plugins(self):
  54. self.logger.info("Shutting down plugins")
  55. with self.session_factory() as session:
  56. for cmd in self.to_stop:
  57. cmd.on_shutdown(session)
  58. self.logger.info("Finished shutting down plugins")
  59. def run_command(self, message):
  60. if not message.is_command:
  61. self.logger.warn(f"Tried to run non-command message {message.message_id}")
  62. return RollbotResponse(message, failure=RollbotFailure.INTERNAL_ERROR)
  63. plugin = self.commands.get(message.command, None)
  64. if plugin is None:
  65. self.logger.warn(f"Message {message.message_id} had a command {message.command} that could not be run.")
  66. return RollbotResponse(message, failure=RollbotFailure.INVALID_COMMAND)
  67. with self.session_factory() as session:
  68. response = plugin.on_command(session, message)
  69. if not response.is_success:
  70. self.logger.warn(f"Message {message.message_id} caused failure")
  71. self.logger.warn(response.info)
  72. return response
  73. def handle_command(self, message):
  74. if not message.is_command:
  75. self.logger.debug("Ignoring non-command message")
  76. return
  77. self.logger.info(f"Handling message {message.message_id}")
  78. t = time.time()
  79. try:
  80. response = self.run_command(message)
  81. except Exception as e:
  82. self.logger.exception(f"Exception during command execution for message {message.message_id}")
  83. response = RollbotResponse(message, failure=RollbotFailure.INTERNAL_ERROR)
  84. if not response.respond:
  85. self.logger.info(f"Skipping response to message {message.message_id}")
  86. return
  87. self.logger.info(f"Responding to message {message.message_id}")
  88. sleep = self.sleep_time - time.time() + t
  89. if sleep > 0:
  90. self.logger.info(f"Sleeping for {sleep:.3f}s before responding")
  91. time.sleep(sleep)
  92. if response.is_success:
  93. if response.txt is not None:
  94. self.post_callback(response.txt, message.group_id)
  95. if response.img is not None:
  96. self.post_callback(response.img, message.group_id)
  97. else:
  98. self.post_callback(response.failure_msg, message.group_id)
  99. self.logger.warning(f"Failed command response: {response}")
  100. t = time.time() - t
  101. self.logger.info(f"Exiting command thread for {message.message_id} after {t:.3f}s")
  102. def manually_post_message(self, message_text, group_id):
  103. self.post_callback(message_text, group_id)