Selaa lähdekoodia

Adding a Command type for caching

Kirk Trombley 4 vuotta sitten
vanhempi
commit
0d3c24beba
2 muutettua tiedostoa jossa 38 lisäystä ja 10 poistoa
  1. 9 8
      lib/rollbot/bot.py
  2. 29 2
      lib/rollbot/types.py

+ 9 - 8
lib/rollbot/bot.py

@@ -4,7 +4,7 @@ import asyncio
 
 import aiosqlite
 
-from .types import CommandConfiguration, Message, Response, Context
+from .types import CommandConfiguration, Message, Response, Context, Command
 
 # TODO logging
 
@@ -48,15 +48,16 @@ class Rollbot(Generic[RawMsg]):
         if message.text is None:
             return
 
-        cleaned = message.text.lstrip()
-        if len(cleaned) == 0 or cleaned[0] not in self.command_config.bangs:
+        message.command = Command.from_text(message.text)
+        if (
+            message.command is None
+            or message.command.bang not in self.command_config.bangs
+        ):
             return
 
-        parts = cleaned[1:].lstrip().split(maxsplit=1)
-        if len(parts) == 0:
-            return
-
-        command = self.command_config.aliases.get(parts[0], parts[0])
+        command = self.command_config.aliases.get(
+            message.command.name, message.command.name
+        )
         res = self.command_config.call_and_response.get(command, None)
         if res is not None:
             await self.respond(Response.from_message(message, res))

+ 29 - 2
lib/rollbot/types.py

@@ -20,8 +20,35 @@ class Message:
     timestamp: datetime
     origin_admin: bool
     channel_admin: bool
-    text: Optional[str]
-    attachments: list[Attachment]
+    text: Optional[str] = None
+    attachments: list[Attachment] = field(default_factory=list)
+
+    def __post_init__(self):
+        self.command = None
+
+
+@dataclass
+class Command:
+    bang: str
+    name: str
+    args: str
+
+    @staticmethod
+    def from_text(text: str) -> Optional["Command"]:
+        cleaned = text.lstrip()
+
+        if len(cleaned) < 2:
+            return None
+
+        parts = cleaned[1:].lstrip().split(maxsplit=1)
+        if len(parts) == 0:
+            return None
+
+        return Command(
+            bang=cleaned[0],
+            name=parts[0],
+            args=parts[1] if len(parts) > 1 else "",
+        )
 
 
 @dataclass