bot.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from dataclasses import dataclass
  2. from typing import Any, Generic, TypeVar
  3. from .types import CommandConfiguration, Message, Response, Context
  4. # TODO logging
  5. RawMsg = TypeVar('RawMsg')
  6. @dataclass
  7. class Rollbot(Generic[RawMsg]):
  8. command_config: CommandConfiguration
  9. database_file: str
  10. def read_config(self, key: str) -> Any:
  11. raise NotImplemented("Must be implemented by driver")
  12. def parse(self, incoming: RawMsg) -> Message:
  13. raise NotImplemented("Must be implemented by driver")
  14. async def respond(self, response: Response):
  15. raise NotImplemented("Must be implemented by driver")
  16. async def on_message(self, incoming: RawMsg):
  17. message = self.parse(incoming)
  18. if message.text is None:
  19. return
  20. cleaned = message.text.lstrip()
  21. if len(cleaned) == 0 or cleaned[0] not in self.command_config.bangs:
  22. return
  23. parts = cleaned[1:].lstrip().split(maxsplit=1)
  24. if len(parts) == 0:
  25. return
  26. command = self.command_config.aliases.get(parts[0], parts[0])
  27. res = self.command_config.call_and_response.get(command, None)
  28. if res is not None:
  29. await self.respond(Response.from_message(message, res))
  30. return
  31. command_call = self.command_config.commands.get(command, None)
  32. if command is None:
  33. await self.respond(Response.from_message(message, f"Sorry! I don't know the command {command}."))
  34. return
  35. await command_call(Context(
  36. message=message,
  37. config=self.read_config,
  38. respond=self.respond,
  39. # database=..., # TODO database
  40. ))