bot.py 5.4 KB

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