-
Notifications
You must be signed in to change notification settings - Fork 3
/
commandsmanager.py
159 lines (123 loc) · 4.96 KB
/
commandsmanager.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import inspect
import json
import jsonpickle
import logging
import os
import toml
from argparser import ArgumentsParser
from config import PATH
from util import get_version
COMMANDS_PATH = PATH + "/commands"
VERSION = get_version()
class CommandsManager:
def __init__(self):
self.commands = self.parse()
# This command is used to load the modules when needed
def get(self, name):
# For the reason why we need the fromlist argument see
# < http://stackoverflow.com/questions/2724260 >
return __import__("commands.%s.command" % name, fromlist="commands")
# List all commands with arguments and methods
def listall(self):
commands = {}
cmdnames = sorted(list(set(self.commands.values())))
for cmdname in cmdnames:
cmd = self.get(cmdname)
if cmd.__doc__:
description = cmd.__doc__.strip()
else:
description = None
commands[cmdname] = {
"aliases" : getattr(cmd, "aliases", None),
"arguments" : getattr(cmd, "arguments", None),
"cacheable" : getattr(cmd, "CACHEABLE", None),
"description" : description,
"methods" : getattr(cmd, "methods", None),
"name" : cmdname
}
return json.loads(jsonpickle.encode(commands, unpicklable = False))
def parse(self):
commands = {}
logging.info("Parsing commands")
cmddirs = [c for c in os.listdir(COMMANDS_PATH) if c[0] != "_" and c[0] != "."]
logging.info("Commands we're going to load %s" % cmddirs)
for cmdname in cmddirs:
logging.debug("Parsing <%s>" % cmdname)
command = self.get(cmdname)
commands[cmdname] = cmdname
if hasattr(command, "aliases"):
for alias in command.aliases:
commands[alias] = cmdname
logging.info("Okay, loaded <%s>" % cmdname)
logging.debug("Done loading")
return commands
def execute(self, params, cmd, cmdmethod, name):
logging.debug("Executing command %s/%s" % (name, cmdmethod))
logging.debug("With params " + json.dumps(params, indent = 4))
if not hasattr(cmd, "run"):
raise TypeError("Chantek commands required a 'run' method")
# If there is an 'arguments' dict, use that to fill in default
# values for the params
if hasattr(cmd, "arguments"):
logging.debug(f"Parsing default arguments for <{name}>")
parser = ArgumentsParser(params, cmd.arguments, cmdmethod)
params = parser.get_params()
if hasattr(cmd, "methods"):
# Python casts tuples with one value to a string, so we
# need to explicitely make it a tuple
if isinstance(cmd.methods, str):
cmd.methods = (cmd.methods, )
# Check if methods is not something weird
if not isinstance(cmd.methods, tuple) and \
not isinstance(cmd.methods, list):
raise Exception("Methods need to be of type tuple or list")
if not cmdmethod:
raise TypeError(f"This command needs one of these methods: {cmd.methods}")
elif cmdmethod not in cmd.methods:
raise Exception("Invalid method for <%s>" % name)
response = cmd.run(params, cmdmethod)
else:
# Check if this command wants the 'params' array or not
spec = inspect.getargspec(cmd.run)
if len(spec.args) == 0:
logging.debug("Command has no arguments, not providing params")
response = cmd.run()
else:
response = cmd.run(params)
return response
def error(self, msg):
return { "error" : msg }
def run(self, cmdname, cmdmethod = None, params = False):
if cmdname not in self.commands:
return False, self.error("unknown command %s" % cmdname)
name = self.commands[cmdname]
cmd = self.get(name)
if cmdmethod and not hasattr(cmd, 'methods'):
return False, self.error("<%s> does not have any methods" % name)
data_response = {
"chantek" : VERSION,
"command" : name,
"params" : params,
}
try:
response = self.execute(
params = params,
cmd = cmd,
cmdmethod = cmdmethod,
name = name
)
except Exception as e:
data_response.update({
"error" : {
"message" : "<%s>: %s" % (name, e)
},
"response" : False
})
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
raise
else:
data_response.update({
"error" : False,
"response" : response
})
return cmd, data_response