From 1e3182e79e22522ebba3c5572fe50dcaf5d11327 Mon Sep 17 00:00:00 2001 From: GC <30398469+gc@users.noreply.github.com> Date: Thu, 28 Nov 2024 11:25:41 +1100 Subject: [PATCH] Remove config file (#6242) --- SETUP.md | 3 - .../toolkit/src/lib/MahojiClient/Mahoji.ts | 3 - prisma/schema.prisma | 2 + src/config.ts | 9 -- src/index.ts | 8 +- src/lib/addXP.ts | 9 +- src/lib/constants.ts | 95 ++++++++----------- src/lib/events.ts | 5 +- src/lib/globals.ts | 7 +- src/lib/grandExchange.ts | 7 +- src/lib/perkTiers.ts | 5 +- src/lib/rolesTask.ts | 5 +- src/lib/tickers.ts | 13 ++- src/lib/types/index.ts | 1 - src/lib/util.ts | 5 +- src/lib/util/cachedUserIDs.ts | 4 +- src/lib/util/logError.ts | 3 +- src/lib/util/webhook.ts | 7 +- src/mahoji/commands/admin.ts | 30 +++--- src/mahoji/commands/allCommands.ts | 4 +- src/mahoji/commands/bingo.ts | 5 +- src/mahoji/commands/config.ts | 5 +- src/mahoji/commands/gearpresets.ts | 5 +- src/mahoji/commands/rp.ts | 30 +++--- src/mahoji/commands/testpotato.ts | 7 +- .../lib/abstracted_commands/dailyCommand.ts | 5 +- src/mahoji/lib/events.ts | 4 +- src/mahoji/lib/inhibitors.ts | 12 +-- 28 files changed, 126 insertions(+), 172 deletions(-) delete mode 100644 src/config.ts diff --git a/SETUP.md b/SETUP.md index 56f02f1d66d..dd0065738a8 100644 --- a/SETUP.md +++ b/SETUP.md @@ -34,9 +34,6 @@ This assumes you are using VSCode as your IDE. If you have errors or issues, you - Using **pgAdmin 4** select `Servers > PostgreSQL > Databases > Create > Database...`. - Enter the database name into `Database` and hit `Save`. 4. Change `DATABASE_URL` and `ROBOCHIMP_DATABASE_URL` in your .env file with the format `postgresql://USER:PASSWORD@HOST:PORT/DATABASE_NAME`. -5. Edit `config.ts`: - - Copy your Discord ID into both `OWNER_IDS` and `ADMIN_IDS`. - - Enter the Server ID where you want to Administer your bot from in `SupportServer`. ### Finalizing Setup diff --git a/packages/toolkit/src/lib/MahojiClient/Mahoji.ts b/packages/toolkit/src/lib/MahojiClient/Mahoji.ts index a9929461971..bf4c11fe4f2 100644 --- a/packages/toolkit/src/lib/MahojiClient/Mahoji.ts +++ b/packages/toolkit/src/lib/MahojiClient/Mahoji.ts @@ -202,7 +202,6 @@ export type ICommand = Readonly<{ }>; interface MahojiOptions { - developmentServerID: string; applicationID: string; handlers?: Handlers; djsClient: Client; @@ -226,13 +225,11 @@ export interface Handlers { export class MahojiClient { commands: Map = new Map(); - developmentServerID: string; applicationID: string; handlers: Handlers; djsClient: Client; constructor(options: MahojiOptions) { - this.developmentServerID = options.developmentServerID; this.applicationID = options.applicationID; this.handlers = options.handlers ?? {}; this.djsClient = options.djsClient; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index cf9252ba7c4..632696f7711 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -138,6 +138,8 @@ model ClientStorage { grand_exchange_total_tax BigInt @default(0) grand_exchange_tax_bank BigInt @default(0) + maxing_message String @default("Congratulations on maxing!") + @@map("clientStorage") } diff --git a/src/config.ts b/src/config.ts deleted file mode 100644 index 7c3d2c498fc..00000000000 --- a/src/config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { IDiscordSettings } from './lib/types'; - -export const production = false; -export const SENTRY_DSN: string | null = null; -export const DISCORD_SETTINGS: Partial = {}; -export const OWNER_IDS = ['157797566833098752']; -export const ADMIN_IDS = ['425134194436341760']; -export const MAXING_MESSAGE = 'Congratulations on maxing!'; -export const SupportServer = '940758552425955348'; diff --git a/src/index.ts b/src/index.ts index 6a3ba0b34b7..ad6ecf92b62 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,6 @@ import type { TextChannel } from 'discord.js'; import { GatewayIntentBits, Options, Partials } from 'discord.js'; import { isObject } from 'e'; -import { SENTRY_DSN, SupportServer } from './config'; import { BLACKLISTED_GUILDS, BLACKLISTED_USERS } from './lib/blacklists'; import { Channel, Events, gitHash, globalConfig } from './lib/constants'; import { economyLog } from './lib/economyLogs'; @@ -29,9 +28,9 @@ import { postCommand } from './mahoji/lib/postCommand'; import { preCommand } from './mahoji/lib/preCommand'; import { convertMahojiCommandToAbstractCommand } from './mahoji/lib/util'; -if (SENTRY_DSN) { +if (globalConfig.sentryDSN) { init({ - dsn: SENTRY_DSN, + dsn: globalConfig.sentryDSN, enableTracing: false, defaultIntegrations: false, integrations: [], @@ -67,7 +66,7 @@ const client = new OldSchoolBotClient({ }, GuildEmojiManager: { maxSize: 1, - keepOverLimit: i => [globalConfig.testingServerID, SupportServer].includes(i.guild.id) + keepOverLimit: i => globalConfig.supportServerID === i.guild.id }, GuildStickerManager: { maxSize: 0 }, PresenceManager: { maxSize: 0 }, @@ -100,7 +99,6 @@ const client = new OldSchoolBotClient({ }); export const mahojiClient = new MahojiClient({ - developmentServerID: globalConfig.testingServerID, applicationID: globalConfig.clientID, commands: allCommands, handlers: { diff --git a/src/lib/addXP.ts b/src/lib/addXP.ts index 1f5bbacad7f..bba619f5242 100644 --- a/src/lib/addXP.ts +++ b/src/lib/addXP.ts @@ -4,12 +4,12 @@ import { bold } from 'discord.js'; import { Time, noOp } from 'e'; import { convertXPtoLVL, toKMB } from './util'; -import { MAXING_MESSAGE, SupportServer } from '../config'; -import { Events, LEVEL_99_XP, MAX_TOTAL_LEVEL, MAX_XP } from './constants'; +import { Events, LEVEL_99_XP, MAX_TOTAL_LEVEL, MAX_XP, globalConfig } from './constants'; import { skillEmoji } from './data/emojis'; import type { AddXpParams } from './minions/types'; import { sql } from './postgres'; import Skills from './skilling/skills'; +import { mahojiClientSettingsFetch } from './util/clientSettings'; import { insertUserEvent } from './util/userEvents'; import { sendToChannelID } from './util/webhook'; @@ -43,9 +43,10 @@ async function onMax(user: MUser) { } 🎉`; globalClient.emit(Events.ServerNotification, str); - sendToChannelID(SupportServer, { content: str }).catch(noOp); + sendToChannelID(globalConfig.supportServerID, { content: str }).catch(noOp); const kUser = await globalClient.fetchUser(user.id); - kUser.send(MAXING_MESSAGE).catch(noOp); + const clientSettings = await mahojiClientSettingsFetch({ maxing_message: true }); + kUser.send(clientSettings.maxing_message).catch(noOp); } export async function addXP(user: MUser, params: AddXpParams): Promise { diff --git a/src/lib/constants.ts b/src/lib/constants.ts index c8fa97820d8..fd74dd6400b 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -6,7 +6,6 @@ import * as dotenv from 'dotenv'; import { getItemOrThrow, resolveItems } from 'oldschooljs'; import { z } from 'zod'; -import { DISCORD_SETTINGS, production } from '../config'; import type { AbstractCommand } from '../mahoji/lib/inhibitors'; import { SkillsEnum } from './skilling/types'; import type { ActivityTaskData } from './types/minions'; @@ -14,56 +13,43 @@ import type { CanvasImage } from './util/canvasUtil'; export { PerkTier }; -const TestingMainChannelID = DISCORD_SETTINGS.Channels?.TestingMain ?? '940760643525570591'; - export const BOT_TYPE: 'BSO' | 'OSB' = 'OSB' as 'BSO' | 'OSB'; export const BOT_TYPE_LOWERCASE: 'bso' | 'osb' = BOT_TYPE.toLowerCase() as 'bso' | 'osb'; +const isProduction = process.env.NODE_ENV === 'production'; +const TEST_SERVER_LOG_CHANNEL = '1042760447830536212'; +const GENERAL_CHANNEL_ID = + BOT_TYPE === 'OSB' + ? isProduction + ? '346304390858145792' + : '1154056119019393035' + : isProduction + ? '792691343284764693' + : '1154056119019393035'; +const OLDSCHOOLGG_TESTING_SERVER_ID = '940758552425955348'; export const Channel = { - General: DISCORD_SETTINGS.Channels?.General ?? '342983479501389826', - Notifications: - DISCORD_SETTINGS.Channels?.Notifications ?? (production ? '469523207691436042' : '1042760447830536212'), - GrandExchange: DISCORD_SETTINGS.Channels?.GrandExchange ?? '682996313209831435', - Developers: DISCORD_SETTINGS.Channels?.Developers ?? '648196527294251020', - BlacklistLogs: DISCORD_SETTINGS.Channels?.BlacklistLogs ?? '782459317218967602', - EconomyLogs: DISCORD_SETTINGS.Channels?.EconomyLogs ?? '802029843712573510', - PatronLogs: '806744016309714966', + General: isProduction ? '342983479501389826' : GENERAL_CHANNEL_ID, + Notifications: isProduction ? '469523207691436042' : GENERAL_CHANNEL_ID, + GrandExchange: isProduction ? '682996313209831435' : GENERAL_CHANNEL_ID, + EconomyLogs: isProduction ? '802029843712573510' : TEST_SERVER_LOG_CHANNEL, HelpAndSupport: '668073484731154462', - TestingMain: TestingMainChannelID, - BarbarianAssault: DISCORD_SETTINGS.Channels?.BarbarianAssault ?? '789717054902763520', - ChambersOfXeric: DISCORD_SETTINGS.Channels?.ChambersOfXeric ?? '835876917252587581', - BotLogs: production ? '1051725977320964197' : TestingMainChannelID, - GeneralChannel: - BOT_TYPE === 'OSB' - ? production - ? '346304390858145792' - : '1154056119019393035' - : production - ? '792691343284764693' - : '1154056119019393035' + BotLogs: isProduction ? '1051725977320964197' : GENERAL_CHANNEL_ID, + GeneralChannel: GENERAL_CHANNEL_ID }; export const Roles = { - Booster: DISCORD_SETTINGS.Roles?.Booster ?? '665908237152813057', - Contributor: DISCORD_SETTINGS.Roles?.Contributor ?? '456181501437018112', - Moderator: DISCORD_SETTINGS.Roles?.Moderator ?? '622806157563527178', - PatronTier1: DISCORD_SETTINGS.Roles?.PatronTier1 ?? '678970545789730826', - PatronTier2: DISCORD_SETTINGS.Roles?.PatronTier2 ?? '678967943979204608', - PatronTier3: DISCORD_SETTINGS.Roles?.PatronTier3 ?? '687408140832342043', - Patron: DISCORD_SETTINGS.Roles?.Patron ?? '679620175838183424', - Testers: DISCORD_SETTINGS.Roles?.Tester ?? '682052620809928718', - MassHoster: DISCORD_SETTINGS.Roles?.MassHoster ?? '734055552933429280', - Mass: DISCORD_SETTINGS.Roles?.Mass ?? '711215501543473182', - BarbarianAssaultMass: DISCORD_SETTINGS.Roles?.BarbarianAssaultMass ?? '789724904885846016', - ChambersOfXericMass: DISCORD_SETTINGS.Roles?.ChambersOfXericMass ?? '836539487815204865', + Booster: '665908237152813057', + Contributor: '456181501437018112', + Moderator: '622806157563527178', + Patron: '679620175838183424', // Top Roles - TopSkiller: DISCORD_SETTINGS.Roles?.TopSkiller ?? '795266465329709076', - TopCollector: DISCORD_SETTINGS.Roles?.TopCollector ?? '795271210141351947', - TopSacrificer: DISCORD_SETTINGS.Roles?.TopSacrificer ?? '795933981715464192', - TopMinigamer: DISCORD_SETTINGS.Roles?.TopMinigamer ?? '832798997033779220', - TopClueHunter: DISCORD_SETTINGS.Roles?.TopClueHunter ?? '839135887467610123', - TopSlayer: DISCORD_SETTINGS.Roles?.TopSlayer ?? '856080958247010324', - TopFarmer: DISCORD_SETTINGS.Roles?.TopFarmer ?? '894194027363205150', + TopSkiller: '795266465329709076', + TopCollector: '795271210141351947', + TopSacrificer: '795933981715464192', + TopMinigamer: '832798997033779220', + TopClueHunter: '839135887467610123', + TopSlayer: '856080958247010324', + TopFarmer: '894194027363205150', TopGlobalCL: '1072426869028294747' }; @@ -495,14 +481,18 @@ export const ParsedCustomEmojiWithGroups = /(?a?):(?[^:]+):(?({ max: 1000 }); function rareRoles(msg: Message) { if (!globalConfig.isProduction) return; - if (!msg.guild || msg.guild.id !== SupportServer) { + if (!msg.guild || msg.guild.id !== globalConfig.supportServerID) { return; } @@ -58,7 +57,7 @@ function rareRoles(msg: Message) { for (const [roleID, chance, name] of rareRolesSrc) { if (roll(chance / 10)) { if (msg.member?.roles.cache.has(roleID)) continue; - if (!production && msg.channel.isSendable()) { + if (!globalConfig.isProduction && msg.channel.isSendable()) { return msg.channel.send(`${msg.author}, you would've gotten the **${name}** role.`); } msg.member?.roles.add(roleID); diff --git a/src/lib/globals.ts b/src/lib/globals.ts index 0115afd8b6c..52a0081322f 100644 --- a/src/lib/globals.ts +++ b/src/lib/globals.ts @@ -3,7 +3,6 @@ import { TSRedis } from '@oldschoolgg/toolkit/structures'; import { PrismaClient } from '@prisma/client'; import { PrismaClient as RobochimpPrismaClient } from '@prisma/robochimp'; -import { production } from '../config'; import { globalConfig } from './constants'; import { handleDeletedPatron, handleEditPatron } from './patreonUtils'; @@ -14,7 +13,7 @@ declare global { } function makePrismaClient(): PrismaClient { - if (!production && !process.env.TEST) console.log('Making prisma client...'); + if (!globalConfig.isProduction && !process.env.TEST) console.log('Making prisma client...'); if (!isMainThread && !process.env.TEST) { throw new Error('Prisma client should only be created on the main thread.'); } @@ -26,7 +25,7 @@ function makePrismaClient(): PrismaClient { global.prisma = global.prisma || makePrismaClient(); function makeRobochimpPrismaClient(): RobochimpPrismaClient { - if (!production && !process.env.TEST) console.log('Making robochimp client...'); + if (!globalConfig.isProduction && !process.env.TEST) console.log('Making robochimp client...'); if (!isMainThread && !process.env.TEST) { throw new Error('Robochimp client should only be created on the main thread.'); } @@ -38,7 +37,7 @@ function makeRobochimpPrismaClient(): RobochimpPrismaClient { global.roboChimpClient = global.roboChimpClient || makeRobochimpPrismaClient(); function makeRedisClient(): TSRedis { - if (!production && !process.env.TEST) console.log('Making Redis client...'); + if (!globalConfig.isProduction && !process.env.TEST) console.log('Making Redis client...'); if (!isMainThread && !process.env.TEST) { throw new Error('Redis client should only be created on the main thread.'); } diff --git a/src/lib/grandExchange.ts b/src/lib/grandExchange.ts index 95f6ad4cb66..855b9fe72f1 100644 --- a/src/lib/grandExchange.ts +++ b/src/lib/grandExchange.ts @@ -7,7 +7,6 @@ import { LRUCache } from 'lru-cache'; import { Bank, type Item, type ItemBank } from 'oldschooljs'; import PQueue from 'p-queue'; -import { ADMIN_IDS, OWNER_IDS, production } from '../config'; import { BLACKLISTED_USERS } from './blacklists'; import { BitField, ONE_TRILLION, PerkTier, globalConfig } from './constants'; import { marketPricemap } from './marketPrices'; @@ -233,12 +232,12 @@ class GrandExchangeSingleton { async lockGE(reason: string) { if (this.locked) return; - const idsToNotify = [...ADMIN_IDS, ...OWNER_IDS]; + const idsToNotify = globalConfig.adminUserIDs; await sendToChannelID(globalConfig.geAdminChannelID, { content: `The Grand Exchange has encountered an error and has been locked. Reason: ${reason}. ${idsToNotify .map(i => userMention(i)) .join(', ')}`, - allowedMentions: production ? { users: idsToNotify } : undefined + allowedMentions: globalConfig.isProduction ? { users: idsToNotify } : undefined }).catch(noOp); await mahojiClientSettingsUpdate({ grand_exchange_is_locked: true @@ -976,7 +975,7 @@ Difference: ${shouldHave.difference(currentBank)}`); } async totalReset() { - if (production) throw new Error("You can't reset the GE in production."); + if (globalConfig.isProduction) throw new Error("You can't reset the GE in production."); await mahojiClientSettingsUpdate({ grand_exchange_is_locked: false, grand_exchange_tax_bank: 0, diff --git a/src/lib/perkTiers.ts b/src/lib/perkTiers.ts index 31139af4707..a861a28ce8e 100644 --- a/src/lib/perkTiers.ts +++ b/src/lib/perkTiers.ts @@ -1,6 +1,5 @@ -import { SupportServer } from '../config'; import { perkTierCache } from './cache'; -import { BitField, PerkTier, Roles } from './constants'; +import { BitField, PerkTier, Roles, globalConfig } from './constants'; import { roboChimpCache } from './perkTier'; export const allPerkBitfields: BitField[] = [ @@ -27,7 +26,7 @@ function getUsersPerkTierRaw(user: { bitfield: BitField[]; id: string }): PerkTi ) { elligibleTiers.push(PerkTier.Two); } else { - const guild = globalClient.guilds.cache.get(SupportServer); + const guild = globalClient.guilds.cache.get(globalConfig.supportServerID); const member = guild?.members.cache.get(user.id); if (member && [Roles.Booster].some(roleID => member.roles.cache.has(roleID))) { elligibleTiers.push(PerkTier.One); diff --git a/src/lib/rolesTask.ts b/src/lib/rolesTask.ts index 9d6268bc7e8..96887b685c6 100644 --- a/src/lib/rolesTask.ts +++ b/src/lib/rolesTask.ts @@ -6,8 +6,7 @@ import PQueue from 'p-queue'; import { partition } from 'remeda'; import z from 'zod'; -import { SupportServer } from '../config'; -import { BadgesEnum, Roles } from '../lib/constants'; +import { BadgesEnum, Roles, globalConfig } from '../lib/constants'; import { getCollectionItems } from '../lib/data/Collections'; import { Minigames } from '../lib/settings/minigames'; import { ClueTiers } from './clues/clueTiers'; @@ -399,7 +398,7 @@ export async function runRolesTask(dryRun: boolean): Promise { if (!dryRun) { const roleNames = new Map(); - const supportServerGuild = globalClient.guilds.cache.get(SupportServer)!; + const supportServerGuild = globalClient.guilds.cache.get(globalConfig.supportServerID)!; if (!supportServerGuild) throw new Error('No support guild'); // Remove all top badges from all users (and add back later) diff --git a/src/lib/tickers.ts b/src/lib/tickers.ts index a2f3935e682..a2c8ba7951e 100644 --- a/src/lib/tickers.ts +++ b/src/lib/tickers.ts @@ -3,11 +3,10 @@ import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from 'disc import { Time, noOp, randInt, removeFromArr, shuffleArr } from 'e'; import { TimerManager } from '@sapphire/timer-manager'; -import { production } from '../config'; import { userStatsUpdate } from '../mahoji/mahojiSettings'; import { mahojiUserSettingsUpdate } from './MUser'; import { processPendingActivities } from './Task'; -import { BitField, Channel, PeakTier } from './constants'; +import { BitField, Channel, PeakTier, globalConfig } from './constants'; import { GrandExchange } from './grandExchange'; import { collectMetrics } from './metrics'; import { runCommand } from './settings/settings'; @@ -115,7 +114,7 @@ export const tickers: { name: 'minion_activities', startupWait: Time.Second * 10, timer: null, - interval: production ? Time.Second * 5 : 500, + interval: globalConfig.isProduction ? Time.Second * 5 : 500, cb: async () => { await processPendingActivities(); } @@ -143,7 +142,7 @@ WHERE bitfield && '{2,3,4,5,6,7,8,12,21,24}'::int[] AND user_stats."last_daily_t const str = 'Your daily is ready!'; for (const row of result.values()) { - if (!production) continue; + if (!globalConfig.isProduction) continue; if (Number(row.last_daily_timestamp) === -1) continue; await userStatsUpdate( @@ -207,7 +206,7 @@ WHERE bitfield && '{2,3,4,5,6,7,8,12,21,24}'::int[] AND user_stats."last_daily_t interval: Time.Minute * 3.5, timer: null, cb: async () => { - if (!production) return; + if (!globalConfig.isProduction) return; const basePlantTime = 1_626_556_507_451; const now = Date.now(); const users = await prisma.user.findMany({ @@ -326,7 +325,7 @@ WHERE bitfield && '{2,3,4,5,6,7,8,12,21,24}'::int[] AND user_stats."last_daily_t startupWait: Time.Second * 22, interval: Time.Minute * 20, cb: async () => { - if (!production) return; + if (!globalConfig.isProduction) return; const guild = getSupportGuild(); const channel = guild?.channels.cache.get(Channel.HelpAndSupport) as TextChannel | undefined; if (!channel) return; @@ -351,7 +350,7 @@ WHERE bitfield && '{2,3,4,5,6,7,8,12,21,24}'::int[] AND user_stats."last_daily_t timer: null, interval: Time.Minute * 20, cb: async () => { - if (!production) return; + if (!globalConfig.isProduction) return; const guild = getSupportGuild(); const channel = guild?.channels.cache.get(Channel.GrandExchange) as TextChannel | undefined; if (!channel) return; diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts index 8066bf6face..929f2de335d 100644 --- a/src/lib/types/index.ts +++ b/src/lib/types/index.ts @@ -36,5 +36,4 @@ export interface IDiscordSettings { Roles: Record; Channels: Record; Emojis: Record; - SupportServer: string; } diff --git a/src/lib/util.ts b/src/lib/util.ts index fb7370da81e..a827dd9fc2f 100644 --- a/src/lib/util.ts +++ b/src/lib/util.ts @@ -26,7 +26,6 @@ import { bool, integer, nativeMath, nodeCrypto, real } from 'random-js'; import { Stopwatch } from '@oldschoolgg/toolkit/structures'; import type { Prisma } from '@prisma/client'; import { LRUCache } from 'lru-cache'; -import { ADMIN_IDS, OWNER_IDS, SupportServer } from '../config'; import type { MUserClass } from './MUser'; import { PaginatedMessage } from './PaginatedMessage'; import { BitField, MAX_XP, globalConfig, projectiles } from './constants'; @@ -121,7 +120,7 @@ export function isNexActivity(data: any): data is NexTaskOptions { export function getSupportGuild(): Guild | null { if (!globalClient || Object.keys(globalClient).length === 0) return null; - const guild = globalClient.guilds.cache.get(SupportServer); + const guild = globalClient.guilds.cache.get(globalConfig.supportServerID); if (!guild) return null; return guild; } @@ -363,7 +362,7 @@ export function logWrapFn Promise>( } export function isModOrAdmin(user: MUser) { - return [...OWNER_IDS, ...ADMIN_IDS].includes(user.id) || user.bitfield.includes(BitField.isModerator); + return globalConfig.adminUserIDs.includes(user.id) || user.bitfield.includes(BitField.isModerator); } export { assert } from './util/logError'; diff --git a/src/lib/util/cachedUserIDs.ts b/src/lib/util/cachedUserIDs.ts index 4158efe1d50..30802160f0c 100644 --- a/src/lib/util/cachedUserIDs.ts +++ b/src/lib/util/cachedUserIDs.ts @@ -2,13 +2,11 @@ import { Prisma } from '@prisma/client'; import { ChannelType } from 'discord.js'; import { objectEntries } from 'e'; -import { OWNER_IDS, SupportServer } from '../../config'; import { globalConfig } from '../constants'; import { runTimedLoggedFn } from '../util'; export const CACHED_ACTIVE_USER_IDS = new Set(); CACHED_ACTIVE_USER_IDS.add(globalConfig.clientID); -for (const id of OWNER_IDS) CACHED_ACTIVE_USER_IDS.add(id); export const syncActiveUserIDs = async () => { const users = await prisma.$queryRawUnsafe< @@ -127,7 +125,7 @@ export function cacheCleanup() { await runTimedLoggedFn('Guild Emoji/Roles/Member cache clear', async () => { for (const guild of globalClient.guilds.cache.values()) { - if (guild.id !== SupportServer) { + if (guild.id !== globalConfig.supportServerID) { for (const member of guild.members.cache.values()) { if (member.user.id === globalConfig.clientID) continue; guild.members.cache.delete(member.user.id); diff --git a/src/lib/util/logError.ts b/src/lib/util/logError.ts index ad604152473..b0111809fef 100644 --- a/src/lib/util/logError.ts +++ b/src/lib/util/logError.ts @@ -3,12 +3,11 @@ import { captureException } from '@sentry/node'; import type { Interaction } from 'discord.js'; import { isObject } from 'e'; -import { production } from '../../config'; import { globalConfig } from '../constants'; export function assert(condition: boolean, desc?: string, context?: Record) { if (!condition) { - if (production) { + if (globalConfig.isProduction) { logError(new Error(desc ?? 'Failed assertion'), context); } else { throw new Error(desc ?? 'Failed assertion'); diff --git a/src/lib/util/webhook.ts b/src/lib/util/webhook.ts index 5686e480994..162a9610845 100644 --- a/src/lib/util/webhook.ts +++ b/src/lib/util/webhook.ts @@ -2,7 +2,7 @@ import { channelIsSendable, splitMessage } from '@oldschoolgg/toolkit/util'; import type { AttachmentBuilder, BaseMessageOptions, EmbedBuilder, Message } from 'discord.js'; import { PartialGroupDMChannel, PermissionsBitField, WebhookClient } from 'discord.js'; -import { production } from '../../config'; +import { globalConfig } from '../constants'; import { logError } from './logError'; async function resolveChannel(channelID: string): Promise { @@ -15,7 +15,10 @@ async function resolveChannel(channelID: string): Promise !i.guildID); const guildCommands = totalCommands.filter(i => Boolean(i.guildID)); @@ -924,7 +925,7 @@ Guilds Blacklisted: ${BLACKLISTED_GUILDS.size}`; } // If not in production, remove all global commands. - if (!production) { + if (!globalConfig.isProduction) { await bulkUpdateCommands({ client: globalClient.mahojiClient, commands: [], @@ -969,15 +970,6 @@ ${guildCommands.length} Guild commands`; return `Gave ${items} to ${user.mention}`; } - /** - * - * Owner Only Commands - * - */ - if (!isOwner) { - return randArrItem(gifs); - } - if (options.item_stats) { const item = getItem(options.item_stats.item); if (!item) return 'Invalid item.'; diff --git a/src/mahoji/commands/allCommands.ts b/src/mahoji/commands/allCommands.ts index 1aff6cf011a..75a0dfe68fa 100644 --- a/src/mahoji/commands/allCommands.ts +++ b/src/mahoji/commands/allCommands.ts @@ -1,4 +1,4 @@ -import { production } from '../../config'; +import { globalConfig } from '../../lib/constants'; import type { OSBMahojiCommand } from '../lib/util'; import { activitiesCommand } from './activities'; import { adminCommand } from './admin'; @@ -169,7 +169,7 @@ export const allCommands: OSBMahojiCommand[] = [ xpCommand ]; -if (!production && testPotatoCommand) { +if (!globalConfig.isProduction && testPotatoCommand) { allCommands.push(testPotatoCommand); } diff --git a/src/mahoji/commands/bingo.ts b/src/mahoji/commands/bingo.ts index 471139154bb..6e3b70fdda9 100644 --- a/src/mahoji/commands/bingo.ts +++ b/src/mahoji/commands/bingo.ts @@ -18,10 +18,9 @@ import { Time, chunk, noOp, notEmpty, uniqueArr } from 'e'; import { Bank } from 'oldschooljs'; import type { ItemBank } from 'oldschooljs/dist/meta/types'; -import { production } from '../../config'; import { BLACKLISTED_USERS } from '../../lib/blacklists'; import { clImageGenerator } from '../../lib/collectionLogTask'; -import { BOT_TYPE, Emoji } from '../../lib/constants'; +import { BOT_TYPE, Emoji, globalConfig } from '../../lib/constants'; import { channelIsSendable, getUsername, getUsernameSync, isValidNickname, toKMB } from '../../lib/util'; import { getItem } from '../../lib/util/getOSItem'; @@ -686,7 +685,7 @@ export const bingoCommand: OSBMahojiCommand = { return 'Invalid title.'; } const member = await channel.guild.members.fetch(userID).catch(noOp); - if (production && (!member || !member.permissions.has('Administrator'))) { + if (globalConfig.isProduction && (!member || !member.permissions.has('Administrator'))) { return 'You can only use a notifications channel if you are an Administrator of that server.'; } if (channel.guild.id !== interaction.guildId) { diff --git a/src/mahoji/commands/config.ts b/src/mahoji/commands/config.ts index 451078e9bf9..0210796b51e 100644 --- a/src/mahoji/commands/config.ts +++ b/src/mahoji/commands/config.ts @@ -9,8 +9,7 @@ import { Time, clamp, removeFromArr, uniqueArr } from 'e'; import { Bank } from 'oldschooljs'; import type { ItemBank } from 'oldschooljs/dist/meta/types'; -import { production } from '../../config'; -import { BitField, ItemIconPacks, ParsedCustomEmojiWithGroups, PerkTier } from '../../lib/constants'; +import { BitField, ItemIconPacks, ParsedCustomEmojiWithGroups, PerkTier, globalConfig } from '../../lib/constants'; import { Eatables } from '../../lib/data/eatables'; import { CombatOptionsArray, CombatOptionsEnum } from '../../lib/minions/data/combatConstants'; @@ -635,7 +634,7 @@ export async function pinTripCommand( emoji = res[3]; const cachedEmoji = globalClient.emojis.cache.get(emoji); - if ((!cachedEmoji || !emojiServers.has(cachedEmoji.guild.id)) && production) { + if ((!cachedEmoji || !emojiServers.has(cachedEmoji.guild.id)) && globalConfig.isProduction) { return "Sorry, that emoji can't be used. Only emojis in the main support server, or our emoji servers can be used."; } } diff --git a/src/mahoji/commands/gearpresets.ts b/src/mahoji/commands/gearpresets.ts index 7c2929b1f9b..1a43ba39b03 100644 --- a/src/mahoji/commands/gearpresets.ts +++ b/src/mahoji/commands/gearpresets.ts @@ -2,8 +2,7 @@ import { type CommandOption, type CommandRunOptions, cleanString, stringMatches import type { GearPreset } from '@prisma/client'; import { ApplicationCommandOptionType } from 'discord.js'; -import { production } from '../../config'; -import { ParsedCustomEmojiWithGroups } from '../../lib/constants'; +import { ParsedCustomEmojiWithGroups, globalConfig } from '../../lib/constants'; import { generateGearImage } from '../../lib/gear/functions/generateGearImage'; import type { GearSetup, GearSetupType } from '../../lib/gear/types'; import { GearSetupTypes } from '../../lib/gear/types'; @@ -120,7 +119,7 @@ export async function createOrEditGearSetup( emoji = res[3]; const cachedEmoji = globalClient.emojis.cache.get(emoji); - if ((!cachedEmoji || !emojiServers.has(cachedEmoji.guild.id)) && production) { + if ((!cachedEmoji || !emojiServers.has(cachedEmoji.guild.id)) && globalConfig.isProduction) { return "Sorry, that emoji can't be used. Only emojis in the main support server, or our emoji servers can be used."; } } diff --git a/src/mahoji/commands/rp.ts b/src/mahoji/commands/rp.ts index 4bc358ab14e..285625a8f4d 100644 --- a/src/mahoji/commands/rp.ts +++ b/src/mahoji/commands/rp.ts @@ -13,7 +13,6 @@ import { ApplicationCommandOptionType, SnowflakeUtil, codeBlock } from 'discord. import { Time, objectValues, randArrItem, sumArr } from 'e'; import { Bank, type Item } from 'oldschooljs'; -import { ADMIN_IDS, OWNER_IDS, SupportServer, production } from '../../config'; import { BitField, Channel, globalConfig } from '../../lib/constants'; import { allCollectionLogsFlat } from '../../lib/data/Collections'; import type { GearSetupType } from '../../lib/gear/types'; @@ -147,7 +146,7 @@ async function usernameSync() { function isProtectedAccount(user: MUser) { const botAccounts = ['303730326692429825', '729244028989603850', '969542224058654790']; - if ([...ADMIN_IDS, ...OWNER_IDS, ...botAccounts].includes(user.id)) return true; + if (globalConfig.adminUserIDs.includes(user.id) || botAccounts.includes(user.id)) return true; if ([BitField.isModerator].some(bf => user.bitfield.includes(bf))) return true; return false; } @@ -155,7 +154,7 @@ function isProtectedAccount(user: MUser) { const actions = [ { name: 'validate_ge', - allowed: (user: MUser) => ADMIN_IDS.includes(user.id) || OWNER_IDS.includes(user.id), + allowed: (user: MUser) => globalConfig.adminUserIDs.includes(user.id), run: async () => { const isValid = await GrandExchange.extensiveVerification(); if (isValid) { @@ -167,21 +166,21 @@ const actions = [ { name: 'sync_roles', allowed: (user: MUser) => - ADMIN_IDS.includes(user.id) || OWNER_IDS.includes(user.id) || user.bitfield.includes(BitField.isModerator), + globalConfig.adminUserIDs.includes(user.id) || user.bitfield.includes(BitField.isModerator), run: async () => { return runRolesTask(!globalConfig.isProduction); } }, { name: 'sync_usernames', - allowed: (user: MUser) => ADMIN_IDS.includes(user.id) || OWNER_IDS.includes(user.id), + allowed: (user: MUser) => globalConfig.adminUserIDs.includes(user.id), run: async () => { return usernameSync(); } }, { name: 'force_garbage_collection', - allowed: (user: MUser) => ADMIN_IDS.includes(user.id) || OWNER_IDS.includes(user.id), + allowed: (user: MUser) => globalConfig.adminUserIDs.includes(user.id), run: async () => { const timer = new Stopwatch(); for (let i = 0; i < 3; i++) { @@ -192,7 +191,7 @@ const actions = [ }, { name: 'prismadebug', - allowed: (user: MUser) => ADMIN_IDS.includes(user.id) || OWNER_IDS.includes(user.id), + allowed: (user: MUser) => globalConfig.adminUserIDs.includes(user.id), run: async () => { const debugs = [ { @@ -274,7 +273,7 @@ const actions = [ export const rpCommand: OSBMahojiCommand = { name: 'rp', description: 'Admin tools second set', - guildID: SupportServer, + guildID: globalConfig.supportServerID, options: [ { type: ApplicationCommandOptionType.SubcommandGroup, @@ -651,10 +650,11 @@ export const rpCommand: OSBMahojiCommand = { await deferInteraction(interaction); const adminUser = await mUserFetch(userID); - const isOwner = OWNER_IDS.includes(userID.toString()); - const isAdmin = ADMIN_IDS.includes(userID); - const isMod = isOwner || isAdmin || adminUser.bitfield.includes(BitField.isModerator); - if (!guildID || (production && guildID.toString() !== SupportServer)) return randArrItem(gifs); + const isAdmin = globalConfig.adminUserIDs.includes(userID); + const isMod = isAdmin || adminUser.bitfield.includes(BitField.isModerator); + if (!guildID || (globalConfig.isProduction && guildID.toString() !== globalConfig.supportServerID)) { + return randArrItem(gifs); + } if (!isAdmin && !isMod) return randArrItem(gifs); if (options.user_event) { @@ -766,7 +766,7 @@ Date: ${dateFm(date)}`; // Unequip Items if (options.player?.unequip_all_items) { - if (!isOwner && !isAdmin) { + if (!isAdmin) { return randArrItem(gifs); } const allGearSlots = ['melee', 'range', 'mage', 'misc', 'skilling', 'other', 'wildy', 'fashion']; @@ -804,7 +804,7 @@ Date: ${dateFm(date)}`; // Steal Items if (options.player?.steal_items) { - if (!isOwner && !isAdmin) { + if (!isAdmin) { return randArrItem(gifs); } const toDelete = options.player.steal_items.delete ?? false; @@ -863,7 +863,7 @@ Date: ${dateFm(date)}`; } if (options.player?.migrate_user) { - if (!isOwner && !isAdmin) { + if (!isAdmin) { return randArrItem(gifs); } diff --git a/src/mahoji/commands/testpotato.ts b/src/mahoji/commands/testpotato.ts index 76a1030cf8f..738f798ae61 100644 --- a/src/mahoji/commands/testpotato.ts +++ b/src/mahoji/commands/testpotato.ts @@ -9,11 +9,10 @@ import { Bank, Items, calcDropRatesFromBankWithoutUniques } from 'oldschooljs'; import { convertLVLtoXP, itemID, toKMB } from 'oldschooljs/dist/util'; import { getItem, resolveItems } from 'oldschooljs/dist/util/util'; -import { production } from '../../config'; import { mahojiUserSettingsUpdate } from '../../lib/MUser'; import { allStashUnitTiers, allStashUnitsFlat } from '../../lib/clues/stashUnits'; import { CombatAchievements } from '../../lib/combat_achievements/combatAchievements'; -import { MAX_INT_JAVA } from '../../lib/constants'; +import { MAX_INT_JAVA, globalConfig } from '../../lib/constants'; import { leaguesCreatables } from '../../lib/data/creatables/leagueCreatables'; import { Eatables } from '../../lib/data/eatables'; import { TOBMaxMageGear, TOBMaxMeleeGear, TOBMaxRangeGear } from '../../lib/data/tob'; @@ -245,7 +244,7 @@ const spawnPresets = [ const thingsToWipe = ['bank', 'combat_achievements', 'cl', 'quests', 'buypayout', 'kc'] as const; -export const testPotatoCommand: OSBMahojiCommand | null = production +export const testPotatoCommand: OSBMahojiCommand | null = globalConfig.isProduction ? null : { name: 'testpotato', @@ -611,7 +610,7 @@ export const testPotatoCommand: OSBMahojiCommand | null = production setslayertask?: { master: string; monster: string; quantity: number }; events?: {}; }>) => { - if (production) { + if (globalConfig.isProduction) { logError('Test command ran in production', { userID: userID.toString() }); return 'This will never happen...'; } diff --git a/src/mahoji/lib/abstracted_commands/dailyCommand.ts b/src/mahoji/lib/abstracted_commands/dailyCommand.ts index 11ac69220c6..da15ba4bf69 100644 --- a/src/mahoji/lib/abstracted_commands/dailyCommand.ts +++ b/src/mahoji/lib/abstracted_commands/dailyCommand.ts @@ -3,9 +3,8 @@ import type { ChatInputCommandInteraction, TextChannel } from 'discord.js'; import { Time, roll, shuffleArr, uniqueArr } from 'e'; import type { ItemBank } from 'oldschooljs/dist/meta/types'; -import { SupportServer } from '../../../config'; import { DynamicButtons } from '../../../lib/DynamicButtons'; -import { Emoji } from '../../../lib/constants'; +import { Emoji, globalConfig } from '../../../lib/constants'; import pets from '../../../lib/data/pets'; import { getRandomTriviaQuestions } from '../../../lib/roboChimp'; import dailyRoll from '../../../lib/simulation/dailyTable'; @@ -31,7 +30,7 @@ export async function isUsersDailyReady( } async function reward(user: MUser, triviaCorrect: boolean): CommandResponse { - const guild = globalClient.guilds.cache.get(SupportServer); + const guild = globalClient.guilds.cache.get(globalConfig.supportServerID); const member = await guild?.members.fetch(user.id).catch(() => null); const loot = dailyRoll(1, triviaCorrect); diff --git a/src/mahoji/lib/events.ts b/src/mahoji/lib/events.ts index 405ccfb9d86..2f2de401b25 100644 --- a/src/mahoji/lib/events.ts +++ b/src/mahoji/lib/events.ts @@ -78,7 +78,7 @@ export const onStartup = logWrapFn('onStartup', async () => { : bulkUpdateCommands({ client: globalClient.mahojiClient, commands: Array.from(globalClient.mahojiClient.commands.values()), - guildID: globalConfig.testingServerID + guildID: globalConfig.supportServerID }); initCrons(); @@ -92,7 +92,7 @@ export const onStartup = logWrapFn('onStartup', async () => { await Promise.all([ globalClient.application.commands.fetch({ - guildId: globalConfig.isProduction ? undefined : globalConfig.testingServerID + guildId: globalConfig.isProduction ? undefined : globalConfig.supportServerID }), updateTestBotStatus(), sendStartupMessage, diff --git a/src/mahoji/lib/inhibitors.ts b/src/mahoji/lib/inhibitors.ts index a47cec91ad6..b9afe695a02 100644 --- a/src/mahoji/lib/inhibitors.ts +++ b/src/mahoji/lib/inhibitors.ts @@ -2,10 +2,9 @@ import { PerkTier, formatDuration } from '@oldschoolgg/toolkit/util'; import type { DMChannel, Guild, GuildMember, InteractionReplyOptions, TextChannel } from 'discord.js'; import { ComponentType, PermissionsBitField } from 'discord.js'; -import { OWNER_IDS, SupportServer } from '../../config'; import { BLACKLISTED_GUILDS, BLACKLISTED_USERS } from '../../lib/blacklists'; import { type PartialUser, partialUserCache, perkTierCache } from '../../lib/cache'; -import { BadgesEnum, BitField, Channel, DISABLED_COMMANDS } from '../../lib/constants'; +import { BadgesEnum, BitField, Channel, DISABLED_COMMANDS, globalConfig } from '../../lib/constants'; import { minionBuyButton } from '../../lib/sharedComponents'; import type { CategoryFlag } from '../../lib/types'; import { minionIsBusy } from '../../lib/util/minionIsBusy'; @@ -91,7 +90,7 @@ const inhibitors: Inhibitor[] = [ name: 'disabled', run: ({ command, guild, userID }) => { if ( - !OWNER_IDS.includes(userID) && + globalConfig.adminUserIDs.includes(userID) && (command.attributes?.enabled === false || DISABLED_COMMANDS.has(command.name)) ) { return { content: 'This command is globally disabled.' }; @@ -108,7 +107,7 @@ const inhibitors: Inhibitor[] = [ { name: 'commandRoleLimit', run: ({ member, guild, channel, userID }) => { - if (!guild || guild.id !== SupportServer) return false; + if (!guild || guild.id !== globalConfig.supportServerID) return false; if (channel.id !== Channel.General) return false; const perkTier = perkTierCache.get(userID) ?? 0; if (member && perkTier >= PerkTier.Two) { @@ -132,7 +131,7 @@ const inhibitors: Inhibitor[] = [ // Allow contributors + moderators to use disabled channels in SupportServer const userBitfield = cachedUser.bitfield; const isStaff = userBitfield.includes(BitField.isModerator); - if (guild.id === SupportServer && isStaff) { + if (guild.id === globalConfig.supportServerID && isStaff) { return false; } @@ -154,7 +153,8 @@ const inhibitors: Inhibitor[] = [ name: 'cooldown', run: ({ userID, command, cachedUser }) => { if (!command.attributes?.cooldown || !cachedUser) return false; - if (OWNER_IDS.includes(userID) || cachedUser.bitfield.includes(BitField.isModerator)) return false; + if (globalConfig.adminUserIDs.includes(userID) || cachedUser.bitfield.includes(BitField.isModerator)) + return false; const cooldownForThis = Cooldowns.get(userID, command.name, command.attributes.cooldown); if (cooldownForThis) { return {