-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCmdHandler.js
87 lines (79 loc) · 2.1 KB
/
CmdHandler.js
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
const fs = require('fs');
const ErrorMessages = require('./json_resources/ErrorMessages.json');
const config = require("./libs/config");
const logger = require("./libs/logger");
class CmdHandler {
constructor(folder) {
if (!folder)
throw new Error(ErrorMessages.CmdHandler.NO_FOLDER);
this.cmdFolder = folder;
this.commands = {};
this.files = [];
if (CmdHandler.verbose) {
logger.info("CmdHandler instance created");
}
}
/**
* We load all the commands in the "commands" folder.
*/
loadAllCommands() {
this.files = fs.readdirSync(`./${this.cmdFolder}/`);
this.files.forEach((file) => {
let cmdName = file.substr(0, file.length - 3);
this.commands[cmdName] = require(`./${this.cmdFolder}/${file}`);
});
if (CmdHandler.verbose) {
this.files.forEach(function(value) {
logger.info(`Loading file: ${value}`);
});
}
}
/**
* We look at the first parameter to execute the class that will execute the request command by the user.
* @param client
* @param message
*/
treatMessage(client, message) {
try {
if (message.content.startsWith(config.cmd_prefix)) {
let parsedMsg = this.getMsgParams(message.content);
let command = new this.commands[parsedMsg.cmd]();
command.run(client, message, parsedMsg.args);
}
} catch (err) {
throw err;
}
}
/**
* It is given the complete message, it passes to seperate the beginning of the message (command) of the continuation.
* @param msgContent
* @returns {{cmd: string, args: Array}}
*/
getMsgParams(msgContent) {
try {
let parsedMsg = {
cmd: '',
args: []
};
msgContent = msgContent.slice(config.cmd_prefix.length).trim().split(/ +/g);
parsedMsg.cmd = msgContent[0];
parsedMsg.args = msgContent.slice(1);
return parsedMsg;
} catch (err) {
throw err;
}
}
/**
* If this parameter is true, we will have more information at the level of the cli.
*/
static setVerbose() {
this.verbose = true;
}
/**
* If this parameter is false, we will have less information at the level of the cli.
*/
static unsetVerbose() {
this.verbose = false;
}
}
module.exports = CmdHandler;