Skip to content

Commit

Permalink
commands: added a simple argument error highlighting system
Browse files Browse the repository at this point in the history
Doesn't seem to work that great with Adjacent though.
  • Loading branch information
eras committed Mar 26, 2022
1 parent 7e923a9 commit 1272900
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 18 additions & 2 deletions teslabot/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,20 @@ class ParseError(CommandsException):
class InvocationParseError(ParseError):
pass

@dataclass
class MarkedWord:
word: str
marked: bool

def mark_words(args: List[str], processed: int) -> List[MarkedWord]:
return [MarkedWord(word=word, marked=idx == processed) for idx, word in enumerate(args)]

class CommandParseError(ParseError):
pass
marked_args: List[MarkedWord]

def __init__(self, message: str, marked_args: List[MarkedWord]) -> None:
super().__init__(message)
self.marked_args = marked_args

@dataclass
class Invocation:
Expand Down Expand Up @@ -72,7 +84,11 @@ def __init__(self, name: str, description: str,
async def invoke(self, context: Context, invocation: Invocation) -> None:
validated = self.parser(invocation.args)
if isinstance(validated, ParseFail):
raise CommandParseError(validated.message)
marked_args = [MarkedWord(word=invocation.name, marked=False)]
marked_args.extend(mark_words(invocation.args,
validated.processed))
raise CommandParseError(validated.message,
marked_args=marked_args)
assert isinstance(validated, ParseOK)
await self.fn[0](context, validated.value)

Expand Down
10 changes: 10 additions & 0 deletions teslabot/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,16 @@ async def process_message(self, command_context: CommandContext, message: str) -
await self.local_commands.invoke(command_context, invocation)
else:
await self.callback.command_callback(command_context, invocation)
except commands.CommandParseError as exn:
logger.error(f"{command_context.txn}: Failed to parse command: {message}")
def format(word: str, highlight: bool) -> str:
if highlight:
return f"_{word}_"
else:
return word
marked = [format(mw.word, mw.marked) for mw in exn.marked_args]
await self.send_message(command_context.to_message_context(),
f"{command_context.txn}\n{exn.args[0]}\n{' '.join(marked)}")
except commands.ParseError as exn:
logger.error(f"{command_context.txn}: Failed to parse command: {message}")
await self.send_message(command_context.to_message_context(),
Expand Down

0 comments on commit 1272900

Please sign in to comment.