File size: 2,001 Bytes
c323312 7e4014b fb7c0d6 7e4014b c323312 7e4014b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
from custom_exceptions import InvalidCommandError
class CommandCenter:
def __init__(self, default_input_type, default_function=None, all_commands=None):
self.commands = {}
self.add_command("/default", default_input_type, default_function)
if all_commands:
for command, input_type, function in all_commands:
self.add_command(command, input_type, function)
def add_command(self, command, input_type, function=None):
assert input_type in [None, str, int, float, bool, list], "Invalid input type"
self.commands[command] = {"input_type": input_type, "function": function}
def parse_command(self, input_string):
# parsing the input string
input_string = input_string.strip()
if not input_string.startswith("/"):
command = "/default"
argument = input_string.split(" ")
else:
inputs = input_string.split(" ")
command = inputs[0]
argument = inputs[1:]
if command not in self.commands:
raise InvalidCommandError("Invalid command")
# type casting the arguments
if self.commands[command]["input_type"] == str:
argument = " ".join(argument)
elif self.commands[command]["input_type"] == int:
argument = int(" ".join(argument))
elif self.commands[command]["input_type"] == float:
argument = float(" ".join(argument))
elif self.commands[command]["input_type"] == bool:
argument = bool(" ".join(argument))
elif self.commands[command]["input_type"] == list:
argument = argument
else:
argument = None
return command, argument
def execute_command(self, input_string):
command, argument = self.parse_command(input_string)
if command in self.commands:
return self.commands[command]["function"](argument)
else:
return "Invalid command"
|