Browse Source

Improving the as_plugin decorator to allow more custom behavior

Kirk Trombley 6 years ago
parent
commit
30731bc2e6
1 changed files with 16 additions and 2 deletions
  1. 16 2
      src/command_system.py

+ 16 - 2
src/command_system.py

@@ -1,6 +1,7 @@
 import logging
 from dataclasses import dataclass
 from enum import Enum, auto
+import inspect
 
 from sqlalchemy.ext.declarative import declarative_base
 
@@ -148,7 +149,6 @@ class RollbotPlugin:
         raise NotImplementedError
 
 
-
 def as_plugin(command):
     if isinstance(command, str):
         command_name = command
@@ -159,12 +159,26 @@ def as_plugin(command):
         RollbotPlugin.__init__(self, command_name, bot, logger=logger)
 
     def decorator(fn):
+        sig = inspect.signature(fn)
+        converters = []
+        for p in sig.parameters:
+            if p in ("msg", "message"):
+                converters.append(lambda self, db, msg: msg)
+            elif p in ("db", "database"):
+                converters.append(lambda self, db, msg: db)
+            elif p in ("log", "logger"):
+                converters.append(lambda self, db, msg: self.logger)
+            elif p == "bot":
+                converters.append(lambda self, db, msg: self.bot)
+            else:
+                raise ValueError(f"Illegal argument name {p} in decorated plugin {command_name}")
+
         return type(
             f"AutoGenerated`{command_name}`Command",
             (RollbotPlugin,),
             dict(
                 __init__=init_standin,
-                on_command=(lambda _, *a: fn(*a))
+                on_command=(lambda *a: fn(*[c(*a) for c in converters]))
             )
         )