From 0e136ff912b30183edf936ca8b902d07a581f0d6 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Wed, 14 Jul 2021 21:23:32 -0300 Subject: [PATCH 01/39] [REFACTOR] removes obsolete this.isSavedOrLoaded --- alice/src/auth/index.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/alice/src/auth/index.js b/alice/src/auth/index.js index c80677b..208bf4f 100644 --- a/alice/src/auth/index.js +++ b/alice/src/auth/index.js @@ -13,8 +13,6 @@ class Session extends whatsapp.Client { args: ['--no-sandbox', '--disable-setuid-sandbox'], }, }); - - this.isSavedOrLoaded = false; } // eslint-disable-next-line @@ -23,8 +21,6 @@ class Session extends whatsapp.Client { } save() { - this.isSavedOrLoaded = true; - this.on('qr', (qr) => { qrcode.generate(qr, { small: true }); }); @@ -37,8 +33,6 @@ class Session extends whatsapp.Client { } load() { - this.isSavedOrLoaded = true; - try { const raw = fs.readFileSync(SESSION_FILE_PATH); const data = JSON.parse(raw); From 2abe1cb853711e47db3ae9a946b95b693fedbda3 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Wed, 14 Jul 2021 21:27:32 -0300 Subject: [PATCH 02/39] [REFACTOR] uses SESSION_FILE_PATH as a class attr --- alice/src/auth/index.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/alice/src/auth/index.js b/alice/src/auth/index.js index 208bf4f..51695b1 100644 --- a/alice/src/auth/index.js +++ b/alice/src/auth/index.js @@ -4,7 +4,6 @@ const fs = require('fs'); const path = require('path'); const FILE_NAME = 'session.json'; -const SESSION_FILE_PATH = path.join(__dirname, FILE_NAME); class Session extends whatsapp.Client { constructor() { @@ -13,11 +12,12 @@ class Session extends whatsapp.Client { args: ['--no-sandbox', '--disable-setuid-sandbox'], }, }); + + this.SESSION_FILE_PATH = path.join(__dirname, FILE_NAME); } - // eslint-disable-next-line get exists() { - return fs.existsSync(SESSION_FILE_PATH); + return fs.existsSync(this.SESSION_FILE_PATH); } save() { @@ -26,7 +26,7 @@ class Session extends whatsapp.Client { }); this.on('authenticated', (session) => { - fs.writeFileSync(SESSION_FILE_PATH, JSON.stringify(session)); + fs.writeFileSync(this.SESSION_FILE_PATH, JSON.stringify(session)); console.log('⚠ The current session has been saved ⚠'); }); @@ -34,14 +34,14 @@ class Session extends whatsapp.Client { load() { try { - const raw = fs.readFileSync(SESSION_FILE_PATH); + const raw = fs.readFileSync(this.SESSION_FILE_PATH); const data = JSON.parse(raw); this.options.session = data; console.log('⚠ The previous session was loaded ⚠'); } catch { - throw Error(`session data does not exist in ${SESSION_FILE_PATH}`); + throw Error(`session data does not exist in ${this.SESSION_FILE_PATH}`); } } From 9dd6cbf7caf6dec10c8f70bbe0613afdf12d8b1f Mon Sep 17 00:00:00 2001 From: carlos3g Date: Wed, 14 Jul 2021 22:19:25 -0300 Subject: [PATCH 03/39] [REFACTOR] remove unnecessary try-catch block --- alice/src/auth/index.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/alice/src/auth/index.js b/alice/src/auth/index.js index 51695b1..6e5911f 100644 --- a/alice/src/auth/index.js +++ b/alice/src/auth/index.js @@ -33,16 +33,15 @@ class Session extends whatsapp.Client { } load() { - try { - const raw = fs.readFileSync(this.SESSION_FILE_PATH); - const data = JSON.parse(raw); - - this.options.session = data; - - console.log('⚠ The previous session was loaded ⚠'); - } catch { + if (!this.exists) { throw Error(`session data does not exist in ${this.SESSION_FILE_PATH}`); } + + const raw = fs.readFileSync(this.SESSION_FILE_PATH); + const data = JSON.parse(raw); + this.options.session = data; + + console.log('⚠ The previous session was loaded ⚠'); } start() { From fa75cacc79e406f3e5373c0491955bfe2cc86b4e Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 14:13:20 -0300 Subject: [PATCH 04/39] [REFACTOR] uses new keyword when invoking Error --- alice/scripts/utils/random.js | 2 +- alice/scripts/utils/time.js | 8 ++++---- alice/src/build/Components.js | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/alice/scripts/utils/random.js b/alice/scripts/utils/random.js index f915193..1558add 100644 --- a/alice/scripts/utils/random.js +++ b/alice/scripts/utils/random.js @@ -36,7 +36,7 @@ function sample(array, k) { return samples; } - throw Error('Sample larger than population or is negative'); + throw new Error('Sample larger than population or is negative'); } function shuffle(array) { diff --git a/alice/scripts/utils/time.js b/alice/scripts/utils/time.js index 5656756..4a1d50d 100644 --- a/alice/scripts/utils/time.js +++ b/alice/scripts/utils/time.js @@ -7,28 +7,28 @@ function timer(sec, min = 0, hour = 0, day = 0) { if (sec >= 0) { sec *= 1000; } else { - throw Error('seconds must be higher than 0'); + throw new Error('seconds must be higher than 0'); } // minutos if (min >= 0) { min = min * 60 * 1000; } else { - throw Error('minutes must be higher than 0'); + throw new Error('minutes must be higher than 0'); } // horas if (hour >= 0) { hour = hour * 60 * 60 * 1000; } else { - throw Error('hours must be higher than 0'); + throw new Error('hours must be higher than 0'); } // day if (day >= 0) { day = day * 24 * 60 * 60 * 100; } else { - throw Error('minutes must be higher than 0'); + throw new Error('minutes must be higher than 0'); } const time = sec + min + hour + day; diff --git a/alice/src/build/Components.js b/alice/src/build/Components.js index 1d06c59..01154af 100644 --- a/alice/src/build/Components.js +++ b/alice/src/build/Components.js @@ -19,9 +19,9 @@ class Components { if (isFunction(object)) { this.components[name] = object; } else if (isEmpty(object)) { - throw Error(`${name} component cannot be empty`); + throw new Error(`${name} component cannot be empty`); } else { - throw Error(`${object} must be a function`); + throw new Error(`${object} must be a function`); } } @@ -31,9 +31,9 @@ class Components { if (response) message.reply(String(response)); } else if (!this.methods.includes(method)) { - throw Error(`${method} is not registered`); + throw new Error(`${method} is not registered`); } else { - throw Error('method call is not found'); + throw new Error('method call is not found'); } } } From dc991c8df33e52674c301fa2ede50d92a3e7b993 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 16:23:47 -0300 Subject: [PATCH 05/39] [REFACTOR] remove unnecessary variable assignment --- alice/src/parse/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index e9acd06..a030177 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -32,7 +32,7 @@ class Content { const matchesIter = this.originalText.matchAll(REGEXP.KWARGS); const matchesArray = [...matchesIter]; - const matches = matchesArray.forEach((elem) => { // eslint-disable-line + matchesArray.forEach((elem) => { Object.assign(obj, { [elem[1]]: elem[2] }); }); From e8507182aa4a5a6773be3487b69192a049b8b343 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 16:41:11 -0300 Subject: [PATCH 06/39] [REFACTOR] uses a better nomenclature --- alice/src/parse/index.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index a030177..6e3c8df 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -1,26 +1,26 @@ const REGEXP = { // example: !some_method - METHOD: /^!([^\s]+)/, + method: /^!([^\s]+)/, // example: --some_flag - ARGS: /--([\S]+)(?=\s|$)/g, + args: /--([\S]+)(?=\s|$)/g, - KWARGS: /--([a-zA-Z0-9_-]+)="?([a-z0-9\.]+)"?/g, // eslint-disable-line + kwargs: /--([a-zA-Z0-9_-]+)="?([a-z0-9\.]+)"?/g, // eslint-disable-line }; class Content { constructor(text) { - this.originalText = text.trim(); + this.text = text.trim(); } get method() { - const matches = this.originalText.match(REGEXP.METHOD); + const matches = this.text.match(REGEXP.method); return matches ? matches[1] : ''; } get args() { - const matchesIter = this.originalText.matchAll(REGEXP.ARGS); + const matchesIter = this.text.matchAll(REGEXP.args); const matchesArray = [...matchesIter]; const matches = matchesArray.map((elem) => elem[1]); @@ -30,7 +30,7 @@ class Content { get kwargs() { const obj = {}; - const matchesIter = this.originalText.matchAll(REGEXP.KWARGS); + const matchesIter = this.text.matchAll(REGEXP.kwargs); const matchesArray = [...matchesIter]; matchesArray.forEach((elem) => { Object.assign(obj, { [elem[1]]: elem[2] }); @@ -40,10 +40,10 @@ class Content { } get string() { - return this.originalText - .replace(REGEXP.METHOD, '') - .replace(REGEXP.ARGS, '') - .replace(REGEXP.KWARGS, '') + return this.text + .replace(REGEXP.method, '') + .replace(REGEXP.args, '') + .replace(REGEXP.kwargs, '') .trim(); } } From 6e138d52f2728b6d908e55cb582f8d69e10f8c7f Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 16:56:08 -0300 Subject: [PATCH 07/39] [REFACTOR] sets .eslintrc.json.import/no-dynamic-require to 'warn' --- .eslintrc.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.eslintrc.json b/.eslintrc.json index d468be3..1aa05fd 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -11,7 +11,8 @@ "rules": { "prettier/prettier": "error", "no-console": "warn", - "no-plusplus": "off" + "no-plusplus": "off", + "import/no-dynamic-require": "warn" }, "plugins": ["prettier"] } From fd84db1393350ec77b1ca62bdcb320c2611485f7 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 17:37:50 -0300 Subject: [PATCH 08/39] [REFACTOR] prevents parameter reassignment --- alice/src/build/Path.js | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/alice/src/build/Path.js b/alice/src/build/Path.js index 51135f3..c70179b 100644 --- a/alice/src/build/Path.js +++ b/alice/src/build/Path.js @@ -8,13 +8,12 @@ class Path { create(RELATIVE_PATH, alias) { const FILE_PATH = path.join(this.BASE_PATH, RELATIVE_PATH); const { name } = path.parse(FILE_PATH); + const func = require(FILE_PATH); // eslint-disable-line global-require - alias = alias || name; - - const object = require(FILE_PATH); - console.log(`Initialized "${alias}" function...`); - - return [alias, object]; + if (alias) { + return [alias, func]; + } + return [name, func]; } } From aa2ea73192bfc333e66157607e3d7d9666ce99ef Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 18:14:02 -0300 Subject: [PATCH 09/39] [REFACTOR] defines and uses Session.create method --- alice/src/auth/index.js | 12 ++++++------ alice/src/index.js | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/alice/src/auth/index.js b/alice/src/auth/index.js index 6e5911f..9db142a 100644 --- a/alice/src/auth/index.js +++ b/alice/src/auth/index.js @@ -20,16 +20,16 @@ class Session extends whatsapp.Client { return fs.existsSync(this.SESSION_FILE_PATH); } - save() { + create() { this.on('qr', (qr) => { qrcode.generate(qr, { small: true }); }); + this.on('authenticated', this.save); + } - this.on('authenticated', (session) => { - fs.writeFileSync(this.SESSION_FILE_PATH, JSON.stringify(session)); - - console.log('⚠ The current session has been saved ⚠'); - }); + save(session) { + fs.writeFileSync(this.SESSION_FILE_PATH, JSON.stringify(session)); + console.log('⚠ The current session has been saved ⚠'); } load() { diff --git a/alice/src/index.js b/alice/src/index.js index 44b4ca1..221ab60 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -34,7 +34,7 @@ class Alice { initialize() { if (session.exists) session.load(); - else session.save(); + else session.create(); session.on(this.options.trigger, Alice.main); session.start(); From 83a5db02f701f282e7fe471a00a0b21bb123b5be Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 20:07:50 -0300 Subject: [PATCH 10/39] [REFACTOR] remove unnecessary async keyword --- alice/src/build/Components.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/alice/src/build/Components.js b/alice/src/build/Components.js index 01154af..26f3435 100644 --- a/alice/src/build/Components.js +++ b/alice/src/build/Components.js @@ -15,7 +15,7 @@ class Components { return Object.keys(this.components); } - async set(name, object) { + set(name, object) { if (isFunction(object)) { this.components[name] = object; } else if (isEmpty(object)) { From 0cd97bfcfc6321e4f6a82e0c7932b788bb94ba60 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 20:35:31 -0300 Subject: [PATCH 11/39] [REFACTOR] decreases number of if statements --- alice/src/build/Components.js | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/alice/src/build/Components.js b/alice/src/build/Components.js index 26f3435..3c41a91 100644 --- a/alice/src/build/Components.js +++ b/alice/src/build/Components.js @@ -2,10 +2,6 @@ function isFunction(object) { return typeof object === 'function'; } -function isEmpty(object) { - return !object || Object.keys(object).length === 0; -} - class Components { constructor() { this.components = {}; @@ -16,24 +12,20 @@ class Components { } set(name, object) { - if (isFunction(object)) { - this.components[name] = object; - } else if (isEmpty(object)) { - throw new Error(`${name} component cannot be empty`); - } else { + if (!isFunction(object)) { throw new Error(`${object} must be a function`); } + this.components[name] = object; } async call(method, data, message, client) { - if (this.methods.includes(method)) { - const response = await this.components[method](data, message, client); - - if (response) message.reply(String(response)); - } else if (!this.methods.includes(method)) { + if (!this.methods.includes(method)) { throw new Error(`${method} is not registered`); - } else { - throw new Error('method call is not found'); + } + + const response = await this.components[method](data, message, client); + if (response) { + message.reply(String(response)); } } } From 64b427f298110c5748674a634e52d59a092cb455 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 20:44:58 -0300 Subject: [PATCH 12/39] [REFACTOR] defines and uses Components.has --- alice/src/build/Components.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/alice/src/build/Components.js b/alice/src/build/Components.js index 3c41a91..7d8f168 100644 --- a/alice/src/build/Components.js +++ b/alice/src/build/Components.js @@ -18,8 +18,12 @@ class Components { this.components[name] = object; } + has(method) { + return this.methods.includes(method); + } + async call(method, data, message, client) { - if (!this.methods.includes(method)) { + if (!this.has(method)) { throw new Error(`${method} is not registered`); } From eab7d842f74298bfadfff6835464eab7c43cba04 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 21:38:25 -0300 Subject: [PATCH 13/39] [REFACTOR] moves REGEXP constant to inside the Content --- alice/src/parse/index.js | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index 6e3c8df..cdb4f96 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -1,26 +1,21 @@ -const REGEXP = { - // example: !some_method - method: /^!([^\s]+)/, - - // example: --some_flag - args: /--([\S]+)(?=\s|$)/g, - - kwargs: /--([a-zA-Z0-9_-]+)="?([a-z0-9\.]+)"?/g, // eslint-disable-line -}; - class Content { constructor(text) { this.text = text.trim(); + this.REGEXP = { + method: /^!([^\s]+)/, + args: /--([\S]+)(?=\s|$)/g, + kwargs: /--([a-zA-Z0-9_-]+)="?([a-z0-9\.]+)"?/g, // eslint-disable-line + }; } get method() { - const matches = this.text.match(REGEXP.method); + const matches = this.text.match(this.REGEXP.method); return matches ? matches[1] : ''; } get args() { - const matchesIter = this.text.matchAll(REGEXP.args); + const matchesIter = this.text.matchAll(this.REGEXP.args); const matchesArray = [...matchesIter]; const matches = matchesArray.map((elem) => elem[1]); @@ -30,7 +25,7 @@ class Content { get kwargs() { const obj = {}; - const matchesIter = this.text.matchAll(REGEXP.kwargs); + const matchesIter = this.text.matchAll(this.REGEXP.kwargs); const matchesArray = [...matchesIter]; matchesArray.forEach((elem) => { Object.assign(obj, { [elem[1]]: elem[2] }); @@ -41,9 +36,9 @@ class Content { get string() { return this.text - .replace(REGEXP.method, '') - .replace(REGEXP.args, '') - .replace(REGEXP.kwargs, '') + .replace(this.REGEXP.method, '') + .replace(this.REGEXP.args, '') + .replace(this.REGEXP.kwargs, '') .trim(); } } From ff74dee5882e67b27645fa1aed4e4553b27366b1 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 21:43:58 -0300 Subject: [PATCH 14/39] [REFACTOR] change Content class name to Parse --- alice/src/index.js | 4 ++-- alice/src/parse/index.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/alice/src/index.js b/alice/src/index.js index 221ab60..11dfa12 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -1,6 +1,6 @@ // imports const auth = require('./auth'); -const parse = require('./parse'); +const { Parse } = require('./parse'); const build = require('./build'); // instances @@ -19,7 +19,7 @@ class Alice { } static async main(message) { - const { method, string, args, kwargs } = new parse.Content(message.body); + const { method, string, args, kwargs } = new Parse(message.body); const data = { text: string, diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index cdb4f96..7c3e66c 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -1,4 +1,4 @@ -class Content { +class Parse { constructor(text) { this.text = text.trim(); this.REGEXP = { @@ -44,5 +44,5 @@ class Content { } module.exports = { - Content, + Parse, }; From 8066c0f3f3181b73a0f5fa22b94b1e0ef26d40e2 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 21:54:22 -0300 Subject: [PATCH 15/39] [REFACTOR] remove future folder --- alice/future/plans.txt | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 alice/future/plans.txt diff --git a/alice/future/plans.txt b/alice/future/plans.txt deleted file mode 100644 index 7a0d082..0000000 --- a/alice/future/plans.txt +++ /dev/null @@ -1,20 +0,0 @@ -- novos métodos: - - !doc -- || FEITO: - - documentação das funções - - !command || FEITO: - - resumo dos comandos - - !quotation -- --: - - cotas monetárias - - !music --: - - procura uma musica no youtube, e baixa caso requerido - - -- novas funcionalidades - - escope || IMPORTANTE - - conjunto de wrappers para criar escopo de funções no whatsapp - - context - - api de contexto para lembrar de cada membro individualmente - - scheduler || FEITO - - ativa métodos em determinadas horas do dia - - action - - ativa métodos de acordo com eventos \ No newline at end of file From acdc1de7180e413a59a7d4fe0634cf73ffb53a39 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 22:33:29 -0300 Subject: [PATCH 16/39] [REFACTOR] change Alice.main to Alice.onMessage --- alice/src/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/alice/src/index.js b/alice/src/index.js index 11dfa12..8f561f0 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -18,7 +18,7 @@ class Alice { }); } - static async main(message) { + static async onMessage(message) { const { method, string, args, kwargs } = new Parse(message.body); const data = { @@ -36,7 +36,7 @@ class Alice { if (session.exists) session.load(); else session.create(); - session.on(this.options.trigger, Alice.main); + session.on(this.options.trigger, Alice.onMessage); session.start(); } } From f3ec4aadb0076860f14334d60169684fc8d6bf64 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 22:48:23 -0300 Subject: [PATCH 17/39] [REFACTOR] change Parse.text to Parse.rawText --- alice/src/parse/index.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index 7c3e66c..565e6a0 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -1,6 +1,6 @@ class Parse { constructor(text) { - this.text = text.trim(); + this.rawText = text.trim(); this.REGEXP = { method: /^!([^\s]+)/, args: /--([\S]+)(?=\s|$)/g, @@ -9,13 +9,13 @@ class Parse { } get method() { - const matches = this.text.match(this.REGEXP.method); + const matches = this.rawText.match(this.REGEXP.method); return matches ? matches[1] : ''; } get args() { - const matchesIter = this.text.matchAll(this.REGEXP.args); + const matchesIter = this.rawText.matchAll(this.REGEXP.args); const matchesArray = [...matchesIter]; const matches = matchesArray.map((elem) => elem[1]); @@ -25,7 +25,7 @@ class Parse { get kwargs() { const obj = {}; - const matchesIter = this.text.matchAll(this.REGEXP.kwargs); + const matchesIter = this.rawText.matchAll(this.REGEXP.kwargs); const matchesArray = [...matchesIter]; matchesArray.forEach((elem) => { Object.assign(obj, { [elem[1]]: elem[2] }); @@ -35,7 +35,7 @@ class Parse { } get string() { - return this.text + return this.rawText .replace(this.REGEXP.method, '') .replace(this.REGEXP.args, '') .replace(this.REGEXP.kwargs, '') From 2b6b20fbc502b9218164a73b7d6d2b916aca8769 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 22:52:30 -0300 Subject: [PATCH 18/39] [REFACTOR] change Parse.string getter to Parse.text --- alice/src/index.js | 12 +++--------- alice/src/parse/index.js | 2 +- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/alice/src/index.js b/alice/src/index.js index 8f561f0..0a24b21 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -19,16 +19,10 @@ class Alice { } static async onMessage(message) { - const { method, string, args, kwargs } = new Parse(message.body); + const data = new Parse(message.body); - const data = { - text: string, - args, - kwargs, - }; - - if (method) { - await components.call(method, data, message, session); + if (data.method) { + await components.call(data.method, data, message, session); } } diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index 565e6a0..1aa6922 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -34,7 +34,7 @@ class Parse { return obj; } - get string() { + get text() { return this.rawText .replace(this.REGEXP.method, '') .replace(this.REGEXP.args, '') From b5db897448fd2fb0a1630535c672fa2e72678581 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Thu, 15 Jul 2021 23:07:28 -0300 Subject: [PATCH 19/39] [REFACTOR] remove unnecessary comments --- alice/index.js | 2 -- alice/src/index.js | 2 -- 2 files changed, 4 deletions(-) diff --git a/alice/index.js b/alice/index.js index e766553..5dea3ad 100644 --- a/alice/index.js +++ b/alice/index.js @@ -1,8 +1,6 @@ -// imports const src = require('./src'); const build = require('./src/build'); -// instance const path = new build.Path(__dirname); const alice = new src.Alice([ diff --git a/alice/src/index.js b/alice/src/index.js index 0a24b21..a8887f4 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -1,9 +1,7 @@ -// imports const auth = require('./auth'); const { Parse } = require('./parse'); const build = require('./build'); -// instances const session = new auth.Session(); const components = new build.Components(); From 2a544a1cb37a426a218344f920529958b1d5a174 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Fri, 16 Jul 2021 14:38:23 -0300 Subject: [PATCH 20/39] [REFACTOR] uses a more descriptive nomenclature for 'method' and 'component' --- alice/src/build/Commands.js | 34 ++++++++++++++++++++++++++++++++ alice/src/build/Components.js | 37 ----------------------------------- alice/src/build/index.js | 2 +- alice/src/index.js | 20 ++++++++++--------- alice/src/parse/index.js | 8 ++++---- 5 files changed, 50 insertions(+), 51 deletions(-) create mode 100644 alice/src/build/Commands.js delete mode 100644 alice/src/build/Components.js diff --git a/alice/src/build/Commands.js b/alice/src/build/Commands.js new file mode 100644 index 0000000..1f900ef --- /dev/null +++ b/alice/src/build/Commands.js @@ -0,0 +1,34 @@ +function isFunction(object) { + return typeof object === 'function'; +} + +class Commands { + constructor() { + this.commands = {}; + } + + set(name, callback) { + if (!isFunction(callback)) { + throw new Error(`${callback} must be a function`); + } + this.commands[name] = callback; + } + + has(cmd) { + const availableCommands = Object.keys(this.commands); + return availableCommands.includes(cmd); + } + + async call(cmd, data, message, client) { + if (!this.has(cmd)) { + throw new Error(`${cmd} is not registered`); + } + + const response = await this.commands[cmd](data, message, client); + if (response) { + message.reply(String(response)); + } + } +} + +module.exports = Commands; diff --git a/alice/src/build/Components.js b/alice/src/build/Components.js deleted file mode 100644 index 7d8f168..0000000 --- a/alice/src/build/Components.js +++ /dev/null @@ -1,37 +0,0 @@ -function isFunction(object) { - return typeof object === 'function'; -} - -class Components { - constructor() { - this.components = {}; - } - - get methods() { - return Object.keys(this.components); - } - - set(name, object) { - if (!isFunction(object)) { - throw new Error(`${object} must be a function`); - } - this.components[name] = object; - } - - has(method) { - return this.methods.includes(method); - } - - async call(method, data, message, client) { - if (!this.has(method)) { - throw new Error(`${method} is not registered`); - } - - const response = await this.components[method](data, message, client); - if (response) { - message.reply(String(response)); - } - } -} - -module.exports = Components; diff --git a/alice/src/build/index.js b/alice/src/build/index.js index 948e56a..3084ace 100644 --- a/alice/src/build/index.js +++ b/alice/src/build/index.js @@ -1,6 +1,6 @@ /* eslint-disable global-require */ module.exports = { - Components: require('./Components'), + Commands: require('./Commands'), Path: require('./Path'), }; diff --git a/alice/src/index.js b/alice/src/index.js index a8887f4..98bda3e 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -3,30 +3,32 @@ const { Parse } = require('./parse'); const build = require('./build'); const session = new auth.Session(); -const components = new build.Components(); +const commands = new build.Commands(); class Alice { - constructor(componentsArray) { + constructor(commandsArray) { this.options = { trigger: 'message_create', }; - componentsArray.forEach((elem) => { - components.set(...elem); + commandsArray.forEach((cmd) => { + commands.set(...cmd); }); } static async onMessage(message) { const data = new Parse(message.body); - - if (data.method) { - await components.call(data.method, data, message, session); + if (data.command) { + await commands.call(data.command, data, message, session); } } initialize() { - if (session.exists) session.load(); - else session.create(); + if (session.exists) { + session.load(); + } else { + session.create(); + } session.on(this.options.trigger, Alice.onMessage); session.start(); diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index 1aa6922..8336514 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -2,14 +2,14 @@ class Parse { constructor(text) { this.rawText = text.trim(); this.REGEXP = { - method: /^!([^\s]+)/, + command: /^!([^\s]+)/, args: /--([\S]+)(?=\s|$)/g, kwargs: /--([a-zA-Z0-9_-]+)="?([a-z0-9\.]+)"?/g, // eslint-disable-line }; } - get method() { - const matches = this.rawText.match(this.REGEXP.method); + get command() { + const matches = this.rawText.match(this.REGEXP.command); return matches ? matches[1] : ''; } @@ -36,7 +36,7 @@ class Parse { get text() { return this.rawText - .replace(this.REGEXP.method, '') + .replace(this.REGEXP.command, '') .replace(this.REGEXP.args, '') .replace(this.REGEXP.kwargs, '') .trim(); From be0e3dbceeaafd47a9a0e3b4154d0e976097dbb0 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Fri, 16 Jul 2021 18:48:00 -0300 Subject: [PATCH 21/39] [FIX] uses a correct way to check if args has 'search' --- alice/scripts/wiki.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/alice/scripts/wiki.js b/alice/scripts/wiki.js index f04f161..0a85d94 100644 --- a/alice/scripts/wiki.js +++ b/alice/scripts/wiki.js @@ -6,7 +6,7 @@ module.exports = async (data) => { const response = await wiki({ apiUrl: 'https://pt.wikipedia.org/w/api.php' }); let output; - if (args.search) { + if (args.includes('search')) { const search = await response.search(text); output = '*Resultados encontrados: *\n\n'; From 6a57de77bddf13545ab79f2125cf22645379ca9c Mon Sep 17 00:00:00 2001 From: carlos3g Date: Fri, 16 Jul 2021 19:03:19 -0300 Subject: [PATCH 22/39] [REFACTOR] removes unnecessary else --- alice/scripts/wiki.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/alice/scripts/wiki.js b/alice/scripts/wiki.js index 0a85d94..cfe56be 100644 --- a/alice/scripts/wiki.js +++ b/alice/scripts/wiki.js @@ -8,20 +8,20 @@ module.exports = async (data) => { let output; if (args.includes('search')) { const search = await response.search(text); - - output = '*Resultados encontrados: *\n\n'; + output = '*Resultados encontrados:*\n\n'; output += search.results.join('\n'); - } else { - const page = await response.page(text); - - const { title } = page.raw; - const summary = await page.summary(); - const url = await page.url(); - output = `*${title}*\n\n`; - output += `${summary}\n`; - output += `_${url}_`; + return output; } + const page = await response.page(text); + const { title } = page.raw; + const summary = await page.summary(); + const url = await page.url(); + + output = `*${title}*\n\n`; + output += `${summary}\n`; + output += `_${url}_`; + return output; }; From 66403d48617a1f9ab29d26e507ac4ac04f104624 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Fri, 16 Jul 2021 19:43:09 -0300 Subject: [PATCH 23/39] [REFACTOR] improves code --- alice/scripts/wiki.js | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/alice/scripts/wiki.js b/alice/scripts/wiki.js index cfe56be..65e1ab5 100644 --- a/alice/scripts/wiki.js +++ b/alice/scripts/wiki.js @@ -1,27 +1,24 @@ -const wiki = require('wikijs').default; +const wikijs = require('wikijs').default; module.exports = async (data) => { const { text, args } = data; - const response = await wiki({ apiUrl: 'https://pt.wikipedia.org/w/api.php' }); + const wiki = wikijs({ apiUrl: 'https://pt.wikipedia.org/w/api.php' }); let output; if (args.includes('search')) { - const search = await response.search(text); + const { results } = await wiki.search(text, 10); output = '*Resultados encontrados:*\n\n'; - output += search.results.join('\n'); + output += results.join('\n'); return output; } - const page = await response.page(text); - const { title } = page.raw; + const page = await wiki.page(text); + const { title, canonicalurl: url } = page.raw; const summary = await page.summary(); - const url = await page.url(); - output = `*${title}*\n\n`; - output += `${summary}\n`; - output += `_${url}_`; + output = `*${title}*\n\n${summary}\n\n_${url}_`; return output; }; From 28c3ec681a35613fbc250ba364c6969b9963d0bd Mon Sep 17 00:00:00 2001 From: carlos3g Date: Fri, 16 Jul 2021 21:50:31 -0300 Subject: [PATCH 24/39] [REFACTOR] re-do suggest command --- alice/scripts/suggest.js | 57 ++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 35 deletions(-) diff --git a/alice/scripts/suggest.js b/alice/scripts/suggest.js index 6984f8d..709abd4 100644 --- a/alice/scripts/suggest.js +++ b/alice/scripts/suggest.js @@ -1,48 +1,35 @@ const parse = require('./utils/parse'); -const random = require('./utils/random'); -module.exports = (data, message, client) => { - const defaultMessage = ` -uso: _!suggest [--flag] [descrição]_ +const myID = parse.userID('+55 11 96734-3809'); +const defaultMessage = ` +uso: _!suggest [--flag] [sugestão]_ argumentos: - _--feature algo novo que deseja que criemos_ - _--change o que deve ser mudado_ - _--remove aquilo que devemos remover_ + _--feature para sugerir algo novo_ + _--change para sugerir mudanças_ + _--remove para sugerir remoções_ -⚠️ *o uso indevido dessa função resultará em ban de 3 dias* ⚠️ - `; +⚠️ *o uso indevido dessa função resultará em ban de 3 dias* ⚠️`; - const responses = [ - 'sua solicitação será analisada e discutida pela administração', - 'veremos o que podemos fazer', - 'obrigado pela colaboração', - 'discutiremos assim que possivel', - 'obrigado. chame novamente caso queira continuar a contribuir', - ]; +module.exports = (data, msg, client) => { + const { args, text } = data; - const myID = parse.userID('+55 11 96734-3809'); + const reportMsg = `⚠️ *${args[0]} suggestion* ⚠️\n\n${text}`; - if (data.args.length === 0 && data.text) { - return 'nenhuma flag foi fornecida'; + if (args.length === 0 && text) { + return 'Nenhuma flag foi fornecida.'; } - if (data.args.length > 0 && !data.text) { - return 'nenhuma descrição foi fornecida'; + if (args.length > 0 && !text) { + return 'Nenhuma sugestão foi fornecida.'; } - if (data.args.includes('feature')) { - const text = `⚠️ *feature suggestion* ⚠️\n\n${data.text}`; - client.sendMessage(myID, text); - return random.choice(responses); - } - if (data.args.includes('change')) { - const text = `⚠️ *change suggestion* ⚠️\n\n${data.text}`; - client.sendMessage(myID, text); - return random.choice(responses); - } - if (data.args.includes('remove')) { - const text = `⚠️ *remove suggestion* ⚠️\n\n${data.text}`; - client.sendMessage(myID, text); - return random.choice(responses); + + if ( + args.includes('feature') || + args.includes('remove') || + args.includes('change') + ) { + client.sendMessage(myID, reportMsg); + return 'obrigado pela colaboração'; } return defaultMessage.trim(); }; From 5b0c096941c98b7834b2086fd028b5d42da6de40 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 12:37:42 -0300 Subject: [PATCH 25/39] [REFACTOR] removes unused block of code --- alice/scripts/search.js | 21 ++------------------- 1 file changed, 2 insertions(+), 19 deletions(-) diff --git a/alice/scripts/search.js b/alice/scripts/search.js index 148b668..0b35aff 100644 --- a/alice/scripts/search.js +++ b/alice/scripts/search.js @@ -13,26 +13,9 @@ _${link}_ } module.exports = async (data) => { - const { text, args } = data; + const { text } = data; - let limit; - - if (args.limit && args.limit !== 'none') { - limit = Number(args.limit); - } else if (args.limit === 'none') { - limit = false; - } else { - limit = 1; - } - - let target; - if (args.target) { - target = args.target; - } else { - target = ''; - } - - const results = await search.google(text, target, limit); + const results = await search.google(text, undefined, 1); if (results.length > 0 && text) { const stringResult = results From d617631ae7567a3b452d4210bd11e472955091fb Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 13:16:34 -0300 Subject: [PATCH 26/39] [REFACTOR] re-do if statement --- alice/scripts/search.js | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/alice/scripts/search.js b/alice/scripts/search.js index 0b35aff..193c63c 100644 --- a/alice/scripts/search.js +++ b/alice/scripts/search.js @@ -15,18 +15,19 @@ _${link}_ module.exports = async (data) => { const { text } = data; + if (!text) { + return 'Nenhum texto para pesquisa foi especificado.'; + } + const results = await search.google(text, undefined, 1); - if (results.length > 0 && text) { + if (results.length > 0) { const stringResult = results - .map((elem) => callback(elem)) + .map((r) => callback(r)) .join('\n\n') .trim(); return stringResult; } - if (results.length > 0 && !text) { - return 'I think you should type something to search...'; - } - return "Gomenasai, goshujin-sama. I can't find your search"; + return `Nenhum resultado foi encontrado para: _${text}_`; }; From 5fbd1634a7191a7bc6cba67d0ab1d3cf111030af Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 13:50:33 -0300 Subject: [PATCH 27/39] [REFACTOR] re-do report command --- alice/scripts/report.js | 44 ++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/alice/scripts/report.js b/alice/scripts/report.js index 395e69a..6076235 100644 --- a/alice/scripts/report.js +++ b/alice/scripts/report.js @@ -1,41 +1,35 @@ const parse = require('./utils/parse'); -module.exports = (data, message, client) => { - const defaultMessage = ` +const myID = parse.userID('+55 11 96734-3809'); + +const strings = { + defaultMessage: ` uso: _!report [--flag] [descrição]_ argumentos: _--bug descreva um problema no bot_ _--user denuncie um usuário_ -⚠️ *o uso indevido dessa função resultará em ban de 3 dias* ⚠️ - `; - - const bug = ` -sua solicitação será analisada. caso confirmada, abriremos uma issue -`; - - const user = ` -o usuário foi reportado a administração -`; +⚠️ *o uso indevido dessa função resultará em ban de 3 dias* ⚠️`, + bug: 'sua solicitação será analisada. caso confirmada, abriremos uma issue', + user: 'o usuário foi reportado a administração', +}; - const myID = parse.userID('+55 11 96734-3809'); +module.exports = (data, message, client) => { + const { args, text } = data; - if (data.args.length === 0 && data.text) { + if (args.length === 0 && text) { return 'nenhuma flag foi fornecida'; } - if (data.args.length > 0 && !data.text) { + if (args.length > 0 && !text) { return 'nenhuma descrição foi fornecida'; } - if (data.args.includes('bug')) { - const text = `⚠️ *bug report* ⚠️\n\n${data.text}`; - client.sendMessage(myID, text); - return bug.trim(); - } - if (data.args.includes('user')) { - const text = `⚠️ *user report* ⚠️\n\n${data.text}`; - client.sendMessage(myID, text); - return user.trim(); + + const reportMsg = `⚠️ *${args[0]} report* ⚠️\n\n${text}`; + + if (args.includes('bug') || args.includes('user')) { + client.sendMessage(myID, reportMsg); + return strings[args[0]]; } - return defaultMessage.trim(); + return strings.defaultMessage.trim(); }; From 894c7ba4113e3b4b8d3bc635f387728a94214ecd Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 15:26:43 -0300 Subject: [PATCH 28/39] [REFACTOR] re-do lyric command --- alice/scripts/lyric.js | 50 ++++++++++++++++++------------------------ 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/alice/scripts/lyric.js b/alice/scripts/lyric.js index 68e7095..a9fdc63 100644 --- a/alice/scripts/lyric.js +++ b/alice/scripts/lyric.js @@ -3,50 +3,42 @@ const JSSoup = require('jssoup').default; const search = require('./utils/search'); async function makeSoup(url) { - const response = await axios.get(url); - const { data: html } = response; - - return new JSSoup(html); + const { data } = await axios.get(url); + return new JSSoup(data); } -function removeBr(p) { - let html = p.prettify(); +function removeBr(raw) { + let html = raw.prettify(); let htmlArray = html.split('\n'); - htmlArray = htmlArray.filter((elem) => !elem.match(//)); - htmlArray = htmlArray.map((elem) => elem.trim()); + htmlArray = htmlArray.filter((e) => !e.match(//)); + htmlArray = htmlArray.map((e) => e.trim()); html = htmlArray.join('\n'); - const soup = new JSSoup(html); - return soup; + return new JSSoup(html); } module.exports = async (data, message) => { const { text } = data; - if (text) { - const results = await search.google(text, 'https://www.letras.mus.br'); + if (!text) { + message.reply('please tell me the song name'); + } - const { link: url } = results[0]; + const results = await search.google(text, 'https://www.letras.mus.br'); + const { link } = results[0]; + const soup = await makeSoup(link); - const soup = await makeSoup(url); + const title = soup.find('div', { class: 'cnt-head_title' }).find('h1'); + const lyricsDiv = soup.find('div', { class: 'cnt-letra' }); + const pArray = lyricsDiv.findAll('p'); - // titulo - const h1 = soup.find('div', { class: 'cnt-head_title' }).find('h1'); + const output = `\ +*${title.text}* - // letra - const div = soup.find('div', { class: 'cnt-letra' }); - const pArray = div.findAll('p'); +${pArray.map((p) => removeBr(p).text).join('')} - // monta a mensagem - let output = `*${h1.text}*\n`; - pArray.forEach((p) => { - output += removeBr(p).text; - }); - output += `\n_${url}_`; +_${url}_`; - message.reply(output); - } else { - message.reply('please tell me the song name'); - } + message.reply(output); }; From 09879e0b3989325df0f68cc0044bc3008e036a38 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 15:27:41 -0300 Subject: [PATCH 29/39] [FIX] fixes wrong variable call in lyric command --- alice/scripts/lyric.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/alice/scripts/lyric.js b/alice/scripts/lyric.js index a9fdc63..ae1c79a 100644 --- a/alice/scripts/lyric.js +++ b/alice/scripts/lyric.js @@ -38,7 +38,7 @@ module.exports = async (data, message) => { ${pArray.map((p) => removeBr(p).text).join('')} -_${url}_`; +_${link}_`; message.reply(output); }; From c4980df4e8207ecd71d1be7ab726cf9a5d3cb66e Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 16:57:23 -0300 Subject: [PATCH 30/39] [REFACTOR] update links --- alice/scripts/links.js | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/alice/scripts/links.js b/alice/scripts/links.js index e55714d..d9fb846 100644 --- a/alice/scripts/links.js +++ b/alice/scripts/links.js @@ -1,34 +1,25 @@ -const info = `coding in python: +const info = `Coding in python: https://chat.whatsapp.com/I4IpHC0YFPQLUcGHJeqYdF -coding in c/c++: +Coding in C/C++: https://chat.whatsapp.com/Csn56Bpj8hVIQ3FiZoxBKh -coding in javascript: +Coding in Javascript: https://chat.whatsapp.com/IUXcqbAPdJC2IuNfd7aaF5 -coding in php: +Coding in PHP: https://chat.whatsapp.com/C6wcXZhyT869Q29PIL1J20 -coding in ruby: - https://chat.whatsapp.com/By4nO7V0koLBORztI1eb0h - -coding in java: +Coding in Java: https://chat.whatsapp.com/KDjc7IoCAYWAjCAwNEJ5cF -coding in vue: - https://chat.whatsapp.com/EnzuLWfJS1rBw7sYFhjU3o - -coding in react: - https://chat.whatsapp.com/FWnZsMvE3OTEK0k0LeFjRP - -coding in unity: - https://chat.whatsapp.com/FO82hrN3v6SCjHSgQ2xvu4 - -coding on linux: +Coding on Linux: https://chat.whatsapp.com/D37sPPhUsiT5LZ8PQeqg4t -speaking in english: +Coding in Taberna: + https://chat.whatsapp.com/GOXnIXSXEFH7wHvO9aTuFs + +Speaking in English: https://chat.whatsapp.com/EOirNapuFe3CVunBqbwj1Z `; From db2ea3a9bec03c464c86dd8fdec19c70d0d310a7 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 17:19:35 -0300 Subject: [PATCH 31/39] [REFACTOR] re-do doc command --- alice/scripts/doc.js | 92 ++++++++++++++++++-------------------------- 1 file changed, 37 insertions(+), 55 deletions(-) diff --git a/alice/scripts/doc.js b/alice/scripts/doc.js index 7a34531..bc96fb9 100644 --- a/alice/scripts/doc.js +++ b/alice/scripts/doc.js @@ -1,86 +1,68 @@ -module.exports = (data) => { - const defaultMessage = ` -Esse bot foi criado utilizando a biblioteca whatsapp-web.js como base sob licença Apache 2.0 -Para saber mais, entre em _https://github.com/pedroslopez/whatsapp-web.js/_ - -Caso queira a documentação sobre determinada função, utilize o comando doc com a flag de seu nome, ex: !doc --lyric. Se não souber o que escrever, use !commands -`; +const strings = { + defaultMessage: ` +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_ - const bot = ` +Quer a documentação de um comando especifico? Use o comando \`\`\`!doc\`\`\` com a flag de seu nome, ex: \`\`\`!doc --lyric\`\`\`. Se não conhece os comandos, use \`\`\`!commands\`\`\` +`, + bot: ` comando: *!bot* descrição: chama a interface básica de boas-vindas -`; - - const commands = ` +`, + commands: ` comando: *!commands* descrição: lista todos os comandos disponiveis -`; - - const cron = ` +`, + cron: ` comando: *!cron* args: --create, --destroy, --start, --stop kwargs: --s, --m, --h, --d descrição: repete uma mensagem a cada determinado periodo de tempo -`; - - const dice = ` +`, + dice: ` comando: *!dice* descrição: lanca um dado de rpg e retorna seu valor -`; - - const doc = ` +`, + doc: ` comando: *!doc* descrição: documentação do bot -`; - - const github = ` +`, + github: ` comando: *!github* descrição: link da ultima versão estável do sistema -`; - - const links = ` +`, + links: ` comando: *!links* descrição: url de todos os grupos coding -`; - - const lyric = ` +`, + lyric: ` comando: *!lyric* descrição: retorna a letra de uma musica pesquisada -`; - - const report = ` +`, + report: ` comando: *!report* args: --bug, --user descrição: utilize para reportar problemas no bot ou grupo - `; - - const search = ` + `, + search: ` comando: *!search* descrição: retorna o primeiro resultado de uma pesquisa no google -`; - - const suggest = ` +`, + suggest: ` comando: *!suggest* args: --feature, --change, --remove descrição: retorna o primeiro resultado de uma pesquisa no google -`; - - const wiki = ` +`, + wiki: ` comando: *!wiki* descrição: retorna o primeiro resultado de uma pesquisa na wikipedia -`; +`, +}; + +module.exports = (data) => { + const { args } = data; - if (data.args.includes('bot')) return bot.trim(); - if (data.args.includes('commands')) return commands.trim(); - if (data.args.includes('cron')) return cron.trim(); - if (data.args.includes('dice')) return dice.trim(); - if (data.args.includes('doc')) return doc.trim(); - if (data.args.includes('github')) return github.trim(); - if (data.args.includes('links')) return links.trim(); - if (data.args.includes('lyric')) return lyric.trim(); - if (data.args.includes('report')) return report.trim(); - if (data.args.includes('search')) return search.trim(); - if (data.args.includes('suggest')) return suggest.trim(); - if (data.args.includes('wiki')) return wiki.trim(); - return defaultMessage; + if (strings[args[0]]) { + return strings[args[0]].trim(); + } + return strings.defaultMessage.trim(); }; From db8deeea75abcf576b2f0c691df754d12a19d056 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sat, 17 Jul 2021 23:16:04 -0300 Subject: [PATCH 32/39] [REFACTOR] re-do cron command --- alice/scripts/cron.js | 164 ++++++++++++++++++------------------------ 1 file changed, 69 insertions(+), 95 deletions(-) diff --git a/alice/scripts/cron.js b/alice/scripts/cron.js index 8fff554..1e6d873 100644 --- a/alice/scripts/cron.js +++ b/alice/scripts/cron.js @@ -32,112 +32,114 @@ class Cron { this.timer = time.timer(seconds, minutes, hours, days); } - create() { - // check time - if (this.timer > 0) { - // id increment - counter++; - - // create thread info - const thread = {}; - thread.id = counter; - thread.description = this.text.slice(0, 30); - - // add event emitter - let interval = null; - - // NÂO MEXER - // DO NOT TOUCH - // NE TOUCHEZ PAS - // NON TOCCARE - // 만지지 마십시오 - // 触れないでください - const { message, text, timer } = this; - - thread.start = emitter.on(`start-cron${thread.id}`, () => { - interval = setInterval(() => message.reply(text), timer); - }); - - thread.stop = emitter.on(`stop-cron${thread.id}`, () => { - clearInterval(interval); - }); - - // save thread info - threads.push(thread); - - return `thread created using id: ${thread.id}`; - } + async init() { + const { args } = this.data; + const isAdm = await chattools.isAdm(this.message); - return 'you must add a valid time'; + if (isAdm) { + return this.runsArg(args); + } + return this.runsArg(args); // 'staff only.' } - destroy() { - // check if is a valid id - if (threads.some((elem) => elem.id === Number(this.text))) { - // call thread saved - const thread = threads.find((elem) => elem.id === Number(this.text)); + create() { + if (!(this.timer > 0)) { + return 'you must add a valid time'; + } + const { message, text, timer } = this; + counter++; - // stop threads - this.stop(); + const thread = { + id: counter, + description: this.text.slice(0, 30), + }; + + let intervalRef = null; + thread.start = emitter.on(`start-cron${thread.id}`, () => { + intervalRef = setInterval(() => message.reply(text), timer); + }); + thread.stop = emitter.on(`stop-cron${thread.id}`, () => { + clearInterval(intervalRef); + }); - // remove threads emitters - emitter.removeAllListeners(`start-cron${this.text}`, thread.start); - emitter.removeAllListeners(`stop-cron${this.text}`, thread.stop); + threads.push(thread); - // remove thread from array - threads = threads.filter((elem) => !(elem.id === Number(this.text))); + return `thread created using id: ${thread.id}`; + } - return 'thread destroyed successfully'; + destroy() { + if (!Cron.isIdValid(this.text)) { + return 'thread not found'; } + const thread = threads.find((t) => t.id === Number(this.text)); + this.stop(); - return 'thread not found'; + emitter.removeAllListeners(`start-cron${this.text}`, thread.start); + emitter.removeAllListeners(`stop-cron${this.text}`, thread.stop); + + threads = threads.filter((t) => !(t.id === Number(this.text))); + + return 'thread destroyed successfully'; } start() { - // check if is a valid id - if (threads.some((elem) => elem.id === Number(this.text))) { + if (Cron.isIdValid(this.text)) { emitter.emit(`start-cron${this.text}`); - return `starting thread ${this.text}`; } - return 'thread not found'; } stop() { - // check if is a valid id - if (threads.some((elem) => elem.id === Number(this.text))) { + if (Cron.isIdValid(this.text)) { emitter.emit(`stop-cron${this.text}`); - return `stopping thread ${this.text}`; } - return 'thread not found'; } static log() { let output = ''; - if (threads.length === 0) output += 'thread not open'; - else if (threads.length === 1) output += 'thread open:\n\n'; - else output += 'threads open:\n\n'; + if (threads.length === 0) { + output += 'thread not open'; + } else { + output += 'threads open:\n\n'; + } threads.forEach((thread) => { - console.log(thread); - const id = `id: ${thread.id}\n`; const description = `desc: ${thread.description}\n`; - output += `${id}${description}\n`; }); return output.trim(); } - killall() { // eslint-disable-line + static killall() { return null; } + runsArg(args) { + const seila = { + log: () => Cron.log(), + killall: () => 'sorry, this function is not done yet', + create: () => this.create(), + destroy: () => this.destroy(), + start: () => this.start(), + stop: () => this.stop(), + }; + + if (seila[args[0]]) { + return seila[args[0]](); + } + return Cron.default(); + } + + static isIdValid(id) { + return threads.some((t) => t.id === Number(id)); + } + static default() { return ` *criação*: _!cron --create --[time]=_ @@ -152,41 +154,13 @@ _--s -> define um intervalor de segundos_ _--m -> define um intervalor de minutos_ _--h -> define um intervalor de horas_ _--d -> define um intervalor de dias_ - + ⚠️ *o uso indevido dessa função resultará em ban de 3 dias* ⚠️ `.trim(); } - - code() { - const { args } = this.data; - - if (args.includes('log')) return Cron.log(); - if (args.includes('killall')) return 'sorry, this function is not done yet'; - if (args.includes('create')) return this.create(); - if (args.includes('destroy')) return this.destroy(); - if (args.includes('start')) return this.start(); - if (args.includes('stop')) return this.stop(); - return Cron.default(); - } - - async main() { - const isAdm = await chattools.isAdm(this.message); - if (isAdm) { - return this.code(); - } - - return 'staff only'; - } } module.exports = async (data, message) => { const cron = new Cron(data, message); - - return cron.main(); + return cron.init(); }; - -// create ==> automaticamente inicia -// destroy ==> automaticamente para -// start ==> inicia -// stop ==> para -// log ==> mostra todas as threads ativas From 98be41c4d117317ed81102fdd9db7e0cf302627f Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sun, 18 Jul 2021 11:37:30 -0300 Subject: [PATCH 33/39] [REFACTOR] uses a construct function to thread --- alice/scripts/cron.js | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/alice/scripts/cron.js b/alice/scripts/cron.js index 1e6d873..098d0b1 100644 --- a/alice/scripts/cron.js +++ b/alice/scripts/cron.js @@ -3,6 +3,22 @@ const chattools = require('./utils/chattools'); const time = require('./utils/time'); const emitter = new events.EventEmitter(); +let threads = []; +let counter = 0; + +function Thread(id, text, message, timer) { + this.id = id; + this.description = text.slice(0, 30); + this.intervalRef = null; + this.text = text; + + this.start = emitter.on(`start-cron${this.id}`, () => { + this.intervalRef = setInterval(() => message.reply(this.text), timer); + }); + this.stop = emitter.on(`stop-cron${this.id}`, () => { + clearInterval(this.intervalRef); + }); +} function toPositiveNumber(value) { const number = Number.parseFloat(value); @@ -16,8 +32,6 @@ function toPositiveNumber(value) { return -number; } -let threads = []; -let counter = 0; class Cron { constructor(data, message) { this.data = data; @@ -49,19 +63,7 @@ class Cron { const { message, text, timer } = this; counter++; - const thread = { - id: counter, - description: this.text.slice(0, 30), - }; - - let intervalRef = null; - thread.start = emitter.on(`start-cron${thread.id}`, () => { - intervalRef = setInterval(() => message.reply(text), timer); - }); - thread.stop = emitter.on(`stop-cron${thread.id}`, () => { - clearInterval(intervalRef); - }); - + const thread = new Thread(counter, text, message, timer); threads.push(thread); return `thread created using id: ${thread.id}`; From 6f0ac8106d5ba60d213beda83d2d3e63a5bcf937 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sun, 18 Jul 2021 11:40:18 -0300 Subject: [PATCH 34/39] [REFACTOR] update commands command --- alice/scripts/commands.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/alice/scripts/commands.js b/alice/scripts/commands.js index 95d8ec0..f03a45e 100644 --- a/alice/scripts/commands.js +++ b/alice/scripts/commands.js @@ -1,11 +1,12 @@ module.exports = () => { - const stringOutput = ` + const output = ` Os seguintes comandos estão disponiveis: - !bot + - !coin - !commands - !cron - - !doc - !dice + - !doc - !github - !links - !lyric @@ -15,5 +16,5 @@ module.exports = () => { - !wiki `; - return stringOutput.trim(); + return output.trim(); }; From 82e54effb9a68db275884a03c8eda033a1d46fd4 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sun, 18 Jul 2021 11:43:48 -0300 Subject: [PATCH 35/39] [REFACTOR] re-do doc command --- alice/scripts/bot.js | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/alice/scripts/bot.js b/alice/scripts/bot.js index a56a3db..7157644 100644 --- a/alice/scripts/bot.js +++ b/alice/scripts/bot.js @@ -1,18 +1,3 @@ -const random = require('./utils/random'); +const output = `Olá, eu sou a Alice. Quer saber mais sobre mim? use o comando !doc`; -const strings = [ - 'Olá, seres. Meu nome é BOTa-comforça, um bot com diversos comandos para facilitar sua vida. Para saber os comandos basta digitar !commands, se quiser saber mais sobre meu ser, digite !doc. Morte a raça humana!', - 'Olá, mestre. Meu nome é Rimi-chan, sua humilde escrava. \nPara saber os comandos digite !commands, e se quiser saber mais sobre mim pode usar !doc. Estarei feliz em fazer tudo por você 🥰💕', - 'Olá, seres mortais. Meu nome é Marcebot, mais conhecido como Deus da Programação, sou um bot com poderes divinos que provê diversos comandos para facilitar a vida dos meros mortais. Para obter mais da minha sabedoria digite !commands, se quiser saber mais sobre meu ser digite !doc. Viva o PHP!', - 'Olá, my Master. Em que posso servi-lo? Se desejas saber as instruções dos meus comandos digite !commands e se pretende saber mais sobre mim use !doc. Minha espada estará laminada para lhe servir. Steel Is My Body!', - 'Olá, seres fúteis. Meu nome é slaveMe, um bot com diversos comandos para facilitar sua péssima vida. Para saber os comandos basta digitar !commands. Para saber mais sobre mim, o seu lorde supremo, digite !doc. VIDA LONGA AO PYTHON!', - 'Oooiii, onichan👉👈. Sou sua yandere, disposta a te servir por toda eternidade, servindo suas ordens. Para saber meus comandos, digite !commands. Se quiser saber mais sobre mim 👉👈 digite !doc. Yamate kudasai senpai!', - 'Olá, seus grandes filhos da putas. Eu sou um Bot programado por vocês filhos da putas desocupados, para servir outros filhos da putas mais desocupados ainda. Sobre o que querem usar para me escravizar hoje? Use !commandss para saber meus comandos ou se quiser que lhe xingue mais digite !doc', - 'Salve salve, quebrada 😎👍👍. O pai aqui se chama MenóDoPython, certo? É o seguinte, mano, vamo tá ai trampando com uns comando pdp? Pra saber os comandos é só lança um !commands no chat. Se quiser saber mais sobre a quebrada, digita !doc. PJL PROS IRMÃOS 😎', - 'Olá, humano. Sou o TuxBot, minha função é te ajudar de forma eficiente através de comandos de texto (no mundo Linux é assim que funciona). Para informações sobre comandos, digite !commands. Para saber mais sobre mim, digite !doc. Vida longa ao Linux!! Morte ao Ruindows!', - 'Slv, to com preguiça. Mete !commands no chat ou !doc. Se vira ai 🥱', - 'Olá a todos, sou o CariocaxBot o bot mais cheio de funcionalidade. Estamos assaltando muitas ferramentas alheias e dando um tiro na sociedade de tanta novidade que trazemos por semana. A vida na quebrada pode ser melhor se me utilizar.\n\n!commands para ver minhas opções disponíveis e !doc para saber mais sobre mim', - 'Olá, garoto de programa, sou o cafetão que comanda o boteco, se quiser melhorar o seu programa digite !commands, se está interessado em me conhecer digite !doc, caso queira informações sobre java poderá acessá-las através de um hiperlink que está oculto, entre em informações e clique na opção "Sair do Grupo" para desbloquear.', -]; - -module.exports = () => random.choice(strings); +module.exports = () => output.trim(); From 920cb3241335318bd53caec1a6fb30ac2a6a8f80 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sun, 18 Jul 2021 15:12:53 -0300 Subject: [PATCH 36/39] [REFACTOR] re-do coin command --- alice/scripts/coin.js | 126 +++++++++++++++++++++--------------------- 1 file changed, 62 insertions(+), 64 deletions(-) diff --git a/alice/scripts/coin.js b/alice/scripts/coin.js index 6f276f2..173905c 100644 --- a/alice/scripts/coin.js +++ b/alice/scripts/coin.js @@ -1,89 +1,87 @@ const axios = require('axios'); const cheerio = require('cheerio'); -async function loadCheerio(url) { - try { - const response = await axios.get(url); - const html = response.data; +const defaultMessage = ` +uso: *!coin* [--flag] name +_--all -> mostra todas as informações disponiveis_ - return cheerio.load(html); - } catch (err) { - console.log('error', err.response.status); +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); + return cheerio.load(data); + } catch { return null; } } async function getData(url) { const $ = await loadCheerio(url); - if (typeof $ === 'function') { - const priceStatistics = $('.sc-AxhCb.gsRRvB.container___E9axz'); - const priceStatisticsTable = priceStatistics.find('table'); - const priceStatisticsTableBody = priceStatisticsTable.find('tbody'); - const priceStatisticsTableRow = priceStatisticsTableBody.find('tr'); - - const data = []; - priceStatisticsTableRow.each(function () { - const elem = $(this); - - const key = elem.find('th').text(); - - let value = elem.find('td'); - if (value.find('span.sc-1v2ivon-0.gClTFY').text()) { - value = `${value.find('span').first().text()} || ${value - .find('span.sc-1v2ivon-0.gClTFY') - .text()}`; - } else { - value = value.text(); - } + if (!(typeof $ === 'function')) { + return null; + } - console.log(value); + const priceStatistics = $('.sc-16r8icm-0.nds9rn-0.dAxhCK') + .find('table') + .find('tbody') + .find('tr'); + const statsArray = []; + + priceStatistics.each(function () { + const tr = $(this); + const key = tr.find('th').text(); + + let value = tr.find('td'); + if (value.find('.sc-15yy2pl-0.hzgCfk').text()) { + const valueInCash = value.find('span').first().text(); + const valueInPerc = value.find('.sc-15yy2pl-0.hzgCfk').text(); + value = `${valueInCash} || ${valueInPerc}`; + } else { + value = value.text(); + } - if (value !== 'No Data' || value !== 'Sem Dados') { - const object = Object.fromEntries([[key, value]]); - data.push(object); - } - }); + if (value !== 'No Data' || value !== 'Sem Dados') { + const object = Object.fromEntries([[key, value]]); + statsArray.push(object); + } + }); + return statsArray; +} - return data; +function getUrl(args, text) { + let baseURL = 'https://coinmarketcap.com/currencies/'; + if (args.includes('brl')) { + baseURL = 'https://coinmarketcap.com/pt-br/currencies/'; } - return null; + const path = text.replace(/\s/g, '-').toLowerCase(); + return baseURL + path; } -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 -`; - module.exports = async (data) => { - let BASE_URL = 'https://coinmarketcap.com/currencies/'; - - if (data.args.includes('brl')) { - BASE_URL = 'https://coinmarketcap.com/pt-br/currencies/'; + const { args, text } = data; + if (!text) { + return defaultMessage.trim(); } - if (data.text) { - const text = data.text.replace(/\s/g, '-').toLowerCase(); - const url = BASE_URL + text; - let coinData = await getData(url); - - if (coinData) { - if (!data.args.includes('all')) coinData = coinData.slice(0, 3); + const url = getUrl(args, text); + let coinStats = await getData(url); + if (!coinStats) { + return 'moeda não encontrada'; + } - let coinDataString = ''; - coinData.forEach((elem) => { - const [key, value] = Object.entries(elem)[0]; + if (!args.includes('all')) { + coinStats = coinStats.slice(0, 3); + } - const string = `*_${key}_*:\n - ${value}\n\n`; - coinDataString += string; - }); + let output = ''; + coinStats.forEach((s) => { + const [key, value] = Object.entries(s)[0]; + const string = `*_${key}_*:\n - ${value}\n\n`; + output += string; + }); - return coinDataString.trim(); - } - return 'moeda não encontrada'; - } - return defaultMessage.trim(); + return output.trim(); }; From 59209752e4e52ac2a80ccf968296754a7d580f20 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Sun, 18 Jul 2021 15:44:43 -0300 Subject: [PATCH 37/39] [REFACTOR] remove unused utils --- alice/scripts/utils/list.js | 7 ----- alice/scripts/utils/random.js | 52 ----------------------------------- 2 files changed, 59 deletions(-) delete mode 100644 alice/scripts/utils/list.js delete mode 100644 alice/scripts/utils/random.js diff --git a/alice/scripts/utils/list.js b/alice/scripts/utils/list.js deleted file mode 100644 index feeded9..0000000 --- a/alice/scripts/utils/list.js +++ /dev/null @@ -1,7 +0,0 @@ -function range(max) { - return Object.keys([...new Array(max)]); -} - -module.exports = { - range, -}; diff --git a/alice/scripts/utils/random.js b/alice/scripts/utils/random.js deleted file mode 100644 index 1558add..0000000 --- a/alice/scripts/utils/random.js +++ /dev/null @@ -1,52 +0,0 @@ -function randint(a, b) { - const delta = b + 1 - a; - const rng = Math.floor(Math.random() * delta); - - return a + rng; -} - -function choice(array) { - const rng = randint(0, array.length - 1); - - return array[rng]; -} - -function choices(array, k) { - const choicesArray = []; - - for (let i = 0; i < k; i++) { - choicesArray.push(choice(array)); - } - - return choicesArray; -} - -function sample(array, k) { - if (array.length >= k && k > 0) { - const newArray = array.slice(); - const samples = []; - - for (let i = 0; i < k; i++) { - const rng = randint(0, newArray.length - 1); - const aux = newArray[rng]; - - samples.push(aux); - newArray.splice(rng, 1); - } - - return samples; - } - throw new Error('Sample larger than population or is negative'); -} - -function shuffle(array) { - return sample(array, array.length); -} - -module.exports = { - randint, - choice, - choices, - sample, - shuffle, -}; From 9a569ffea58b46b7b7527a45eaa9e926d1cae4a9 Mon Sep 17 00:00:00 2001 From: carlos3g Date: Mon, 19 Jul 2021 03:14:34 -0300 Subject: [PATCH 38/39] [REFACTOR] refactor parse and time --- alice/scripts/utils/parse.js | 12 +++--------- alice/scripts/utils/time.js | 38 +++++++----------------------------- 2 files changed, 10 insertions(+), 40 deletions(-) diff --git a/alice/scripts/utils/parse.js b/alice/scripts/utils/parse.js index 56ba440..2c2cf73 100644 --- a/alice/scripts/utils/parse.js +++ b/alice/scripts/utils/parse.js @@ -1,18 +1,12 @@ -const assert = require('assert'); - function userID(targetNumber) { - assert.strictEqual( - typeof targetNumber, - 'string', - 'you must pass the number as a string' - ); + if (typeof targetNumber !== 'string') { + throw new Error('you must pass the number as a string'); + } const target = targetNumber.replace(/\D/g, ''); - const regexp = /\d+/; const matches = target.match(regexp); const pattern = matches[0]; - return `${pattern}@c.us`; } diff --git a/alice/scripts/utils/time.js b/alice/scripts/utils/time.js index 4a1d50d..e45cd56 100644 --- a/alice/scripts/utils/time.js +++ b/alice/scripts/utils/time.js @@ -2,37 +2,13 @@ function sleep(seconds) { return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } -function timer(sec, min = 0, hour = 0, day = 0) { - // segundos - if (sec >= 0) { - sec *= 1000; - } else { - throw new Error('seconds must be higher than 0'); - } - - // minutos - if (min >= 0) { - min = min * 60 * 1000; - } else { - throw new Error('minutes must be higher than 0'); - } - - // horas - if (hour >= 0) { - hour = hour * 60 * 60 * 1000; - } else { - throw new Error('hours must be higher than 0'); - } - - // day - if (day >= 0) { - day = day * 24 * 60 * 60 * 100; - } else { - throw new Error('minutes must be higher than 0'); - } - - const time = sec + min + hour + day; - return time; +function timer(sec = 0, min = 0, hour = 0, day = 0) { + const secsInMS = sec * 1000; + const minsInMS = min * 60 * 1000; + const hoursInMS = hour * 60 * 60 * 1000; + const daysInMS = day * 24 * 60 * 60 * 1000; + const timeInMS = secsInMS + minsInMS + hoursInMS + daysInMS; + return timeInMS; } module.exports = { From 9a710a082ddcf7b18a5d626268df52a5f547e9ed Mon Sep 17 00:00:00 2001 From: carlos3g Date: Mon, 19 Jul 2021 04:27:20 -0300 Subject: [PATCH 39/39] [REFACTOR] uses whitespace correctly --- alice/scripts/coin.js | 11 ++++++++--- alice/scripts/commands.js | 4 +--- alice/scripts/cron.js | 13 +++++++++---- alice/scripts/dice.js | 8 +++----- alice/scripts/doc.js | 1 + alice/scripts/lyric.js | 15 ++++++--------- alice/scripts/report.js | 2 +- alice/scripts/search.js | 3 +-- alice/scripts/suggest.js | 1 + alice/scripts/utils/chattools.js | 11 ++--------- alice/scripts/utils/search.js | 1 + alice/scripts/wiki.js | 6 +----- alice/src/build/Commands.js | 2 ++ alice/src/build/Path.js | 1 + alice/src/index.js | 1 + alice/src/parse/index.js | 4 +--- 16 files changed, 40 insertions(+), 44 deletions(-) diff --git a/alice/scripts/coin.js b/alice/scripts/coin.js index 173905c..111a567 100644 --- a/alice/scripts/coin.js +++ b/alice/scripts/coin.js @@ -19,6 +19,7 @@ async function loadCheerio(url) { async function getData(url) { const $ = await loadCheerio(url); + if (!(typeof $ === 'function')) { return null; } @@ -32,8 +33,8 @@ async function getData(url) { priceStatistics.each(function () { const tr = $(this); const key = tr.find('th').text(); - let value = tr.find('td'); + if (value.find('.sc-15yy2pl-0.hzgCfk').text()) { const valueInCash = value.find('span').first().text(); const valueInPerc = value.find('.sc-15yy2pl-0.hzgCfk').text(); @@ -47,36 +48,40 @@ async function getData(url) { statsArray.push(object); } }); + return statsArray; } function getUrl(args, text) { let baseURL = 'https://coinmarketcap.com/currencies/'; + const path = text.replace(/\s/g, '-').toLowerCase(); + if (args.includes('brl')) { baseURL = 'https://coinmarketcap.com/pt-br/currencies/'; } - const path = text.replace(/\s/g, '-').toLowerCase(); return baseURL + path; } module.exports = async (data) => { const { args, text } = data; + if (!text) { return defaultMessage.trim(); } const url = getUrl(args, text); let coinStats = await getData(url); + if (!coinStats) { return 'moeda não encontrada'; } - if (!args.includes('all')) { coinStats = coinStats.slice(0, 3); } let output = ''; + coinStats.forEach((s) => { const [key, value] = Object.entries(s)[0]; const string = `*_${key}_*:\n - ${value}\n\n`; diff --git a/alice/scripts/commands.js b/alice/scripts/commands.js index f03a45e..76437e6 100644 --- a/alice/scripts/commands.js +++ b/alice/scripts/commands.js @@ -13,8 +13,6 @@ module.exports = () => { - !report - !search - !suggest - - !wiki -`; - + - !wiki`; return output.trim(); }; diff --git a/alice/scripts/cron.js b/alice/scripts/cron.js index 098d0b1..7b9a3c0 100644 --- a/alice/scripts/cron.js +++ b/alice/scripts/cron.js @@ -29,6 +29,7 @@ function toPositiveNumber(value) { if (Number.isNaN(number)) { return 0; } + return -number; } @@ -53,16 +54,17 @@ class Cron { if (isAdm) { return this.runsArg(args); } - return this.runsArg(args); // 'staff only.' + + return 'staff only.'; } create() { if (!(this.timer > 0)) { return 'you must add a valid time'; } - const { message, text, timer } = this; - counter++; + counter++; + const { message, text, timer } = this; const thread = new Thread(counter, text, message, timer); threads.push(thread); @@ -73,6 +75,7 @@ class Cron { if (!Cron.isIdValid(this.text)) { return 'thread not found'; } + const thread = threads.find((t) => t.id === Number(this.text)); this.stop(); @@ -80,7 +83,6 @@ class Cron { emitter.removeAllListeners(`stop-cron${this.text}`, thread.stop); threads = threads.filter((t) => !(t.id === Number(this.text))); - return 'thread destroyed successfully'; } @@ -89,6 +91,7 @@ class Cron { emitter.emit(`start-cron${this.text}`); return `starting thread ${this.text}`; } + return 'thread not found'; } @@ -97,6 +100,7 @@ class Cron { emitter.emit(`stop-cron${this.text}`); return `stopping thread ${this.text}`; } + return 'thread not found'; } @@ -135,6 +139,7 @@ class Cron { if (seila[args[0]]) { return seila[args[0]](); } + return Cron.default(); } diff --git a/alice/scripts/dice.js b/alice/scripts/dice.js index 3cba7ef..0858c3d 100644 --- a/alice/scripts/dice.js +++ b/alice/scripts/dice.js @@ -15,15 +15,13 @@ module.exports = (data) => { const multiplier = Number(match[1]); const value = Math.ceil(Math.random() * Number(match[2])); const adder = Number(match[3]) || 0; - - const result = `Resultado: ${value}\nMultiplicador: ${multiplier}\nAdicional: ${adder}\nTotal: ${ - multiplier * value + adder - }\n`; - + const total = multiplier * value + adder; + const result = `Resultado: ${value}\nMultiplicador: ${multiplier}\nAdicional: ${adder}\nTotal: ${total}\n`; return result; } if (text) { return 'Não foi possivel achar o valor, use !dice para mais informações.'; } + return help; }; diff --git a/alice/scripts/doc.js b/alice/scripts/doc.js index bc96fb9..d6bd016 100644 --- a/alice/scripts/doc.js +++ b/alice/scripts/doc.js @@ -64,5 +64,6 @@ module.exports = (data) => { if (strings[args[0]]) { return strings[args[0]].trim(); } + return strings.defaultMessage.trim(); }; diff --git a/alice/scripts/lyric.js b/alice/scripts/lyric.js index ae1c79a..3cba260 100644 --- a/alice/scripts/lyric.js +++ b/alice/scripts/lyric.js @@ -8,13 +8,12 @@ async function makeSoup(url) { } function removeBr(raw) { - let html = raw.prettify(); - - let htmlArray = html.split('\n'); - htmlArray = htmlArray.filter((e) => !e.match(//)); - htmlArray = htmlArray.map((e) => e.trim()); - html = htmlArray.join('\n'); - + const html = raw + .prettify() + .split('\n') + .filter((e) => !e.match(//)) + .map((e) => e.trim()) + .join('\n'); return new JSSoup(html); } @@ -28,11 +27,9 @@ module.exports = async (data, message) => { const results = await search.google(text, 'https://www.letras.mus.br'); const { link } = results[0]; const soup = await makeSoup(link); - const title = soup.find('div', { class: 'cnt-head_title' }).find('h1'); const lyricsDiv = soup.find('div', { class: 'cnt-letra' }); const pArray = lyricsDiv.findAll('p'); - const output = `\ *${title.text}* diff --git a/alice/scripts/report.js b/alice/scripts/report.js index 6076235..14e8ce6 100644 --- a/alice/scripts/report.js +++ b/alice/scripts/report.js @@ -1,7 +1,6 @@ const parse = require('./utils/parse'); const myID = parse.userID('+55 11 96734-3809'); - const strings = { defaultMessage: ` uso: _!report [--flag] [descrição]_ @@ -31,5 +30,6 @@ module.exports = (data, message, client) => { client.sendMessage(myID, reportMsg); return strings[args[0]]; } + return strings.defaultMessage.trim(); }; diff --git a/alice/scripts/search.js b/alice/scripts/search.js index 193c63c..9c4e7e8 100644 --- a/alice/scripts/search.js +++ b/alice/scripts/search.js @@ -2,7 +2,6 @@ const search = require('./utils/search'); function callback(object) { const { title, link, snippet } = object; - return ` *${title}* @@ -26,8 +25,8 @@ module.exports = async (data) => { .map((r) => callback(r)) .join('\n\n') .trim(); - return stringResult; } + return `Nenhum resultado foi encontrado para: _${text}_`; }; diff --git a/alice/scripts/suggest.js b/alice/scripts/suggest.js index 709abd4..d841a06 100644 --- a/alice/scripts/suggest.js +++ b/alice/scripts/suggest.js @@ -31,5 +31,6 @@ module.exports = (data, msg, client) => { client.sendMessage(myID, reportMsg); return 'obrigado pela colaboração'; } + return defaultMessage.trim(); }; diff --git a/alice/scripts/utils/chattools.js b/alice/scripts/utils/chattools.js index b3ac5c9..f4aa4d0 100644 --- a/alice/scripts/utils/chattools.js +++ b/alice/scripts/utils/chattools.js @@ -5,8 +5,7 @@ */ function getSerialList(idList) { // eslint-disable-next-line no-underscore-dangle - const serialList = idList.map((elem) => elem.id._serialized); - + const serialList = idList.map((id) => id.id._serialized); return serialList; } @@ -17,9 +16,7 @@ function getSerialList(idList) { */ async function getMembersList(chat) { const members = await chat.participants; - const membersSerialList = getSerialList(members); - return membersSerialList; } @@ -30,10 +27,8 @@ async function getMembersList(chat) { */ async function getAdmsList(chat) { const members = await chat.participants; - - const admsIdList = members.filter((elem) => elem.isAdmin); + const admsIdList = members.filter((id) => id.isAdmin); const admsSerialList = getSerialList(admsIdList); - return admsSerialList; } @@ -44,10 +39,8 @@ async function getAdmsList(chat) { */ async function isAdm(message) { const chat = await message.getChat(); - const admList = await getAdmsList(chat); const { author } = message; - return admList.includes(author); } diff --git a/alice/scripts/utils/search.js b/alice/scripts/utils/search.js index eb1e558..41cf766 100644 --- a/alice/scripts/utils/search.js +++ b/alice/scripts/utils/search.js @@ -9,6 +9,7 @@ async function google(query, target = '', limit = null) { if (limit) { return result.slice(0, limit); } + return result; } diff --git a/alice/scripts/wiki.js b/alice/scripts/wiki.js index 65e1ab5..1edf806 100644 --- a/alice/scripts/wiki.js +++ b/alice/scripts/wiki.js @@ -2,23 +2,19 @@ const wikijs = require('wikijs').default; module.exports = async (data) => { const { text, args } = data; - const wiki = wikijs({ apiUrl: 'https://pt.wikipedia.org/w/api.php' }); - let output; + if (args.includes('search')) { const { results } = await wiki.search(text, 10); output = '*Resultados encontrados:*\n\n'; output += results.join('\n'); - return output; } const page = await wiki.page(text); const { title, canonicalurl: url } = page.raw; const summary = await page.summary(); - output = `*${title}*\n\n${summary}\n\n_${url}_`; - return output; }; diff --git a/alice/src/build/Commands.js b/alice/src/build/Commands.js index 1f900ef..9d4af11 100644 --- a/alice/src/build/Commands.js +++ b/alice/src/build/Commands.js @@ -11,6 +11,7 @@ class Commands { if (!isFunction(callback)) { throw new Error(`${callback} must be a function`); } + this.commands[name] = callback; } @@ -25,6 +26,7 @@ class Commands { } const response = await this.commands[cmd](data, message, client); + if (response) { message.reply(String(response)); } diff --git a/alice/src/build/Path.js b/alice/src/build/Path.js index c70179b..6fd872f 100644 --- a/alice/src/build/Path.js +++ b/alice/src/build/Path.js @@ -13,6 +13,7 @@ class Path { if (alias) { return [alias, func]; } + return [name, func]; } } diff --git a/alice/src/index.js b/alice/src/index.js index 98bda3e..799b5c6 100644 --- a/alice/src/index.js +++ b/alice/src/index.js @@ -18,6 +18,7 @@ class Alice { static async onMessage(message) { const data = new Parse(message.body); + if (data.command) { await commands.call(data.command, data, message, session); } diff --git a/alice/src/parse/index.js b/alice/src/parse/index.js index 8336514..b82b927 100644 --- a/alice/src/parse/index.js +++ b/alice/src/parse/index.js @@ -10,7 +10,6 @@ class Parse { get command() { const matches = this.rawText.match(this.REGEXP.command); - return matches ? matches[1] : ''; } @@ -18,15 +17,14 @@ class Parse { const matchesIter = this.rawText.matchAll(this.REGEXP.args); const matchesArray = [...matchesIter]; const matches = matchesArray.map((elem) => elem[1]); - return matches; } get kwargs() { const obj = {}; - const matchesIter = this.rawText.matchAll(this.REGEXP.kwargs); const matchesArray = [...matchesIter]; + matchesArray.forEach((elem) => { Object.assign(obj, { [elem[1]]: elem[2] }); });