From 891a36a9baf1a48d5e2ef1d688cacf0a330f8027 Mon Sep 17 00:00:00 2001 From: "Ean Milligan (Bastion)" Date: Sun, 22 May 2022 15:29:59 -0400 Subject: [PATCH] Sonar Cleanup - Phase 1 --- db/populateDefaults.ts | 6 +++--- mod.ts | 2 +- src/commands/emoji.ts | 16 ++++++++-------- src/constantCmds.ts | 17 ++++++++++------- src/solver/parser.ts | 6 +++--- src/solver/rollUtils.ts | 18 +++++++++++------- src/solver/roller.ts | 6 +++--- www/api/index.html | 12 ++++++------ www/api/main.js | 6 +++--- www/home/index.html | 22 +++++++++++----------- 10 files changed, 59 insertions(+), 52 deletions(-) diff --git a/db/populateDefaults.ts b/db/populateDefaults.ts index 108e0b9..37043e5 100644 --- a/db/populateDefaults.ts +++ b/db/populateDefaults.ts @@ -11,9 +11,9 @@ console.log('Inesrtion done'); console.log('Attempting to insert default commands into command_cnt'); const commands = ['ping', 'rip', 'rollhelp', 'help', 'info', 'version', 'report', 'stats', 'roll', 'emojis', 'api', 'privacy', 'mention']; -for (let i = 0; i < commands.length; i++) { - await dbClient.execute('INSERT INTO command_cnt(command) values(?)', [commands[i]]).catch((e) => { - console.log(`Failed to insert into database`, e); +for (const command of commands) { + await dbClient.execute('INSERT INTO command_cnt(command) values(?)', [command]).catch((e) => { + console.log(`Failed to insert ${command} into database`, e); }); } console.log('Insertion done'); diff --git a/mod.ts b/mod.ts index 0c8b632..d30b0d9 100644 --- a/mod.ts +++ b/mod.ts @@ -100,7 +100,7 @@ startBot({ log(LT.ERROR, `Failed to send message: ${JSON.stringify(e)}`); }); }, - debug: DEVMODE ? (dmsg) => log(LT.LOG, `Debug Message | ${JSON.stringify(dmsg)}`) : () => {}, + debug: DEVMODE ? (dmsg) => log(LT.LOG, `Debug Message | ${JSON.stringify(dmsg)}`) : undefined, messageCreate: (message: DiscordenoMessage) => { // Ignore all other bots if (message.isBot) return; diff --git a/src/commands/emoji.ts b/src/commands/emoji.ts index 395958d..f998db3 100644 --- a/src/commands/emoji.ts +++ b/src/commands/emoji.ts @@ -11,29 +11,29 @@ import { EmojiConf } from '../mod.d.ts'; const allEmojiAliases: string[] = []; -config.emojis.forEach((emoji: EmojiConf) => { - allEmojiAliases.push(...emoji.aliases); +config.emojis.forEach((emji: EmojiConf) => { + allEmojiAliases.push(...emji.aliases); }); export const emoji = (message: DiscordenoMessage, command: string) => { // shortcut if (allEmojiAliases.indexOf(command)) { // Start looping thru the possible emojis - config.emojis.some((emoji: EmojiConf) => { - log(LT.LOG, `Checking if command was emoji ${JSON.stringify(emoji)}`); + config.emojis.some((emji: EmojiConf) => { + log(LT.LOG, `Checking if command was emoji ${JSON.stringify(emji)}`); // If a match gets found - if (emoji.aliases.indexOf(command || '') > -1) { + if (emji.aliases.indexOf(command || '') > -1) { // Light telemetry to see how many times a command is being run dbClient.execute(`CALL INC_CNT("emojis");`).catch((e) => { log(LT.ERROR, `Failed to call stored procedure INC_CNT: ${JSON.stringify(e)}`); }); - // Send the needed emoji1 - message.send(`<${emoji.animated ? 'a' : ''}:${emoji.name}:${emoji.id}>`).catch((e) => { + // Send the needed emoji + message.send(`<${emji.animated ? 'a' : ''}:${emji.name}:${emji.id}>`).catch((e) => { log(LT.ERROR, `Failed to send message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); // And attempt to delete if needed - if (emoji.deleteSender) { + if (emji.deleteSender) { message.delete().catch((e) => { log(LT.WARN, `Failed to delete message: ${JSON.stringify(message)} | ${JSON.stringify(e)}`); }); diff --git a/src/constantCmds.ts b/src/constantCmds.ts index 87fecba..981133e 100644 --- a/src/constantCmds.ts +++ b/src/constantCmds.ts @@ -530,13 +530,16 @@ export const generateApiFailed = (args: string) => ({ }], }); -export const generateApiStatus = (banned: boolean, active: boolean) => ({ - embeds: [{ - color: infoColor1, - title: `The Artificer's API is ${config.api.enable ? 'currently enabled' : 'currently disabled'}.`, - description: banned ? 'API rolls are banned from being used in this guild.\n\nThis will not be reversed.' : `API rolls are ${active ? 'allowed' : 'blocked from being used'} in this guild.`, - }], -}); +export const generateApiStatus = (banned: boolean, active: boolean) => { + const apiStatus = active ? 'allowed' : 'blocked from being used'; + return { + embeds: [{ + color: infoColor1, + title: `The Artificer's API is ${config.api.enable ? 'currently enabled' : 'currently disabled'}.`, + description: banned ? 'API rolls are banned from being used in this guild.\n\nThis will not be reversed.' : `API rolls are ${apiStatus} in this guild.`, + }] + }; +}; export const generateApiSuccess = (args: string) => ({ embeds: [{ diff --git a/src/solver/parser.ts b/src/solver/parser.ts index 8142621..3c29ec6 100644 --- a/src/solver/parser.ts +++ b/src/solver/parser.ts @@ -32,10 +32,10 @@ export const parseRoll = (fullCmd: string, modifiers: RollModifiers): SolvedRoll const tempReturnData: ReturnData[] = []; // Loop thru all roll/math ops - for (let i = 0; i < sepRolls.length; i++) { - log(LT.LOG, `Parsing roll ${fullCmd} | Working ${sepRolls[i]}`); + for (const sepRoll of sepRolls) { + log(LT.LOG, `Parsing roll ${fullCmd} | Working ${sepRoll}`); // Split the current iteration on the command postfix to separate the operation to be parsed and the text formatting after the opertaion - const [tempConf, tempFormat] = sepRolls[i].split(config.postfix); + const [tempConf, tempFormat] = sepRoll.split(config.postfix); // Remove all spaces from the operation config and split it by any operator (keeping the operator in mathConf for fullSolver to do math on) const mathConf: (string | number | SolvedStep)[] = <(string | number | SolvedStep)[]> tempConf.replace(/ /g, '').split(/([-+()*/%^])/g); diff --git a/src/solver/rollUtils.ts b/src/solver/rollUtils.ts index 8059f35..06599ff 100644 --- a/src/solver/rollUtils.ts +++ b/src/solver/rollUtils.ts @@ -13,9 +13,13 @@ export const MAXLOOPS = 5000000; // genRoll(size) returns number // genRoll rolls a die of size size and returns the result -export const genRoll = (size: number): number => { - // Math.random * size will return a decimal number between 0 and size (excluding size), so add 1 and floor the result to not get 0 as a result - return Math.floor((Math.random() * size) + 1); +export const genRoll = (size: number, maximiseRoll: boolean, nominalRoll: boolean): number => { + if (maximiseRoll) { + return size; + } else { + // Math.random * size will return a decimal number between 0 and size (excluding size), so add 1 and floor the result to not get 0 as a result + return nominalRoll ? ((size / 2) + 0.5) : Math.floor((Math.random() * size) + 1); + } }; // compareRolls(a, b) returns -1|0|1 @@ -58,11 +62,11 @@ export const compareOrigidx = (a: RollSet, b: RollSet): number => { // escapeCharacters escapes all characters listed in esc export const escapeCharacters = (str: string, esc: string): string => { // Loop thru each esc char one at a time - for (let i = 0; i < esc.length; i++) { - log(LT.LOG, `Escaping character ${esc[i]} | ${str}, ${esc}`); + for (const e of esc) { + log(LT.LOG, `Escaping character ${e} | ${str}, ${esc}`); // Create a new regex to look for that char that needs replaced and escape it - const temprgx = new RegExp(`[${esc[i]}]`, 'g'); - str = str.replace(temprgx, `\\${esc[i]}`); + const temprgx = new RegExp(`[${e}]`, 'g'); + str = str.replace(temprgx, `\\${e}`); } return str; }; diff --git a/src/solver/roller.ts b/src/solver/roller.ts index 3f42e43..995439c 100644 --- a/src/solver/roller.ts +++ b/src/solver/roller.ts @@ -349,7 +349,7 @@ export const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolea // Copy the template to fill out for this iteration const rolling = JSON.parse(JSON.stringify(templateRoll)); // If maximiseRoll is on, set the roll to the dieSize, else if nominalRoll is on, set the roll to the average roll of dieSize, else generate a new random roll - rolling.roll = maximiseRoll ? rollConf.dieSize : (nominalRoll ? ((rollConf.dieSize / 2) + 0.5) : genRoll(rollConf.dieSize)); + rolling.roll = genRoll(rollConf.dieSize, maximiseRoll, nominalRoll); // Set origidx of roll rolling.origidx = i; @@ -388,7 +388,7 @@ export const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolea // Copy the template to fill out for this iteration const newRoll = JSON.parse(JSON.stringify(templateRoll)); // If maximiseRoll is on, set the roll to the dieSize, else if nominalRoll is on, set the roll to the average roll of dieSize, else generate a new random roll - newRoll.roll = maximiseRoll ? rollConf.dieSize : (nominalRoll ? ((rollConf.dieSize / 2) + 0.5) : genRoll(rollConf.dieSize)); + newRoll.roll = genRoll(rollConf.dieSize, maximiseRoll, nominalRoll); // If critScore arg is on, check if the roll should be a crit, if its off, check if the roll matches the die size if (rollConf.critScore.on && rollConf.critScore.range.indexOf(newRoll.roll) >= 0) { @@ -415,7 +415,7 @@ export const roll = (rollStr: string, maximiseRoll: boolean, nominalRoll: boolea // Copy the template to fill out for this iteration const newRoll = JSON.parse(JSON.stringify(templateRoll)); // If maximiseRoll is on, set the roll to the dieSize, else if nominalRoll is on, set the roll to the average roll of dieSize, else generate a new random roll - newRoll.roll = maximiseRoll ? rollConf.dieSize : (nominalRoll ? ((rollConf.dieSize / 2) + 0.5) : genRoll(rollConf.dieSize)); + newRoll.roll = genRoll(rollConf.dieSize, maximiseRoll, nominalRoll); // Always mark this roll as exploding newRoll.exploding = true; diff --git a/www/api/index.html b/www/api/index.html index f801315..fa1e022 100644 --- a/www/api/index.html +++ b/www/api/index.html @@ -1,5 +1,5 @@ - + @@ -33,9 +33,9 @@ The Artificer API Tools
- Invite Me! + Invite Me! | - About + About
@@ -44,11 +44,11 @@
-

This website will help you manage your API Key (or create one if you do not already have one). To get started, select an option from the dropdown below and enter the requested information. For more information, check out the GitHub Repository.

+

This website will help you manage your API Key (or create one if you do not already have one). To get started, select an option from the dropdown below and enter the requested information. For more information, check out the GitHub Repository.


-

Javascript is required for this website to function. If you do not want to enable Javascript, you may access all of these endpoints from a third party tool (such as Postman). Endpoints are fully documented on the GitHub Repository.

+

Javascript is required for this website to function. If you do not want to enable Javascript, you may access all of these endpoints from a third party tool (such as Postman). Endpoints are fully documented on the GitHub Repository.

Available Commands:

Rolling Command:

-

This command is what the bot is all about. Using the Roll20 format, any form of dice roll can be performed, with any needed math calculated into the results. This command can even be used as a fairly advanced calculator, supporting parenthesis, exponentials, multiplication, division, modulus, addition, and subtraction.

+

This command is what the bot is all about. Using the Roll20 format, any form of dice roll can be performed, with any needed math calculated into the results. This command can even be used as a fairly advanced calculator, supporting parenthesis, exponentials, multiplication, division, modulus, addition, and subtraction.

Examples:

[[d20]] - Rolls a simple d20 without anything fancy

[[4d20r1!]] - Rolls 4 d20 dice, rerolling any dice that land on 1, and repeatedly rolling a new d20 for any critical success rolled

@@ -72,10 +72,10 @@

Examples:

[[stats or [[s - Shows the stats on how many servers and users are using the bot

[[help or [[? - Gives the full list of available commands

-

[[rollhelp or [[?? - Gives the full details on the roll command, explaining the Roll20 format

+

[[rollhelp or [[?? - Gives the full details on the roll command, explaining the Roll20 format


Full Documentation:

-

Full Documentation can be found on the GitHub Repository.

+

Full Documentation can be found on the GitHub Repository.

@@ -83,15 +83,15 @@

This API was developed to let DnD groups that use Excel to manage player sheets to roll dice directly from Excel to Discord. The API is limited to rolling dice and managing your API Key and has a harsh rate limit to prevent spam.

There is a ZERO tolerance for API abuse. If abuse is detected or reported, the user will be banned with no chance to appeal.

-

If you would like to get an API Key, head on over to the API Tools page linked at the top of this page. Basic administration of your API key can also be done via the API Tools.

-

Once you have your API Key, detailed information on the API endpoints can be found in the GitHub Repository.

+

If you would like to get an API Key, head on over to the API Tools page linked at the top of this page. Basic administration of your API key can also be done via the API Tools.

+

Once you have your API Key, detailed information on the API endpoints can be found in the GitHub Repository.