Skip to content

Commit 5e7f1ff

Browse files
authored
Merge pull request #35 from carlos3g/command-refactor
[REFACTOR] Command refactor
2 parents 6a0d922 + fbce136 commit 5e7f1ff

File tree

20 files changed

+388
-351
lines changed

20 files changed

+388
-351
lines changed

index.js

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,31 @@
11
require('dotenv').config();
22
const { Alice } = require('./src/Alice');
3-
const build = require('./src/build');
4-
5-
const path = new build.Path(__dirname);
3+
const {
4+
Bot,
5+
Coin,
6+
Commands,
7+
Cron,
8+
Doc,
9+
Links,
10+
Lyric,
11+
Report,
12+
Search,
13+
Suggest,
14+
Wiki,
15+
} = require('./src/commands');
616

717
const alice = new Alice([
8-
path.create('src/commands/bot', 'bot'),
9-
path.create('src/commands/coin', 'coin'),
10-
path.create('src/commands/commands', 'commands'),
11-
path.create('src/commands/cron', 'cron'),
12-
path.create('src/commands/dice', 'dice'),
13-
path.create('src/commands/doc', 'doc'),
14-
path.create('src/commands/links', 'links'),
15-
path.create('src/commands/lyric', 'lyric'),
16-
path.create('src/commands/report', 'report'),
17-
path.create('src/commands/search', 'search'),
18-
path.create('src/commands/suggest', 'suggest'),
19-
path.create('src/commands/wiki', 'wiki'),
18+
new Bot(),
19+
new Coin(),
20+
new Commands(),
21+
new Cron(),
22+
new Doc(),
23+
new Links(),
24+
new Lyric(),
25+
new Report(),
26+
new Search(),
27+
new Suggest(),
28+
new Wiki(),
2029
]);
2130

2231
alice.initialize();

src/Alice.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const auth = require('./auth');
2-
const { Parse } = require('./utils/Parse');
2+
const { Parse } = require('./utils');
33
const build = require('./build');
44

55
const session = new auth.Session();
@@ -12,7 +12,7 @@ class Alice {
1212
};
1313

1414
commandsArray.forEach((cmd) => {
15-
commands.set(...cmd);
15+
commands.register(cmd);
1616
});
1717
}
1818

