1 |
const fs = require("fs"); |
2 |
const path = require("path"); |
3 |
const MessageEmbed = require("./MessageEmbed"); |
4 |
const SnippetManager = require("./SnippetManager"); |
5 |
const Shield = require("./Shield"); |
6 |
const { escapeRegex } = require("./util"); |
7 |
|
8 |
class CommandManager { |
9 |
constructor(cmdDir) { |
10 |
this.msg = null; |
11 |
this.commandsDirectory = cmdDir; |
12 |
this.commands = []; |
13 |
this.commandName = ""; |
14 |
this.argv = []; |
15 |
this.args = []; |
16 |
this.options = []; |
17 |
this.normalArgs = []; |
18 |
this.loadCommands(); |
19 |
this.snippetManager = new SnippetManager(); |
20 |
this.shield = new Shield(); |
21 |
} |
22 |
|
23 |
setMessage(msg) { |
24 |
this.msg = msg; |
25 |
this.argv = msg.content.split(/ +/g); |
26 |
this.args = this.argv; |
27 |
this.commandName = this.args.shift().trim().replace(new RegExp(`^${escapeRegex(app.config.get('prefix'))}`), ""); |
28 |
} |
29 |
|
30 |
loadCommands() { |
31 |
fs.readdir(this.commandsDirectory, (err, files) => { |
32 |
if (err) { |
33 |
return console.log('Unable to scan commands directory: ' + err); |
34 |
} |
35 |
|
36 |
this.commandNames = files.map(file => file.replace('\.js', '')); |
37 |
|
38 |
for (let index in files) { |
39 |
this.commands[this.commandNames[index]] = require(path.resolve(this.commandsDirectory, files[index])); |
40 |
} |
41 |
}); |
42 |
} |
43 |
|
44 |
has() { |
45 |
return typeof this.commands[this.commandName] !== 'undefined'; |
46 |
} |
47 |
|
48 |
snippet() { |
49 |
return this.snippetManager.find(this.commandName); |
50 |
} |
51 |
|
52 |
hasValid() { |
53 |
return this.has() && this.valid(); |
54 |
} |
55 |
|
56 |
valid() { |
57 |
return this.msg.content.startsWith(app.config.get('prefix')); |
58 |
} |
59 |
|
60 |
async notFound() { |
61 |
if (app.config.get('debug')) { |
62 |
await app.msg.reply({ |
63 |
embeds: [ |
64 |
new MessageEmbed() |
65 |
.setColor('#f14a60') |
66 |
.setDescription(`${escapeRegex(this.commandName)}: command not found`) |
67 |
] |
68 |
}); |
69 |
} |
70 |
} |
71 |
|
72 |
async notAllowed() { |
73 |
if (app.config.get('warn_notallowed')) { |
74 |
await app.msg.reply({ |
75 |
embeds: [ |
76 |
new MessageEmbed() |
77 |
.setColor('#f14a60') |
78 |
.setDescription(`:x: You don't have permission to run this command.`) |
79 |
] |
80 |
}); |
81 |
} |
82 |
} |
83 |
|
84 |
async exec() { |
85 |
let cmd = this.commands[this.commandName]; |
86 |
|
87 |
if (cmd.needsOptionParse) { |
88 |
this.normalArgs = await this.args.filter(arg => arg[0] !== '-'); |
89 |
this.options = await this.args.filter(arg => arg[0] === '-'); |
90 |
} |
91 |
|
92 |
return await cmd.handle(this.msg, this); |
93 |
} |
94 |
|
95 |
verify() { |
96 |
return this.shield.verify(this.msg, this); |
97 |
} |
98 |
} |
99 |
|
100 |
module.exports = CommandManager; |