Skip to content

Commit dc4f1a4

Browse files
authored
Merge pull request #31 from carlos3g/documentation
[DOCS] Documents some files
2 parents f1a9ebb + 2c4c36c commit dc4f1a4

File tree

6 files changed

+140
-25
lines changed

6 files changed

+140
-25
lines changed

src/auth/index.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
1-
const whatsapp = require('whatsapp-web.js');
1+
const { Client } = require('whatsapp-web.js');
22
const qrcode = require('qrcode-terminal');
33
const fs = require('fs');
44
const path = require('path');
55

66
const FILE_NAME = 'session.json';
77

8-
class Session extends whatsapp.Client {
8+
/**
9+
* Starting point for interacting with the WhatsApp Web API.
10+
* @param {string} SESSION_FILE_PATH - Path to `session.json` file.
11+
* @see https://docs.wwebjs.dev/Client.html
12+
* @extends {Client}
13+
*/
14+
class Session extends Client {
915
constructor() {
1016
super({
1117
puppeteer: {
@@ -16,22 +22,36 @@ class Session extends whatsapp.Client {
1622
this.SESSION_FILE_PATH = path.join(__dirname, FILE_NAME);
1723
}
1824

25+
/**
26+
* Checks if the `session.json` file already exists.
27+
* @returns {boolean} - `True` if exists, `False` if not.
28+
*/
1929
get exists() {
2030
return fs.existsSync(this.SESSION_FILE_PATH);
2131
}
2232

33+
/**
34+
* Throws the QR-Code to authenticate the session. When the QR-Code is read, the session file is written.
35+
*/
2336
create() {
2437
this.on('qr', (qr) => {
2538
qrcode.generate(qr, { small: true });
2639
});
2740
this.on('authenticated', this.save);
2841
}
2942

43+
/**
44+
* Writes the session in a .json file (`this.SESSION_FILE_PATH`)
45+
* @param {object} session - The session file returned in the authentication.
46+
*/
3047
save(session) {
3148
fs.writeFileSync(this.SESSION_FILE_PATH, JSON.stringify(session));
3249
console.log('⚠ The current session has been saved ⚠');
3350
}
3451

52+
/**
53+
* Loads the saved session file.
54+
*/
3555
load() {
3656
if (!this.exists) {
3757
throw Error(`session data does not exist in ${this.SESSION_FILE_PATH}`);
@@ -44,6 +64,9 @@ class Session extends whatsapp.Client {
4464
console.log('⚠ The previous session was loaded ⚠');
4565
}
4666

67+
/**
68+
* Starts the session.
69+
*/
4770
start() {
4871
this.on('ready', () => {
4972
console.log('Client is ready!');

src/build/Commands.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,21 @@ function isFunction(object) {
22
return typeof object === 'function';
33
}
44

5+
/**
6+
* Commands wrapper
7+
* @param {object} commands - Object that contains the commands.
8+
* @param {object} commands.* - A command. The key and value must be, respectively, the command name and a callback function for the command.
9+
*/
510
class Commands {
611
constructor() {
712
this.commands = {};
813
}
914

15+
/**
16+
* Sets a command in Commands instance.
17+
* @param {string} name - Command's name.
18+
* @param {function} callback - Callback to command.
19+
*/
1020
set(name, callback) {
1121
if (!isFunction(callback)) {
1222
throw new Error(`${callback} must be a function`);
@@ -15,11 +25,29 @@ class Commands {
1525
this.commands[name] = callback;
1626
}
1727

28+
/**
29+
* Checks if a command is set in Commands instance.
30+
* @param {string} cmd - The command's name.
31+
* @returns {boolean} `True` if the command is set in Commands instance, `False` if not.
32+
*/
1833
has(cmd) {
1934
const availableCommands = Object.keys(this.commands);
2035
return availableCommands.includes(cmd);
2136
}
2237

38+
/**
39+
* Calls (executes) a command.
40+
* @param {string} cmd - The command's name to be called.
41+
* @param {object} data - The data extracted from the message that called the command.
42+
* @param {string} data.command - The command's name extracted from the message.
43+
* @param {string[]} data.args - The args extracted from the message.
44+
* @param {object} data.kwargs - The kwargs extracted from the message.
45+
* @param {string} data.text - The text extracted from the message. This text NOT includes command's name, args and kwargs.
46+
* @param {Message} message - The message that called the command.
47+
* @param {Session} client - The whatsapp web session.
48+
* @see https://docs.wwebjs.dev/Message.html
49+
* @see https://docs.wwebjs.dev/Client.html
50+
*/
2351
async call(cmd, data, message, client) {
2452
if (!this.has(cmd)) {
2553
throw new Error(`${cmd} is not registered`);

src/utils/Parse.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,56 @@
1+
/**
2+
* Extract useful data from a given string (usually the content of a message).
3+
* @example
4+
* const messageContent = '!command --arg1 --kwarg=1 any text here'
5+
* const data = new Parse(messageContent)
6+
* data.command // command
7+
* data.args // ['arg1']
8+
* data.kwargs // { kwarg: 1 }
9+
* data.text // 'any text here'
10+
* @param {string} text - Text to be parsed.
11+
*/
112
class Parse {
213
constructor(text) {
14+
/** The original text. */
315
this.rawText = text.trim();
16+
17+
/**
18+
* A collection of regular expressions used in the extraction of data from the `this.rawText`.
19+
* @property {string} REGEXP.command - Regular expression for commands. Ex: !command
20+
* @property {string[]} REGEXP.args - Regular expression for args. Ex: --arg1
21+
* @property {object} REGEXP.kwargs - Regular expression for kwargs. Ex: --kwarg=1
22+
*/
423
this.REGEXP = {
524
command: /^!([^\s]+)/,
625
args: /--([\S]+)(?=\s|$)/g,
726
kwargs: /--([a-zA-Z0-9_-]+)="?([a-z0-9\.]+)"?/g, // eslint-disable-line
827
};
928
}
1029

30+
/**
31+
* Gets the command extracted from the `this.rawText`.
32+
* @returns {string}
33+
*/
1134
get command() {
1235
const matches = this.rawText.match(this.REGEXP.command);
1336
return matches ? matches[1] : '';
1437
}
1538

39+
/**
40+
* Gets the args extracted from `this.rawText`.
41+
* @returns {string[]}
42+
*/
1643
get args() {
1744
const matchesIter = this.rawText.matchAll(this.REGEXP.args);
1845
const matchesArray = [...matchesIter];
1946
const matches = matchesArray.map((elem) => elem[1]);
2047
return matches;
2148
}
2249

50+
/**
51+
* Gets the kwargs extracted from `this.rawText`.
52+
* @returns {object}
53+
*/
2354
get kwargs() {
2455
const obj = {};
2556
const matchesIter = this.rawText.matchAll(this.REGEXP.kwargs);
@@ -32,6 +63,10 @@ class Parse {
3263
return obj;
3364
}
3465

66+
/**
67+
* Gets the text extracted from `this.rawText`.
68+
* @returns {string}
69+
*/
3570
get text() {
3671
return this.rawText
3772
.replace(this.REGEXP.command, '')

src/utils/chattools.js

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
/**
2-
* Get serialized number
3-
* @param {Array<Object>} idList - An array containing objects about user identification.
4-
* @return {Array<String>} - Contains serialized phone numbers
2+
* Get serialized phone number from a given array of users.
3+
* @param {Contact[]} users - Whatsapp users.
4+
* @see https://docs.wwebjs.dev/Contact.html
5+
* @returns {string[]} - Serialized phone numbers.
56
*/
6-
function getSerialList(idList) {
7+
function getSerialList(users) {
78
// eslint-disable-next-line no-underscore-dangle
8-
const serialList = idList.map((id) => id.id._serialized);
9+
const serialList = users.map((u) => u.id._serialized);
910
return serialList;
1011
}
1112

1213
/**
13-
* Get serialized number of all members in group
14-
* @param {Object} chat - Object that represents the current chat
15-
* @return {Array<String>} - Contains serialized phone numbers of all members
14+
* Get serialized phone number of all members from a given group.
15+
* @param {Chat} chat - A whatsapp chat.
16+
* @see https://docs.wwebjs.dev/Chat.html
17+
* @returns {string[]} - Serialized phone numbers of all members.
1618
*/
1719
async function getMembersList(chat) {
1820
const members = await chat.participants;
@@ -21,9 +23,10 @@ async function getMembersList(chat) {
2123
}
2224

2325
/**
24-
* Get serialized number of all administrators in group
25-
* @param {Object} chat - Object that represents the current chat
26-
* @return {Array<String>} - Contains serialized phone numbers of all administrators
26+
* Get serialized phone number of all administrators from a given group.
27+
* @param {Chat} chat - A whatsapp chat.
28+
* @see https://docs.wwebjs.dev/Chat.html
29+
* @returns {string[]} - Serialized phone numbers of all administrators.
2730
*/
2831
async function getAdmsList(chat) {
2932
const members = await chat.participants;
@@ -33,9 +36,10 @@ async function getAdmsList(chat) {
3336
}
3437

3538
/**
36-
* Check if a message if from an adm
37-
* @param {Object} message - Object that represents the current message
38-
* @return {Boolean}
39+
* Checks if a message is from an ADM.
40+
* @param {Message} message - Message to check if is from an ADM.
41+
* @see https://docs.wwebjs.dev/Message.html
42+
* @returns {boolean}
3943
*/
4044
async function isAdm(message) {
4145
const chat = await message.getChat();
@@ -44,12 +48,17 @@ async function isAdm(message) {
4448
return admList.includes(author);
4549
}
4650

47-
function userID(targetNumber) {
48-
if (typeof targetNumber !== 'string') {
51+
/**
52+
* Get a whatsapp user id for a given phone number.
53+
* @param {string} phoneNumber
54+
* @returns {string}
55+
*/
56+
function userID(phoneNumber) {
57+
if (typeof phoneNumber !== 'string') {
4958
throw new Error('you must pass the number as a string');
5059
}
5160

52-
const target = targetNumber.replace(/\D/g, '');
61+
const target = phoneNumber.replace(/\D/g, '');
5362
const regexp = /\d+/;
5463
const matches = target.match(regexp);
5564
const pattern = matches[0];

src/utils/search.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
const googleIt = require('google-it');
22

3-
async function google(query, target = '', limit = null) {
3+
/**
4+
* Searchs for a given string in google.
5+
* @param {string} query Text that must be searched.
6+
* @param {string} [target=''] Target site to search in.
7+
* @param {number} [limit=0] Max number of results that must be returned.
8+
* @returns {object[]} Array of results found.
9+
*/
10+
async function google(query, target = '', limit = 0) {
411
const result = await googleIt({
512
query,
613
includeSites: target,

src/utils/time.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
1+
/**
2+
* Suspends (waits) execution of the current thread for a given number of seconds.
3+
* @param {number} seconds
4+
* @returns {Promise}
5+
*/
16
function sleep(seconds) {
27
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
38
}
49

5-
function timer(sec = 0, min = 0, hour = 0, day = 0) {
6-
const secsInMS = sec * 1000;
7-
const minsInMS = min * 60 * 1000;
8-
const hoursInMS = hour * 60 * 60 * 1000;
9-
const daysInMS = day * 24 * 60 * 60 * 1000;
10+
/**
11+
* Converts a given set of seconds, minutes, hours and days in miliseconds.
12+
* @param {number} [secs=0]
13+
* @param {number} [mins=0]
14+
* @param {number} [hours=0]
15+
* @param {number} [days=0]
16+
* @returns {number} Total time in miliseconds.
17+
*/
18+
function timer(secs = 0, mins = 0, hours = 0, days = 0) {
19+
const secsInMS = secs * 1000;
20+
const minsInMS = mins * 60 * 1000;
21+
const hoursInMS = hours * 60 * 60 * 1000;
22+
const daysInMS = days * 24 * 60 * 60 * 1000;
1023
const timeInMS = secsInMS + minsInMS + hoursInMS + daysInMS;
1124
return timeInMS;
1225
}

0 commit comments

Comments
 (0)