src/build/Commands.js

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
function isFunction(object) {
2-
return typeof object === 'function';
3-
}
4-
51
/**
62
* Commands wrapper
73
* @param {object} commands - Object that contains the commands.
@@ -17,27 +13,39 @@ class Commands {
1713
* @param {string} name - Command's name.
1814
* @param {function} callback - Callback to command.
1915
*/
20-
set(name, callback) {
21-
if (!isFunction(callback)) {
22-
throw new Error(`${callback} must be a function`);
16+
register(cmd) {
17+
if (!Commands.isValid(cmd)) {
18+
throw new Error(`${cmd} isn't a valid Command!`);
2319
}
2420

25-
this.commands[name] = callback;
21+
this.commands[cmd.name] = cmd;
2622
}
2723

2824
/**
2925
* Checks if a command is set in Commands instance.
30-
* @param {string} cmd - The command's name.
26+
* @param {string} cmdName - The command's name.
3127
* @returns {boolean} `True` if the command is set in Commands instance, `False` if not.
3228
*/
33-
has(cmd) {
29+
has(cmdName) {
3430
const availableCommands = Object.keys(this.commands);
35-
return availableCommands.includes(cmd);
31+
return availableCommands.includes(cmdName);
32+
}
33+
34+
/**
35+
* Checks if a command is valid.
36+
* @param {any} cmd - The command instance.
37+
* @returns {boolean} `True` if the command is valid, `False` if not.
38+
*/
39+
static isValid(cmd) {
40+
if (cmd.name && cmd.execute && typeof cmd.execute === 'function') {
41+
return true;
42+
}
43+
return false;
3644
}
3745

3846
/**
3947
* Calls (executes) a command.
40-
* @param {string} cmd - The command's name to be called.
48+
* @param {string} cmdName - The command's name to be called.
4149
* @param {object} data - The data extracted from the message that called the command.
4250
* @param {string} data.command - The command's name extracted from the message.
4351
* @param {string[]} data.args - The args extracted from the message.
@@ -48,15 +56,15 @@ class Commands {
4856
* @see https://docs.wwebjs.dev/Message.html
4957
* @see https://docs.wwebjs.dev/Client.html
5058
*/
51-
async call(cmd, data, message, client) {
52-
if (!this.has(cmd)) {
53-
throw new Error(`${cmd} is not registered`);
59+
async call(cmdName, data, message, client) {
60+
if (!this.has(cmdName)) {
61+
throw new Error(`${cmdName} is not registered.`);
5462
}
5563

56-
const response = await this.commands[cmd](data, message, client);
57-
58-
if (response) {
59-
message.reply(String(response));
64+
try {
65+
await this.commands[cmdName].execute(data, message, client);
66+
} catch (e) {
67+
message.reply(`❗ ${e.message}`);
6068
}
6169
}
6270
}

src/build/Path.js

Lines changed: 0 additions & 21 deletions
This file was deleted.

src/build/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,4 @@
22

33
module.exports = {
44
Commands: require('./Commands'),
5-
Path: require('./Path'),
65
};

src/commands/bot.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,13 @@
1-
module.exports = () =>
2-
`Olá, eu sou a Alice. Quer saber mais sobre mim? use o comando !doc`;
1+
class Bot {
2+
constructor() {
3+
this.name = 'bot';
4+
this.defaultMessage =
5+
'Olá, eu sou a Alice. Quer saber mais sobre mim? use o comando !doc';
6+
}
7+
8+
execute(_, message) {
9+
message.reply(this.defaultMessage);
10+
}
11+
}
12+
13+
module.exports = Bot;

src/commands/coin.js

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,6 @@
11
const axios = require('axios');
22
const cheerio = require('cheerio');
33

4-
const defaultMessage = `
5-
uso: *!coin* [--flag] name
6-
_--all -> mostra todas as informações disponiveis_
7-
8-
a flag _all_ pode retornar dados em excesso, sua utilização repetida será considera spam
9-
`;
10-
114
async function loadCheerio(url) {
125
try {
136
const { data } = await axios.get(url);
@@ -17,7 +10,7 @@ async function loadCheerio(url) {
1710
}
1811
}
1912

20-
async function getData(url) {
13+
async function getCoinStats(url) {
2114
const $ = await loadCheerio(url);
2215

2316
if (!(typeof $ === 'function')) {
@@ -30,8 +23,8 @@ async function getData(url) {
3023
.find('tr');
3124
const statsArray = [];
3225

33-
priceStatistics.each(function () {
34-
const tr = $(this);
26+
priceStatistics.each((_, pS) => {
27+
const tr = $(pS);
3528
const key = tr.find('th').text();
3629
let value = tr.find('td');
3730

@@ -43,7 +36,7 @@ async function getData(url) {
4336
value = value.text();
4437
}
4538

46-
if (value !== 'No Data' || value !== 'Sem Dados') {
39+
if (value !== 'No Data') {
4740
const object = Object.fromEntries([[key, value]]);
4841
statsArray.push(object);
4942
}
@@ -52,41 +45,53 @@ async function getData(url) {
5245
return statsArray;
5346
}
5447

55-
function getUrl(args, text) {
56-
let baseURL = 'https://coinmarketcap.com/currencies/';
57-
const path = text.replace(/\s/g, '-').toLowerCase();
48+
class Coin {
49+
constructor() {
50+
this.name = 'coin';
51+
this.BASE_URL = 'https://coinmarketcap.com/currencies/';
52+
this.defaultMessage = `
53+
uso: *!coin* [--flag] name
54+
_--all -> mostra todas as informações disponiveis_
5855
59-
if (args.includes('brl')) {
60-
baseURL = 'https://coinmarketcap.com/pt-br/currencies/';
56+
a flag _all_ pode retornar dados em excesso, sua utilização repetida será considera spam
57+
`.trim();
6158
}
6259

63-
return baseURL + path;
64-
}
60+
async execute(data, message) {
61+
const { args, text } = data;
6562

66-
module.exports = async (data) => {
67-
const { args, text } = data;
63+
if (!text) {
64+
message.reply(this.defaultMessage);
65+
return;
66+
}
6867

69-
if (!text) {
70-
return defaultMessage.trim();
71-
}
68+
const url = this.getUrl(text);
69+
let coinStats = await getCoinStats(url);
7270

73-
const url = getUrl(args, text);
74-
let coinStats = await getData(url);
71+
if (!coinStats) {
72+
message.reply('Moeda não encontrada.');
73+
return;
74+
}
7575

76-
if (!coinStats) {
77-
return 'moeda não encontrada';
78-
}
79-
if (!args.includes('all')) {
80-
coinStats = coinStats.slice(0, 3);
81-
}
76+
if (!args.includes('all')) {
77+
coinStats = coinStats.slice(0, 3);
78+
}
8279

83-
let output = '';
80+
let output = '';
8481

85-
coinStats.forEach((s) => {
86-
const [key, value] = Object.entries(s)[0];
87-
const string = `*_${key}_*:\n - ${value}\n\n`;
88-
output += string;
89-
});
82+
coinStats.forEach((s) => {
83+
const [key, value] = Object.entries(s)[0];
84+
const string = `*_${key}_*:\n - ${value}\n\n`;
85+
output += string;
86+
});
87+
88+
message.reply(output.trim());
89+
}
90+
91+
getUrl(text) {
92+
const path = text.replace(/\s/g, '-').toLowerCase();
93+
return this.BASE_URL + path;
94+
}
95+
}
9096

91-
return output.trim();
92-
};
97+
module.exports = Coin;

src/commands/commands.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,25 @@
1-
module.exports = () =>
2-
`Os seguintes comandos estão disponiveis:
1+
class Commands {
2+
constructor() {
3+
this.name = 'commands';
4+
this.defaultMessage = `
5+
Os seguintes comandos estão disponiveis:
36
- !bot
47
- !coin
58
- !commands
69
- !cron
7-
- !dice
810
- !doc
9-
- !github
1011
- !links
1112
- !lyric
1213
- !report
1314
- !search
1415
- !suggest
15-
- !wiki`.trim();
16+
- !wiki
17+
`.trim();
18+
}
19+
20+
execute(_, message) {
21+
message.reply(this.defaultMessage);
22+
}
23+
}
24+
25+
module.exports = Commands;

0 commit comments

Comments
 (0)