Skip to content

Commit 60abd51

Browse files
authored
Merge pull request #40 from carlos3g/master
REFACTOR
2 parents d404126 + 2e733e8 commit 60abd51

File tree

14 files changed

+248
-174
lines changed

14 files changed

+248
-174
lines changed

index.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
require('dotenv').config();
22
const { Alice } = require('./src/Alice');
33
const {
4-
Bot,
4+
About,
55
Coin,
66
Commands,
77
Cron,
8-
Doc,
98
Links,
109
Lyric,
1110
Report,
@@ -15,11 +14,10 @@ const {
1514
} = require('./src/commands');
1615

1716
const alice = new Alice([
18-
new Bot(),
17+
new About(),
1918
new Coin(),
2019
new Commands(),
2120
new Cron(),
22-
new Doc(),
2321
new Links(),
2422
new Lyric(),
2523
new Report(),

src/commands/about.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const STRINGS = {
2+
help: `
3+
Mostra informações sobre o bot.
4+
5+
*uso:* \`\`\`!about [--args]\`\`\`
6+
7+
*args válidos:*
8+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
9+
`.trim(),
10+
11+
about: `
12+
Alice foi criada utilizando a biblioteca \`\`\`whatsapp-web.js\`\`\` como base sob licença Apache 2.0. Saiba mais em _https://github.com/pedroslopez/whatsapp-web.js_
13+
14+
Não sabe como usar um comando? Use a flag help, ex: \`\`\`!lyric --help\`\`\`. Se não conhece os comandos, use \`\`\`!commands\`\`\`
15+
16+
_Quer contribuir? Então dá uma olhada em https://github.com/Coding-in-community/alice_
17+
`.trim(),
18+
};
19+
20+
class About {
21+
constructor() {
22+
this.name = 'about';
23+
this.strings = STRINGS;
24+
}
25+
26+
execute(data, message) {
27+
const { args } = data;
28+
29+
if (args.includes('help')) {
30+
message.reply(this.strings.help);
31+
return;
32+
}
33+
34+
message.reply(this.strings.about);
35+
}
36+
}
37+
38+
module.exports = About;

src/commands/bot.js

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

src/commands/coin.js

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

4+
const STRINGS = {
5+
help: `
6+
Retorna dados de uma moeda disponível no CoinMarketCap (https://coinmarketcap.com).
7+
8+
*uso:* \`\`\`!coin [--args] coin_name\`\`\`
9+
10+
*args válidos:*
11+
\`\`\`--all\`\`\` -> _retorna todos os dados disponíveis._
12+
\`\`\`--help\`\`\` -> _mostra essa mensagem._
13+
`.trim(),
14+
};
15+
416
async function loadCheerio(url) {
517
try {
618
const { data } = await axios.get(url);
@@ -13,8 +25,8 @@ async function loadCheerio(url) {
1325
async function getCoinStats(url) {
1426
const $ = await loadCheerio(url);
1527

16-
if (!(typeof $ === 'function')) {
17-
return null;
28+
if (typeof $ !== 'function') {
29+
throw new Error('Moeda não encontrada.');
1830
}
1931

2032
const priceStatistics = $('.sc-16r8icm-0.nds9rn-0.dAxhCK')
@@ -49,34 +61,38 @@ class Coin {
4961
constructor() {
5062
this.name = 'coin';
5163
this.BASE_URL = 'https://coinmarketcap.com/currencies/';
52-
this.defaultMessage = `
53-
uso: *!coin* [--flag] name
54-
_--all -> mostra todas as informações disponiveis_
55-
56-
a flag _all_ pode retornar dados em excesso, sua utilização repetida será considera spam
57-
`.trim();
64+
this.strings = STRINGS;
5865
}
5966

6067
async execute(data, message) {
6168
const { args, text } = data;
6269

63-
if (!text) {
64-
message.reply(this.defaultMessage);
70+
if (args.includes('help')) {
71+
message.reply(this.strings.help, undefined, { linkPreview: false });
6572
return;
6673
}
6774

6875
const url = this.getUrl(text);
6976
let coinStats = await getCoinStats(url);
7077

71-
if (!coinStats) {
72-
message.reply('Moeda não encontrada.');
73-
return;
74-
}
75-
7678
if (!args.includes('all')) {
7779
coinStats = coinStats.slice(0, 3);
7880
}
7981

82+
const output = Coin.formatStats(coinStats);
83+
message.reply(output);
84+
}
85+
86+
getUrl(text) {
87+
if (!text) {
88+
throw new Error('Nenhuma moeda foi passada.');
89+
}
90+
91+
const path = text.replace(/\s/g, '-').toLowerCase();
92+
return this.BASE_URL + path;
93+
}
94+
95+
static formatStats(coinStats) {
8096
let output = '';
8197

8298
coinStats.forEach((s) => {
@@ -85,12 +101,7 @@ a flag _all_ pode retornar dados em excesso, sua utilização repetida será con
85101
output += string;
86102
});
87103

88-
message.reply(output.trim());
89-
}
90-
91-
getUrl(text) {
92-
const path = text.replace(/\s/g, '-').toLowerCase();
93-
return this.BASE_URL + path;
104+
return output.trim();
94105
}
95106
}
96107

src/commands/commands.js

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
1-
class Commands {
2-
constructor() {
3-
this.name = 'commands';
4-
this.defaultMessage = `
1+
const STRINGS = {
2+
help: `
3+
Lista todos os comandos disponíveis.
4+
5+
*uso:* \`\`\`!commands [--args]\`\`\`
6+
7+
*args válidos:*
8+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
9+
`.trim(),
10+
11+
availableCommands: `
512
Os seguintes comandos estão disponiveis:
613
- !bot
714
- !coin
@@ -14,11 +21,24 @@ Os seguintes comandos estão disponiveis:
1421
- !search
1522
- !suggest
1623
- !wiki
17-
`.trim();
24+
`.trim(),
25+
};
26+
27+
class Commands {
28+
constructor() {
29+
this.name = 'commands';
30+
this.strings = STRINGS;
1831
}
1932

20-
execute(_, message) {
21-
message.reply(this.defaultMessage);
33+
execute(data, message) {
34+
const { args } = data;
35+
36+
if (args.includes('help')) {
37+
message.reply(this.strings.help);
38+
return;
39+
}
40+
41+
message.reply(this.strings.availableCommands);
2242
}
2343
}
2444

src/commands/cron.js

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
const events = require('events');
22
const { chattools, Time } = require('../utils');
33

4+
const STRINGS = {
5+
help: `
6+
Repete uma mensagem em um determinado período de tempo. Cada mensagem é representada por uma thread.
7+
8+
*uso:* \`\`\`!cron --args [--kwargs=<type>] ...\`\`\`
9+
10+
*args válidos:*
11+
\`\`\`--create\`\`\` -> _cria uma nova thread._
12+
\`\`\`--destroy\`\`\` -> _para e apaga uma thread._
13+
\`\`\`--stop\`\`\` -> _para uma thread._
14+
\`\`\`--start\`\`\` -> _inicia uma thread._
15+
\`\`\`--log\`\`\` -> _mostra as threads existentes._
16+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
17+
18+
*kwargs válidos:*
19+
\`\`\`--s=<int>\`\`\` -> _define um periodo em segundos._
20+
\`\`\`--m=<int>\`\`\` -> _define um periodo em minutos._
21+
\`\`\`--h=<int>\`\`\` -> _define um periodo em horas._
22+
\`\`\`--d=<int>\`\`\` -> _define um periodo em dias._
23+
`.trim(),
24+
};
425
const emitter = new events.EventEmitter();
526

627
function Thread(id, text, message, timer) {
@@ -22,35 +43,18 @@ class Cron {
2243
this.name = 'cron';
2344
this.threads = [];
2445
this.counter = 0;
25-
this.defaultMessage = `
26-
Repete uma mensagem em um determinado período de tempo. Cada mensagem é representada por uma thread.
27-
28-
*uso:* \`\`\`!command [--args] [--kwargs=<type>] ...\`\`\`
29-
30-
*args válidos:*
31-
\`\`\`--create\`\`\` -> _cria uma nova thread._
32-
\`\`\`--destroy\`\`\` -> _para e apaga uma thread._
33-
\`\`\`--stop\`\`\` -> _para uma thread._
34-
\`\`\`--start\`\`\` -> _inicia uma thread._
35-
\`\`\`--log\`\`\` -> _mostra as threads existentes._
36-
37-
*kwargs válidos:*
38-
\`\`\`--s=<int>\`\`\` -> _define um periodo em segundos._
39-
\`\`\`--m=<int>\`\`\` -> _define um periodo em minutos._
40-
\`\`\`--h=<int>\`\`\` -> _define um periodo em horas._
41-
\`\`\`--d=<int>\`\`\` -> _define um periodo em dias._
42-
`.trim();
46+
this.strings = STRINGS;
4347
}
4448

4549
async execute(data, message) {
4650
const isAdm = await chattools.isAdm(message);
4751

48-
if (isAdm) {
49-
message.reply(this.runs(data, message));
52+
if (!isAdm) {
53+
message.reply('staff only.');
5054
return;
5155
}
5256

53-
message.reply('staff only.');
57+
message.reply(this.runs(data, message));
5458
}
5559

5660
create(data, message) {
@@ -127,13 +131,14 @@ Repete uma mensagem em um determinado período de tempo. Cada mensagem é repres
127131
destroy: () => this.destroy(data.text),
128132
start: () => this.start(data.text),
129133
stop: () => this.stop(data.text),
134+
help: () => this.strings.help,
130135
};
131136

132137
if (methods[data.args[0]]) {
133138
return methods[data.args[0]]();
134139
}
135140

136-
return this.defaultMessage;
141+
throw new Error('Nenhum arg válido foi passado.');
137142
}
138143

139144
isIdValid(id) {

src/commands/doc.js

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

src/commands/index.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
/* eslint-disable global-require */
22

33
module.exports = {
4-
Bot: require('./bot'),
4+
About: require('./about'),
55
Coin: require('./coin'),
66
Commands: require('./commands'),
77
Cron: require('./cron'),
8-
Doc: require('./doc'),
98
Links: require('./links'),
109
Lyric: require('./lyric'),
1110
Report: require('./report'),

0 commit comments

Comments
 (0)