Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 24 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
require('dotenv').config();
const { Alice } = require('./src/Alice');
const build = require('./src/build');

const path = new build.Path(__dirname);
const {
Bot,
Coin,
Commands,
Cron,
Doc,
Links,
Lyric,
Report,
Search,
Suggest,
Wiki,
} = require('./src/commands');

const alice = new Alice([
path.create('src/commands/bot', 'bot'),
path.create('src/commands/coin', 'coin'),
path.create('src/commands/commands', 'commands'),
path.create('src/commands/cron', 'cron'),
path.create('src/commands/dice', 'dice'),
path.create('src/commands/doc', 'doc'),
path.create('src/commands/links', 'links'),
path.create('src/commands/lyric', 'lyric'),
path.create('src/commands/report', 'report'),
path.create('src/commands/search', 'search'),
path.create('src/commands/suggest', 'suggest'),
path.create('src/commands/wiki', 'wiki'),
new Bot(),
new Coin(),
new Commands(),
new Cron(),
new Doc(),
new Links(),
new Lyric(),
new Report(),
new Search(),
new Suggest(),
new Wiki(),
]);

alice.initialize();
4 changes: 2 additions & 2 deletions src/Alice.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const auth = require('./auth');
const { Parse } = require('./utils/Parse');
const { Parse } = require('./utils');
const build = require('./build');

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

commandsArray.forEach((cmd) => {
commands.set(...cmd);
commands.register(cmd);
});
}

Expand Down
46 changes: 27 additions & 19 deletions src/build/Commands.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
function isFunction(object) {
return typeof object === 'function';
}

