2020-09-12 14:57:08 +08:00
|
|
|
WHITESPACES = [' ', '\t', '\n']
|
|
|
|
|
|
|
|
class Command:
|
|
|
|
command_prefix = '$'
|
|
|
|
__callbacks = {}
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def __getWords(string):
|
|
|
|
words = []
|
|
|
|
# Add whitespace to accept last word
|
|
|
|
string += " "
|
|
|
|
word = ""
|
|
|
|
for c in string:
|
|
|
|
if c in WHITESPACES and len(word) > 0:
|
|
|
|
words.append(word)
|
|
|
|
word = ""
|
|
|
|
elif c not in WHITESPACES:
|
|
|
|
word = word + c
|
|
|
|
return words
|
|
|
|
|
|
|
|
@staticmethod
|
2020-09-25 16:22:14 +08:00
|
|
|
def __getCommand(string):
|
2020-09-12 14:57:08 +08:00
|
|
|
words = Command.__getWords(string);
|
2020-09-24 22:03:07 +08:00
|
|
|
if len(words) == 0: return
|
|
|
|
if words[0].startswith(Command.command_prefix):
|
2020-09-12 14:57:08 +08:00
|
|
|
return words[0][1:]
|
|
|
|
return ""
|
|
|
|
|
|
|
|
@staticmethod
|
2020-09-25 16:22:14 +08:00
|
|
|
def __getArgs(string):
|
2020-09-12 14:57:08 +08:00
|
|
|
words = Command.__getWords(string);
|
|
|
|
return words[1:]
|
|
|
|
|
2020-09-25 16:22:14 +08:00
|
|
|
# Add a command
|
2020-09-12 14:57:08 +08:00
|
|
|
@staticmethod
|
|
|
|
def registerCallback(command, callback):
|
|
|
|
Command.__callbacks[command] = callback
|
|
|
|
|
|
|
|
@staticmethod
|
2020-09-15 19:01:02 +08:00
|
|
|
async def call(channel, command):
|
2020-09-25 16:22:14 +08:00
|
|
|
func = Command.__callbacks.get(Command.__getCommand(command), None)
|
2020-09-12 14:57:08 +08:00
|
|
|
if func is not None:
|
2020-09-15 19:01:02 +08:00
|
|
|
try:
|
2020-09-25 16:22:14 +08:00
|
|
|
await func(channel, *tuple(Command.__getArgs(command)))
|
2020-09-24 22:03:07 +08:00
|
|
|
except TypeError as e:
|
|
|
|
print(e)
|
2020-09-15 19:01:02 +08:00
|
|
|
await channel.send("Incorrect usage.")
|
|
|
|
|
2020-09-12 14:57:08 +08:00
|
|
|
|