diff options
| author | 8cy <[email protected]> | 2020-04-29 04:36:14 -0700 |
|---|---|---|
| committer | 8cy <[email protected]> | 2020-04-29 04:36:14 -0700 |
| commit | 68d32ab1fa9c79e848038ca1c451e7d8f368531b (patch) | |
| tree | 6142669ecc054e8a94bad4723dc6fb5c83f8cee1 /src/utils | |
| parent | The Return, v8.2.0 (diff) | |
| download | dep-core-68d32ab1fa9c79e848038ca1c451e7d8f368531b.tar.xz dep-core-68d32ab1fa9c79e848038ca1c451e7d8f368531b.zip | |
Cerasus, v9.0.0
basically just add an insane amount of things
- all new animal commands
- waifu cmds
- change/ move clientid, invite, uwufy, support, howify, say, pfp
- add ip, security key, vote, datefacts, githubzen, fmk, fml, offsptring, facts, rate, opinion, onion, quantum coin, rolldie, romannumerals, russianrullete, smashorpass, spoiler, sub
- minecraft cmds
- SERVER check cmds
- lewd cmds
- roleplay commands
- fun commands and games
- utils
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/Util.ts | 185 | ||||
| -rw-r--r-- | src/utils/gameDigHelper.ts | 46 | ||||
| -rw-r--r-- | src/utils/genCmdURL.ts | 1 | ||||
| -rw-r--r-- | src/utils/simpleFormat.ts | 9 | ||||
| -rw-r--r-- | src/utils/stripWebhookURL.ts | 11 | ||||
| -rw-r--r-- | src/utils/truncateText.ts | 6 | ||||
| -rw-r--r-- | src/utils/wait.ts | 6 | ||||
| -rw-r--r-- | src/utils/winPercentage.ts | 16 |
8 files changed, 280 insertions, 0 deletions
diff --git a/src/utils/Util.ts b/src/utils/Util.ts new file mode 100644 index 0000000..6e00d04 --- /dev/null +++ b/src/utils/Util.ts @@ -0,0 +1,185 @@ +import crypto from 'crypto'; +const yes = ['yes', 'y', 'ye', 'yeah', 'yup', 'yea', 'ya', 'hai', 'si', 'sí', 'oui', 'はい', 'correct']; +const no = ['no', 'n', 'nah', 'nope', 'nop', 'iie', 'いいえ', 'non', 'fuck off']; + +module.exports = class Util { + static delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + static shuffle(array) { + const arr = array.slice(0); + for (let i = arr.length - 1; i >= 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + return arr; + } + + static list(arr, conj = 'and') { + const len = arr.length; + if (len === 0) return ''; + if (len === 1) return arr[0]; + return `${arr.slice(0, -1).join(', ')}${len > 1 ? `${len > 2 ? ',' : ''} ${conj} ` : ''}${arr.slice(-1)}`; + } + + static shorten(text, maxLen = 2000) { + return text.length > maxLen ? `${text.substr(0, maxLen - 3)}...` : text; + } + + static randomRange(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + static trimArray(arr, maxLen = 10) { + if (arr.length > maxLen) { + const len = arr.length - maxLen; + arr = arr.slice(0, maxLen); + arr.push(`${len} more...`); + } + return arr; + } + + static removeDuplicates(arr) { + if (arr.length === 0 || arr.length === 1) return arr; + const newArr = []; + for (let i = 0; i < arr.length; i++) { + if (newArr.includes(arr[i])) continue; + newArr.push(arr[i]); + } + return newArr; + } + + static sortByName(arr, prop) { + return arr.sort((a, b) => { + if (prop) return a[prop].toLowerCase() > b[prop].toLowerCase() ? 1 : -1; + return a.toLowerCase() > b.toLowerCase() ? 1 : -1; + }); + } + + static firstUpperCase(text, split = ' ') { + return text.split(split).map(word => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join(' '); + } + + static formatNumber(number, minimumFractionDigits = 0) { + return Number.parseFloat(number).toLocaleString(undefined, { + minimumFractionDigits, + maximumFractionDigits: 2 + }); + } + + static base64(text, mode = 'encode') { + if (mode === 'encode') return Buffer.from(text).toString('base64'); + if (mode === 'decode') return Buffer.from(text, 'base64').toString('utf8') || null; + throw new TypeError(`${mode} is not a supported base64 mode.`); + } + + static hash(text, algorithm) { + return crypto.createHash(algorithm).update(text).digest('hex'); + } + + static streamToArray(stream) { + if (!stream.readable) return Promise.resolve([]); + return new Promise((resolve, reject) => { + const array = []; + function onData(data) { + array.push(data); + } + function onEnd(error) { + if (error) reject(error); + else resolve(array); + cleanup(); + } + function onClose() { + resolve(array); + cleanup(); + } + function cleanup() { + stream.removeListener('data', onData); + stream.removeListener('end', onEnd); + stream.removeListener('error', onEnd); + stream.removeListener('close', onClose); + } + stream.on('data', onData); + stream.on('end', onEnd); + stream.on('error', onEnd); + stream.on('close', onClose); + }); + } + + static percentColor(pct, percentColors) { + let i = 1; + for (i; i < percentColors.length - 1; i++) { + if (pct < percentColors[i].pct) { + break; + } + } + const lower = percentColors[i - 1]; + const upper = percentColors[i]; + const range = upper.pct - lower.pct; + const rangePct = (pct - lower.pct) / range; + const pctLower = 1 - rangePct; + const pctUpper = rangePct; + const color = { + r: Math.floor((lower.color.r * pctLower) + (upper.color.r * pctUpper)).toString(16).padStart(2, '0'), + g: Math.floor((lower.color.g * pctLower) + (upper.color.g * pctUpper)).toString(16).padStart(2, '0'), + b: Math.floor((lower.color.b * pctLower) + (upper.color.b * pctUpper)).toString(16).padStart(2, '0') + }; + return `#${color.r}${color.g}${color.b}`; + } + + static today(timeZone) { + const now = new Date(); + now.setHours(0); + now.setMinutes(0); + now.setSeconds(0); + now.setMilliseconds(0); + if (timeZone) now.setUTCHours(now.getUTCHours() + timeZone); + return now; + } + + static tomorrow(timeZone) { + const today = Util.today(timeZone); + today.setDate(today.getDate() + 1); + return today; + } + + static embedURL(title, url, display) { + return `[${title}](${url.replace(/\)/g, '%27')}${display ? ` "${display}"` : ''})`; + } + + static async verify(channel, user, { time = 30000, extraYes = [], extraNo = [] } = {}) { + const filter = res => { + const value = res.content.toLowerCase(); + return (user ? res.author.id === user.id : true) + && (yes.includes(value) || no.includes(value) || extraYes.includes(value) || extraNo.includes(value)); + }; + const verify = await channel.awaitMessages(filter, { + max: 1, + time + }); + if (!verify.size) return 0; + const choice = verify.first().content.toLowerCase(); + if (yes.includes(choice) || extraYes.includes(choice)) return true; + if (no.includes(choice) || extraNo.includes(choice)) return false; + return false; + } + + static cleanAnilistHTML(html) { + let clean = html + .replace(/\r|\n|\f/g, '') + .replace(/<br>/g, '\n') + .replace(/'/g, '\'') + .replace(/"/g, '"') + .replace(/<\/?i>/g, '*') + .replace(/<\/?b>/g, '**') + .replace(/~!|!~/g, '||') + .replace(/—/g, '—'); + if (clean.length > 2000) clean = `${clean.substr(0, 1995)}...`; + const spoilers = (clean.match(/\|\|/g) || []).length; + if (spoilers !== 0 && (spoilers && (spoilers % 2))) clean += '||'; + return clean; + } +};
\ No newline at end of file diff --git a/src/utils/gameDigHelper.ts b/src/utils/gameDigHelper.ts new file mode 100644 index 0000000..647777d --- /dev/null +++ b/src/utils/gameDigHelper.ts @@ -0,0 +1,46 @@ +import ms from "ms"; +import { Util, MessageEmbed } from 'discord.js' + +/** +* Quickly create an embed for a GameDig status using values found in all responses +* @name gamedigHelper +* @param {Object} res Result from GameDig +* @returns {MessageEmbed} +*/ +module.exports = res => { + const playerCount = res.players.length + const maxPlayers = res.maxPlayers + + const emb = new MessageEmbed() + .setTitle(res.name) + .setFooter(`Took ${ms(res.ping)} to complete.`) + .addFields([ + { + name: 'Connect', + value: `${res.connect}` + }, + { + name: 'Online Players', + value: `${playerCount}/${maxPlayers} (${Math.round((playerCount / maxPlayers) * 100)}%)` + }, + { + name: 'Map', + value: Util.escapeMarkdown(res.map) + }, + { + name: 'Password Required', + value: res.password ? 'Yes' : 'No' + } + ]) + + const unconfirmedValues = new Map([ + [res.raw.secure, secure => emb.addField('Vac Secured', secure ? 'Yes' : 'No')], + [res.raw.games, game => emb.addField('Game', Util.escapeMarkdown(game))] + ]) + + unconfirmedValues.forEach((val, key) => { + if (typeof key !== 'undefined') val(key) + }) + + return emb +}
\ No newline at end of file diff --git a/src/utils/genCmdURL.ts b/src/utils/genCmdURL.ts new file mode 100644 index 0000000..4d658bc --- /dev/null +++ b/src/utils/genCmdURL.ts @@ -0,0 +1 @@ +module.exports = cmd => `/commands/${cmd.group.name.toLowerCase().replace(/\s/g, "-")}/${cmd.name}`;
\ No newline at end of file diff --git a/src/utils/simpleFormat.ts b/src/utils/simpleFormat.ts new file mode 100644 index 0000000..0985546 --- /dev/null +++ b/src/utils/simpleFormat.ts @@ -0,0 +1,9 @@ +/** +* @name simpleFormat +* @param {number|string} value Value to format +* @returns {number} A number in fixed-point notation up to 2 decimal points +*/ +module.exports = value => { + const result = parseFloat(parseFloat(value).toFixed(2)); + return result; +};
\ No newline at end of file diff --git a/src/utils/stripWebhookURL.ts b/src/utils/stripWebhookURL.ts new file mode 100644 index 0000000..fa8c240 --- /dev/null +++ b/src/utils/stripWebhookURL.ts @@ -0,0 +1,11 @@ +/** +* Gets the ID and token for a webhook from a webhook URL from the Discord client +* @param {string} url URL for the webhook from the Discord client +* @returns {Object} Object with the webhook ID and token +*/ +module.exports = url => { + const regex = /https:\/\/discordapp\.com\/api\/webhooks\/(\d{1,})\/([\w-_]{1,})/; + const matches = regex.exec(url); + + return { id: matches[1], token: matches[2] }; +};
\ No newline at end of file diff --git a/src/utils/truncateText.ts b/src/utils/truncateText.ts new file mode 100644 index 0000000..bd2f311 --- /dev/null +++ b/src/utils/truncateText.ts @@ -0,0 +1,6 @@ +/** +* @param {string} string String to truncate +* @param {number} [number=2048] Number to truncate to +* @returns {string} Truncated string or original if string was short enough to begin with +*/ +module.exports = (string, number = 2048) => (string.length > number ? `${string.substring(0, number - 3)}...` : string);
\ No newline at end of file diff --git a/src/utils/wait.ts b/src/utils/wait.ts new file mode 100644 index 0000000..bac3b72 --- /dev/null +++ b/src/utils/wait.ts @@ -0,0 +1,6 @@ +/** +* @name wait +* @param {number} delay Delay in milliseconds to wait for +* @returns {Promise<resolve>} +*/ +module.exports = delay => new Promise(resolve => setTimeout(resolve, delay));
\ No newline at end of file diff --git a/src/utils/winPercentage.ts b/src/utils/winPercentage.ts new file mode 100644 index 0000000..022f079 --- /dev/null +++ b/src/utils/winPercentage.ts @@ -0,0 +1,16 @@ +import config from '../config.json' +/** +* @name winPercentage +* @param {number} multiplier Multiplier to calculate win percentage for +* @param {User} user User to calculate win percentage for +* @returns {number} User balance +*/ +module.exports = (multiplier, user) => { + // Load the default setting + //let { houseEdgePercentage } = config; + + // If they're a crown supporter, set it to the patron percentage + //if (config.patrons[user.id] && config.patrons[user.id].crown === true) houseEdgePercentage = 0; + + //return (100 - houseEdgePercentage) / multiplier; +};
\ No newline at end of file |