Skip to content

Commit 01a4835

Browse files
committed
[FEAT] adds help kwarg to commands
1 parent 11c8562 commit 01a4835

File tree

9 files changed

+207
-82
lines changed

9 files changed

+207
-82
lines changed

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/links.js

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
1-
class Links {
2-
constructor() {
3-
this.name = 'links';
4-
this.defaultMessage = `
1+
const STRINGS = {
2+
help: `
3+
Lista links para os grupos coding.
4+
5+
*uso:* \`\`\`!links [--args]\`\`\`
6+
7+
*args válidos:*
8+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
9+
`.trim(),
10+
11+
groupsLinks: `
512
Coding in python:
613
https://chat.whatsapp.com/I4IpHC0YFPQLUcGHJeqYdF
714
@@ -25,11 +32,24 @@ https://chat.whatsapp.com/GOXnIXSXEFH7wHvO9aTuFs
2532
2633
Speaking in English:
2734
https://chat.whatsapp.com/EOirNapuFe3CVunBqbwj1Z
28-
`.trim();
35+
`.trim(),
36+
};
37+
38+
class Links {
39+
constructor() {
40+
this.name = 'links';
41+
this.strings = STRINGS;
2942
}
3043

31-
execute(_, message) {
32-
message.reply(this.defaultMessage);
44+
execute(data, message) {
45+
const { args } = data;
46+
47+
if (args.includes('help')) {
48+
message.reply(this.strings.help);
49+
return;
50+
}
51+
52+
message.reply(this.strings.groupsLinks);
3353
}
3454
}
3555

src/commands/lyric.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@ const axios = require('axios');
22
const JSSoup = require('jssoup').default;
33
const { search } = require('../utils');
44

5+
const STRINGS = {
6+
help: `
7+
Retorna a letra de uma música.
8+
9+
*uso:* \`\`\`!lyric [--args] music_name\`\`\`
10+
11+
*args válidos:*
12+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
13+
`.trim(),
14+
};
15+
516
async function makeSoup(url) {
617
const { data } = await axios.get(url);
718
return new JSSoup(data);
@@ -20,11 +31,17 @@ function removeBr(raw) {
2031
class Lyric {
2132
constructor() {
2233
this.name = 'lyric';
34+
this.strings = STRINGS;
2335
}
2436

2537
// eslint-disable-next-line
2638
async execute(data, message) {
27-
const { text } = data;
39+
const { text, args } = data;
40+
41+
if (args.includes('help')) {
42+
message.reply(this.strings.help);
43+
return;
44+
}
2845

2946
if (!text) {
3047
throw new Error('Nenhum nome foi passado');

src/commands/report.js

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
const { chattools } = require('../utils');
22

3-
const strings = {
4-
defaultMessage: `
5-
uso: _!report [--flag] [descrição]_
3+
const STRINGS = {
4+
help: `
5+
Reporte problemas no bot ou um usuário.
66
7-
argumentos:
8-
_--bug descreva um problema no bot_
9-
_--user denuncie um usuário_
7+
*uso:* \`\`\`!report --args ...\`\`\`
108
11-
⚠️ *o uso indevido dessa função resultará em ban de 3 dias* ⚠️`,
9+
*args válidos:*
10+
\`\`\`--bug\`\`\` -> _reporta um bug._
11+
\`\`\`--user\`\`\` -> reporta um usuário._
12+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
13+
`.trim(),
1214
bug: 'sua solicitação será analisada. caso confirmada, abriremos uma issue',
1315
user: 'o usuário foi reportado a administração',
1416
};
@@ -17,13 +19,18 @@ class Report {
1719
constructor() {
1820
this.name = 'report';
1921
this.reportID = chattools.userID(process.env.REPORT_NUMBER);
20-
this.strings = strings;
22+
this.strings = STRINGS;
2123
}
2224

2325
execute(data, message, client) {
2426
const { args, text } = data;
2527
const reportMsg = `⚠️ *${args[0]} report* ⚠️\n\n${text}`;
2628

29+
if (args.includes('help')) {
30+
message.reply(this.strings.help);
31+
return;
32+
}
33+
2734
if (args.length === 0 && text) {
2835
throw new Error('Nenhuma flag foi fornecida.');
2936
}
@@ -37,7 +44,7 @@ class Report {
3744
return;
3845
}
3946

40-
message.reply(this.strings.defaultMessage.trim());
47+
throw new Error('Nenhum arg válido foi passado.');
4148
}
4249
}
4350

src/commands/search.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
11
const { search } = require('../utils');
22

3+
const STRINGS = {
4+
help: `
5+
Retorna o primeiro resultado de uma pesquisa no google.
6+
7+
*uso:* \`\`\`!cron [--args] ...\`\`\`
8+
9+
*args válidos:*
10+
\`\`\`--help\`\`\` -> _mostra esta mensagem._
11+
`.trim(),
12+
};
13+
314
class Search {
415
constructor() {
516
this.name = 'search';
17+
this.strings = STRINGS;
618
}
719

8-
// eslint-disable-next-line
920
async execute(data, message) {
10-
const { text } = data;
21+
const { args, text } = data;
22+
23+
if (args.includes('help')) {
24+
message.reply(this.strings.help);
25+
return;
26+
}
1127

1228
if (!text) {
1329
throw new Error('Nenhum texto para pesquisa foi especificado.');

0 commit comments

Comments
 (0)