From d2a020837267bf024f508b402f596f8e242672ed Mon Sep 17 00:00:00 2001 From: IRONM00N <64110067+IRONM00N@users.noreply.github.com> Date: Mon, 11 Jul 2022 18:44:09 +0200 Subject: create task categories --- src/lib/extensions/discord-akairo/BushClient.ts | 4 +- src/tasks/cache/cpuUsage.ts | 62 ++++++++++++++++++ src/tasks/cache/updateCache.ts | 60 ++++++++++++++++++ src/tasks/cache/updateHighlightCache.ts | 15 +++++ src/tasks/cache/updatePriceItemCache.ts | 27 ++++++++ src/tasks/cpuUsage.ts | 62 ------------------ src/tasks/feature/handleReminders.ts | 39 ++++++++++++ src/tasks/feature/memberCount.ts | 28 +++++++++ src/tasks/feature/removeExpiredPunishements.ts | 84 +++++++++++++++++++++++++ src/tasks/feature/updateStats.ts | 26 ++++++++ src/tasks/handleReminders.ts | 39 ------------ src/tasks/memberCount.ts | 28 --------- src/tasks/removeExpiredPunishements.ts | 84 ------------------------- src/tasks/updateCache.ts | 60 ------------------ src/tasks/updateHighlightCache.ts | 15 ----- src/tasks/updatePriceItemCache.ts | 27 -------- src/tasks/updateStats.ts | 26 -------- 17 files changed, 343 insertions(+), 343 deletions(-) create mode 100644 src/tasks/cache/cpuUsage.ts create mode 100644 src/tasks/cache/updateCache.ts create mode 100644 src/tasks/cache/updateHighlightCache.ts create mode 100644 src/tasks/cache/updatePriceItemCache.ts delete mode 100644 src/tasks/cpuUsage.ts create mode 100644 src/tasks/feature/handleReminders.ts create mode 100644 src/tasks/feature/memberCount.ts create mode 100644 src/tasks/feature/removeExpiredPunishements.ts create mode 100644 src/tasks/feature/updateStats.ts delete mode 100644 src/tasks/handleReminders.ts delete mode 100644 src/tasks/memberCount.ts delete mode 100644 src/tasks/removeExpiredPunishements.ts delete mode 100644 src/tasks/updateCache.ts delete mode 100644 src/tasks/updateHighlightCache.ts delete mode 100644 src/tasks/updatePriceItemCache.ts delete mode 100644 src/tasks/updateStats.ts diff --git a/src/lib/extensions/discord-akairo/BushClient.ts b/src/lib/extensions/discord-akairo/BushClient.ts index 5f63839..286d9cf 100644 --- a/src/lib/extensions/discord-akairo/BushClient.ts +++ b/src/lib/extensions/discord-akairo/BushClient.ts @@ -47,8 +47,8 @@ import type { Options as SequelizeOptions, Sequelize as SequelizeType } from 'se import { fileURLToPath } from 'url'; import type { Config } from '../../../../config/Config.js'; import { tinyColor } from '../../../arguments/tinyColor.js'; -import UpdateCacheTask from '../../../tasks/updateCache.js'; -import UpdateStatsTask from '../../../tasks/updateStats.js'; +import UpdateCacheTask from '../../../tasks/cache/updateCache.js'; +import UpdateStatsTask from '../../../tasks/feature/updateStats.js'; import { HighlightManager } from '../../common/HighlightManager.js'; import { ActivePunishment } from '../../models/instance/ActivePunishment.js'; import { Guild as GuildDB } from '../../models/instance/Guild.js'; diff --git a/src/tasks/cache/cpuUsage.ts b/src/tasks/cache/cpuUsage.ts new file mode 100644 index 0000000..61e7a54 --- /dev/null +++ b/src/tasks/cache/cpuUsage.ts @@ -0,0 +1,62 @@ +import { BushTask, Time } from '#lib'; +import os from 'node:os'; + +export default class CpuUsageTask extends BushTask { + public constructor() { + super('cpuUsage', { + delay: Time.Minute, + runOnStart: true + }); + } + + public async exec() { + const cpuStats = await cpu.usage(this.client.stats.cpu === undefined ? 100 * Time.Millisecond : Time.Minute); + this.client.stats.cpu = cpuStats; + } +} + +/* Everything inside the cpu namespace is adapted from the "node-os-utils" npm package which is licensed under a MIT license by Sunil Wang */ +namespace cpu { + export function usage(interval = Time.Second): Promise { + return new Promise((resolve) => { + const startMeasure = average(); + + setTimeout(() => { + const endMeasure = average(); + const idleDifference = endMeasure.avgIdle - startMeasure.avgIdle; + const totalDifference = endMeasure.avgTotal - startMeasure.avgTotal; + const cpuPercentage = (10000 - Math.round((10000 * idleDifference) / totalDifference)) / 100; + + return resolve(cpuPercentage); + }, interval); + }); + } + + export function average(): CpuAverageInfo { + let totalIdle = 0; + let totalTick = 0; + const cpus = os.cpus(); + + for (let i = 0, len = cpus.length; i < len; i++) { + const cpu = cpus[i]; + for (const type in cpu.times) { + totalTick += cpu.times[type as keyof typeof cpu.times]; + } + totalIdle += cpu.times.idle; + } + + return { + totalIdle: totalIdle, + totalTick: totalTick, + avgIdle: totalIdle / cpus.length, + avgTotal: totalTick / cpus.length + }; + } + + export interface CpuAverageInfo { + totalIdle: number; + totalTick: number; + avgIdle: number; + avgTotal: number; + } +} diff --git a/src/tasks/cache/updateCache.ts b/src/tasks/cache/updateCache.ts new file mode 100644 index 0000000..87636e8 --- /dev/null +++ b/src/tasks/cache/updateCache.ts @@ -0,0 +1,60 @@ +import { Time } from '#constants'; +import { Global, Guild, Shared, type BushClient } from '#lib'; +import type { Client } from 'discord.js'; +import config from '../../../config/options.js'; +import { BushTask } from '../../lib/extensions/discord-akairo/BushTask.js'; + +export default class UpdateCacheTask extends BushTask { + public constructor() { + super('updateCache', { + delay: 5 * Time.Minute, + runOnStart: false // done in preinit task + }); + } + + public async exec() { + await Promise.all([ + UpdateCacheTask.#updateGlobalCache(this.client), + UpdateCacheTask.#updateSharedCache(this.client), + UpdateCacheTask.#updateGuildCache(this.client) + ]); + void this.client.logger.verbose(`UpdateCache`, `Updated cache.`); + } + + public static async init(client: BushClient) { + await Promise.all([ + UpdateCacheTask.#updateGlobalCache(client), + UpdateCacheTask.#updateSharedCache(client), + UpdateCacheTask.#updateGuildCache(client) + ]); + } + + static async #updateGlobalCache(client: Client) { + const environment = config.environment; + const row: { [x: string]: any } = ((await Global.findByPk(environment)) ?? (await Global.create({ environment }))).toJSON(); + + for (const option in row) { + if (Object.keys(client.cache.global).includes(option)) { + client.cache.global[option as keyof typeof client.cache.global] = row[option]; + } + } + } + + static async #updateSharedCache(client: Client) { + const row: { [x: string]: any } = ((await Shared.findByPk(0)) ?? (await Shared.create())).toJSON(); + + for (const option in row) { + if (Object.keys(client.cache.shared).includes(option)) { + client.cache.shared[option as keyof typeof client.cache.shared] = row[option]; + if (option === 'superUsers') client.superUserID = row[option]; + } + } + } + + static async #updateGuildCache(client: Client) { + const rows = await Guild.findAll(); + for (const row of rows) { + client.cache.guilds.set(row.id, row.toJSON() as Guild); + } + } +} diff --git a/src/tasks/cache/updateHighlightCache.ts b/src/tasks/cache/updateHighlightCache.ts new file mode 100644 index 0000000..44ddd90 --- /dev/null +++ b/src/tasks/cache/updateHighlightCache.ts @@ -0,0 +1,15 @@ +import { Time } from '#constants'; +import { BushTask } from '../../lib/extensions/discord-akairo/BushTask.js'; + +export default class UpdateHighlightCacheTask extends BushTask { + public constructor() { + super('updateHighlightCache', { + delay: 5 * Time.Minute, + runOnStart: false + }); + } + + public async exec() { + return this.client.highlightManager.syncCache(); + } +} diff --git a/src/tasks/cache/updatePriceItemCache.ts b/src/tasks/cache/updatePriceItemCache.ts new file mode 100644 index 0000000..9809cbd --- /dev/null +++ b/src/tasks/cache/updatePriceItemCache.ts @@ -0,0 +1,27 @@ +import { BushTask, Time } from '#lib'; +import got from 'got'; +import PriceCommand, { AuctionAverages, Bazaar, LowestBIN } from '../../commands/utilities/price.js'; + +export default class UpdatePriceItemCache extends BushTask { + public constructor() { + super('updatePriceItemCache', { + delay: 10 * Time.Minute, + runOnStart: true + }); + } + + public async exec() { + const [bazaar, currentLowestBIN, averageLowestBIN, auctionAverages] = (await Promise.all( + PriceCommand.urls.map(({ url }) => got.get(url).json().catch(undefined)) + )) as [Bazaar?, LowestBIN?, LowestBIN?, AuctionAverages?]; + + const itemNames = new Set([ + ...Object.keys(averageLowestBIN ?? {}), + ...Object.keys(currentLowestBIN ?? {}), + ...Object.keys(auctionAverages ?? {}), + ...Object.keys(bazaar?.products ?? {}) + ]); + + PriceCommand.cachedItemList = [...itemNames]; + } +} diff --git a/src/tasks/cpuUsage.ts b/src/tasks/cpuUsage.ts deleted file mode 100644 index 61e7a54..0000000 --- a/src/tasks/cpuUsage.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { BushTask, Time } from '#lib'; -import os from 'node:os'; - -export default class CpuUsageTask extends BushTask { - public constructor() { - super('cpuUsage', { - delay: Time.Minute, - runOnStart: true - }); - } - - public async exec() { - const cpuStats = await cpu.usage(this.client.stats.cpu === undefined ? 100 * Time.Millisecond : Time.Minute); - this.client.stats.cpu = cpuStats; - } -} - -/* Everything inside the cpu namespace is adapted from the "node-os-utils" npm package which is licensed under a MIT license by Sunil Wang */ -namespace cpu { - export function usage(interval = Time.Second): Promise { - return new Promise((resolve) => { - const startMeasure = average(); - - setTimeout(() => { - const endMeasure = average(); - const idleDifference = endMeasure.avgIdle - startMeasure.avgIdle; - const totalDifference = endMeasure.avgTotal - startMeasure.avgTotal; - const cpuPercentage = (10000 - Math.round((10000 * idleDifference) / totalDifference)) / 100; - - return resolve(cpuPercentage); - }, interval); - }); - } - - export function average(): CpuAverageInfo { - let totalIdle = 0; - let totalTick = 0; - const cpus = os.cpus(); - - for (let i = 0, len = cpus.length; i < len; i++) { - const cpu = cpus[i]; - for (const type in cpu.times) { - totalTick += cpu.times[type as keyof typeof cpu.times]; - } - totalIdle += cpu.times.idle; - } - - return { - totalIdle: totalIdle, - totalTick: totalTick, - avgIdle: totalIdle / cpus.length, - avgTotal: totalTick / cpus.length - }; - } - - export interface CpuAverageInfo { - totalIdle: number; - totalTick: number; - avgIdle: number; - avgTotal: number; - } -} diff --git a/src/tasks/feature/handleReminders.ts b/src/tasks/feature/handleReminders.ts new file mode 100644 index 0000000..7863c9a --- /dev/null +++ b/src/tasks/feature/handleReminders.ts @@ -0,0 +1,39 @@ +import { BushTask, dateDelta, format, Reminder, Time } from '#lib'; +const { Op } = (await import('sequelize')).default; + +export default class HandlerRemindersTask extends BushTask { + public constructor() { + super('handlerReminders', { + delay: 30 * Time.Second, + runOnStart: true + }); + } + + public async exec() { + const expiredEntries = await Reminder.findAll({ + where: { + expires: { + [Op.lt]: new Date(Date.now() + 30 * Time.Second) // Find all rows with an expiry date before 30 seconds from now + }, + notified: false + } + }); + + void this.client.logger.verbose( + `handlerReminders`, + `Queried reminders, found <<${expiredEntries.length}>> expired reminders.` + ); + + for (const entry of expiredEntries) { + setTimeout(() => { + void this.client.users + .send( + entry.user, + `The reminder you set ${dateDelta(entry.created)} ago has expired: ${format.bold(entry.content)}\n${entry.messageUrl}` + ) + .catch(() => false); + void entry.update({ notified: true }); + }, entry.expires.getTime() - new Date().getTime()); + } + } +} diff --git a/src/tasks/feature/memberCount.ts b/src/tasks/feature/memberCount.ts new file mode 100644 index 0000000..ea422fa --- /dev/null +++ b/src/tasks/feature/memberCount.ts @@ -0,0 +1,28 @@ +import { BushTask, MemberCount, Time } from '#lib'; +import assert from 'assert'; + +export default class MemberCountTask extends BushTask { + public constructor() { + super('memberCount', { + delay: Time.Minute, + runOnStart: true + }); + } + + public override async exec() { + if (!this.client.config.isProduction) return; + + const res = await Promise.allSettled( + this.client.guilds.cache + .filter((g) => g.memberCount >= 100) + .map((g) => MemberCount.create({ guildId: g.id, memberCount: g.memberCount })) + ); + + res + .filter((r) => r.status === 'rejected') + .forEach((r) => { + assert(r.status === 'rejected'); + void this.client.console.error('memberCount', r.status); + }); + } +} diff --git a/src/tasks/feature/removeExpiredPunishements.ts b/src/tasks/feature/removeExpiredPunishements.ts new file mode 100644 index 0000000..0b20a27 --- /dev/null +++ b/src/tasks/feature/removeExpiredPunishements.ts @@ -0,0 +1,84 @@ +import { ActivePunishment, ActivePunishmentType, BushTask, Time } from '#lib'; +import assert from 'assert'; +const { Op } = (await import('sequelize')).default; + +export default class RemoveExpiredPunishmentsTask extends BushTask { + public constructor() { + super('removeExpiredPunishments', { + delay: 15 * Time.Second, + runOnStart: true + }); + } + + public async exec() { + const expiredEntries = await ActivePunishment.findAll({ + where: { + expires: { + [Op.lt]: new Date(Date.now() + 15 * Time.Second) // Find all rows with an expiry date before 15 seconds from now + } + } + }); + + void this.client.logger.verbose( + `removeExpiredPunishments`, + `Queried punishments, found <<${expiredEntries.length}>> expired punishments.` + ); + + for (const entry of expiredEntries) { + const guild = this.client.guilds.cache.get(entry.guild); + if (!guild) continue; + + // eslint-disable-next-line @typescript-eslint/no-misused-promises + setTimeout(async () => { + const member = guild.members.cache.get(entry.user); + const user = await this.client.utils.resolveNonCachedUser(entry.user); + assert(guild); + + switch (entry.type) { + case ActivePunishmentType.BAN: { + assert(user); + const result = await guild.bushUnban({ user: user, reason: 'Punishment expired' }); + if (['success', 'user not banned', 'cannot resolve user'].includes(result)) await entry.destroy(); + else throw new Error(result); + void this.client.logger.verbose(`removeExpiredPunishments`, `Unbanned ${entry.user}.`); + break; + } + case ActivePunishmentType.BLOCK: { + if (!member) { + await entry.destroy(); // channel overrides are removed when the member leaves the guild + return; + } + const result = await member.bushUnblock({ reason: 'Punishment expired', channel: entry.extraInfo }); + if (['success', 'user not blocked'].includes(result)) await entry.destroy(); + else throw new Error(result); + void this.client.logger.verbose(`removeExpiredPunishments`, `Unblocked ${entry.user}.`); + break; + } + case ActivePunishmentType.MUTE: { + if (!member) return; + const result = await member.bushUnmute({ reason: 'Punishment expired' }); + if (['success', 'failed to dm'].includes(result)) await entry.destroy(); + else throw new Error(result); + void this.client.logger.verbose(`removeExpiredPunishments`, `Unmuted ${entry.user}.`); + break; + } + case ActivePunishmentType.ROLE: { + if (!member) return; + const role = guild?.roles?.cache?.get(entry.extraInfo); + if (!role) throw new Error(`Cannot unmute ${member.user.tag} because I cannot find the mute role.`); + const result = await member.bushRemoveRole({ + reason: 'Punishment expired', + role: role, + addToModlog: true + }); + + if (['success', 'failed to dm'].includes(result)) await entry.destroy(); + else throw new Error(result); + void this.client.logger.verbose(`removeExpiredPunishments`, `Removed a punishment role from ${entry.user}.`); + break; + } + } + }, entry.expires!.getTime() - new Date().getTime()); + } + } +} diff --git a/src/tasks/feature/updateStats.ts b/src/tasks/feature/updateStats.ts new file mode 100644 index 0000000..0d0e661 --- /dev/null +++ b/src/tasks/feature/updateStats.ts @@ -0,0 +1,26 @@ +import { BushTask, Stat, Time } from '#lib'; +import { Client } from 'discord.js'; + +export default class UpdateStatsTask extends BushTask { + public constructor() { + super('updateStats', { + delay: 10 * Time.Minute, + runOnStart: true + }); + } + + public async exec() { + const row = + (await Stat.findByPk(this.client.config.environment)) ?? + (await Stat.create({ environment: this.client.config.environment })); + row.commandsUsed = this.client.stats.commandsUsed; + row.slashCommandsUsed = this.client.stats.slashCommandsUsed; + await row.save(); + } + + public static async init(client: Client): Promise<{ commandsUsed: bigint; slashCommandsUsed: bigint }> { + const temp = + (await Stat.findByPk(client.config.environment)) ?? (await Stat.create({ environment: client.config.environment })); + return { commandsUsed: temp.commandsUsed, slashCommandsUsed: temp.slashCommandsUsed }; + } +} diff --git a/src/tasks/handleReminders.ts b/src/tasks/handleReminders.ts deleted file mode 100644 index 7863c9a..0000000 --- a/src/tasks/handleReminders.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { BushTask, dateDelta, format, Reminder, Time } from '#lib'; -const { Op } = (await import('sequelize')).default; - -export default class HandlerRemindersTask extends BushTask { - public constructor() { - super('handlerReminders', { - delay: 30 * Time.Second, - runOnStart: true - }); - } - - public async exec() { - const expiredEntries = await Reminder.findAll({ - where: { - expires: { - [Op.lt]: new Date(Date.now() + 30 * Time.Second) // Find all rows with an expiry date before 30 seconds from now - }, - notified: false - } - }); - - void this.client.logger.verbose( - `handlerReminders`, - `Queried reminders, found <<${expiredEntries.length}>> expired reminders.` - ); - - for (const entry of expiredEntries) { - setTimeout(() => { - void this.client.users - .send( - entry.user, - `The reminder you set ${dateDelta(entry.created)} ago has expired: ${format.bold(entry.content)}\n${entry.messageUrl}` - ) - .catch(() => false); - void entry.update({ notified: true }); - }, entry.expires.getTime() - new Date().getTime()); - } - } -} diff --git a/src/tasks/memberCount.ts b/src/tasks/memberCount.ts deleted file mode 100644 index ea422fa..0000000 --- a/src/tasks/memberCount.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { BushTask, MemberCount, Time } from '#lib'; -import assert from 'assert'; - -export default class MemberCountTask extends BushTask { - public constructor() { - super('memberCount', { - delay: Time.Minute, - runOnStart: true - }); - } - - public override async exec() { - if (!this.client.config.isProduction) return; - - const res = await Promise.allSettled( - this.client.guilds.cache - .filter((g) => g.memberCount >= 100) - .map((g) => MemberCount.create({ guildId: g.id, memberCount: g.memberCount })) - ); - - res - .filter((r) => r.status === 'rejected') - .forEach((r) => { - assert(r.status === 'rejected'); - void this.client.console.error('memberCount', r.status); - }); - } -} diff --git a/src/tasks/removeExpiredPunishements.ts b/src/tasks/removeExpiredPunishements.ts deleted file mode 100644 index 0b20a27..0000000 --- a/src/tasks/removeExpiredPunishements.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { ActivePunishment, ActivePunishmentType, BushTask, Time } from '#lib'; -import assert from 'assert'; -const { Op } = (await import('sequelize')).default; - -export default class RemoveExpiredPunishmentsTask extends BushTask { - public constructor() { - super('removeExpiredPunishments', { - delay: 15 * Time.Second, - runOnStart: true - }); - } - - public async exec() { - const expiredEntries = await ActivePunishment.findAll({ - where: { - expires: { - [Op.lt]: new Date(Date.now() + 15 * Time.Second) // Find all rows with an expiry date before 15 seconds from now - } - } - }); - - void this.client.logger.verbose( - `removeExpiredPunishments`, - `Queried punishments, found <<${expiredEntries.length}>> expired punishments.` - ); - - for (const entry of expiredEntries) { - const guild = this.client.guilds.cache.get(entry.guild); - if (!guild) continue; - - // eslint-disable-next-line @typescript-eslint/no-misused-promises - setTimeout(async () => { - const member = guild.members.cache.get(entry.user); - const user = await this.client.utils.resolveNonCachedUser(entry.user); - assert(guild); - - switch (entry.type) { - case ActivePunishmentType.BAN: { - assert(user); - const result = await guild.bushUnban({ user: user, reason: 'Punishment expired' }); - if (['success', 'user not banned', 'cannot resolve user'].includes(result)) await entry.destroy(); - else throw new Error(result); - void this.client.logger.verbose(`removeExpiredPunishments`, `Unbanned ${entry.user}.`); - break; - } - case ActivePunishmentType.BLOCK: { - if (!member) { - await entry.destroy(); // channel overrides are removed when the member leaves the guild - return; - } - const result = await member.bushUnblock({ reason: 'Punishment expired', channel: entry.extraInfo }); - if (['success', 'user not blocked'].includes(result)) await entry.destroy(); - else throw new Error(result); - void this.client.logger.verbose(`removeExpiredPunishments`, `Unblocked ${entry.user}.`); - break; - } - case ActivePunishmentType.MUTE: { - if (!member) return; - const result = await member.bushUnmute({ reason: 'Punishment expired' }); - if (['success', 'failed to dm'].includes(result)) await entry.destroy(); - else throw new Error(result); - void this.client.logger.verbose(`removeExpiredPunishments`, `Unmuted ${entry.user}.`); - break; - } - case ActivePunishmentType.ROLE: { - if (!member) return; - const role = guild?.roles?.cache?.get(entry.extraInfo); - if (!role) throw new Error(`Cannot unmute ${member.user.tag} because I cannot find the mute role.`); - const result = await member.bushRemoveRole({ - reason: 'Punishment expired', - role: role, - addToModlog: true - }); - - if (['success', 'failed to dm'].includes(result)) await entry.destroy(); - else throw new Error(result); - void this.client.logger.verbose(`removeExpiredPunishments`, `Removed a punishment role from ${entry.user}.`); - break; - } - } - }, entry.expires!.getTime() - new Date().getTime()); - } - } -} diff --git a/src/tasks/updateCache.ts b/src/tasks/updateCache.ts deleted file mode 100644 index 27df1ca..0000000 --- a/src/tasks/updateCache.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Time } from '#constants'; -import { Global, Guild, Shared, type BushClient } from '#lib'; -import type { Client } from 'discord.js'; -import config from '../../config/options.js'; -import { BushTask } from '../lib/extensions/discord-akairo/BushTask.js'; - -export default class UpdateCacheTask extends BushTask { - public constructor() { - super('updateCache', { - delay: 5 * Time.Minute, - runOnStart: false // done in preinit task - }); - } - - public async exec() { - await Promise.all([ - UpdateCacheTask.#updateGlobalCache(this.client), - UpdateCacheTask.#updateSharedCache(this.client), - UpdateCacheTask.#updateGuildCache(this.client) - ]); - void this.client.logger.verbose(`UpdateCache`, `Updated cache.`); - } - - public static async init(client: BushClient) { - await Promise.all([ - UpdateCacheTask.#updateGlobalCache(client), - UpdateCacheTask.#updateSharedCache(client), - UpdateCacheTask.#updateGuildCache(client) - ]); - } - - static async #updateGlobalCache(client: Client) { - const environment = config.environment; - const row: { [x: string]: any } = ((await Global.findByPk(environment)) ?? (await Global.create({ environment }))).toJSON(); - - for (const option in row) { - if (Object.keys(client.cache.global).includes(option)) { - client.cache.global[option as keyof typeof client.cache.global] = row[option]; - } - } - } - - static async #updateSharedCache(client: Client) { - const row: { [x: string]: any } = ((await Shared.findByPk(0)) ?? (await Shared.create())).toJSON(); - - for (const option in row) { - if (Object.keys(client.cache.shared).includes(option)) { - client.cache.shared[option as keyof typeof client.cache.shared] = row[option]; - if (option === 'superUsers') client.superUserID = row[option]; - } - } - } - - static async #updateGuildCache(client: Client) { - const rows = await Guild.findAll(); - for (const row of rows) { - client.cache.guilds.set(row.id, row.toJSON() as Guild); - } - } -} diff --git a/src/tasks/updateHighlightCache.ts b/src/tasks/updateHighlightCache.ts deleted file mode 100644 index 4677ea7..0000000 --- a/src/tasks/updateHighlightCache.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Time } from '#constants'; -import { BushTask } from '../lib/extensions/discord-akairo/BushTask.js'; - -export default class UpdateHighlightCacheTask extends BushTask { - public constructor() { - super('updateHighlightCache', { - delay: 5 * Time.Minute, - runOnStart: false - }); - } - - public async exec() { - return this.client.highlightManager.syncCache(); - } -} diff --git a/src/tasks/updatePriceItemCache.ts b/src/tasks/updatePriceItemCache.ts deleted file mode 100644 index 5f68a8c..0000000 --- a/src/tasks/updatePriceItemCache.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { BushTask, Time } from '#lib'; -import got from 'got'; -import PriceCommand, { AuctionAverages, Bazaar, LowestBIN } from '../commands/utilities/price.js'; - -export default class UpdatePriceItemCache extends BushTask { - public constructor() { - super('updatePriceItemCache', { - delay: 10 * Time.Minute, - runOnStart: true - }); - } - - public async exec() { - const [bazaar, currentLowestBIN, averageLowestBIN, auctionAverages] = (await Promise.all( - PriceCommand.urls.map(({ url }) => got.get(url).json().catch(undefined)) - )) as [Bazaar?, LowestBIN?, LowestBIN?, AuctionAverages?]; - - const itemNames = new Set([ - ...Object.keys(averageLowestBIN ?? {}), - ...Object.keys(currentLowestBIN ?? {}), - ...Object.keys(auctionAverages ?? {}), - ...Object.keys(bazaar?.products ?? {}) - ]); - - PriceCommand.cachedItemList = [...itemNames]; - } -} diff --git a/src/tasks/updateStats.ts b/src/tasks/updateStats.ts deleted file mode 100644 index 0d0e661..0000000 --- a/src/tasks/updateStats.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { BushTask, Stat, Time } from '#lib'; -import { Client } from 'discord.js'; - -export default class UpdateStatsTask extends BushTask { - public constructor() { - super('updateStats', { - delay: 10 * Time.Minute, - runOnStart: true - }); - } - - public async exec() { - const row = - (await Stat.findByPk(this.client.config.environment)) ?? - (await Stat.create({ environment: this.client.config.environment })); - row.commandsUsed = this.client.stats.commandsUsed; - row.slashCommandsUsed = this.client.stats.slashCommandsUsed; - await row.save(); - } - - public static async init(client: Client): Promise<{ commandsUsed: bigint; slashCommandsUsed: bigint }> { - const temp = - (await Stat.findByPk(client.config.environment)) ?? (await Stat.create({ environment: client.config.environment })); - return { commandsUsed: temp.commandsUsed, slashCommandsUsed: temp.slashCommandsUsed }; - } -} -- cgit