/**
* Commands wrapper
* @param {object} commands - Object that contains the commands.
Expand All @@ -17,27 +13,39 @@ class Commands {
* @param {string} name - Command's name.
* @param {function} callback - Callback to command.
*/
set(name, callback) {
if (!isFunction(callback)) {
throw new Error(`${callback} must be a function`);
register(cmd) {
if (!Commands.isValid(cmd)) {
throw new Error(`${cmd} isn't a valid Command!`);
}

this.commands[name] = callback;
this.commands[cmd.name] = cmd;
}

/**
* Checks if a command is set in Commands instance.
* @param {string} cmd - The command's name.
* @param {string} cmdName - The command's name.
* @returns {boolean} `True` if the command is set in Commands instance, `False` if not.
*/
has(cmd) {
has(cmdName) {
const availableCommands = Object.keys(this.commands);
return availableCommands.includes(cmd);
return availableCommands.includes(cmdName);
}

/**
* Checks if a command is valid.
* @param {any} cmd - The command instance.
* @returns {boolean} `True` if the command is valid, `False` if not.
*/
static isValid(cmd) {
if (cmd.name && cmd.execute && typeof cmd.execute === 'function') {
return true;
}
return false;
}

/**
* Calls (executes) a command.
* @param {string} cmd - The command's name to be called.
* @param {string} cmdName - The command's name to be called.
* @param {object} data - The data extracted from the message that called the command.
* @param {string} data.command - The command's name extracted from the message.
* @param {string[]} data.args - The args extracted from the message.
Expand All @@ -48,15 +56,15 @@ class Commands {
* @see https://docs.wwebjs.dev/Message.html
* @see https://docs.wwebjs.dev/Client.html
*/
async call(cmd, data, message, client) {
if (!this.has(cmd)) {
throw new Error(`${cmd} is not registered`);
async call(cmdName, data, message, client) {
if (!this.has(cmdName)) {
throw new Error(`${cmdName} is not registered.`);
}

const response = await this.commands[cmd](data, message, client);

if (response) {
message.reply(String(response));
try {
await this.commands[cmdName].execute(data, message, client);
} catch (e) {
message.reply(`❗ ${e.message}`);
}
}
}
Expand Down
21 changes: 0 additions & 21 deletions src/build/Path.js

This file was deleted.

1 change: 0 additions & 1 deletion src/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@

module.exports = {
Commands: require('./Commands'),
Path: require('./Path'),
};
15 changes: 13 additions & 2 deletions src/commands/bot.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
module.exports = () =>
`Olá, eu sou a Alice. Quer saber mais sobre mim? use o comando !doc`;
class Bot {
constructor() {
this.name = 'bot';
this.defaultMessage =
'Olá, eu sou a Alice. Quer saber mais sobre mim? use o comando !doc';
}

execute(_, message) {
message.reply(this.defaultMessage);
}
}

module.exports = Bot;
83 changes: 44 additions & 39 deletions src/commands/coin.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
const axios = require('axios');
const cheerio = require('cheerio');

const defaultMessage = `
uso: *!coin* [--flag] name
_--all -> mostra todas as informações disponiveis_

a flag _all_ pode retornar dados em excesso, sua utilização repetida será considera spam
`;

async function loadCheerio(url) {
try {
const { data } = await axios.get(url);
Expand All @@ -17,7 +10,7 @@ async function loadCheerio(url) {
}
}

async function getData(url) {
async function getCoinStats(url) {
const $ = await loadCheerio(url);

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

priceStatistics.each(function () {
const tr = $(this);
priceStatistics.each((_, pS) => {
const tr = $(pS);
const key = tr.find('th').text();
let value = tr.find('td');

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

if (value !== 'No Data' || value !== 'Sem Dados') {
if (value !== 'No Data') {
const object = Object.fromEntries([[key, value]]);
statsArray.push(object);
}
Expand All @@ -52,41 +45,53 @@ async function getData(url) {
return statsArray;
}

function getUrl(args, text) {
let baseURL = 'https://coinmarketcap.com/currencies/';
const path = text.replace(/\s/g, '-').toLowerCase();
class Coin {
constructor() {
this.name = 'coin';
this.BASE_URL = 'https://coinmarketcap.com/currencies/';
this.defaultMessage = `
uso: *!coin* [--flag] name
_--all -> mostra todas as informações disponiveis_

if (args.includes('brl')) {
baseURL = 'https://coinmarketcap.com/pt-br/currencies/';
a flag _all_ pode retornar dados em excesso, sua utilização repetida será considera spam
`.trim();
}

return baseURL + path;
}
async execute(data, message) {
const { args, text } = data;

module.exports = async (data) => {
const { args, text } = data;
if (!text) {
message.reply(this.defaultMessage);
return;
}

if (!text) {
return defaultMessage.trim();
}
const url = this.getUrl(text);
let coinStats = await getCoinStats(url);

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

if (!coinStats) {
return 'moeda não encontrada';
}
if (!args.includes('all')) {
coinStats = coinStats.slice(0, 3);
}
if (!args.includes('all')) {
coinStats = coinStats.slice(0, 3);
}

let output = '';
let output = '';

coinStats.forEach((s) => {
const [key, value] = Object.entries(s)[0];
const string = `*_${key}_*:\n - ${value}\n\n`;
output += string;
});
coinStats.forEach((s) => {
const [key, value] = Object.entries(s)[0];
const string = `*_${key}_*:\n - ${value}\n\n`;
output += string;
});

message.reply(output.trim());
}

getUrl(text) {
const path = text.replace(/\s/g, '-').toLowerCase();
return this.BASE_URL + path;
}
}

return output.trim();
};
module.exports = Coin;
20 changes: 15 additions & 5 deletions src/commands/commands.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
module.exports = () =>
`Os seguintes comandos estão disponiveis:
class Commands {
constructor() {
this.name = 'commands';
this.defaultMessage = `
Os seguintes comandos estão disponiveis:
- !bot
- !coin
- !commands
- !cron
- !dice
- !doc
- !github
- !links
- !lyric
- !report
- !search
- !suggest
- !wiki`.trim();
- !wiki
`.trim();
}

execute(_, message) {
message.reply(this.defaultMessage);
}
}

module.exports = Commands;
Loading