From ac79eb09f5025141d9c060a9db26253f99259c5f Mon Sep 17 00:00:00 2001 From: Dragory <2606411+Dragory@users.noreply.github.com> Date: Sat, 11 Sep 2021 19:06:51 +0300 Subject: [PATCH] Reformat all files with Prettier --- backend/ormconfig.js | 30 +-- backend/register-tsconfig-paths.js | 6 +- backend/src/Queue.ts | 4 +- backend/src/QueuedEventEmitter.ts | 2 +- backend/src/RegExpRunner.ts | 2 +- backend/src/api/auth.ts | 6 +- backend/src/api/docs.ts | 10 +- backend/src/api/guilds.ts | 2 +- backend/src/configValidator.ts | 2 +- backend/src/data/ApiLogins.ts | 10 +- backend/src/data/ApiUserInfo.ts | 2 +- backend/src/data/Configs.ts | 8 +- backend/src/data/GuildArchives.ts | 4 +- backend/src/data/GuildCases.ts | 4 +- backend/src/data/GuildCounters.ts | 54 ++--- backend/src/data/GuildLogs.ts | 4 +- backend/src/data/GuildMemberTimezones.ts | 2 +- backend/src/data/GuildMutes.ts | 16 +- backend/src/data/GuildNicknameHistory.ts | 2 +- backend/src/data/GuildSavedMessages.ts | 8 +- backend/src/data/GuildScheduledPosts.ts | 5 +- backend/src/data/GuildSlowmodes.ts | 5 +- backend/src/data/GuildTempbans.ts | 10 +- backend/src/data/GuildVCAlerts.ts | 5 +- backend/src/data/UsernameHistory.ts | 2 +- backend/src/data/cleanup/configs.ts | 14 +- backend/src/data/cleanup/messages.ts | 17 +- backend/src/data/cleanup/nicknames.ts | 7 +- backend/src/data/cleanup/usernames.ts | 7 +- backend/src/data/db.ts | 4 +- backend/src/data/entities/ApiLogin.ts | 5 +- .../data/entities/ApiPermissionAssignment.ts | 5 +- backend/src/data/entities/ApiUserInfo.ts | 10 +- backend/src/data/entities/Case.ts | 5 +- backend/src/data/entities/CaseNote.ts | 5 +- backend/src/data/entities/Config.ts | 2 +- backend/src/data/entities/StarboardMessage.ts | 2 +- .../src/data/entities/StarboardReaction.ts | 2 +- backend/src/index.ts | 18 +- ...12501-MigrateUsernamesToNewHistoryTable.ts | 4 +- backend/src/pluginUtils.ts | 8 +- .../plugins/AutoDelete/AutoDeletePlugin.ts | 6 +- .../plugins/AutoDelete/util/deleteNextItem.ts | 2 +- .../AutoDelete/util/onMessageDelete.ts | 2 +- backend/src/plugins/Automod/AutomodPlugin.ts | 6 +- .../src/plugins/Automod/actions/addRoles.ts | 6 +- backend/src/plugins/Automod/actions/alert.ts | 2 +- .../plugins/Automod/actions/archiveThread.ts | 4 +- backend/src/plugins/Automod/actions/ban.ts | 2 +- .../plugins/Automod/actions/changeNickname.ts | 4 +- backend/src/plugins/Automod/actions/kick.ts | 4 +- backend/src/plugins/Automod/actions/log.ts | 2 +- backend/src/plugins/Automod/actions/mute.ts | 2 +- .../plugins/Automod/actions/removeRoles.ts | 6 +- backend/src/plugins/Automod/actions/reply.ts | 6 +- backend/src/plugins/Automod/actions/warn.ts | 4 +- .../functions/clearOldRecentActions.ts | 2 +- .../Automod/functions/clearOldRecentSpam.ts | 2 +- .../functions/clearRecentActionsForMessage.ts | 2 +- .../functions/createMessageSpamTrigger.ts | 6 +- .../Automod/functions/findRecentSpam.ts | 2 +- .../functions/getMatchingRecentActions.ts | 2 +- .../functions/getTextMatchPartialSummary.ts | 2 +- .../Automod/triggers/exampleTrigger.ts | 2 +- .../Automod/triggers/matchAttachmentType.ts | 9 +- .../plugins/Automod/triggers/matchMimeType.ts | 4 +- .../plugins/Automod/triggers/matchWords.ts | 2 +- .../Automod/triggers/memberJoinSpam.ts | 2 +- .../commands/AddDashboardUserCmd.ts | 2 +- .../commands/AddServerFromInviteCmd.ts | 5 +- .../BotControl/commands/AllowServerCmd.ts | 5 +- .../commands/ListDashboardUsersCmd.ts | 2 +- .../BotControl/commands/PerformanceCmd.ts | 2 +- .../commands/RemoveDashboardUserCmd.ts | 2 +- .../plugins/BotControl/commands/ServersCmd.ts | 14 +- .../plugins/Cases/functions/createCaseNote.ts | 2 +- .../functions/getCaseTypeAmountForUserId.ts | 4 +- backend/src/plugins/Censor/CensorPlugin.ts | 4 +- .../plugins/Censor/util/applyFiltersToMsg.ts | 4 +- .../ChannelArchiver/ChannelArchiverPlugin.ts | 2 +- .../commands/ArchiveChannelCmd.ts | 6 +- ...etCompanionChannelOptsForVoiceChannelId.ts | 4 +- .../functions/handleCompanionPermissions.ts | 2 +- .../src/plugins/ContextMenus/actions/mute.ts | 5 +- .../ContextMenus/utils/loadAllCommands.ts | 2 +- .../src/plugins/Counters/CountersPlugin.ts | 2 +- .../Counters/commands/CountersListCmd.ts | 4 +- .../Counters/functions/changeCounterValue.ts | 4 +- .../Counters/functions/decayCounter.ts | 4 +- .../Counters/functions/setCounterValue.ts | 4 +- .../CustomEvents/actions/addRoleAction.ts | 2 +- .../LocateUser/events/BanRemoveAlertsEvt.ts | 2 +- .../LocateUser/events/SendAlertsEvts.ts | 2 +- .../LocateUser/utils/fillAlertsList.ts | 2 +- .../plugins/LocateUser/utils/sendAlerts.ts | 2 +- backend/src/plugins/Logs/LogsPlugin.ts | 6 +- .../plugins/Logs/events/LogsUserUpdateEvts.ts | 8 +- .../Logs/logFunctions/logAutomodAction.ts | 2 +- .../Logs/logFunctions/logMemberRoleAdd.ts | 2 +- .../Logs/logFunctions/logMemberRoleChanges.ts | 4 +- .../Logs/logFunctions/logMemberRoleRemove.ts | 2 +- backend/src/plugins/Logs/types.ts | 5 +- .../src/plugins/Logs/util/getLogMessage.ts | 10 +- backend/src/plugins/Logs/util/log.ts | 4 +- .../plugins/Logs/util/onMessageDeleteBulk.ts | 2 +- .../src/plugins/Logs/util/onMessageUpdate.ts | 8 +- .../MessageSaver/events/SaveMessagesEvts.ts | 8 +- .../ModActions/commands/CasesModCmd.ts | 4 +- .../ModActions/commands/CasesUserCmd.ts | 10 +- .../ModActions/commands/MassUnbanCmd.ts | 10 +- .../ModActions/commands/MassmuteCmd.ts | 2 +- .../functions/clearIgnoredEvents.ts | 2 +- .../functions/formatReasonWithAttachments.ts | 2 +- .../ModActions/functions/isEventIgnored.ts | 2 +- .../Mutes/commands/ClearBannedMutesCmd.ts | 2 +- .../src/plugins/Mutes/commands/MutesCmd.ts | 37 ++-- .../Mutes/functions/clearExpiredMutes.ts | 2 +- .../src/plugins/Mutes/functions/muteUser.ts | 12 +- .../src/plugins/Mutes/functions/unmuteUser.ts | 2 +- .../plugins/NameHistory/commands/NamesCmd.ts | 4 +- .../Post/commands/ScheduledPostsListCmd.ts | 2 +- .../src/plugins/Post/util/actualPostCmd.ts | 12 +- .../ReactionRoles/ReactionRolesPlugin.ts | 2 +- .../commands/InitReactionRolesCmd.ts | 20 +- .../commands/PostButtonRolesCmd.ts | 4 +- .../events/AddReactionRoleEvt.ts | 2 +- .../applyReactionRoleReactionsToMessage.ts | 2 +- .../ReactionRoles/util/runAutoRefresh.ts | 2 +- .../plugins/Reminders/commands/RemindCmd.ts | 5 +- .../plugins/Roles/commands/MassAddRoleCmd.ts | 2 +- .../Roles/commands/MassRemoveRoleCmd.ts | 2 +- .../SelfGrantableRolesPlugin.ts | 4 +- .../SelfGrantableRoles/commands/RoleAddCmd.ts | 8 +- .../commands/RoleRemoveCmd.ts | 8 +- .../util/findMatchingRoles.ts | 2 +- .../util/getApplyingEntries.ts | 2 +- .../util/normalizeRoleNames.ts | 2 +- .../SelfGrantableRoles/util/splitRoleNames.ts | 2 +- .../src/plugins/Slowmode/SlowmodePlugin.ts | 2 +- .../Slowmode/commands/SlowmodeListCmd.ts | 2 +- backend/src/plugins/Spam/SpamPlugin.ts | 2 +- .../Spam/util/clearOldRecentActions.ts | 4 +- .../Spam/util/clearRecentUserActions.ts | 2 +- .../src/plugins/Spam/util/getRecentActions.ts | 2 +- .../Spam/util/logAndDetectMessageSpam.ts | 12 +- .../src/plugins/Starboard/StarboardPlugin.ts | 2 +- .../events/StarboardReactionAddEvt.ts | 6 +- .../util/createStarboardEmbedFromMessage.ts | 5 +- .../util/removeMessageFromStarboard.ts | 2 +- backend/src/plugins/Tags/TagsPlugin.ts | 18 +- .../src/plugins/Tags/commands/TagListCmd.ts | 2 +- .../src/plugins/Tags/util/onMessageCreate.ts | 2 +- .../src/plugins/Tags/util/renderTagBody.ts | 2 +- .../plugins/Tags/util/renderTagFromString.ts | 2 +- .../src/plugins/Utility/commands/AboutCmd.ts | 11 +- .../src/plugins/Utility/commands/CleanCmd.ts | 12 +- .../src/plugins/Utility/commands/HelpCmd.ts | 5 +- .../src/plugins/Utility/commands/RolesCmd.ts | 6 +- .../src/plugins/Utility/commands/VcmoveCmd.ts | 4 +- .../Utility/functions/getChannelInfoEmbed.ts | 8 +- .../Utility/functions/getEmojiInfoEmbed.ts | 2 +- .../Utility/functions/getInviteInfoEmbed.ts | 4 +- .../Utility/functions/getRoleInfoEmbed.ts | 9 +- .../Utility/functions/getServerInfoEmbed.ts | 8 +- .../Utility/functions/getUserInfoEmbed.ts | 8 +- backend/src/plugins/Utility/search.ts | 37 ++-- .../src/plugins/ZeppelinPluginBlueprint.ts | 12 +- backend/src/templateFormatter.test.ts | 18 +- backend/src/templateFormatter.ts | 4 +- backend/src/utils.test.ts | 18 +- backend/src/utils.ts | 71 +++---- backend/src/utils/crypt.test.ts | 2 +- backend/src/utils/normalizeText.test.ts | 8 +- backend/src/utils/parseFuzzyTimezone.ts | 2 +- backend/src/utils/tColor.ts | 4 +- backend/src/utils/tValidTimezone.ts | 4 +- backend/src/utils/templateSafeObjects.ts | 12 +- backend/src/utils/typeUtils.ts | 9 +- .../src/utils/validateNoObjectAliases.test.ts | 6 +- backend/src/utils/waitForInteraction.ts | 2 +- backend/src/validation.test.ts | 2 +- backend/src/validatorUtils.ts | 20 +- backend/start-dev.js | 4 +- backend/tsconfig.json | 12 +- dashboard/.htmlnanorc.js | 2 +- dashboard/src/api.ts | 4 +- dashboard/src/directives/trim-indents.ts | 2 +- dashboard/src/index.html | 32 +-- dashboard/src/splash.html | 2 +- dashboard/src/store/guilds.ts | 6 +- dashboard/tailwind.config.js | 26 +-- dashboard/tsconfig.json | 5 +- dashboard/webpack.config.js | 81 ++++---- presetup-configurator/snowpack.config.js | 6 +- presetup-configurator/src/App.tsx | 10 +- presetup-configurator/src/Configurator.css | 1 - presetup-configurator/src/Configurator.tsx | 47 +++-- presetup-configurator/src/Levels.tsx | 12 +- presetup-configurator/src/LogChannels.tsx | 191 +++++++++--------- presetup-configurator/src/index.html | 26 +-- presetup-configurator/src/index.tsx | 2 +- presetup-configurator/tsconfig.json | 5 +- shared/src/apiPermissions.test.ts | 4 +- shared/src/apiPermissions.ts | 2 +- shared/tsconfig.json | 8 +- tslint.json | 5 +- 206 files changed, 727 insertions(+), 888 deletions(-) diff --git a/backend/ormconfig.js b/backend/ormconfig.js index 9b8b311e..161346a4 100644 --- a/backend/ormconfig.js +++ b/backend/ormconfig.js @@ -1,24 +1,24 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); try { - fs.accessSync(path.resolve(__dirname, 'bot.env')); - require('dotenv').config({ path: path.resolve(__dirname, 'bot.env') }); + fs.accessSync(path.resolve(__dirname, "bot.env")); + require("dotenv").config({ path: path.resolve(__dirname, "bot.env") }); } catch { try { - fs.accessSync(path.resolve(__dirname, 'api.env')); - require('dotenv').config({ path: path.resolve(__dirname, 'api.env') }); + fs.accessSync(path.resolve(__dirname, "api.env")); + require("dotenv").config({ path: path.resolve(__dirname, "api.env") }); } catch { throw new Error("bot.env or api.env required"); } } -const moment = require('moment-timezone'); -moment.tz.setDefault('UTC'); +const moment = require("moment-timezone"); +moment.tz.setDefault("UTC"); -const entities = path.relative(process.cwd(), path.resolve(__dirname, 'dist/backend/src/data/entities/*.js')); -const migrations = path.relative(process.cwd(), path.resolve(__dirname, 'dist/backend/src/migrations/*.js')); -const migrationsDir = path.relative(process.cwd(), path.resolve(__dirname, 'src/migrations')); +const entities = path.relative(process.cwd(), path.resolve(__dirname, "dist/backend/src/data/entities/*.js")); +const migrations = path.relative(process.cwd(), path.resolve(__dirname, "dist/backend/src/migrations/*.js")); +const migrationsDir = path.relative(process.cwd(), path.resolve(__dirname, "src/migrations")); module.exports = { type: "mysql", @@ -26,7 +26,7 @@ module.exports = { username: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_DATABASE, - charset: 'utf8mb4', + charset: "utf8mb4", supportBigNumbers: true, bigNumberStrings: true, dateStrings: true, @@ -39,13 +39,13 @@ module.exports = { // Pool options extra: { typeCast(field, next) { - if (field.type === 'DATETIME') { + if (field.type === "DATETIME") { const val = field.string(); - return val != null ? moment.utc(val).format('YYYY-MM-DD HH:mm:ss') : null; + return val != null ? moment.utc(val).format("YYYY-MM-DD HH:mm:ss") : null; } return next(); - } + }, }, // Migrations diff --git a/backend/register-tsconfig-paths.js b/backend/register-tsconfig-paths.js index 2cc33ff1..9f182acf 100644 --- a/backend/register-tsconfig-paths.js +++ b/backend/register-tsconfig-paths.js @@ -6,9 +6,9 @@ * https://github.com/TypeStrong/ts-node/pull/254 */ -const path = require('path'); -const tsconfig = require('./tsconfig.json'); -const tsconfigPaths = require('tsconfig-paths'); +const path = require("path"); +const tsconfig = require("./tsconfig.json"); +const tsconfigPaths = require("tsconfig-paths"); // E.g. ./dist/backend const baseUrl = path.resolve(tsconfig.compilerOptions.outDir, path.basename(__dirname)); diff --git a/backend/src/Queue.ts b/backend/src/Queue.ts index ddedc56a..2ca63d2f 100644 --- a/backend/src/Queue.ts +++ b/backend/src/Queue.ts @@ -29,7 +29,7 @@ export class Queue { } public add(fn: TQueueFunction): Promise { - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { this.queue.push(async () => { const result = await fn(); resolve(result); @@ -50,7 +50,7 @@ export class Queue { } const fn = this.queue.shift()!; - new Promise(resolve => { + new Promise((resolve) => { // Either fn() completes or the timeout is reached void fn().then(resolve); setTimeout(resolve, this._timeout); diff --git a/backend/src/QueuedEventEmitter.ts b/backend/src/QueuedEventEmitter.ts index 3da957d3..2402c491 100644 --- a/backend/src/QueuedEventEmitter.ts +++ b/backend/src/QueuedEventEmitter.ts @@ -42,7 +42,7 @@ export class QueuedEventEmitter { const listeners = [...(this.listeners.get(eventName) || []), ...(this.listeners.get("*") || [])]; let promise: Promise = Promise.resolve(); - listeners.forEach(listener => { + listeners.forEach((listener) => { promise = this.queue.add(listener.bind(null, ...args)); }); diff --git a/backend/src/RegExpRunner.ts b/backend/src/RegExpRunner.ts index 96d39be3..1ac5f47c 100644 --- a/backend/src/RegExpRunner.ts +++ b/backend/src/RegExpRunner.ts @@ -27,7 +27,7 @@ const INITIAL_REGEX_TIMEOUT = 5 * SECONDS; const INITIAL_REGEX_TIMEOUT_DURATION = 30 * SECONDS; const FINAL_REGEX_TIMEOUT = 5 * SECONDS; -const regexTimeoutUpgradePromise = new Promise(resolve => setTimeout(resolve, INITIAL_REGEX_TIMEOUT_DURATION)); +const regexTimeoutUpgradePromise = new Promise((resolve) => setTimeout(resolve, INITIAL_REGEX_TIMEOUT_DURATION)); let newWorkerTimeout = INITIAL_REGEX_TIMEOUT; regexTimeoutUpgradePromise.then(() => (newWorkerTimeout = FINAL_REGEX_TIMEOUT)); diff --git a/backend/src/api/auth.ts b/backend/src/api/auth.ts index 92e8e594..b59da332 100644 --- a/backend/src/api/auth.ts +++ b/backend/src/api/auth.ts @@ -33,21 +33,21 @@ function simpleDiscordAPIRequest(bearerToken, path): Promise { Authorization: `Bearer ${bearerToken}`, }, }, - res => { + (res) => { if (res.statusCode !== 200) { reject(new Error(`Discord API error ${res.statusCode}`)); return; } let rawData = ""; - res.on("data", data => (rawData += data)); + res.on("data", (data) => (rawData += data)); res.on("end", () => { resolve(JSON.parse(rawData)); }); }, ); - request.on("error", err => reject(err)); + request.on("error", (err) => reject(err)); }); } diff --git a/backend/src/api/docs.ts b/backend/src/api/docs.ts index 8dbeb116..29a3dba9 100644 --- a/backend/src/api/docs.ts +++ b/backend/src/api/docs.ts @@ -22,21 +22,21 @@ function formatConfigSchema(schema) { } else if (schema.name.startsWith("Optional<")) { return `Optional<${formatConfigSchema(schema.types[0])}>`; } else { - return schema.types.map(t => formatConfigSchema(t)).join(" | "); + return schema.types.map((t) => formatConfigSchema(t)).join(" | "); } } else if (schema._tag === "IntersectionType") { - return schema.types.map(t => formatConfigSchema(t)).join(" & "); + return schema.types.map((t) => formatConfigSchema(t)).join(" & "); } else { return schema.name; } } export function initDocs(app: express.Express) { - const docsPlugins = guildPlugins.filter(plugin => plugin.showInDocs); + const docsPlugins = guildPlugins.filter((plugin) => plugin.showInDocs); app.get("/docs/plugins", (req: express.Request, res: express.Response) => { res.json( - docsPlugins.map(plugin => { + docsPlugins.map((plugin) => { const thinInfo = plugin.info ? { prettyName: plugin.info.prettyName, legacy: plugin.info.legacy ?? false } : {}; return { name: plugin.name, @@ -56,7 +56,7 @@ export function initDocs(app: express.Express) { const name = plugin.name; const info = plugin.info || {}; - const commands = (plugin.commands || []).map(cmd => ({ + const commands = (plugin.commands || []).map((cmd) => ({ trigger: cmd.trigger, permission: cmd.permission, signature: cmd.signature, diff --git a/backend/src/api/guilds.ts b/backend/src/api/guilds.ts index 412f526f..0706b4be 100644 --- a/backend/src/api/guilds.ts +++ b/backend/src/api/guilds.ts @@ -131,7 +131,7 @@ export function initGuildsAPI(app: express.Express) { } const validPermissions = new Set(Object.values(ApiPermissions)); validPermissions.delete(ApiPermissions.Owner); - if (!Array.isArray(permissions) || permissions.some(p => !validPermissions.has(p))) { + if (!Array.isArray(permissions) || permissions.some((p) => !validPermissions.has(p))) { return clientError(res, "Invalid permissions"); } if (expiresAt != null && !moment.utc(expiresAt).isValid()) { diff --git a/backend/src/configValidator.ts b/backend/src/configValidator.ts index 0c45c611..b5543dc4 100644 --- a/backend/src/configValidator.ts +++ b/backend/src/configValidator.ts @@ -36,7 +36,7 @@ export async function validateGuildConfig(config: any): Promise { const plugin = pluginNameToPlugin.get(pluginName)!; try { const mergedOptions = configUtils.mergeConfig(plugin.defaultOptions || {}, pluginOptions); - await plugin.configPreprocessor?.((mergedOptions as unknown) as PluginOptions, true); + await plugin.configPreprocessor?.(mergedOptions as unknown as PluginOptions, true); } catch (err) { if (err instanceof ConfigValidationError || err instanceof StrictValidationError) { return `${pluginName}: ${err.message}`; diff --git a/backend/src/data/ApiLogins.ts b/backend/src/data/ApiLogins.ts index 23bb7e49..ab8779d0 100644 --- a/backend/src/data/ApiLogins.ts +++ b/backend/src/data/ApiLogins.ts @@ -68,10 +68,7 @@ export class ApiLogins extends BaseRepository { token: hashedToken, user_id: userId, logged_in_at: moment.utc().format(DBDateFormat), - expires_at: moment - .utc() - .add(LOGIN_EXPIRY_TIME, "ms") - .format(DBDateFormat), + expires_at: moment.utc().add(LOGIN_EXPIRY_TIME, "ms").format(DBDateFormat), }); return `${loginId}.${token}`; @@ -96,10 +93,7 @@ export class ApiLogins extends BaseRepository { await this.apiLogins.update( { id: loginId }, { - expires_at: moment() - .utc() - .add(LOGIN_EXPIRY_TIME, "ms") - .format(DBDateFormat), + expires_at: moment().utc().add(LOGIN_EXPIRY_TIME, "ms").format(DBDateFormat), }, ); } diff --git a/backend/src/data/ApiUserInfo.ts b/backend/src/data/ApiUserInfo.ts index 73633d01..b7cd34ae 100644 --- a/backend/src/data/ApiUserInfo.ts +++ b/backend/src/data/ApiUserInfo.ts @@ -22,7 +22,7 @@ export class ApiUserInfo extends BaseRepository { } update(id, data: ApiUserInfoData) { - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const repo = entityManager.getRepository(ApiUserInfoEntity); const existingInfo = await repo.findOne({ where: { id } }); diff --git a/backend/src/data/Configs.ts b/backend/src/data/Configs.ts index 3e0882f0..2b3e4089 100644 --- a/backend/src/data/Configs.ts +++ b/backend/src/data/Configs.ts @@ -41,11 +41,7 @@ export class Configs extends BaseRepository { } getActiveLargerThanId(id) { - return this.configs - .createQueryBuilder() - .where("id > :id", { id }) - .andWhere("is_active = 1") - .getMany(); + return this.configs.createQueryBuilder().where("id > :id", { id }).andWhere("is_active = 1").getMany(); } async hasConfig(key) { @@ -65,7 +61,7 @@ export class Configs extends BaseRepository { } async saveNewRevision(key, config, editedBy) { - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const repo = entityManager.getRepository(Config); // Mark all old revisions inactive await repo.update({ key }, { is_active: false }); diff --git a/backend/src/data/GuildArchives.ts b/backend/src/data/GuildArchives.ts index 4fae975b..a84817ae 100644 --- a/backend/src/data/GuildArchives.ts +++ b/backend/src/data/GuildArchives.ts @@ -88,10 +88,10 @@ export class GuildArchives extends BaseGuildRepository { id: msg.id, timestamp: moment.utc(msg.posted_at).format("YYYY-MM-DD HH:mm:ss"), content: msg.data.content, - attachments: msg.data.attachments?.map(att => { + attachments: msg.data.attachments?.map((att) => { return JSON.stringify({ name: att.name, url: att.url, type: att.contentType }); }), - stickers: msg.data.stickers?.map(sti => { + stickers: msg.data.stickers?.map((sti) => { return JSON.stringify({ name: sti.name, id: sti.id, isDefault: isDefaultSticker(sti.id) }); }), user: partialUser, diff --git a/backend/src/data/GuildCases.ts b/backend/src/data/GuildCases.ts index f0e9de43..b13b7c4a 100644 --- a/backend/src/data/GuildCases.ts +++ b/backend/src/data/GuildCases.ts @@ -123,7 +123,7 @@ export class GuildCases extends BaseGuildRepository { guild_id: this.guildId, case_number: () => `(SELECT IFNULL(MAX(case_number)+1, 1) FROM cases AS ma2 WHERE guild_id = ${this.guildId})`, }) - .catch(err => { + .catch((err) => { if (err?.code === "ER_DUP_ENTRY") { if (data.audit_log_id) { console.trace(`Tried to insert case with duplicate audit_log_id`); @@ -148,7 +148,7 @@ export class GuildCases extends BaseGuildRepository { } async softDelete(id: number, deletedById: string, deletedByName: string, deletedByText: string) { - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const cases = entityManager.getRepository(Case); const caseNotes = entityManager.getRepository(CaseNote); diff --git a/backend/src/data/GuildCounters.ts b/backend/src/data/GuildCounters.ts index 0a1ff57e..52f20293 100644 --- a/backend/src/data/GuildCounters.ts +++ b/backend/src/data/GuildCounters.ts @@ -17,19 +17,11 @@ const MAX_COUNTER_VALUE = 2147483647; // 2^31-1, for MySQL INT const decayQueue = new Queue(); async function deleteCountersMarkedToBeDeleted(): Promise { - await getRepository(Counter) - .createQueryBuilder() - .where("delete_at <= NOW()") - .delete() - .execute(); + await getRepository(Counter).createQueryBuilder().where("delete_at <= NOW()").delete().execute(); } async function deleteTriggersMarkedToBeDeleted(): Promise { - await getRepository(CounterTrigger) - .createQueryBuilder() - .where("delete_at <= NOW()") - .delete() - .execute(); + await getRepository(CounterTrigger).createQueryBuilder().where("delete_at <= NOW()").delete().execute(); } setInterval(deleteCountersMarkedToBeDeleted, 1 * HOURS); @@ -97,10 +89,7 @@ export class GuildCounters extends BaseGuildRepository { criteria.id = Not(In(idsToKeep)); } - const deleteAt = moment - .utc() - .add(DELETE_UNUSED_COUNTERS_AFTER, "ms") - .format(DBDateFormat); + const deleteAt = moment.utc().add(DELETE_UNUSED_COUNTERS_AFTER, "ms").format(DBDateFormat); await this.counters.update(criteria, { delete_at: deleteAt, @@ -108,11 +97,7 @@ export class GuildCounters extends BaseGuildRepository { } async deleteCountersMarkedToBeDeleted(): Promise { - await this.counters - .createQueryBuilder() - .where("delete_at <= NOW()") - .delete() - .execute(); + await this.counters.createQueryBuilder().where("delete_at <= NOW()").delete().execute(); } async changeCounterValue( @@ -230,14 +215,11 @@ export class GuildCounters extends BaseGuildRepository { const triggersToMark = await triggersToMarkQuery.getMany(); if (triggersToMark.length) { - const deleteAt = moment - .utc() - .add(DELETE_UNUSED_COUNTER_TRIGGERS_AFTER, "ms") - .format(DBDateFormat); + const deleteAt = moment.utc().add(DELETE_UNUSED_COUNTER_TRIGGERS_AFTER, "ms").format(DBDateFormat); await this.counterTriggers.update( { - id: In(triggersToMark.map(t => t.id)), + id: In(triggersToMark.map((t) => t.id)), }, { delete_at: deleteAt, @@ -247,11 +229,7 @@ export class GuildCounters extends BaseGuildRepository { } async deleteTriggersMarkedToBeDeleted(): Promise { - await this.counterTriggers - .createQueryBuilder() - .where("delete_at <= NOW()") - .delete() - .execute(); + await this.counterTriggers.createQueryBuilder().where("delete_at <= NOW()").delete().execute(); } async initCounterTrigger( @@ -278,7 +256,7 @@ export class GuildCounters extends BaseGuildRepository { throw new Error(`Invalid comparison value: ${reverseComparisonValue}`); } - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const existing = await entityManager.findOne(CounterTrigger, { counter_id: counterId, name: triggerName, @@ -330,7 +308,7 @@ export class GuildCounters extends BaseGuildRepository { channelId = channelId || "0"; userId = userId || "0"; - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const previouslyTriggered = await entityManager.findOne(CounterTriggerState, { trigger_id: counterTrigger.id, user_id: userId!, @@ -378,7 +356,7 @@ export class GuildCounters extends BaseGuildRepository { async checkAllValuesForTrigger( counterTrigger: CounterTrigger, ): Promise> { - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const matchingValues = await entityManager .createQueryBuilder(CounterValue, "cv") .leftJoin( @@ -395,7 +373,7 @@ export class GuildCounters extends BaseGuildRepository { if (matchingValues.length) { await entityManager.insert( CounterTriggerState, - matchingValues.map(row => ({ + matchingValues.map((row) => ({ trigger_id: counterTrigger.id, channel_id: row.channel_id, user_id: row.user_id, @@ -403,7 +381,7 @@ export class GuildCounters extends BaseGuildRepository { ); } - return matchingValues.map(row => ({ + return matchingValues.map((row) => ({ channelId: row.channel_id, userId: row.user_id, })); @@ -429,7 +407,7 @@ export class GuildCounters extends BaseGuildRepository { channelId = channelId || "0"; userId = userId || "0"; - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const matchingValue = await entityManager .createQueryBuilder(CounterValue, "cv") .innerJoin( @@ -468,7 +446,7 @@ export class GuildCounters extends BaseGuildRepository { async checkAllValuesForReverseTrigger( counterTrigger: CounterTrigger, ): Promise> { - return connection.transaction(async entityManager => { + return connection.transaction(async (entityManager) => { const matchingValues: Array<{ id: string; triggerStateId: string; @@ -496,11 +474,11 @@ export class GuildCounters extends BaseGuildRepository { if (matchingValues.length) { await entityManager.delete(CounterTriggerState, { - id: In(matchingValues.map(v => v.triggerStateId)), + id: In(matchingValues.map((v) => v.triggerStateId)), }); } - return matchingValues.map(row => ({ + return matchingValues.map((row) => ({ channelId: row.channel_id, userId: row.user_id, })); diff --git a/backend/src/data/GuildLogs.ts b/backend/src/data/GuildLogs.ts index 457beec6..b324984e 100644 --- a/backend/src/data/GuildLogs.ts +++ b/backend/src/data/GuildLogs.ts @@ -46,12 +46,12 @@ export class GuildLogs extends events.EventEmitter { } isLogIgnored(type: LogType, ignoreId: any) { - return this.ignoredLogs.some(info => type === info.type && ignoreId === info.ignoreId); + return this.ignoredLogs.some((info) => type === info.type && ignoreId === info.ignoreId); } clearIgnoredLog(type: LogType, ignoreId: any) { this.ignoredLogs.splice( - this.ignoredLogs.findIndex(info => type === info.type && ignoreId === info.ignoreId), + this.ignoredLogs.findIndex((info) => type === info.type && ignoreId === info.ignoreId), 1, ); } diff --git a/backend/src/data/GuildMemberTimezones.ts b/backend/src/data/GuildMemberTimezones.ts index 6c4ef82b..3f98b9ef 100644 --- a/backend/src/data/GuildMemberTimezones.ts +++ b/backend/src/data/GuildMemberTimezones.ts @@ -19,7 +19,7 @@ export class GuildMemberTimezones extends BaseGuildRepository { } async set(memberId, timezone: string) { - await connection.transaction(async entityManager => { + await connection.transaction(async (entityManager) => { const repo = entityManager.getRepository(MemberTimezone); const existingRow = await repo.findOne({ guild_id: this.guildId, diff --git a/backend/src/data/GuildMutes.ts b/backend/src/data/GuildMutes.ts index 35f86fc0..f95571a0 100644 --- a/backend/src/data/GuildMutes.ts +++ b/backend/src/data/GuildMutes.ts @@ -35,12 +35,7 @@ export class GuildMutes extends BaseGuildRepository { } async addMute(userId, expiryTime, rolesToRestore?: string[]): Promise { - const expiresAt = expiryTime - ? moment - .utc() - .add(expiryTime, "ms") - .format("YYYY-MM-DD HH:mm:ss") - : null; + const expiresAt = expiryTime ? moment.utc().add(expiryTime, "ms").format("YYYY-MM-DD HH:mm:ss") : null; const result = await this.mutes.insert({ guild_id: this.guildId, @@ -53,12 +48,7 @@ export class GuildMutes extends BaseGuildRepository { } async updateExpiryTime(userId, newExpiryTime, rolesToRestore?: string[]) { - const expiresAt = newExpiryTime - ? moment - .utc() - .add(newExpiryTime, "ms") - .format("YYYY-MM-DD HH:mm:ss") - : null; + const expiresAt = newExpiryTime ? moment.utc().add(newExpiryTime, "ms").format("YYYY-MM-DD HH:mm:ss") : null; if (rolesToRestore && rolesToRestore.length) { return this.mutes.update( @@ -89,7 +79,7 @@ export class GuildMutes extends BaseGuildRepository { .createQueryBuilder("mutes") .where("guild_id = :guild_id", { guild_id: this.guildId }) .andWhere( - new Brackets(qb => { + new Brackets((qb) => { qb.where("expires_at > NOW()").orWhere("expires_at IS NULL"); }), ) diff --git a/backend/src/data/GuildNicknameHistory.ts b/backend/src/data/GuildNicknameHistory.ts index 51ed863c..9f75d24e 100644 --- a/backend/src/data/GuildNicknameHistory.ts +++ b/backend/src/data/GuildNicknameHistory.ts @@ -70,7 +70,7 @@ export class GuildNicknameHistory extends BaseGuildRepository { if (toDelete.length > 0) { await this.nicknameHistory.delete({ - id: In(toDelete.map(v => v.id)), + id: In(toDelete.map((v) => v.id)), }); } } diff --git a/backend/src/data/GuildSavedMessages.ts b/backend/src/data/GuildSavedMessages.ts index 462df642..6d1e29c5 100644 --- a/backend/src/data/GuildSavedMessages.ts +++ b/backend/src/data/GuildSavedMessages.ts @@ -46,7 +46,7 @@ export class GuildSavedMessages extends BaseGuildRepository { }; if (msg.attachments.size) { - data.attachments = Array.from(msg.attachments.values()).map(att => ({ + data.attachments = Array.from(msg.attachments.values()).map((att) => ({ id: att.id, contentType: att.contentType, name: att.name, @@ -59,14 +59,14 @@ export class GuildSavedMessages extends BaseGuildRepository { } if (msg.embeds.length) { - data.embeds = msg.embeds.map(embed => ({ + data.embeds = msg.embeds.map((embed) => ({ title: embed.title, description: embed.description, url: embed.url, timestamp: embed.timestamp, color: embed.color, - fields: embed.fields.map(field => ({ + fields: embed.fields.map((field) => ({ name: field.name, value: field.value, inline: field.inline, @@ -119,7 +119,7 @@ export class GuildSavedMessages extends BaseGuildRepository { } if (msg.stickers?.size) { - data.stickers = Array.from(msg.stickers.values()).map(sticker => ({ + data.stickers = Array.from(msg.stickers.values()).map((sticker) => ({ format: sticker.format, guildId: sticker.guildId, id: sticker.id, diff --git a/backend/src/data/GuildScheduledPosts.ts b/backend/src/data/GuildScheduledPosts.ts index c302b81e..b2f32d54 100644 --- a/backend/src/data/GuildScheduledPosts.ts +++ b/backend/src/data/GuildScheduledPosts.ts @@ -11,10 +11,7 @@ export class GuildScheduledPosts extends BaseGuildRepository { } all(): Promise { - return this.scheduledPosts - .createQueryBuilder() - .where("guild_id = :guildId", { guildId: this.guildId }) - .getMany(); + return this.scheduledPosts.createQueryBuilder().where("guild_id = :guildId", { guildId: this.guildId }).getMany(); } getDueScheduledPosts(): Promise { diff --git a/backend/src/data/GuildSlowmodes.ts b/backend/src/data/GuildSlowmodes.ts index b6452490..dac92ead 100644 --- a/backend/src/data/GuildSlowmodes.ts +++ b/backend/src/data/GuildSlowmodes.ts @@ -67,10 +67,7 @@ export class GuildSlowmodes extends BaseGuildRepository { const slowmode = await this.getChannelSlowmode(channelId); if (!slowmode) return; - const expiresAt = moment - .utc() - .add(slowmode.slowmode_seconds, "seconds") - .format("YYYY-MM-DD HH:mm:ss"); + const expiresAt = moment.utc().add(slowmode.slowmode_seconds, "seconds").format("YYYY-MM-DD HH:mm:ss"); if (await this.userHasSlowmode(channelId, userId)) { // Update existing diff --git a/backend/src/data/GuildTempbans.ts b/backend/src/data/GuildTempbans.ts index f5f52143..6085a193 100644 --- a/backend/src/data/GuildTempbans.ts +++ b/backend/src/data/GuildTempbans.ts @@ -30,10 +30,7 @@ export class GuildTempbans extends BaseGuildRepository { } async addTempban(userId, expiryTime, modId): Promise { - const expiresAt = moment - .utc() - .add(expiryTime, "ms") - .format("YYYY-MM-DD HH:mm:ss"); + const expiresAt = moment.utc().add(expiryTime, "ms").format("YYYY-MM-DD HH:mm:ss"); const result = await this.tempbans.insert({ guild_id: this.guildId, @@ -47,10 +44,7 @@ export class GuildTempbans extends BaseGuildRepository { } async updateExpiryTime(userId, newExpiryTime, modId) { - const expiresAt = moment - .utc() - .add(newExpiryTime, "ms") - .format("YYYY-MM-DD HH:mm:ss"); + const expiresAt = moment.utc().add(newExpiryTime, "ms").format("YYYY-MM-DD HH:mm:ss"); return this.tempbans.update( { diff --git a/backend/src/data/GuildVCAlerts.ts b/backend/src/data/GuildVCAlerts.ts index 4c64c197..4736204a 100644 --- a/backend/src/data/GuildVCAlerts.ts +++ b/backend/src/data/GuildVCAlerts.ts @@ -19,10 +19,7 @@ export class GuildVCAlerts extends BaseGuildRepository { } async getAllGuildAlerts(): Promise { - return this.allAlerts - .createQueryBuilder() - .where("guild_id = :guildId", { guildId: this.guildId }) - .getMany(); + return this.allAlerts.createQueryBuilder().where("guild_id = :guildId", { guildId: this.guildId }).getMany(); } async getAlertsByUserId(userId: string): Promise { diff --git a/backend/src/data/UsernameHistory.ts b/backend/src/data/UsernameHistory.ts index c17a747c..7aa4331a 100644 --- a/backend/src/data/UsernameHistory.ts +++ b/backend/src/data/UsernameHistory.ts @@ -67,7 +67,7 @@ export class UsernameHistory extends BaseRepository { if (toDelete.length > 0) { await this.usernameHistory.delete({ - id: In(toDelete.map(v => v.id)), + id: In(toDelete.map((v) => v.id)), }); } } diff --git a/backend/src/data/cleanup/configs.ts b/backend/src/data/cleanup/configs.ts index 252b6c6d..1d22ea52 100644 --- a/backend/src/data/cleanup/configs.ts +++ b/backend/src/data/cleanup/configs.ts @@ -13,10 +13,7 @@ export async function cleanupConfigs() { let rows; // >1 month old: 1 config retained per month - const oneMonthCutoff = moment - .utc() - .subtract(30, "days") - .format(DBDateFormat); + const oneMonthCutoff = moment.utc().subtract(30, "days").format(DBDateFormat); do { rows = await connection.query( ` @@ -46,7 +43,7 @@ export async function cleanupConfigs() { if (rows.length > 0) { await configRepository.delete({ - id: In(rows.map(r => r.id)), + id: In(rows.map((r) => r.id)), }); } @@ -54,10 +51,7 @@ export async function cleanupConfigs() { } while (rows.length === CLEAN_PER_LOOP); // >2 weeks old: 1 config retained per day - const twoWeekCutoff = moment - .utc() - .subtract(2, "weeks") - .format(DBDateFormat); + const twoWeekCutoff = moment.utc().subtract(2, "weeks").format(DBDateFormat); do { rows = await connection.query( ` @@ -87,7 +81,7 @@ export async function cleanupConfigs() { if (rows.length > 0) { await configRepository.delete({ - id: In(rows.map(r => r.id)), + id: In(rows.map((r) => r.id)), }); } diff --git a/backend/src/data/cleanup/messages.ts b/backend/src/data/cleanup/messages.ts index 06d55c99..0a5d038b 100644 --- a/backend/src/data/cleanup/messages.ts +++ b/backend/src/data/cleanup/messages.ts @@ -18,18 +18,9 @@ export async function cleanupMessages(): Promise { const messagesRepository = getRepository(SavedMessage); - const deletedAtThreshold = moment - .utc() - .subtract(DELETED_MESSAGE_RETENTION_PERIOD, "ms") - .format(DBDateFormat); - const postedAtThreshold = moment - .utc() - .subtract(RETENTION_PERIOD, "ms") - .format(DBDateFormat); - const botPostedAtThreshold = moment - .utc() - .subtract(BOT_MESSAGE_RETENTION_PERIOD, "ms") - .format(DBDateFormat); + const deletedAtThreshold = moment.utc().subtract(DELETED_MESSAGE_RETENTION_PERIOD, "ms").format(DBDateFormat); + const postedAtThreshold = moment.utc().subtract(RETENTION_PERIOD, "ms").format(DBDateFormat); + const botPostedAtThreshold = moment.utc().subtract(BOT_MESSAGE_RETENTION_PERIOD, "ms").format(DBDateFormat); // SELECT + DELETE messages in batches // This is to avoid deadlocks that happened frequently when deleting with the same criteria as the select below @@ -60,7 +51,7 @@ export async function cleanupMessages(): Promise { if (rows.length > 0) { await messagesRepository.delete({ - id: In(rows.map(r => r.id)), + id: In(rows.map((r) => r.id)), }); } diff --git a/backend/src/data/cleanup/nicknames.ts b/backend/src/data/cleanup/nicknames.ts index 4907e004..addaa347 100644 --- a/backend/src/data/cleanup/nicknames.ts +++ b/backend/src/data/cleanup/nicknames.ts @@ -11,10 +11,7 @@ export async function cleanupNicknames(): Promise { let cleaned = 0; const nicknameHistoryRepository = getRepository(NicknameHistoryEntry); - const dateThreshold = moment - .utc() - .subtract(NICKNAME_RETENTION_PERIOD, "ms") - .format(DBDateFormat); + const dateThreshold = moment.utc().subtract(NICKNAME_RETENTION_PERIOD, "ms").format(DBDateFormat); // Clean old nicknames (NICKNAME_RETENTION_PERIOD) let rows; @@ -31,7 +28,7 @@ export async function cleanupNicknames(): Promise { if (rows.length > 0) { await nicknameHistoryRepository.delete({ - id: In(rows.map(r => r.id)), + id: In(rows.map((r) => r.id)), }); } diff --git a/backend/src/data/cleanup/usernames.ts b/backend/src/data/cleanup/usernames.ts index eea441d5..63ac79f8 100644 --- a/backend/src/data/cleanup/usernames.ts +++ b/backend/src/data/cleanup/usernames.ts @@ -11,10 +11,7 @@ export async function cleanupUsernames(): Promise { let cleaned = 0; const usernameHistoryRepository = getRepository(UsernameHistoryEntry); - const dateThreshold = moment - .utc() - .subtract(USERNAME_RETENTION_PERIOD, "ms") - .format(DBDateFormat); + const dateThreshold = moment.utc().subtract(USERNAME_RETENTION_PERIOD, "ms").format(DBDateFormat); // Clean old usernames (USERNAME_RETENTION_PERIOD) let rows; @@ -31,7 +28,7 @@ export async function cleanupUsernames(): Promise { if (rows.length > 0) { await usernameHistoryRepository.delete({ - id: In(rows.map(r => r.id)), + id: In(rows.map((r) => r.id)), }); } diff --git a/backend/src/data/db.ts b/backend/src/data/db.ts index 9888d0b5..42ac5d38 100644 --- a/backend/src/data/db.ts +++ b/backend/src/data/db.ts @@ -7,9 +7,9 @@ export let connection: Connection; export function connect() { if (!connectionPromise) { - connectionPromise = createConnection().then(newConnection => { + connectionPromise = createConnection().then((newConnection) => { // Verify the DB timezone is set to UTC - return newConnection.query("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) AS tz").then(r => { + return newConnection.query("SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) AS tz").then((r) => { if (r[0].tz !== "00:00:00") { throw new SimpleError(`Database timezone must be UTC (detected ${r[0].tz})`); } diff --git a/backend/src/data/entities/ApiLogin.ts b/backend/src/data/entities/ApiLogin.ts index 25f2405a..0cc35f39 100644 --- a/backend/src/data/entities/ApiLogin.ts +++ b/backend/src/data/entities/ApiLogin.ts @@ -19,10 +19,7 @@ export class ApiLogin { @Column() expires_at: string; - @ManyToOne( - type => ApiUserInfo, - userInfo => userInfo.logins, - ) + @ManyToOne((type) => ApiUserInfo, (userInfo) => userInfo.logins) @JoinColumn({ name: "user_id" }) userInfo: ApiUserInfo; } diff --git a/backend/src/data/entities/ApiPermissionAssignment.ts b/backend/src/data/entities/ApiPermissionAssignment.ts index 349544d5..0160241f 100644 --- a/backend/src/data/entities/ApiPermissionAssignment.ts +++ b/backend/src/data/entities/ApiPermissionAssignment.ts @@ -22,10 +22,7 @@ export class ApiPermissionAssignment { @Column({ type: String, nullable: true }) expires_at: string | null; - @ManyToOne( - type => ApiUserInfo, - userInfo => userInfo.permissionAssignments, - ) + @ManyToOne((type) => ApiUserInfo, (userInfo) => userInfo.permissionAssignments) @JoinColumn({ name: "target_id" }) userInfo: ApiUserInfo; } diff --git a/backend/src/data/entities/ApiUserInfo.ts b/backend/src/data/entities/ApiUserInfo.ts index 32c3a1b0..b6146b23 100644 --- a/backend/src/data/entities/ApiUserInfo.ts +++ b/backend/src/data/entities/ApiUserInfo.ts @@ -20,15 +20,9 @@ export class ApiUserInfo { @Column() updated_at: string; - @OneToMany( - type => ApiLogin, - login => login.userInfo, - ) + @OneToMany((type) => ApiLogin, (login) => login.userInfo) logins: ApiLogin[]; - @OneToMany( - type => ApiPermissionAssignment, - p => p.userInfo, - ) + @OneToMany((type) => ApiPermissionAssignment, (p) => p.userInfo) permissionAssignments: ApiPermissionAssignment[]; } diff --git a/backend/src/data/entities/Case.ts b/backend/src/data/entities/Case.ts index f8980b33..84d24618 100644 --- a/backend/src/data/entities/Case.ts +++ b/backend/src/data/entities/Case.ts @@ -35,9 +35,6 @@ export class Case { */ @Column({ type: String, nullable: true }) log_message_id: string | null; - @OneToMany( - type => CaseNote, - note => note.case, - ) + @OneToMany((type) => CaseNote, (note) => note.case) notes: CaseNote[]; } diff --git a/backend/src/data/entities/CaseNote.ts b/backend/src/data/entities/CaseNote.ts index 3f2e8125..f883d79f 100644 --- a/backend/src/data/entities/CaseNote.ts +++ b/backend/src/data/entities/CaseNote.ts @@ -15,10 +15,7 @@ export class CaseNote { @Column() created_at: string; - @ManyToOne( - type => Case, - theCase => theCase.notes, - ) + @ManyToOne((type) => Case, (theCase) => theCase.notes) @JoinColumn({ name: "case_id" }) case: Case; } diff --git a/backend/src/data/entities/Config.ts b/backend/src/data/entities/Config.ts index 8e16514e..d5e391b4 100644 --- a/backend/src/data/entities/Config.ts +++ b/backend/src/data/entities/Config.ts @@ -22,7 +22,7 @@ export class Config { @Column() edited_at: string; - @ManyToOne(type => ApiUserInfo) + @ManyToOne((type) => ApiUserInfo) @JoinColumn({ name: "edited_by" }) userInfo: ApiUserInfo; } diff --git a/backend/src/data/entities/StarboardMessage.ts b/backend/src/data/entities/StarboardMessage.ts index 405222c1..2d8839e6 100644 --- a/backend/src/data/entities/StarboardMessage.ts +++ b/backend/src/data/entities/StarboardMessage.ts @@ -16,7 +16,7 @@ export class StarboardMessage { @Column() guild_id: string; - @OneToOne(type => SavedMessage) + @OneToOne((type) => SavedMessage) @JoinColumn({ name: "message_id" }) message: SavedMessage; } diff --git a/backend/src/data/entities/StarboardReaction.ts b/backend/src/data/entities/StarboardReaction.ts index 8e04a8fb..c2cb0258 100644 --- a/backend/src/data/entities/StarboardReaction.ts +++ b/backend/src/data/entities/StarboardReaction.ts @@ -16,7 +16,7 @@ export class StarboardReaction { @Column() reactor_id: string; - @OneToOne(type => SavedMessage) + @OneToOne((type) => SavedMessage) @JoinColumn({ name: "message_id" }) message: SavedMessage; } diff --git a/backend/src/index.ts b/backend/src/index.ts index 3022f7a7..3b7e1e17 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -144,8 +144,8 @@ if (process.env.NODE_ENV === "production") { // Verify required Node.js version const REQUIRED_NODE_VERSION = "14.0.0"; -const requiredParts = REQUIRED_NODE_VERSION.split(".").map(v => parseInt(v, 10)); -const actualVersionParts = process.versions.node.split(".").map(v => parseInt(v, 10)); +const requiredParts = REQUIRED_NODE_VERSION.split(".").map((v) => parseInt(v, 10)); +const actualVersionParts = process.versions.node.split(".").map((v) => parseInt(v, 10)); for (const [i, part] of actualVersionParts.entries()) { if (part > requiredParts[i]) break; if (part === requiredParts[i]) continue; @@ -188,7 +188,7 @@ connect().then(async () => { }); client.setMaxListeners(200); - client.on(Constants.Events.RATE_LIMIT, data => { + client.on(Constants.Events.RATE_LIMIT, (data) => { // tslint:disable-next-line:no-console // console.log(`[DEBUG] [RATE_LIMIT] ${JSON.stringify(data)}`); }); @@ -196,7 +196,7 @@ connect().then(async () => { const safe429DecayInterval = 5 * SECONDS; const safe429MaxCount = 5; const safe429Counter = new DecayingCounter(safe429DecayInterval); - client.on(Constants.Events.DEBUG, errorText => { + client.on(Constants.Events.DEBUG, (errorText) => { if (!errorText.includes("429")) { return; } @@ -212,7 +212,7 @@ connect().then(async () => { } }); - client.on("error", err => { + client.on("error", (err) => { errorHandler(new DiscordJSError(err.message, (err as any).code, 0)); }); @@ -240,9 +240,9 @@ connect().then(async () => { } const configuredPlugins = ctx.config.plugins; - const basePluginNames = baseGuildPlugins.map(p => p.name); + const basePluginNames = baseGuildPlugins.map((p) => p.name); - return Array.from(plugins.keys()).filter(pluginName => { + return Array.from(plugins.keys()).filter((pluginName) => { if (basePluginNames.includes(pluginName)) return true; return configuredPlugins[pluginName] && configuredPlugins[pluginName].enabled !== false; }); @@ -308,14 +308,14 @@ connect().then(async () => { }); const debugGuilds = ["877581055920603238", "348468156597010432", "134286179121102848"]; - bot.on("guildLoaded", guildId => { + bot.on("guildLoaded", (guildId) => { if (!debugGuilds.includes(guildId)) { return; } console.log(`[!! DEBUG !!] LOADED GUILD ${guildId}`); }); - bot.on("guildUnloaded", guildId => { + bot.on("guildUnloaded", (guildId) => { if (!debugGuilds.includes(guildId)) { return; } diff --git a/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts b/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts index f15417ef..a42c0c7f 100644 --- a/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts +++ b/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts @@ -9,7 +9,7 @@ export class MigrateUsernamesToNewHistoryTable1556909512501 implements Migration const migratedUsernames = new Set(); - await new Promise(async resolve => { + await new Promise(async (resolve) => { const stream = await queryRunner.stream("SELECT CONCAT(user_id, '-', username) AS `key` FROM username_history"); stream.on("data", (row: any) => { migratedUsernames.add(row.key); @@ -18,7 +18,7 @@ export class MigrateUsernamesToNewHistoryTable1556909512501 implements Migration }); const migrateNextBatch = (): Promise<{ finished: boolean; migrated?: number }> => { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const toInsert: any[][] = []; const toDelete: number[] = []; diff --git a/backend/src/pluginUtils.ts b/backend/src/pluginUtils.ts index 8e0cfaf6..f9093ad1 100644 --- a/backend/src/pluginUtils.ts +++ b/backend/src/pluginUtils.ts @@ -85,7 +85,7 @@ export function strictValidationErrorToConfigValidationError(err: StrictValidati return new ConfigValidationError( err .getErrors() - .map(e => e.toString()) + .map((e) => e.toString()) .join("\n"), ); } @@ -199,7 +199,7 @@ export async function sendSuccessMessage( return channel .send({ ...content }) // Force line break - .catch(err => { + .catch((err) => { const channelInfo = channel.guild ? `${channel.id} (${channel.guild.id})` : channel.id; logger.warn(`Failed to send success message to ${channelInfo}): ${err.code} ${err.message}`); return undefined; @@ -220,7 +220,7 @@ export async function sendErrorMessage( return channel .send({ ...content }) // Force line break - .catch(err => { + .catch((err) => { const channelInfo = channel.guild ? `${channel.id} (${channel.guild.id})` : channel.id; logger.warn(`Failed to send error message to ${channelInfo}): ${err.code} ${err.message}`); return undefined; @@ -252,7 +252,7 @@ type AnyFn = (...args: any[]) => any; * Creates a public plugin function out of a function with pluginData as the first parameter */ export function mapToPublicFn(inputFn: T) { - return pluginData => { + return (pluginData) => { return (...args: Tail>): ReturnType => { return inputFn(pluginData, ...args); }; diff --git a/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts b/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts index 593ffb31..6c8251b8 100644 --- a/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts +++ b/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts @@ -45,13 +45,13 @@ export const AutoDeletePlugin = zeppelinGuildPlugin()({ afterLoad(pluginData) { const { state, guild } = pluginData; - state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg); + state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg); state.guildSavedMessages.events.on("create", state.onMessageCreateFn); - state.onMessageDeleteFn = msg => onMessageDelete(pluginData, msg); + state.onMessageDeleteFn = (msg) => onMessageDelete(pluginData, msg); state.guildSavedMessages.events.on("delete", state.onMessageDeleteFn); - state.onMessageDeleteBulkFn = msgs => onMessageDeleteBulk(pluginData, msgs); + state.onMessageDeleteBulkFn = (msgs) => onMessageDeleteBulk(pluginData, msgs); state.guildSavedMessages.events.on("deleteBulk", state.onMessageDeleteBulkFn); }, diff --git a/backend/src/plugins/AutoDelete/util/deleteNextItem.ts b/backend/src/plugins/AutoDelete/util/deleteNextItem.ts index 07ffec69..9ff6a8f0 100644 --- a/backend/src/plugins/AutoDelete/util/deleteNextItem.ts +++ b/backend/src/plugins/AutoDelete/util/deleteNextItem.ts @@ -45,7 +45,7 @@ export async function deleteNextItem(pluginData: GuildPluginData { + (channel as TextChannel).messages.delete(itemToDelete.message.id as Snowflake).catch((err) => { if (err.code === 10008) { // "Unknown Message", probably already deleted by automod or another bot, ignore return; diff --git a/backend/src/plugins/AutoDelete/util/onMessageDelete.ts b/backend/src/plugins/AutoDelete/util/onMessageDelete.ts index 48b7bb72..984a7850 100644 --- a/backend/src/plugins/AutoDelete/util/onMessageDelete.ts +++ b/backend/src/plugins/AutoDelete/util/onMessageDelete.ts @@ -4,7 +4,7 @@ import { AutoDeletePluginType } from "../types"; import { scheduleNextDeletion } from "./scheduleNextDeletion"; export function onMessageDelete(pluginData: GuildPluginData, msg: SavedMessage) { - const indexToDelete = pluginData.state.deletionQueue.findIndex(item => item.message.id === msg.id); + const indexToDelete = pluginData.state.deletionQueue.findIndex((item) => item.message.id === msg.id); if (indexToDelete > -1) { pluginData.state.deletionQueue.splice(indexToDelete, 1); scheduleNextDeletion(pluginData); diff --git a/backend/src/plugins/Automod/AutomodPlugin.ts b/backend/src/plugins/Automod/AutomodPlugin.ts index 60f55296..9a9cbc76 100644 --- a/backend/src/plugins/Automod/AutomodPlugin.ts +++ b/backend/src/plugins/Automod/AutomodPlugin.ts @@ -57,7 +57,7 @@ const defaultOptions = { /** * Config preprocessor to set default values for triggers and perform extra validation */ -const configPreprocessor: ConfigPreprocessorFn = options => { +const configPreprocessor: ConfigPreprocessorFn = (options) => { if (options.config?.rules) { // Loop through each rule for (const [name, rule] of Object.entries(options.config.rules)) { @@ -232,10 +232,10 @@ export const AutomodPlugin = zeppelinGuildPlugin()({ 30 * SECONDS, ); - pluginData.state.onMessageCreateFn = message => runAutomodOnMessage(pluginData, message, false); + pluginData.state.onMessageCreateFn = (message) => runAutomodOnMessage(pluginData, message, false); pluginData.state.savedMessages.events.on("create", pluginData.state.onMessageCreateFn); - pluginData.state.onMessageUpdateFn = message => runAutomodOnMessage(pluginData, message, true); + pluginData.state.onMessageUpdateFn = (message) => runAutomodOnMessage(pluginData, message, true); pluginData.state.savedMessages.events.on("update", pluginData.state.onMessageUpdateFn); const countersPlugin = pluginData.getPlugin(CountersPlugin); diff --git a/backend/src/plugins/Automod/actions/addRoles.ts b/backend/src/plugins/Automod/actions/addRoles.ts index c39cc5e7..ee577ae9 100644 --- a/backend/src/plugins/Automod/actions/addRoles.ts +++ b/backend/src/plugins/Automod/actions/addRoles.ts @@ -17,7 +17,7 @@ export const AddRolesAction = automodAction({ defaultConfig: [], async apply({ pluginData, contexts, actionConfig, ruleName }) { - const members = unique(contexts.map(c => c.member).filter(nonNullish)); + const members = unique(contexts.map((c) => c.member).filter(nonNullish)); const me = pluginData.guild.members.cache.get(pluginData.client.user!.id)!; const missingPermissions = getMissingPermissions(me.permissions, p.MANAGE_ROLES); @@ -41,7 +41,7 @@ export const AddRolesAction = automodAction({ if (rolesWeCannotAssign.length) { const roleNamesWeCannotAssign = rolesWeCannotAssign.map( - roleId => pluginData.guild.roles.cache.get(roleId as Snowflake)?.name || roleId, + (roleId) => pluginData.guild.roles.cache.get(roleId as Snowflake)?.name || roleId, ); const logs = pluginData.getPlugin(LogsPlugin); logs.logBotAlert({ @@ -52,7 +52,7 @@ export const AddRolesAction = automodAction({ } await Promise.all( - members.map(async member => { + members.map(async (member) => { const memberRoles = new Set(member.roles.cache.keys()); for (const roleId of rolesToAssign) { memberRoles.add(roleId as Snowflake); diff --git a/backend/src/plugins/Automod/actions/alert.ts b/backend/src/plugins/Automod/actions/alert.ts index 314bb552..b765811e 100644 --- a/backend/src/plugins/Automod/actions/alert.ts +++ b/backend/src/plugins/Automod/actions/alert.ts @@ -41,7 +41,7 @@ export const AlertAction = automodAction({ const theMessageLink = contexts[0].message && messageLink(pluginData.guild.id, contexts[0].message.channel_id, contexts[0].message.id); - const safeUsers = contexts.map(c => (c.user ? userToTemplateSafeUser(c.user) : null)).filter(isTruthy); + const safeUsers = contexts.map((c) => (c.user ? userToTemplateSafeUser(c.user) : null)).filter(isTruthy); const safeUser = safeUsers[0]; const actionsTaken = Object.keys(pluginData.config.get().rules[ruleName].actions).join(", "); diff --git a/backend/src/plugins/Automod/actions/archiveThread.ts b/backend/src/plugins/Automod/actions/archiveThread.ts index 7c7aa218..6fe871a5 100644 --- a/backend/src/plugins/Automod/actions/archiveThread.ts +++ b/backend/src/plugins/Automod/actions/archiveThread.ts @@ -9,8 +9,8 @@ export const ArchiveThreadAction = automodAction({ async apply({ pluginData, contexts }) { const threads = contexts - .filter(c => c.message?.channel_id) - .map(c => pluginData.guild.channels.cache.get(c.message!.channel_id)) + .filter((c) => c.message?.channel_id) + .map((c) => pluginData.guild.channels.cache.get(c.message!.channel_id)) .filter((c): c is ThreadChannel => c?.isThread() ?? false); for (const thread of threads) { diff --git a/backend/src/plugins/Automod/actions/ban.ts b/backend/src/plugins/Automod/actions/ban.ts index ff92be3a..e32279a7 100644 --- a/backend/src/plugins/Automod/actions/ban.ts +++ b/backend/src/plugins/Automod/actions/ban.ts @@ -35,7 +35,7 @@ export const BanAction = automodAction({ hide: Boolean(actionConfig.hide_case), }; - const userIdsToBan = unique(contexts.map(c => c.user?.id).filter(nonNullish)); + const userIdsToBan = unique(contexts.map((c) => c.user?.id).filter(nonNullish)); const modActions = pluginData.getPlugin(ModActionsPlugin); for (const userId of userIdsToBan) { diff --git a/backend/src/plugins/Automod/actions/changeNickname.ts b/backend/src/plugins/Automod/actions/changeNickname.ts index ed2db27c..0a368355 100644 --- a/backend/src/plugins/Automod/actions/changeNickname.ts +++ b/backend/src/plugins/Automod/actions/changeNickname.ts @@ -15,13 +15,13 @@ export const ChangeNicknameAction = automodAction({ defaultConfig: {}, async apply({ pluginData, contexts, actionConfig }) { - const members = unique(contexts.map(c => c.member).filter(nonNullish)); + const members = unique(contexts.map((c) => c.member).filter(nonNullish)); for (const member of members) { if (pluginData.state.recentNicknameChanges.has(member.id)) continue; const newName = typeof actionConfig === "string" ? actionConfig : actionConfig.name; - member.edit({ nick: newName }).catch(err => { + member.edit({ nick: newName }).catch((err) => { pluginData.getPlugin(LogsPlugin).logBotAlert({ body: `Failed to change the nickname of \`${member.id}\``, }); diff --git a/backend/src/plugins/Automod/actions/kick.ts b/backend/src/plugins/Automod/actions/kick.ts index 98408da3..9e6a792d 100644 --- a/backend/src/plugins/Automod/actions/kick.ts +++ b/backend/src/plugins/Automod/actions/kick.ts @@ -31,8 +31,8 @@ export const KickAction = automodAction({ hide: Boolean(actionConfig.hide_case), }; - const userIdsToKick = unique(contexts.map(c => c.user?.id).filter(nonNullish)); - const membersToKick = await asyncMap(userIdsToKick, id => resolveMember(pluginData.client, pluginData.guild, id)); + const userIdsToKick = unique(contexts.map((c) => c.user?.id).filter(nonNullish)); + const membersToKick = await asyncMap(userIdsToKick, (id) => resolveMember(pluginData.client, pluginData.guild, id)); const modActions = pluginData.getPlugin(ModActionsPlugin); for (const member of membersToKick) { diff --git a/backend/src/plugins/Automod/actions/log.ts b/backend/src/plugins/Automod/actions/log.ts index 4a78442d..62f57a20 100644 --- a/backend/src/plugins/Automod/actions/log.ts +++ b/backend/src/plugins/Automod/actions/log.ts @@ -10,7 +10,7 @@ export const LogAction = automodAction({ defaultConfig: true, async apply({ pluginData, contexts, ruleName, matchResult }) { - const users = unique(contexts.map(c => c.user)).filter(isTruthy); + const users = unique(contexts.map((c) => c.user)).filter(isTruthy); const user = users[0]; const actionsTaken = Object.keys(pluginData.config.get().rules[ruleName].actions).join(", "); diff --git a/backend/src/plugins/Automod/actions/mute.ts b/backend/src/plugins/Automod/actions/mute.ts index 8d4aee6a..a1bb9299 100644 --- a/backend/src/plugins/Automod/actions/mute.ts +++ b/backend/src/plugins/Automod/actions/mute.ts @@ -40,7 +40,7 @@ export const MuteAction = automodAction({ hide: Boolean(actionConfig.hide_case), }; - const userIdsToMute = unique(contexts.map(c => c.user?.id).filter(nonNullish)); + const userIdsToMute = unique(contexts.map((c) => c.user?.id).filter(nonNullish)); const mutes = pluginData.getPlugin(MutesPlugin); for (const userId of userIdsToMute) { diff --git a/backend/src/plugins/Automod/actions/removeRoles.ts b/backend/src/plugins/Automod/actions/removeRoles.ts index 690af257..62b71480 100644 --- a/backend/src/plugins/Automod/actions/removeRoles.ts +++ b/backend/src/plugins/Automod/actions/removeRoles.ts @@ -18,7 +18,7 @@ export const RemoveRolesAction = automodAction({ defaultConfig: [], async apply({ pluginData, contexts, actionConfig, ruleName }) { - const members = unique(contexts.map(c => c.member).filter(nonNullish)); + const members = unique(contexts.map((c) => c.member).filter(nonNullish)); const me = pluginData.guild.members.cache.get(pluginData.client.user!.id)!; const missingPermissions = getMissingPermissions(me.permissions, p.MANAGE_ROLES); @@ -42,7 +42,7 @@ export const RemoveRolesAction = automodAction({ if (rolesWeCannotRemove.length) { const roleNamesWeCannotRemove = rolesWeCannotRemove.map( - roleId => pluginData.guild.roles.cache.get(roleId as Snowflake)?.name || roleId, + (roleId) => pluginData.guild.roles.cache.get(roleId as Snowflake)?.name || roleId, ); const logs = pluginData.getPlugin(LogsPlugin); logs.logBotAlert({ @@ -53,7 +53,7 @@ export const RemoveRolesAction = automodAction({ } await Promise.all( - members.map(async member => { + members.map(async (member) => { const memberRoles = new Set(member.roles.cache.keys()); for (const roleId of rolesToRemove) { memberRoles.delete(roleId as Snowflake); diff --git a/backend/src/plugins/Automod/actions/reply.ts b/backend/src/plugins/Automod/actions/reply.ts index bac6f105..efe833cb 100644 --- a/backend/src/plugins/Automod/actions/reply.ts +++ b/backend/src/plugins/Automod/actions/reply.ts @@ -32,8 +32,8 @@ export const ReplyAction = automodAction({ async apply({ pluginData, contexts, actionConfig, ruleName }) { const contextsWithTextChannels = contexts - .filter(c => c.message?.channel_id) - .filter(c => { + .filter((c) => c.message?.channel_id) + .filter((c) => { const channel = pluginData.guild.channels.cache.get(c.message!.channel_id as Snowflake); return channel instanceof TextChannel || channel instanceof ThreadChannel; }); @@ -48,7 +48,7 @@ export const ReplyAction = automodAction({ }, new Map()); for (const [channelId, _contexts] of contextsByChannelId.entries()) { - const users = unique(Array.from(new Set(_contexts.map(c => c.user).filter(Boolean)))) as User[]; + const users = unique(Array.from(new Set(_contexts.map((c) => c.user).filter(Boolean)))) as User[]; const user = users[0]; const renderReplyText = async (str: string) => diff --git a/backend/src/plugins/Automod/actions/warn.ts b/backend/src/plugins/Automod/actions/warn.ts index 29dd4955..59135cb2 100644 --- a/backend/src/plugins/Automod/actions/warn.ts +++ b/backend/src/plugins/Automod/actions/warn.ts @@ -31,8 +31,8 @@ export const WarnAction = automodAction({ hide: Boolean(actionConfig.hide_case), }; - const userIdsToWarn = unique(contexts.map(c => c.user?.id).filter(nonNullish)); - const membersToWarn = await asyncMap(userIdsToWarn, id => resolveMember(pluginData.client, pluginData.guild, id)); + const userIdsToWarn = unique(contexts.map((c) => c.user?.id).filter(nonNullish)); + const membersToWarn = await asyncMap(userIdsToWarn, (id) => resolveMember(pluginData.client, pluginData.guild, id)); const modActions = pluginData.getPlugin(ModActionsPlugin); for (const member of membersToWarn) { diff --git a/backend/src/plugins/Automod/functions/clearOldRecentActions.ts b/backend/src/plugins/Automod/functions/clearOldRecentActions.ts index 67a79718..9293e9c3 100644 --- a/backend/src/plugins/Automod/functions/clearOldRecentActions.ts +++ b/backend/src/plugins/Automod/functions/clearOldRecentActions.ts @@ -4,7 +4,7 @@ import { AutomodPluginType } from "../types"; export function clearOldRecentActions(pluginData: GuildPluginData) { const now = Date.now(); - pluginData.state.recentActions = pluginData.state.recentActions.filter(info => { + pluginData.state.recentActions = pluginData.state.recentActions.filter((info) => { return info.context.timestamp + RECENT_ACTION_EXPIRY_TIME > now; }); } diff --git a/backend/src/plugins/Automod/functions/clearOldRecentSpam.ts b/backend/src/plugins/Automod/functions/clearOldRecentSpam.ts index a0f34c8b..7cda8329 100644 --- a/backend/src/plugins/Automod/functions/clearOldRecentSpam.ts +++ b/backend/src/plugins/Automod/functions/clearOldRecentSpam.ts @@ -4,7 +4,7 @@ import { AutomodPluginType } from "../types"; export function clearOldRecentSpam(pluginData: GuildPluginData) { const now = Date.now(); - pluginData.state.recentSpam = pluginData.state.recentSpam.filter(spam => { + pluginData.state.recentSpam = pluginData.state.recentSpam.filter((spam) => { return spam.timestamp + RECENT_SPAM_EXPIRY_TIME > now; }); } diff --git a/backend/src/plugins/Automod/functions/clearRecentActionsForMessage.ts b/backend/src/plugins/Automod/functions/clearRecentActionsForMessage.ts index 7aa9750a..e1cadc58 100644 --- a/backend/src/plugins/Automod/functions/clearRecentActionsForMessage.ts +++ b/backend/src/plugins/Automod/functions/clearRecentActionsForMessage.ts @@ -6,7 +6,7 @@ export function clearRecentActionsForMessage(pluginData: GuildPluginData { + pluginData.state.recentActions = pluginData.state.recentActions.filter((act) => { return act.identifier !== globalIdentifier && act.identifier !== perChannelIdentifier; }); } diff --git a/backend/src/plugins/Automod/functions/createMessageSpamTrigger.ts b/backend/src/plugins/Automod/functions/createMessageSpamTrigger.ts index 009a1f52..1dbd233d 100644 --- a/backend/src/plugins/Automod/functions/createMessageSpamTrigger.ts +++ b/backend/src/plugins/Automod/functions/createMessageSpamTrigger.ts @@ -60,7 +60,7 @@ export function createMessageSpamTrigger(spamType: RecentActionType, prettyName: if (matchedSpam) { const messages = matchedSpam.recentActions - .map(action => action.context.message) + .map((action) => action.context.message) .filter(Boolean) .sort(sorter("posted_at")) as SavedMessage[]; @@ -75,8 +75,8 @@ export function createMessageSpamTrigger(spamType: RecentActionType, prettyName: return { extraContexts: matchedSpam.recentActions - .map(action => action.context) - .filter(_context => _context !== context), + .map((action) => action.context) + .filter((_context) => _context !== context), extra: { archiveId, diff --git a/backend/src/plugins/Automod/functions/findRecentSpam.ts b/backend/src/plugins/Automod/functions/findRecentSpam.ts index 0e042ed5..07e68d77 100644 --- a/backend/src/plugins/Automod/functions/findRecentSpam.ts +++ b/backend/src/plugins/Automod/functions/findRecentSpam.ts @@ -7,7 +7,7 @@ export function findRecentSpam( type: RecentActionType, identifier?: string, ) { - return pluginData.state.recentSpam.find(spam => { + return pluginData.state.recentSpam.find((spam) => { return spam.type === type && (!identifier || spam.identifiers.includes(identifier)); }); } diff --git a/backend/src/plugins/Automod/functions/getMatchingRecentActions.ts b/backend/src/plugins/Automod/functions/getMatchingRecentActions.ts index 416c050b..75107e45 100644 --- a/backend/src/plugins/Automod/functions/getMatchingRecentActions.ts +++ b/backend/src/plugins/Automod/functions/getMatchingRecentActions.ts @@ -11,7 +11,7 @@ export function getMatchingRecentActions( ) { to = to || Date.now(); - return pluginData.state.recentActions.filter(action => { + return pluginData.state.recentActions.filter((action) => { return ( action.type === type && (!identifier || action.identifier === identifier) && diff --git a/backend/src/plugins/Automod/functions/getTextMatchPartialSummary.ts b/backend/src/plugins/Automod/functions/getTextMatchPartialSummary.ts index fe0466e4..31ece554 100644 --- a/backend/src/plugins/Automod/functions/getTextMatchPartialSummary.ts +++ b/backend/src/plugins/Automod/functions/getTextMatchPartialSummary.ts @@ -29,6 +29,6 @@ export function getTextMatchPartialSummary( const visibleName = context.member?.nickname || context.user!.username; return `visible name: ${visibleName}`; } else if (type === "customstatus") { - return `custom status: ${context.member!.presence?.activities.find(a => a.type === "CUSTOM")?.name}`; + return `custom status: ${context.member!.presence?.activities.find((a) => a.type === "CUSTOM")?.name}`; } } diff --git a/backend/src/plugins/Automod/triggers/exampleTrigger.ts b/backend/src/plugins/Automod/triggers/exampleTrigger.ts index 7098e713..bf0880a9 100644 --- a/backend/src/plugins/Automod/triggers/exampleTrigger.ts +++ b/backend/src/plugins/Automod/triggers/exampleTrigger.ts @@ -15,7 +15,7 @@ export const ExampleTrigger = automodTrigger()({ }, async match({ triggerConfig, context }) { - const foundFruit = triggerConfig.allowedFruits.find(fruit => context.message?.data.content === fruit); + const foundFruit = triggerConfig.allowedFruits.find((fruit) => context.message?.data.content === fruit); if (foundFruit) { return { extra: { diff --git a/backend/src/plugins/Automod/triggers/matchAttachmentType.ts b/backend/src/plugins/Automod/triggers/matchAttachmentType.ts index 0eb7e764..d905fbc0 100644 --- a/backend/src/plugins/Automod/triggers/matchAttachmentType.ts +++ b/backend/src/plugins/Automod/triggers/matchAttachmentType.ts @@ -33,13 +33,10 @@ export const MatchAttachmentTypeTrigger = automodTrigger()({ } for (const attachment of context.message.data.attachments) { - const attachmentType = attachment.url - .split(".") - .pop()! - .toLowerCase(); + const attachmentType = attachment.url.split(".").pop()!.toLowerCase(); const blacklist = trigger.blacklist_enabled - ? (trigger.filetype_blacklist || []).map(_t => _t.toLowerCase()) + ? (trigger.filetype_blacklist || []).map((_t) => _t.toLowerCase()) : null; if (blacklist && blacklist.includes(attachmentType)) { @@ -52,7 +49,7 @@ export const MatchAttachmentTypeTrigger = automodTrigger()({ } const whitelist = trigger.whitelist_enabled - ? (trigger.filetype_whitelist || []).map(_t => _t.toLowerCase()) + ? (trigger.filetype_whitelist || []).map((_t) => _t.toLowerCase()) : null; if (whitelist && !whitelist.includes(attachmentType)) { diff --git a/backend/src/plugins/Automod/triggers/matchMimeType.ts b/backend/src/plugins/Automod/triggers/matchMimeType.ts index 5e00d4b6..6e1b447e 100644 --- a/backend/src/plugins/Automod/triggers/matchMimeType.ts +++ b/backend/src/plugins/Automod/triggers/matchMimeType.ts @@ -34,7 +34,7 @@ export const MatchMimeTypeTrigger = automodTrigger()({ const contentType = (rawContentType || "").split(";")[0]; // Remove "; charset=utf8" and similar from the end const blacklist = trigger.blacklist_enabled - ? (trigger.mime_type_blacklist ?? []).map(_t => _t.toLowerCase()) + ? (trigger.mime_type_blacklist ?? []).map((_t) => _t.toLowerCase()) : null; if (contentType && blacklist?.includes(contentType)) { @@ -47,7 +47,7 @@ export const MatchMimeTypeTrigger = automodTrigger()({ } const whitelist = trigger.whitelist_enabled - ? (trigger.mime_type_whitelist ?? []).map(_t => _t.toLowerCase()) + ? (trigger.mime_type_whitelist ?? []).map((_t) => _t.toLowerCase()) : null; if (whitelist && (!contentType || !whitelist.includes(contentType))) { diff --git a/backend/src/plugins/Automod/triggers/matchWords.ts b/backend/src/plugins/Automod/triggers/matchWords.ts index 387f2208..fda24726 100644 --- a/backend/src/plugins/Automod/triggers/matchWords.ts +++ b/backend/src/plugins/Automod/triggers/matchWords.ts @@ -64,7 +64,7 @@ export const MatchWordsTrigger = automodTrigger()({ // When performing loose matching, allow any amount of whitespace or up to looseMatchingThreshold number of other // characters between the matched characters. E.g. if we're matching banana, a loose match could also match b a n a n a let pattern = trigger.loose_matching - ? [...word].map(c => escapeStringRegexp(c)).join(`(?:\\s*|.{0,${looseMatchingThreshold})`) + ? [...word].map((c) => escapeStringRegexp(c)).join(`(?:\\s*|.{0,${looseMatchingThreshold})`) : escapeStringRegexp(word); if (trigger.only_full_words) { diff --git a/backend/src/plugins/Automod/triggers/memberJoinSpam.ts b/backend/src/plugins/Automod/triggers/memberJoinSpam.ts index 7ab1964a..60ad02a7 100644 --- a/backend/src/plugins/Automod/triggers/memberJoinSpam.ts +++ b/backend/src/plugins/Automod/triggers/memberJoinSpam.ts @@ -30,7 +30,7 @@ export const MemberJoinSpamTrigger = automodTrigger()({ const totalCount = sumRecentActionCounts(matchingActions); if (totalCount >= triggerConfig.amount) { - const extraContexts = matchingActions.map(a => a.context).filter(c => c !== context); + const extraContexts = matchingActions.map((a) => a.context).filter((c) => c !== context); pluginData.state.recentSpam.push({ type: RecentActionType.MemberJoin, diff --git a/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts b/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts index 84cce432..b417fec6 100644 --- a/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts +++ b/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts @@ -35,7 +35,7 @@ export const AddDashboardUserCmd = botControlCmd({ await pluginData.state.apiPermissionAssignments.addUser(args.guildId, user.id, [ApiPermissions.EditConfig]); } - const userNameList = args.users.map(user => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); + const userNameList = args.users.map((user) => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); sendSuccessMessage( pluginData, msg.channel as TextChannel, diff --git a/backend/src/plugins/BotControl/commands/AddServerFromInviteCmd.ts b/backend/src/plugins/BotControl/commands/AddServerFromInviteCmd.ts index c7e2f28c..385df13b 100644 --- a/backend/src/plugins/BotControl/commands/AddServerFromInviteCmd.ts +++ b/backend/src/plugins/BotControl/commands/AddServerFromInviteCmd.ts @@ -52,10 +52,7 @@ export const AddServerFromInviteCmd = botControlCmd({ invite.guild.id, msg.author.id, [ApiPermissions.ManageAccess], - moment - .utc() - .add(1, "hour") - .format(DBDateFormat), + moment.utc().add(1, "hour").format(DBDateFormat), ); } diff --git a/backend/src/plugins/BotControl/commands/AllowServerCmd.ts b/backend/src/plugins/BotControl/commands/AllowServerCmd.ts index 304e7705..9e786b71 100644 --- a/backend/src/plugins/BotControl/commands/AllowServerCmd.ts +++ b/backend/src/plugins/BotControl/commands/AllowServerCmd.ts @@ -48,10 +48,7 @@ export const AllowServerCmd = botControlCmd({ args.guildId, msg.author.id, [ApiPermissions.ManageAccess], - moment - .utc() - .add(1, "hour") - .format(DBDateFormat), + moment.utc().add(1, "hour").format(DBDateFormat), ); } diff --git a/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts b/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts index 359a6e5b..a97efca6 100644 --- a/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts +++ b/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts @@ -21,7 +21,7 @@ export const ListDashboardUsersCmd = botControlCmd({ const dashboardUsers = await pluginData.state.apiPermissionAssignments.getByGuildId(guild.id); const users = await Promise.all( - dashboardUsers.map(async perm => ({ + dashboardUsers.map(async (perm) => ({ user: await resolveUser(pluginData.client, perm.target_id), permission: perm, })), diff --git a/backend/src/plugins/BotControl/commands/PerformanceCmd.ts b/backend/src/plugins/BotControl/commands/PerformanceCmd.ts index 6e4c857a..55670507 100644 --- a/backend/src/plugins/BotControl/commands/PerformanceCmd.ts +++ b/backend/src/plugins/BotControl/commands/PerformanceCmd.ts @@ -13,7 +13,7 @@ export const PerformanceCmd = botControlCmd({ async run({ pluginData, message: msg, args }) { const stats = pluginData.getKnubInstance().getPluginPerformanceStats(); const averageLoadTimeEntries = Object.entries(stats.averageLoadTimes); - averageLoadTimeEntries.sort(sorter(v => v[1].time, "DESC")); + averageLoadTimeEntries.sort(sorter((v) => v[1].time, "DESC")); const lines = averageLoadTimeEntries.map( ([pluginName, { time }]) => `${pluginName}: **${formatNumber(Math.round(time))}ms**`, ); diff --git a/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts b/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts index 3dfafb42..dff4928d 100644 --- a/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts +++ b/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts @@ -34,7 +34,7 @@ export const RemoveDashboardUserCmd = botControlCmd({ await pluginData.state.apiPermissionAssignments.removeUser(args.guildId, user.id); } - const userNameList = args.users.map(user => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); + const userNameList = args.users.map((user) => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); sendSuccessMessage( pluginData, msg.channel as TextChannel, diff --git a/backend/src/plugins/BotControl/commands/ServersCmd.ts b/backend/src/plugins/BotControl/commands/ServersCmd.ts index d226e14c..f8c91b61 100644 --- a/backend/src/plugins/BotControl/commands/ServersCmd.ts +++ b/backend/src/plugins/BotControl/commands/ServersCmd.ts @@ -22,7 +22,7 @@ export const ServersCmd = botControlCmd({ async run({ pluginData, message: msg, args }) { const showList = Boolean(args.all || args.initialized || args.uninitialized || args.search); - const search = args.search ? new RegExp([...args.search].map(s => escapeStringRegexp(s)).join(".*"), "i") : null; + const search = args.search ? new RegExp([...args.search].map((s) => escapeStringRegexp(s)).join(".*"), "i") : null; const joinedGuilds = Array.from(pluginData.client.guilds.cache.values()); const loadedGuilds = pluginData.getKnubInstance().getLoadedGuilds(); @@ -32,21 +32,21 @@ export const ServersCmd = botControlCmd({ let filteredGuilds = Array.from(joinedGuilds); if (args.initialized) { - filteredGuilds = filteredGuilds.filter(g => loadedGuildsMap.has(g.id)); + filteredGuilds = filteredGuilds.filter((g) => loadedGuildsMap.has(g.id)); } if (args.uninitialized) { - filteredGuilds = filteredGuilds.filter(g => !loadedGuildsMap.has(g.id)); + filteredGuilds = filteredGuilds.filter((g) => !loadedGuildsMap.has(g.id)); } if (args.search) { - filteredGuilds = filteredGuilds.filter(g => search!.test(`${g.id} ${g.name}`)); + filteredGuilds = filteredGuilds.filter((g) => search!.test(`${g.id} ${g.name}`)); } if (filteredGuilds.length) { - filteredGuilds.sort(sorter(g => g.name.toLowerCase())); + filteredGuilds.sort(sorter((g) => g.name.toLowerCase())); const longestId = filteredGuilds.reduce((longest, guild) => Math.max(longest, guild.id.length), 0); - const lines = filteredGuilds.map(g => { + const lines = filteredGuilds.map((g) => { const paddedId = g.id.padEnd(longestId, " "); const owner = getUser(pluginData.client, g.ownerId); return `\`${paddedId}\` **${g.name}** (${g.memberCount} members) (owner **${owner.tag}** \`${owner.id}\`)`; @@ -57,7 +57,7 @@ export const ServersCmd = botControlCmd({ } } else { const total = joinedGuilds.length; - const initialized = joinedGuilds.filter(g => loadedGuildsMap.has(g.id)).length; + const initialized = joinedGuilds.filter((g) => loadedGuildsMap.has(g.id)).length; const unInitialized = total - initialized; msg.channel.send( diff --git a/backend/src/plugins/Cases/functions/createCaseNote.ts b/backend/src/plugins/Cases/functions/createCaseNote.ts index c03a5b3c..30f0ac2e 100644 --- a/backend/src/plugins/Cases/functions/createCaseNote.ts +++ b/backend/src/plugins/Cases/functions/createCaseNote.ts @@ -22,7 +22,7 @@ export async function createCaseNote(pluginData: GuildPluginData `__[${d}]__`).join(" ") + " " + body; + body = args.noteDetails.map((d) => `__[${d}]__`).join(" ") + " " + body; } await pluginData.state.cases.createNote(theCase.id, { diff --git a/backend/src/plugins/Cases/functions/getCaseTypeAmountForUserId.ts b/backend/src/plugins/Cases/functions/getCaseTypeAmountForUserId.ts index 94f35d7f..eb28584d 100644 --- a/backend/src/plugins/Cases/functions/getCaseTypeAmountForUserId.ts +++ b/backend/src/plugins/Cases/functions/getCaseTypeAmountForUserId.ts @@ -7,11 +7,11 @@ export async function getCaseTypeAmountForUserId( userID: string, type: CaseTypes, ): Promise { - const cases = (await pluginData.state.cases.getByUserId(userID)).filter(c => !c.is_hidden); + const cases = (await pluginData.state.cases.getByUserId(userID)).filter((c) => !c.is_hidden); let typeAmount = 0; if (cases.length > 0) { - cases.forEach(singleCase => { + cases.forEach((singleCase) => { if (singleCase.type === type.valueOf()) { typeAmount++; } diff --git a/backend/src/plugins/Censor/CensorPlugin.ts b/backend/src/plugins/Censor/CensorPlugin.ts index 8a533093..d8b74477 100644 --- a/backend/src/plugins/Censor/CensorPlugin.ts +++ b/backend/src/plugins/Censor/CensorPlugin.ts @@ -71,10 +71,10 @@ export const CensorPlugin = zeppelinGuildPlugin()({ afterLoad(pluginData) { const { state, guild } = pluginData; - state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg); + state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg); state.savedMessages.events.on("create", state.onMessageCreateFn); - state.onMessageUpdateFn = msg => onMessageUpdate(pluginData, msg); + state.onMessageUpdateFn = (msg) => onMessageUpdate(pluginData, msg); state.savedMessages.events.on("update", state.onMessageUpdateFn); }, diff --git a/backend/src/plugins/Censor/util/applyFiltersToMsg.ts b/backend/src/plugins/Censor/util/applyFiltersToMsg.ts index ffadcc67..5e92a305 100644 --- a/backend/src/plugins/Censor/util/applyFiltersToMsg.ts +++ b/backend/src/plugins/Censor/util/applyFiltersToMsg.ts @@ -19,7 +19,7 @@ export async function applyFiltersToMsg( let messageContent = savedMessage.data.content || ""; if (savedMessage.data.attachments) messageContent += " " + JSON.stringify(savedMessage.data.attachments); if (savedMessage.data.embeds) { - const embeds = (savedMessage.data.embeds as MessageEmbed[]).map(e => cloneDeep(e)); + const embeds = (savedMessage.data.embeds as MessageEmbed[]).map((e) => cloneDeep(e)); for (const embed of embeds) { if (embed.type === "video") { // Ignore video descriptions as they're not actually shown on the embed @@ -52,7 +52,7 @@ export async function applyFiltersToMsg( const inviteCodes = getInviteCodesInString(messageContent); const invites: Array = await Promise.all( - inviteCodes.map(code => resolveInvite(pluginData.client, code)), + inviteCodes.map((code) => resolveInvite(pluginData.client, code)), ); for (const invite of invites) { diff --git a/backend/src/plugins/ChannelArchiver/ChannelArchiverPlugin.ts b/backend/src/plugins/ChannelArchiver/ChannelArchiverPlugin.ts index 8bdd4133..9ff38a84 100644 --- a/backend/src/plugins/ChannelArchiver/ChannelArchiverPlugin.ts +++ b/backend/src/plugins/ChannelArchiver/ChannelArchiverPlugin.ts @@ -14,5 +14,5 @@ export const ChannelArchiverPlugin = zeppelinGuildPlugin"}`; + let content = `[${ts}] [${message.author.id}] [${message.author.username}#${message.author.discriminator}]: ${ + message.content || "" + }`; if (message.attachments.size) { if (args["attachment-channel"]) { diff --git a/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts b/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts index bfd94cbe..8ecde5e7 100644 --- a/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts +++ b/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts @@ -14,9 +14,9 @@ export async function getCompanionChannelOptsForVoiceChannelId( const config = await pluginData.config.getMatchingConfig({ userId, channelId: voiceChannel.id }); return Object.values(config.entries) .filter( - opts => + (opts) => opts.voice_channel_ids.includes(voiceChannel.id) || (voiceChannel.parentId && opts.voice_channel_ids.includes(voiceChannel.parentId)), ) - .map(opts => Object.assign({}, defaultCompanionChannelOpts, opts)); + .map((opts) => Object.assign({}, defaultCompanionChannelOpts, opts)); } diff --git a/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts b/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts index c4e66f49..ea09b548 100644 --- a/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts +++ b/backend/src/plugins/CompanionChannels/functions/handleCompanionPermissions.ts @@ -65,7 +65,7 @@ export async function handleCompanionPermissions( if (!channel || !(channel instanceof TextChannel)) continue; pluginData.state.serverLogs.ignoreLog(LogType.CHANNEL_UPDATE, channelId, 3 * 1000); const fullSerialized = new Permissions(BigInt(permissions)).serialize(); - const onlyAllowed = filterObject(fullSerialized, v => v === true); + const onlyAllowed = filterObject(fullSerialized, (v) => v === true); await channel.permissionOverwrites.create(userId, onlyAllowed, { reason: `Companion Channel for ${voiceChannel!.id} | User Joined`, }); diff --git a/backend/src/plugins/ContextMenus/actions/mute.ts b/backend/src/plugins/ContextMenus/actions/mute.ts index e69c84db..5735337a 100644 --- a/backend/src/plugins/ContextMenus/actions/mute.ts +++ b/backend/src/plugins/ContextMenus/actions/mute.ts @@ -48,8 +48,9 @@ export async function muteAction( const muteMessage = `Muted **${result.case.user_name}** ${ durationMs ? `for ${humanizeDuration(durationMs)}` : "indefinitely" - } (Case #${result.case.case_number}) (user notified via ${result.notifyResult.method ?? - "dm"})\nPlease update the new case with the \`update\` command`; + } (Case #${result.case.case_number}) (user notified via ${ + result.notifyResult.method ?? "dm" + })\nPlease update the new case with the \`update\` command`; interaction.followUp({ ephemeral: true, content: muteMessage }); } catch (e) { diff --git a/backend/src/plugins/ContextMenus/utils/loadAllCommands.ts b/backend/src/plugins/ContextMenus/utils/loadAllCommands.ts index 77311ba7..8272d8b3 100644 --- a/backend/src/plugins/ContextMenus/utils/loadAllCommands.ts +++ b/backend/src/plugins/ContextMenus/utils/loadAllCommands.ts @@ -26,7 +26,7 @@ export async function loadAllCommands(pluginData: GuildPluginData { + const setCommands = await comms.set(newCommands, pluginData.guild.id).catch((e) => { pluginData.getPlugin(LogsPlugin).logBotAlert({ body: `Unable to overwrite context menus: ${e}` }); return undefined; }); diff --git a/backend/src/plugins/Counters/CountersPlugin.ts b/backend/src/plugins/Counters/CountersPlugin.ts index d2566515..07738195 100644 --- a/backend/src/plugins/Counters/CountersPlugin.ts +++ b/backend/src/plugins/Counters/CountersPlugin.ts @@ -55,7 +55,7 @@ const defaultOptions: PluginOptions = { ], }; -const configPreprocessor: ConfigPreprocessorFn = options => { +const configPreprocessor: ConfigPreprocessorFn = (options) => { for (const [counterName, counter] of Object.entries(options.config?.counters || {})) { counter.name = counterName; counter.per_user = counter.per_user ?? false; diff --git a/backend/src/plugins/Counters/commands/CountersListCmd.ts b/backend/src/plugins/Counters/commands/CountersListCmd.ts index c92a2fe4..f725ac71 100644 --- a/backend/src/plugins/Counters/commands/CountersListCmd.ts +++ b/backend/src/plugins/Counters/commands/CountersListCmd.ts @@ -13,13 +13,13 @@ export const CountersListCmd = typedGuildCommand()({ async run({ pluginData, message, args }) { const config = await pluginData.config.getForMessage(message); - const countersToShow = Array.from(Object.values(config.counters)).filter(c => c.can_view !== false); + const countersToShow = Array.from(Object.values(config.counters)).filter((c) => c.can_view !== false); if (!countersToShow.length) { sendErrorMessage(pluginData, message.channel, "No counters are configured for this server"); return; } - const counterLines = countersToShow.map(counter => { + const counterLines = countersToShow.map((counter) => { const title = counter.pretty_name ? `**${counter.pretty_name}** (\`${counter.name}\`)` : `\`${counter.name}\``; const types: string[] = []; diff --git a/backend/src/plugins/Counters/functions/changeCounterValue.ts b/backend/src/plugins/Counters/functions/changeCounterValue.ts index de61d9be..74a295f9 100644 --- a/backend/src/plugins/Counters/functions/changeCounterValue.ts +++ b/backend/src/plugins/Counters/functions/changeCounterValue.ts @@ -38,10 +38,10 @@ export async function changeCounterValue( if (triggers) { const triggersArr = Array.from(triggers.values()); await Promise.all( - triggersArr.map(trigger => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)), + triggersArr.map((trigger) => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)), ); await Promise.all( - triggersArr.map(trigger => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)), + triggersArr.map((trigger) => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)), ); } diff --git a/backend/src/plugins/Counters/functions/decayCounter.ts b/backend/src/plugins/Counters/functions/decayCounter.ts index c7b813ea..0317ee8c 100644 --- a/backend/src/plugins/Counters/functions/decayCounter.ts +++ b/backend/src/plugins/Counters/functions/decayCounter.ts @@ -25,8 +25,8 @@ export async function decayCounter( const triggers = pluginData.state.counterTriggersByCounterId.get(counterId); if (triggers) { const triggersArr = Array.from(triggers.values()); - await Promise.all(triggersArr.map(trigger => checkAllValuesForTrigger(pluginData, counterName, trigger))); - await Promise.all(triggersArr.map(trigger => checkAllValuesForReverseTrigger(pluginData, counterName, trigger))); + await Promise.all(triggersArr.map((trigger) => checkAllValuesForTrigger(pluginData, counterName, trigger))); + await Promise.all(triggersArr.map((trigger) => checkAllValuesForReverseTrigger(pluginData, counterName, trigger))); } lock.unlock(); diff --git a/backend/src/plugins/Counters/functions/setCounterValue.ts b/backend/src/plugins/Counters/functions/setCounterValue.ts index 697c8503..7a988ee2 100644 --- a/backend/src/plugins/Counters/functions/setCounterValue.ts +++ b/backend/src/plugins/Counters/functions/setCounterValue.ts @@ -35,10 +35,10 @@ export async function setCounterValue( if (triggers) { const triggersArr = Array.from(triggers.values()); await Promise.all( - triggersArr.map(trigger => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)), + triggersArr.map((trigger) => checkCounterTrigger(pluginData, counterName, trigger, channelId, userId)), ); await Promise.all( - triggersArr.map(trigger => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)), + triggersArr.map((trigger) => checkReverseCounterTrigger(pluginData, counterName, trigger, channelId, userId)), ); } diff --git a/backend/src/plugins/CustomEvents/actions/addRoleAction.ts b/backend/src/plugins/CustomEvents/actions/addRoleAction.ts index 6b83770a..52d6fd59 100644 --- a/backend/src/plugins/CustomEvents/actions/addRoleAction.ts +++ b/backend/src/plugins/CustomEvents/actions/addRoleAction.ts @@ -29,7 +29,7 @@ export async function addRoleAction( throw new ActionError("Missing permissions"); } const rolesToAdd = (Array.isArray(action.role) ? action.role : [action.role]).filter( - id => !target.roles.cache.has(id), + (id) => !target.roles.cache.has(id), ); if (rolesToAdd.length === 0) { throw new ActionError("Target already has the role(s) specified"); diff --git a/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts b/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts index bc4e8d0f..c93ad872 100644 --- a/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts +++ b/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts @@ -5,7 +5,7 @@ export const GuildBanRemoveAlertsEvt = locateUserEvt({ async listener(meta) { const alerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.ban.user.id); - alerts.forEach(alert => { + alerts.forEach((alert) => { meta.pluginData.state.alerts.delete(alert.id); }); }, diff --git a/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts b/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts index eaedc015..6510540c 100644 --- a/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts +++ b/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts @@ -19,7 +19,7 @@ export const VoiceStateUpdateAlertEvt = locateUserEvt({ const triggeredAlerts = await meta.pluginData.state.alerts.getAlertsByUserId(memberId); const voiceChannel = meta.args.oldState.channel!; - triggeredAlerts.forEach(alert => { + triggeredAlerts.forEach((alert) => { const txtChannel = meta.pluginData.guild.channels.resolve(alert.channel_id as Snowflake) as TextChannel; txtChannel.send({ content: `🔴 <@!${alert.requestor_id}> the user <@!${alert.user_id}> disconnected out of \`${voiceChannel.name}\``, diff --git a/backend/src/plugins/LocateUser/utils/fillAlertsList.ts b/backend/src/plugins/LocateUser/utils/fillAlertsList.ts index 3c5c90d1..56e4315f 100644 --- a/backend/src/plugins/LocateUser/utils/fillAlertsList.ts +++ b/backend/src/plugins/LocateUser/utils/fillAlertsList.ts @@ -4,7 +4,7 @@ import { LocateUserPluginType } from "../types"; export async function fillActiveAlertsList(pluginData: GuildPluginData) { const allAlerts = await pluginData.state.alerts.getAllGuildAlerts(); - allAlerts.forEach(alert => { + allAlerts.forEach((alert) => { if (!pluginData.state.usersWithAlerts.includes(alert.user_id)) { pluginData.state.usersWithAlerts.push(alert.user_id); } diff --git a/backend/src/plugins/LocateUser/utils/sendAlerts.ts b/backend/src/plugins/LocateUser/utils/sendAlerts.ts index 67f865bf..d93bf47d 100644 --- a/backend/src/plugins/LocateUser/utils/sendAlerts.ts +++ b/backend/src/plugins/LocateUser/utils/sendAlerts.ts @@ -10,7 +10,7 @@ export async function sendAlerts(pluginData: GuildPluginData { + triggeredAlerts.forEach((alert) => { const prepend = `<@!${alert.requestor_id}>, an alert requested by you has triggered!\nReminder: \`${alert.body}\`\n`; const txtChannel = pluginData.guild.channels.resolve(alert.channel_id as Snowflake) as TextChannel; sendWhere(pluginData, member, txtChannel, prepend); diff --git a/backend/src/plugins/Logs/LogsPlugin.ts b/backend/src/plugins/Logs/LogsPlugin.ts index a6eb8443..cc77ac90 100644 --- a/backend/src/plugins/Logs/LogsPlugin.ts +++ b/backend/src/plugins/Logs/LogsPlugin.ts @@ -177,7 +177,7 @@ export const LogsPlugin = zeppelinGuildPlugin()({ ], public: { - getLogMessage: pluginData => { + getLogMessage: (pluginData) => { return ( type: TLogType, data: TypedTemplateSafeValueContainer, @@ -277,10 +277,10 @@ export const LogsPlugin = zeppelinGuildPlugin()({ state.logListener = ({ type, data }) => log(pluginData, type, data); state.guildLogs.on("log", state.logListener); - state.onMessageDeleteFn = msg => onMessageDelete(pluginData, msg); + state.onMessageDeleteFn = (msg) => onMessageDelete(pluginData, msg); state.savedMessages.events.on("delete", state.onMessageDeleteFn); - state.onMessageDeleteBulkFn = msg => onMessageDeleteBulk(pluginData, msg); + state.onMessageDeleteBulkFn = (msg) => onMessageDeleteBulk(pluginData, msg); state.savedMessages.events.on("deleteBulk", state.onMessageDeleteBulkFn); state.onMessageUpdateFn = (newMsg, oldMsg) => onMessageUpdate(pluginData, newMsg, oldMsg); diff --git a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts index 07e0165f..061ab4fe 100644 --- a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts +++ b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts @@ -58,10 +58,10 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ logMemberRoleChanges(pluginData, { member, addedRoles: addedRoles.map( - roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, + (roleId) => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, ), removedRoles: removedRoles.map( - roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, + (roleId) => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, ), mod: null, }); @@ -70,7 +70,7 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ logMemberRoleAdd(pluginData, { member, roles: addedRoles.map( - roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, + (roleId) => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, ), mod: null, }); @@ -79,7 +79,7 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ logMemberRoleRemove(pluginData, { member, roles: removedRoles.map( - roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, + (roleId) => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }, ), mod: null, }); diff --git a/backend/src/plugins/Logs/logFunctions/logAutomodAction.ts b/backend/src/plugins/Logs/logFunctions/logAutomodAction.ts index ffa68c03..d7046826 100644 --- a/backend/src/plugins/Logs/logFunctions/logAutomodAction.ts +++ b/backend/src/plugins/Logs/logFunctions/logAutomodAction.ts @@ -21,7 +21,7 @@ export function logAutomodAction(pluginData: GuildPluginData, da createTypedTemplateSafeValueContainer({ rule: data.rule, user: data.user ? userToTemplateSafeUser(data.user) : null, - users: data.users.map(user => userToTemplateSafeUser(user)), + users: data.users.map((user) => userToTemplateSafeUser(user)), actionsTaken: data.actionsTaken, matchSummary: data.matchSummary ?? "", }), diff --git a/backend/src/plugins/Logs/logFunctions/logMemberRoleAdd.ts b/backend/src/plugins/Logs/logFunctions/logMemberRoleAdd.ts index bfbc03fc..2db68838 100644 --- a/backend/src/plugins/Logs/logFunctions/logMemberRoleAdd.ts +++ b/backend/src/plugins/Logs/logFunctions/logMemberRoleAdd.ts @@ -19,7 +19,7 @@ export function logMemberRoleAdd(pluginData: GuildPluginData, da createTypedTemplateSafeValueContainer({ mod: data.mod ? userToTemplateSafeUser(data.mod) : null, member: memberToTemplateSafeMember(data.member), - roles: data.roles.map(r => r.name).join(", "), + roles: data.roles.map((r) => r.name).join(", "), }), { userId: data.member.id, diff --git a/backend/src/plugins/Logs/logFunctions/logMemberRoleChanges.ts b/backend/src/plugins/Logs/logFunctions/logMemberRoleChanges.ts index b4364419..7eee36a9 100644 --- a/backend/src/plugins/Logs/logFunctions/logMemberRoleChanges.ts +++ b/backend/src/plugins/Logs/logFunctions/logMemberRoleChanges.ts @@ -21,8 +21,8 @@ export function logMemberRoleChanges(pluginData: GuildPluginData createTypedTemplateSafeValueContainer({ mod: data.mod ? userToTemplateSafeUser(data.mod) : null, member: memberToTemplateSafeMember(data.member), - addedRoles: data.addedRoles.map(r => r.name).join(", "), - removedRoles: data.removedRoles.map(r => r.name).join(", "), + addedRoles: data.addedRoles.map((r) => r.name).join(", "), + removedRoles: data.removedRoles.map((r) => r.name).join(", "), }), { userId: data.member.id, diff --git a/backend/src/plugins/Logs/logFunctions/logMemberRoleRemove.ts b/backend/src/plugins/Logs/logFunctions/logMemberRoleRemove.ts index a32f9cd9..54dfff29 100644 --- a/backend/src/plugins/Logs/logFunctions/logMemberRoleRemove.ts +++ b/backend/src/plugins/Logs/logFunctions/logMemberRoleRemove.ts @@ -19,7 +19,7 @@ export function logMemberRoleRemove(pluginData: GuildPluginData, createTypedTemplateSafeValueContainer({ mod: data.mod ? userToTemplateSafeUser(data.mod) : null, member: memberToTemplateSafeMember(data.member), - roles: data.roles.map(r => r.name).join(", "), + roles: data.roles.map((r) => r.name).join(", "), }), { userId: data.member.id, diff --git a/backend/src/plugins/Logs/types.ts b/backend/src/plugins/Logs/types.ts index 39d9d440..71f55c65 100644 --- a/backend/src/plugins/Logs/types.ts +++ b/backend/src/plugins/Logs/types.ts @@ -406,10 +406,7 @@ export const LogTypeData = z.object({ }), [LogType.MEMBER_ROLE_CHANGES]: z.object({ - mod: z - .instanceof(TemplateSafeUser) - .or(z.instanceof(TemplateSafeUnknownUser)) - .or(z.null()), + mod: z.instanceof(TemplateSafeUser).or(z.instanceof(TemplateSafeUnknownUser)).or(z.null()), member: z.instanceof(TemplateSafeMember), addedRoles: z.string(), removedRoles: z.string(), diff --git a/backend/src/plugins/Logs/util/getLogMessage.ts b/backend/src/plugins/Logs/util/getLogMessage.ts index 81714486..3d6bcec5 100644 --- a/backend/src/plugins/Logs/util/getLogMessage.ts +++ b/backend/src/plugins/Logs/util/getLogMessage.ts @@ -60,7 +60,7 @@ export async function getLogMessage( const inputArray = Array.isArray(inputUserOrMember) ? inputUserOrMember : [inputUserOrMember]; // TODO: Resolve IDs to users/members const usersOrMembers = inputArray.filter( - v => v instanceof TemplateSafeUser || v instanceof TemplateSafeMember, + (v) => v instanceof TemplateSafeUser || v instanceof TemplateSafeMember, ) as Array; const mentions: string[] = []; @@ -83,7 +83,7 @@ export async function getLogMessage( const memberConfig = (await pluginData.config.getMatchingConfig({ level, - memberRoles: member ? member.roles.map(r => r.id) : [], + memberRoles: member ? member.roles.map((r) => r.id) : [], userId: user.id, })) || ({} as any); @@ -97,7 +97,7 @@ export async function getLogMessage( return mentions.join(", "); }, - channelMention: channel => { + channelMention: (channel) => { if (!channel) return ""; return verboseChannelMention(channel); }, @@ -109,12 +109,12 @@ export async function getLogMessage( if (type === LogType.BOT_ALERT) { const valuesWithoutTmplEval = { ...values }; - values.tmplEval = str => { + values.tmplEval = (str) => { return renderTemplate(str, valuesWithoutTmplEval); }; } - const renderLogString = str => renderTemplate(str, values); + const renderLogString = (str) => renderTemplate(str, values); let formatted; try { diff --git a/backend/src/plugins/Logs/util/log.ts b/backend/src/plugins/Logs/util/log.ts index 0afc1e1d..4c2ca0f9 100644 --- a/backend/src/plugins/Logs/util/log.ts +++ b/backend/src/plugins/Logs/util/log.ts @@ -100,14 +100,14 @@ export async function log( channelId, new MessageBuffer({ timeout: batchTime, - consume: part => { + consume: (part) => { const parse: MessageMentionTypes[] = pluginData.config.get().allow_user_mentions ? ["users"] : []; channel .send({ ...part, allowedMentions: { parse }, }) - .catch(err => { + .catch((err) => { // tslint:disable-next-line:no-console console.warn( `Error while sending ${typeStr} log to ${pluginData.guild.id}/${channelId}: ${err.message}`, diff --git a/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts b/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts index c62e260b..1dec0101 100644 --- a/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts +++ b/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts @@ -17,7 +17,7 @@ export async function onMessageDeleteBulk(pluginData: GuildPluginData `\`${item.user_id}\``))); + const authorIds = Array.from(new Set(savedMessages.map((item) => `\`${item.user_id}\``))); logMessageDeleteBulk(pluginData, { count: savedMessages.length, diff --git a/backend/src/plugins/Logs/util/onMessageUpdate.ts b/backend/src/plugins/Logs/util/onMessageUpdate.ts index b3269b45..efd92d28 100644 --- a/backend/src/plugins/Logs/util/onMessageUpdate.ts +++ b/backend/src/plugins/Logs/util/onMessageUpdate.ts @@ -17,12 +17,12 @@ export async function onMessageUpdate( let logUpdate = false; const oldEmbedsToCompare = ((oldSavedMessage.data.embeds || []) as MessageEmbed[]) - .map(e => cloneDeep(e)) - .filter(e => (e as MessageEmbed).type === "rich"); + .map((e) => cloneDeep(e)) + .filter((e) => (e as MessageEmbed).type === "rich"); const newEmbedsToCompare = ((savedMessage.data.embeds || []) as MessageEmbed[]) - .map(e => cloneDeep(e)) - .filter(e => (e as MessageEmbed).type === "rich"); + .map((e) => cloneDeep(e)) + .filter((e) => (e as MessageEmbed).type === "rich"); for (const embed of [...oldEmbedsToCompare, ...newEmbedsToCompare]) { if (embed.thumbnail) { diff --git a/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts b/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts index 3e1e91a6..5acaf5fc 100644 --- a/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts +++ b/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts @@ -52,7 +52,11 @@ export const MessageCreateEvt = messageSaverEvt({ console.warn(`Tried to save duplicate message from messageCreate event: ${context} / saved at: ${timestamp}`); return; } - recentlyCreatedMessages.set(meta.args.message.id, [meta.pluginData.state.debugId, Date.now(), meta.pluginData.guild.id]); + recentlyCreatedMessages.set(meta.args.message.id, [ + meta.pluginData.state.debugId, + Date.now(), + meta.pluginData.guild.id, + ]); await meta.pluginData.state.savedMessages.createFromMsg(meta.args.message); }, @@ -97,7 +101,7 @@ export const MessageDeleteBulkEvt = messageSaverEvt({ allowSelf: true, async listener(meta) { - const ids = meta.args.messages.map(m => m.id); + const ids = meta.args.messages.map((m) => m.id); await meta.pluginData.state.savedMessages.markBulkAsDeleted(ids); }, }); diff --git a/backend/src/plugins/ModActions/commands/CasesModCmd.ts b/backend/src/plugins/ModActions/commands/CasesModCmd.ts index 45acbb73..14e89870 100644 --- a/backend/src/plugins/ModActions/commands/CasesModCmd.ts +++ b/backend/src/plugins/ModActions/commands/CasesModCmd.ts @@ -46,9 +46,9 @@ export const CasesModCmd = modActionsCmd({ pluginData.client, msg.channel, totalPages, - async page => { + async (page) => { const cases = await casesPlugin.getRecentCasesByMod(modId, casesPerPage, (page - 1) * casesPerPage); - const lines = await asyncMap(cases, c => casesPlugin.getCaseSummary(c, true, msg.author.id)); + const lines = await asyncMap(cases, (c) => casesPlugin.getCaseSummary(c, true, msg.author.id)); const firstCaseNum = (page - 1) * casesPerPage + 1; const lastCaseNum = page * casesPerPage; diff --git a/backend/src/plugins/ModActions/commands/CasesUserCmd.ts b/backend/src/plugins/ModActions/commands/CasesUserCmd.ts index 39d4050b..90023026 100644 --- a/backend/src/plugins/ModActions/commands/CasesUserCmd.ts +++ b/backend/src/plugins/ModActions/commands/CasesUserCmd.ts @@ -53,13 +53,13 @@ export const CasesUserCmd = modActionsCmd({ if (typesToShow.length > 0) { // Reversed: Hide specified types - if (args.reverseFilters) cases = cases.filter(c => !typesToShow.includes(c.type)); + if (args.reverseFilters) cases = cases.filter((c) => !typesToShow.includes(c.type)); // Normal: Show only specified types - else cases = cases.filter(c => typesToShow.includes(c.type)); + else cases = cases.filter((c) => typesToShow.includes(c.type)); } - const normalCases = cases.filter(c => !c.is_hidden); - const hiddenCases = cases.filter(c => c.is_hidden); + const normalCases = cases.filter((c) => !c.is_hidden); + const hiddenCases = cases.filter((c) => c.is_hidden); const userName = user instanceof UnknownUser && cases.length ? cases[cases.length - 1].user_name : user.tag; @@ -83,7 +83,7 @@ export const CasesUserCmd = modActionsCmd({ } else { // Compact view (= regular message with a preview of each case) const casesPlugin = pluginData.getPlugin(CasesPlugin); - const lines = await asyncMap(casesToDisplay, c => casesPlugin.getCaseSummary(c, true, msg.author.id)); + const lines = await asyncMap(casesToDisplay, (c) => casesPlugin.getCaseSummary(c, true, msg.author.id)); const prefix = getGuildPrefix(pluginData); const linesPerChunk = 10; diff --git a/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts b/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts index 4fee866f..83044c85 100644 --- a/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts @@ -42,7 +42,7 @@ export const MassunbanCmd = modActionsCmd({ // Ignore automatic unban cases and logs for these users // We'll create our own cases below and post a single "mass unbanned" log instead - args.userIds.forEach(userId => { + args.userIds.forEach((userId) => { // Use longer timeouts since this can take a while ignoreEvent(pluginData, IgnoredEventType.Unban, userId, 120 * 1000); pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, userId, 120 * 1000); @@ -91,19 +91,19 @@ export const MassunbanCmd = modActionsCmd({ }); if (failedUnbans.length) { - const notBanned = failedUnbans.filter(x => x.reason === UnbanFailReasons.NOT_BANNED); - const unbanFailed = failedUnbans.filter(x => x.reason === UnbanFailReasons.UNBAN_FAILED); + const notBanned = failedUnbans.filter((x) => x.reason === UnbanFailReasons.NOT_BANNED); + const unbanFailed = failedUnbans.filter((x) => x.reason === UnbanFailReasons.UNBAN_FAILED); let failedMsg = ""; if (notBanned.length > 0) { failedMsg += `${notBanned.length}x ${UnbanFailReasons.NOT_BANNED}:`; - notBanned.forEach(fail => { + notBanned.forEach((fail) => { failedMsg += " " + fail.userId; }); } if (unbanFailed.length > 0) { failedMsg += `\n${unbanFailed.length}x ${UnbanFailReasons.UNBAN_FAILED}:`; - unbanFailed.forEach(fail => { + unbanFailed.forEach((fail) => { failedMsg += " " + fail.userId; }); } diff --git a/backend/src/plugins/ModActions/commands/MassmuteCmd.ts b/backend/src/plugins/ModActions/commands/MassmuteCmd.ts index 7b5d50b1..ecd696df 100644 --- a/backend/src/plugins/ModActions/commands/MassmuteCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassmuteCmd.ts @@ -53,7 +53,7 @@ export const MassmuteCmd = modActionsCmd({ // Ignore automatic mute cases and logs for these users // We'll create our own cases below and post a single "mass muted" log instead - args.userIds.forEach(userId => { + args.userIds.forEach((userId) => { // Use longer timeouts since this can take a while pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_MUTE, userId, 120 * 1000); }); diff --git a/backend/src/plugins/ModActions/functions/clearIgnoredEvents.ts b/backend/src/plugins/ModActions/functions/clearIgnoredEvents.ts index cbcf082f..c16dabcf 100644 --- a/backend/src/plugins/ModActions/functions/clearIgnoredEvents.ts +++ b/backend/src/plugins/ModActions/functions/clearIgnoredEvents.ts @@ -7,7 +7,7 @@ export function clearIgnoredEvents( userId: string, ) { pluginData.state.ignoredEvents.splice( - pluginData.state.ignoredEvents.findIndex(info => type === info.type && userId === info.userId), + pluginData.state.ignoredEvents.findIndex((info) => type === info.type && userId === info.userId), 1, ); } diff --git a/backend/src/plugins/ModActions/functions/formatReasonWithAttachments.ts b/backend/src/plugins/ModActions/functions/formatReasonWithAttachments.ts index 809fe909..77194a3f 100644 --- a/backend/src/plugins/ModActions/functions/formatReasonWithAttachments.ts +++ b/backend/src/plugins/ModActions/functions/formatReasonWithAttachments.ts @@ -1,6 +1,6 @@ import { MessageAttachment } from "discord.js"; export function formatReasonWithAttachments(reason: string, attachments: MessageAttachment[]) { - const attachmentUrls = attachments.map(a => a.url); + const attachmentUrls = attachments.map((a) => a.url); return ((reason || "") + " " + attachmentUrls.join(" ")).trim(); } diff --git a/backend/src/plugins/ModActions/functions/isEventIgnored.ts b/backend/src/plugins/ModActions/functions/isEventIgnored.ts index 32ae4acf..8ec27baf 100644 --- a/backend/src/plugins/ModActions/functions/isEventIgnored.ts +++ b/backend/src/plugins/ModActions/functions/isEventIgnored.ts @@ -6,5 +6,5 @@ export function isEventIgnored( type: IgnoredEventType, userId: string, ) { - return pluginData.state.ignoredEvents.some(info => type === info.type && userId === info.userId); + return pluginData.state.ignoredEvents.some((info) => type === info.type && userId === info.userId); } diff --git a/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts b/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts index ad5b9666..cd18bf0f 100644 --- a/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts @@ -13,7 +13,7 @@ export const ClearBannedMutesCmd = mutesCmd({ const activeMutes = await pluginData.state.mutes.getActiveMutes(); const bans = await pluginData.guild.bans.fetch({ cache: true }); - const bannedIds = bans.map(b => b.user.id); + const bannedIds = bans.map((b) => b.user.id); await msg.channel.send(`Found ${activeMutes.length} mutes and ${bannedIds.length} bans, cross-referencing...`); diff --git a/backend/src/plugins/Mutes/commands/MutesCmd.ts b/backend/src/plugins/Mutes/commands/MutesCmd.ts index 99356e54..eeff2c4f 100644 --- a/backend/src/plugins/Mutes/commands/MutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/MutesCmd.ts @@ -53,12 +53,12 @@ export const MutesCmd = mutesCmd({ if (args.manual) { // Show only manual mutes (i.e. "Muted" role added without a logged mute) - const muteUserIds = new Set(activeMutes.map(m => m.user_id)); + const muteUserIds = new Set(activeMutes.map((m) => m.user_id)); const manuallyMutedMembers: GuildMember[] = []; const muteRole = pluginData.config.get().mute_role; if (muteRole) { - pluginData.guild.members.cache.forEach(member => { + pluginData.guild.members.cache.forEach((member) => { if (muteUserIds.has(member.id)) return; if (member.roles.cache.has(muteRole as Snowflake)) manuallyMutedMembers.push(member); }); @@ -66,7 +66,7 @@ export const MutesCmd = mutesCmd({ totalMutes = manuallyMutedMembers.length; - lines = manuallyMutedMembers.map(member => { + lines = manuallyMutedMembers.map((member) => { return `<@!${member.id}> (**${member.user.tag}**, \`${member.id}\`) 🔧 Manual mute`; }); } else { @@ -76,11 +76,8 @@ export const MutesCmd = mutesCmd({ // Filter: mute age if (args.age) { - const cutoff = moment - .utc() - .subtract(args.age, "ms") - .format(DBDateFormat); - filteredMutes = filteredMutes.filter(m => m.created_at <= cutoff); + const cutoff = moment.utc().subtract(args.age, "ms").format(DBDateFormat); + filteredMutes = filteredMutes.filter((m) => m.created_at <= cutoff); hasFilters = true; } @@ -93,7 +90,7 @@ export const MutesCmd = mutesCmd({ if (!member) { if (!bannedIds) { const bans = await pluginData.guild.bans.fetch({ cache: true }); - bannedIds = bans.map(u => u.user.id); + bannedIds = bans.map((u) => u.user.id); } muteWithDetails.banned = bannedIds.includes(mute.user_id); @@ -106,18 +103,18 @@ export const MutesCmd = mutesCmd({ // Filter: left the server if (args.left != null) { - filteredMutes = filteredMutes.filter(m => (args.left && !m.member) || (!args.left && m.member)); + filteredMutes = filteredMutes.filter((m) => (args.left && !m.member) || (!args.left && m.member)); hasFilters = true; } totalMutes = filteredMutes.length; // Create a message line for each mute - const caseIds = filteredMutes.map(m => m.case_id).filter(v => !!v); + const caseIds = filteredMutes.map((m) => m.case_id).filter((v) => !!v); const muteCases = caseIds.length ? await pluginData.state.cases.get(caseIds) : []; const muteCasesById = muteCases.reduce((map, c) => map.set(c.id, c), new Map()); - lines = filteredMutes.map(mute => { + lines = filteredMutes.map((mute) => { const user = pluginData.client.users.resolve(mute.user_id as Snowflake); const username = user ? user.tag : "Unknown#0000"; const theCase = muteCasesById.get(mute.case_id); @@ -152,7 +149,7 @@ export const MutesCmd = mutesCmd({ let currentPage = 1; const totalPages = Math.ceil(lines.length / mutesPerPage); - const drawListPage = async page => { + const drawListPage = async (page) => { page = Math.max(1, Math.min(totalPages, page)); currentPage = page; @@ -197,19 +194,9 @@ export const MutesCmd = mutesCmd({ const idMod = `${listMessage.id}:muteList`; const buttons: MessageButton[] = []; - buttons.push( - new MessageButton() - .setStyle("SECONDARY") - .setEmoji("⬅") - .setCustomId(`previousButton:${idMod}`), - ); + buttons.push(new MessageButton().setStyle("SECONDARY").setEmoji("⬅").setCustomId(`previousButton:${idMod}`)); - buttons.push( - new MessageButton() - .setStyle("SECONDARY") - .setEmoji("➡") - .setCustomId(`nextButton:${idMod}`), - ); + buttons.push(new MessageButton().setStyle("SECONDARY").setEmoji("➡").setCustomId(`nextButton:${idMod}`)); const row = new MessageActionRow().addComponents(buttons); await listMessage.edit({ components: [row] }); diff --git a/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts b/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts index 308fa5f1..dc83fee6 100644 --- a/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts +++ b/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts @@ -22,7 +22,7 @@ export async function clearExpiredMutes(pluginData: GuildPluginData roleId !== muteRole); + const newRoles = [...member.roles.cache.keys()].filter((roleId) => roleId !== muteRole); for (const toRestore of mute.roles_to_restore) { if (guildRoles.has(toRestore) && toRestore !== muteRole && !newRoles.includes(toRestore)) { newRoles.push(toRestore); diff --git a/backend/src/plugins/Mutes/functions/muteUser.ts b/backend/src/plugins/Mutes/functions/muteUser.ts index 4c39e091..cf0aeca0 100644 --- a/backend/src/plugins/Mutes/functions/muteUser.ts +++ b/backend/src/plugins/Mutes/functions/muteUser.ts @@ -67,12 +67,12 @@ export async function muteUser( if (!Array.isArray(removeRoles)) { if (removeRoles) { // exclude managed roles from being removed - const managedRoles = pluginData.guild.roles.cache.filter(x => x.managed).map(y => y.id); - newRoles = currentUserRoles.filter(r => !managedRoles.includes(r)); + const managedRoles = pluginData.guild.roles.cache.filter((x) => x.managed).map((y) => y.id); + newRoles = currentUserRoles.filter((r) => !managedRoles.includes(r)); await member.roles.set(newRoles as Snowflake[]); } } else { - newRoles = currentUserRoles.filter(x => !(removeRoles).includes(x)); + newRoles = currentUserRoles.filter((x) => !(removeRoles).includes(x)); await member.roles.set(newRoles as Snowflake[]); } @@ -82,7 +82,7 @@ export async function muteUser( rolesToRestore = currentUserRoles; } } else { - rolesToRestore = currentUserRoles.filter(x => (restoreRoles).includes(x)); + rolesToRestore = currentUserRoles.filter((x) => (restoreRoles).includes(x)); } // Apply mute role if it's missing @@ -100,9 +100,9 @@ export async function muteUser( } const zep = await resolveMember(pluginData.client, pluginData.guild, pluginData.client.user!.id); - const zepRoles = pluginData.guild.roles.cache.filter(x => zep!.roles.cache.has(x.id)); + const zepRoles = pluginData.guild.roles.cache.filter((x) => zep!.roles.cache.has(x.id)); // If we have roles and one of them is above the muted role, throw generic error - if (zepRoles.size >= 0 && zepRoles.some(zepRole => zepRole.position > actualMuteRole.position)) { + if (zepRoles.size >= 0 && zepRoles.some((zepRole) => zepRole.position > actualMuteRole.position)) { lock.unlock(); logs.logBotAlert({ body: `Cannot mute user ${member.id}: ${e}`, diff --git a/backend/src/plugins/Mutes/functions/unmuteUser.ts b/backend/src/plugins/Mutes/functions/unmuteUser.ts index 403d37d8..0f2d88d5 100644 --- a/backend/src/plugins/Mutes/functions/unmuteUser.ts +++ b/backend/src/plugins/Mutes/functions/unmuteUser.ts @@ -43,7 +43,7 @@ export async function unmuteUser( } if (existingMute?.roles_to_restore) { const guildRoles = pluginData.guild.roles.cache; - const newRoles = [...member.roles.cache.keys()].filter(roleId => roleId !== muteRole); + const newRoles = [...member.roles.cache.keys()].filter((roleId) => roleId !== muteRole); for (const toRestore of existingMute.roles_to_restore) { if (guildRoles.has(toRestore) && toRestore !== muteRole && !newRoles.includes(toRestore)) { newRoles.push(toRestore); diff --git a/backend/src/plugins/NameHistory/commands/NamesCmd.ts b/backend/src/plugins/NameHistory/commands/NamesCmd.ts index 710e7ba6..fcb8c242 100644 --- a/backend/src/plugins/NameHistory/commands/NamesCmd.ts +++ b/backend/src/plugins/NameHistory/commands/NamesCmd.ts @@ -26,9 +26,9 @@ export const NamesCmd = nameHistoryCmd({ } const nicknameRows = nicknames.map( - r => `\`[${r.timestamp}]\` ${r.nickname ? `**${disableCodeBlocks(r.nickname)}**` : "*None*"}`, + (r) => `\`[${r.timestamp}]\` ${r.nickname ? `**${disableCodeBlocks(r.nickname)}**` : "*None*"}`, ); - const usernameRows = usernames.map(r => `\`[${r.timestamp}]\` **${disableCodeBlocks(r.username)}**`); + const usernameRows = usernames.map((r) => `\`[${r.timestamp}]\` **${disableCodeBlocks(r.username)}**`); const user = await pluginData.client.users.fetch(args.userId as Snowflake).catch(() => null); const currentUsername = user ? user.tag : args.userId; diff --git a/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts b/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts index 17b1fc17..a0a88766 100644 --- a/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts +++ b/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts @@ -21,7 +21,7 @@ export const ScheduledPostsListCmd = postCmd({ scheduledPosts.sort(sorter("post_at")); let i = 1; - const postLines = scheduledPosts.map(p => { + const postLines = scheduledPosts.map((p) => { let previewText = p.content.content || p.content.embeds?.[0]?.description || p.content.embeds?.[0]?.title || ""; const isTruncated = previewText.length > SCHEDULED_POST_PREVIEW_TEXT_LENGTH; diff --git a/backend/src/plugins/Post/util/actualPostCmd.ts b/backend/src/plugins/Post/util/actualPostCmd.ts index dc1d662e..32320368 100644 --- a/backend/src/plugins/Post/util/actualPostCmd.ts +++ b/backend/src/plugins/Post/util/actualPostCmd.ts @@ -147,18 +147,10 @@ export async function actualPostCmd( channel_id: targetChannel.id, content, attachments: [...msg.attachments.values()], - post_at: postAt - .clone() - .tz("Etc/UTC") - .format(DBDateFormat), + post_at: postAt.clone().tz("Etc/UTC").format(DBDateFormat), enable_mentions: opts["enable-mentions"], repeat_interval: opts.repeat, - repeat_until: repeatUntil - ? repeatUntil - .clone() - .tz("Etc/UTC") - .format(DBDateFormat) - : null, + repeat_until: repeatUntil ? repeatUntil.clone().tz("Etc/UTC").format(DBDateFormat) : null, repeat_times: repeatTimes ?? null, }); diff --git a/backend/src/plugins/ReactionRoles/ReactionRolesPlugin.ts b/backend/src/plugins/ReactionRoles/ReactionRolesPlugin.ts index 076e13ed..a217c1e5 100644 --- a/backend/src/plugins/ReactionRoles/ReactionRolesPlugin.ts +++ b/backend/src/plugins/ReactionRoles/ReactionRolesPlugin.ts @@ -42,7 +42,7 @@ const defaultOptions: PluginOptions = { const MAXIMUM_COMPONENT_ROWS = 5; -const configPreprocessor: ConfigPreprocessorFn = options => { +const configPreprocessor: ConfigPreprocessorFn = (options) => { if (options.config.button_groups) { for (const [groupName, group] of Object.entries(options.config.button_groups)) { const defaultButtonNames = Object.keys(group.default_buttons); diff --git a/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts b/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts index 64a6e412..e724168a 100644 --- a/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts +++ b/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts @@ -58,17 +58,15 @@ export const InitReactionRolesCmd = reactionRolesCmd({ const emojiRolePairs: TReactionRolePair[] = args.reactionRolePairs .trim() .split("\n") - .map(v => v.split(/[\s=,]+/).map(v => v.trim())) // tslint:disable-line - .map( - (pair): TReactionRolePair => { - const customEmojiMatch = pair[0].match(/^$/); - if (customEmojiMatch) { - return [customEmojiMatch[2], pair[1], customEmojiMatch[1]]; - } else { - return pair as TReactionRolePair; - } - }, - ); + .map((v) => v.split(/[\s=,]+/).map((v) => v.trim())) // tslint:disable-line + .map((pair): TReactionRolePair => { + const customEmojiMatch = pair[0].match(/^$/); + if (customEmojiMatch) { + return [customEmojiMatch[2], pair[1], customEmojiMatch[1]]; + } else { + return pair as TReactionRolePair; + } + }); // Verify the specified emojis and roles are valid and usable for (const pair of emojiRolePairs) { diff --git a/backend/src/plugins/ReactionRoles/commands/PostButtonRolesCmd.ts b/backend/src/plugins/ReactionRoles/commands/PostButtonRolesCmd.ts index 040acf1b..c9747ed2 100644 --- a/backend/src/plugins/ReactionRoles/commands/PostButtonRolesCmd.ts +++ b/backend/src/plugins/ReactionRoles/commands/PostButtonRolesCmd.ts @@ -31,9 +31,7 @@ export const PostButtonRolesCmd = reactionRolesCmd({ const buttons: MessageButton[] = []; const toInsert: Array<{ customId; buttonGroup; buttonName }> = []; for (const [buttonName, button] of Object.entries(group.default_buttons)) { - const customId = createHash("md5") - .update(`${buttonName}${moment.utc().valueOf()}`) - .digest("hex"); + const customId = createHash("md5").update(`${buttonName}${moment.utc().valueOf()}`).digest("hex"); const btn = new MessageButton() .setLabel(button.label ?? "") diff --git a/backend/src/plugins/ReactionRoles/events/AddReactionRoleEvt.ts b/backend/src/plugins/ReactionRoles/events/AddReactionRoleEvt.ts index 1d7a116f..324405b3 100644 --- a/backend/src/plugins/ReactionRoles/events/AddReactionRoleEvt.ts +++ b/backend/src/plugins/ReactionRoles/events/AddReactionRoleEvt.ts @@ -29,7 +29,7 @@ export const AddReactionRoleEvt = reactionRolesEvt({ if (emoji.name === CLEAR_ROLES_EMOJI) { // User reacted with "clear roles" emoji -> clear their roles - const reactionRoleRoleIds = reactionRoles.map(rr => rr.role_id); + const reactionRoleRoleIds = reactionRoles.map((rr) => rr.role_id); for (const roleId of reactionRoleRoleIds) { addMemberPendingRoleChange(pluginData, userId, "-", roleId); } diff --git a/backend/src/plugins/ReactionRoles/util/applyReactionRoleReactionsToMessage.ts b/backend/src/plugins/ReactionRoles/util/applyReactionRoleReactionsToMessage.ts index 0c6334e9..a2641bfe 100644 --- a/backend/src/plugins/ReactionRoles/util/applyReactionRoleReactionsToMessage.ts +++ b/backend/src/plugins/ReactionRoles/util/applyReactionRoleReactionsToMessage.ts @@ -65,7 +65,7 @@ export async function applyReactionRoleReactionsToMessage( await sleep(1500); // Add reaction role reactions - const emojisToAdd = reactionRoles.map(rr => rr.emoji); + const emojisToAdd = reactionRoles.map((rr) => rr.emoji); emojisToAdd.push(CLEAR_ROLES_EMOJI); for (const rawEmoji of emojisToAdd) { diff --git a/backend/src/plugins/ReactionRoles/util/runAutoRefresh.ts b/backend/src/plugins/ReactionRoles/util/runAutoRefresh.ts index c365c18f..c1d2b42a 100644 --- a/backend/src/plugins/ReactionRoles/util/runAutoRefresh.ts +++ b/backend/src/plugins/ReactionRoles/util/runAutoRefresh.ts @@ -5,7 +5,7 @@ import { refreshReactionRoles } from "./refreshReactionRoles"; export async function runAutoRefresh(pluginData: GuildPluginData) { // Refresh reaction roles on all reaction role messages const reactionRoles = await pluginData.state.reactionRoles.all(); - const idPairs = new Set(reactionRoles.map(r => `${r.channel_id}-${r.message_id}`)); + const idPairs = new Set(reactionRoles.map((r) => `${r.channel_id}-${r.message_id}`)); for (const pair of idPairs) { const [channelId, messageId] = pair.split("-"); await refreshReactionRoles(pluginData, channelId, messageId); diff --git a/backend/src/plugins/Reminders/commands/RemindCmd.ts b/backend/src/plugins/Reminders/commands/RemindCmd.ts index 7cce547f..24c765a7 100644 --- a/backend/src/plugins/Reminders/commands/RemindCmd.ts +++ b/backend/src/plugins/Reminders/commands/RemindCmd.ts @@ -53,10 +53,7 @@ export const RemindCmd = remindersCmd({ await pluginData.state.reminders.add( msg.author.id, msg.channel.id, - reminderTime - .clone() - .tz("Etc/UTC") - .format("YYYY-MM-DD HH:mm:ss"), + reminderTime.clone().tz("Etc/UTC").format("YYYY-MM-DD HH:mm:ss"), reminderBody, moment.utc().format("YYYY-MM-DD HH:mm:ss"), ); diff --git a/backend/src/plugins/Roles/commands/MassAddRoleCmd.ts b/backend/src/plugins/Roles/commands/MassAddRoleCmd.ts index 998518da..0b09535c 100644 --- a/backend/src/plugins/Roles/commands/MassAddRoleCmd.ts +++ b/backend/src/plugins/Roles/commands/MassAddRoleCmd.ts @@ -60,7 +60,7 @@ export const MassAddRoleCmd = rolesCmd({ return; } - const membersWithoutTheRole = members.filter(m => !m.roles.cache.has(roleId)); + const membersWithoutTheRole = members.filter((m) => !m.roles.cache.has(roleId)); let assigned = 0; const failed: string[] = []; const alreadyHadRole = members.length - membersWithoutTheRole.length; diff --git a/backend/src/plugins/Roles/commands/MassRemoveRoleCmd.ts b/backend/src/plugins/Roles/commands/MassRemoveRoleCmd.ts index 1d4c7b0e..e5cedc42 100644 --- a/backend/src/plugins/Roles/commands/MassRemoveRoleCmd.ts +++ b/backend/src/plugins/Roles/commands/MassRemoveRoleCmd.ts @@ -60,7 +60,7 @@ export const MassRemoveRoleCmd = rolesCmd({ return; } - const membersWithTheRole = members.filter(m => m.roles.cache.has(roleId)); + const membersWithTheRole = members.filter((m) => m.roles.cache.has(roleId)); let assigned = 0; const failed: string[] = []; const didNotHaveRole = members.length - membersWithTheRole.length; diff --git a/backend/src/plugins/SelfGrantableRoles/SelfGrantableRolesPlugin.ts b/backend/src/plugins/SelfGrantableRoles/SelfGrantableRolesPlugin.ts index 981776fc..82396cb9 100644 --- a/backend/src/plugins/SelfGrantableRoles/SelfGrantableRolesPlugin.ts +++ b/backend/src/plugins/SelfGrantableRoles/SelfGrantableRolesPlugin.ts @@ -70,7 +70,7 @@ export const SelfGrantableRolesPlugin = zeppelinGuildPlugin { + configPreprocessor: (options) => { const config = options.config; for (const [key, entry] of Object.entries(config.entries)) { // Apply default entry config @@ -79,7 +79,7 @@ export const SelfGrantableRolesPlugin = zeppelinGuildPlugin a.toLowerCase()); + entry.roles[roleId] = aliases.map((a) => a.toLowerCase()); } } } diff --git a/backend/src/plugins/SelfGrantableRoles/commands/RoleAddCmd.ts b/backend/src/plugins/SelfGrantableRoles/commands/RoleAddCmd.ts index 8fa9cca4..ce8a3a73 100644 --- a/backend/src/plugins/SelfGrantableRoles/commands/RoleAddCmd.ts +++ b/backend/src/plugins/SelfGrantableRoles/commands/RoleAddCmd.ts @@ -31,7 +31,7 @@ export const RoleAddCmd = selfGrantableRolesCmd({ const hasUnknownRoles = matchedRoleIds.length !== roleNames.length; const rolesToAdd: Map = Array.from(matchedRoleIds.values()) - .map(id => pluginData.guild.roles.cache.get(id as Snowflake)!) + .map((id) => pluginData.guild.roles.cache.get(id as Snowflake)!) .filter(Boolean) .reduce((map, role) => { map.set(role.id, role); @@ -94,7 +94,7 @@ export const RoleAddCmd = selfGrantableRolesCmd({ } const mentionRoles = pluginData.config.get().mention_roles; - const addedRolesStr = Array.from(rolesToAdd.values()).map(r => (mentionRoles ? `<@&${r.id}>` : `**${r.name}**`)); + const addedRolesStr = Array.from(rolesToAdd.values()).map((r) => (mentionRoles ? `<@&${r.id}>` : `**${r.name}**`)); const addedRolesWord = rolesToAdd.size === 1 ? "role" : "roles"; const messageParts: string[] = []; @@ -104,11 +104,11 @@ export const RoleAddCmd = selfGrantableRolesCmd({ const skippedRolesStr = skipped.size ? "skipped " + Array.from(skipped.values()) - .map(r => (mentionRoles ? `<@&${r.id}>` : `**${r.name}**`)) + .map((r) => (mentionRoles ? `<@&${r.id}>` : `**${r.name}**`)) .join(",") : null; const removedRolesStr = removed.size - ? "removed " + Array.from(removed.values()).map(r => (mentionRoles ? `<@&${r.id}>` : `**${r.name}**`)) + ? "removed " + Array.from(removed.values()).map((r) => (mentionRoles ? `<@&${r.id}>` : `**${r.name}**`)) : null; const skippedRemovedStr = [skippedRolesStr, removedRolesStr].filter(Boolean).join(" and "); diff --git a/backend/src/plugins/SelfGrantableRoles/commands/RoleRemoveCmd.ts b/backend/src/plugins/SelfGrantableRoles/commands/RoleRemoveCmd.ts index 7a4bb83b..007aa459 100644 --- a/backend/src/plugins/SelfGrantableRoles/commands/RoleRemoveCmd.ts +++ b/backend/src/plugins/SelfGrantableRoles/commands/RoleRemoveCmd.ts @@ -29,20 +29,20 @@ export const RoleRemoveCmd = selfGrantableRolesCmd({ const matchedRoleIds = findMatchingRoles(roleNames, applyingEntries); const rolesToRemove = Array.from(matchedRoleIds.values()).map( - id => pluginData.guild.roles.cache.get(id as Snowflake)!, + (id) => pluginData.guild.roles.cache.get(id as Snowflake)!, ); - const roleIdsToRemove = rolesToRemove.map(r => r.id); + const roleIdsToRemove = rolesToRemove.map((r) => r.id); // Remove the roles if (rolesToRemove.length) { - const newRoleIds = msg.member.roles.cache.filter(role => !roleIdsToRemove.includes(role.id)); + const newRoleIds = msg.member.roles.cache.filter((role) => !roleIdsToRemove.includes(role.id)); try { await msg.member.edit({ roles: newRoleIds, }); - const removedRolesStr = rolesToRemove.map(r => `**${r.name}**`); + const removedRolesStr = rolesToRemove.map((r) => `**${r.name}**`); const removedRolesWord = rolesToRemove.length === 1 ? "role" : "roles"; if (rolesToRemove.length !== roleNames.length) { diff --git a/backend/src/plugins/SelfGrantableRoles/util/findMatchingRoles.ts b/backend/src/plugins/SelfGrantableRoles/util/findMatchingRoles.ts index 69daae02..42a6dd34 100644 --- a/backend/src/plugins/SelfGrantableRoles/util/findMatchingRoles.ts +++ b/backend/src/plugins/SelfGrantableRoles/util/findMatchingRoles.ts @@ -11,5 +11,5 @@ export function findMatchingRoles(roleNames: string[], entries: TSelfGrantableRo return map; }, new Map()); - return roleNames.map(roleName => aliasToRoleId.get(roleName)).filter(Boolean); + return roleNames.map((roleName) => aliasToRoleId.get(roleName)).filter(Boolean); } diff --git a/backend/src/plugins/SelfGrantableRoles/util/getApplyingEntries.ts b/backend/src/plugins/SelfGrantableRoles/util/getApplyingEntries.ts index 65495be4..25482d1c 100644 --- a/backend/src/plugins/SelfGrantableRoles/util/getApplyingEntries.ts +++ b/backend/src/plugins/SelfGrantableRoles/util/getApplyingEntries.ts @@ -11,5 +11,5 @@ export async function getApplyingEntries( ([k, e]) => e.can_use && !(!e.can_ignore_cooldown && pluginData.state.cooldowns.isOnCooldown(`${k}:${msg.author.id}`)), ) - .map(pair => pair[1]); + .map((pair) => pair[1]); } diff --git a/backend/src/plugins/SelfGrantableRoles/util/normalizeRoleNames.ts b/backend/src/plugins/SelfGrantableRoles/util/normalizeRoleNames.ts index 7f19a7bb..d0c6d6d2 100644 --- a/backend/src/plugins/SelfGrantableRoles/util/normalizeRoleNames.ts +++ b/backend/src/plugins/SelfGrantableRoles/util/normalizeRoleNames.ts @@ -1,3 +1,3 @@ export function normalizeRoleNames(roleNames: string[]) { - return roleNames.map(v => v.toLowerCase()); + return roleNames.map((v) => v.toLowerCase()); } diff --git a/backend/src/plugins/SelfGrantableRoles/util/splitRoleNames.ts b/backend/src/plugins/SelfGrantableRoles/util/splitRoleNames.ts index efd460d3..3baefee5 100644 --- a/backend/src/plugins/SelfGrantableRoles/util/splitRoleNames.ts +++ b/backend/src/plugins/SelfGrantableRoles/util/splitRoleNames.ts @@ -1,6 +1,6 @@ export function splitRoleNames(roleNames: string[]) { return roleNames - .map(v => v.split(/[\s,]+/)) + .map((v) => v.split(/[\s,]+/)) .flat() .filter(Boolean); } diff --git a/backend/src/plugins/Slowmode/SlowmodePlugin.ts b/backend/src/plugins/Slowmode/SlowmodePlugin.ts index 44fa92d8..8bdc76e2 100644 --- a/backend/src/plugins/Slowmode/SlowmodePlugin.ts +++ b/backend/src/plugins/Slowmode/SlowmodePlugin.ts @@ -69,7 +69,7 @@ export const SlowmodePlugin = zeppelinGuildPlugin()({ state.serverLogs = new GuildLogs(pluginData.guild.id); state.clearInterval = setInterval(() => clearExpiredSlowmodes(pluginData), BOT_SLOWMODE_CLEAR_INTERVAL); - state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg); + state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg); state.savedMessages.events.on("create", state.onMessageCreateFn); }, diff --git a/backend/src/plugins/Slowmode/commands/SlowmodeListCmd.ts b/backend/src/plugins/Slowmode/commands/SlowmodeListCmd.ts index 0ef7733c..58e2bffd 100644 --- a/backend/src/plugins/Slowmode/commands/SlowmodeListCmd.ts +++ b/backend/src/plugins/Slowmode/commands/SlowmodeListCmd.ts @@ -30,7 +30,7 @@ export const SlowmodeListCmd = slowmodeCmd({ } if (slowmodes.length) { - const lines = slowmodes.map(slowmode => { + const lines = slowmodes.map((slowmode) => { const humanized = humanizeDuration(slowmode.seconds * 1000); const type = slowmode.native ? "native slowmode" : "bot slowmode"; diff --git a/backend/src/plugins/Spam/SpamPlugin.ts b/backend/src/plugins/Spam/SpamPlugin.ts index 28cae2be..84182993 100644 --- a/backend/src/plugins/Spam/SpamPlugin.ts +++ b/backend/src/plugins/Spam/SpamPlugin.ts @@ -82,7 +82,7 @@ export const SpamPlugin = zeppelinGuildPlugin()({ const { state } = pluginData; state.expiryInterval = setInterval(() => clearOldRecentActions(pluginData), 1000 * 60); - state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg); + state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg); state.savedMessages.events.on("create", state.onMessageCreateFn); }, diff --git a/backend/src/plugins/Spam/util/clearOldRecentActions.ts b/backend/src/plugins/Spam/util/clearOldRecentActions.ts index 4f42211c..1c0857b3 100644 --- a/backend/src/plugins/Spam/util/clearOldRecentActions.ts +++ b/backend/src/plugins/Spam/util/clearOldRecentActions.ts @@ -6,5 +6,7 @@ const MAX_INTERVAL = 300; export function clearOldRecentActions(pluginData: GuildPluginData) { // TODO: Figure out expiry time from longest interval in the config? const expiryTimestamp = Date.now() - 1000 * MAX_INTERVAL; - pluginData.state.recentActions = pluginData.state.recentActions.filter(action => action.timestamp >= expiryTimestamp); + pluginData.state.recentActions = pluginData.state.recentActions.filter( + (action) => action.timestamp >= expiryTimestamp, + ); } diff --git a/backend/src/plugins/Spam/util/clearRecentUserActions.ts b/backend/src/plugins/Spam/util/clearRecentUserActions.ts index cfaf7b53..f4fab914 100644 --- a/backend/src/plugins/Spam/util/clearRecentUserActions.ts +++ b/backend/src/plugins/Spam/util/clearRecentUserActions.ts @@ -7,7 +7,7 @@ export function clearRecentUserActions( userId: string, actionGroupId: string, ) { - pluginData.state.recentActions = pluginData.state.recentActions.filter(action => { + pluginData.state.recentActions = pluginData.state.recentActions.filter((action) => { return action.type !== type || action.userId !== userId || action.actionGroupId !== actionGroupId; }); } diff --git a/backend/src/plugins/Spam/util/getRecentActions.ts b/backend/src/plugins/Spam/util/getRecentActions.ts index ff3f31ac..de652a28 100644 --- a/backend/src/plugins/Spam/util/getRecentActions.ts +++ b/backend/src/plugins/Spam/util/getRecentActions.ts @@ -8,7 +8,7 @@ export function getRecentActions( actionGroupId: string, since: number, ) { - return pluginData.state.recentActions.filter(action => { + return pluginData.state.recentActions.filter((action) => { if (action.timestamp < since) return false; if (action.type !== type) return false; if (action.actionGroupId !== actionGroupId) return false; diff --git a/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts b/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts index 17d9c748..ab95f5b3 100644 --- a/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts +++ b/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts @@ -103,8 +103,8 @@ export async function logAndDetectMessageSpam( // Get the offending message IDs // We also get the IDs of any messages after the last offending message, to account for lag before detection - const savedMessages = recentActions.map(a => a.extraData as SavedMessage); - const msgIds = savedMessages.map(m => m.id); + const savedMessages = recentActions.map((a) => a.extraData as SavedMessage); + const msgIds = savedMessages.map((m) => m.id); const lastDetectedMsgId = msgIds[msgIds.length - 1]; const additionalMessages = await pluginData.state.savedMessages.getUserMessagesByChannelAfterId( @@ -112,11 +112,11 @@ export async function logAndDetectMessageSpam( savedMessage.channel_id, lastDetectedMsgId, ); - additionalMessages.forEach(m => msgIds.push(m.id)); + additionalMessages.forEach((m) => msgIds.push(m.id)); // Then, if enabled, remove the spam messages if (spamConfig.clean !== false) { - msgIds.forEach(id => pluginData.state.logs.ignoreLog(LogType.MESSAGE_DELETE, id)); + msgIds.forEach((id) => pluginData.state.logs.ignoreLog(LogType.MESSAGE_DELETE, id)); (pluginData.guild.channels.cache.get(savedMessage.channel_id as Snowflake)! as TextChannel | undefined) ?.bulkDelete(msgIds as Snowflake[]) .catch(noop); @@ -126,7 +126,7 @@ export async function logAndDetectMessageSpam( const uniqueMessages = Array.from(new Set([...savedMessages, ...additionalMessages])); uniqueMessages.sort((a, b) => (a.id > b.id ? 1 : -1)); const lastHandledMsgId = uniqueMessages - .map(m => m.id) + .map((m) => m.id) .reduce((last, id): string => { return id > last ? id : last; }); @@ -188,7 +188,7 @@ export async function logAndDetectMessageSpam( }); } }, - err => { + (err) => { logger.error(`Error while detecting spam:\n${err}`); }, ); diff --git a/backend/src/plugins/Starboard/StarboardPlugin.ts b/backend/src/plugins/Starboard/StarboardPlugin.ts index a7ab3ff2..d6a60a11 100644 --- a/backend/src/plugins/Starboard/StarboardPlugin.ts +++ b/backend/src/plugins/Starboard/StarboardPlugin.ts @@ -157,7 +157,7 @@ export const StarboardPlugin = zeppelinGuildPlugin()({ afterLoad(pluginData) { const { state } = pluginData; - state.onMessageDeleteFn = msg => onMessageDelete(pluginData, msg); + state.onMessageDeleteFn = (msg) => onMessageDelete(pluginData, msg); state.savedMessages.events.on("delete", state.onMessageDeleteFn); }, diff --git a/backend/src/plugins/Starboard/events/StarboardReactionAddEvt.ts b/backend/src/plugins/Starboard/events/StarboardReactionAddEvt.ts index 992713bf..45b7e731 100644 --- a/backend/src/plugins/Starboard/events/StarboardReactionAddEvt.ts +++ b/backend/src/plugins/Starboard/events/StarboardReactionAddEvt.ts @@ -37,11 +37,11 @@ export const StarboardReactionAddEvt = starboardEvt({ const boardLock = await pluginData.locks.acquire(allStarboardsLock()); const applicableStarboards = Object.values(config.boards) - .filter(board => board.enabled) + .filter((board) => board.enabled) // Can't star messages in the starboard channel itself - .filter(board => board.channel_id !== msg.channel.id) + .filter((board) => board.channel_id !== msg.channel.id) // Matching emoji - .filter(board => { + .filter((board) => { return board.star_emoji!.some((boardEmoji: string) => { if (emoji.id) { // Custom emoji diff --git a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts index dc6e8781..053389db 100644 --- a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts +++ b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts @@ -59,10 +59,7 @@ export function createStarboardEmbedFromMessage( // If there are no embeds, add the first image attachment explicitly else if (msg.attachments.size) { for (const attachment of msg.attachments) { - const ext = path - .extname(attachment[1].name!) - .slice(1) - .toLowerCase(); + const ext = path.extname(attachment[1].name!).slice(1).toLowerCase(); if (imageAttachmentExtensions.includes(ext)) { embed.image = { url: attachment[1].url }; diff --git a/backend/src/plugins/Starboard/util/removeMessageFromStarboard.ts b/backend/src/plugins/Starboard/util/removeMessageFromStarboard.ts index f4635371..6535852f 100644 --- a/backend/src/plugins/Starboard/util/removeMessageFromStarboard.ts +++ b/backend/src/plugins/Starboard/util/removeMessageFromStarboard.ts @@ -11,7 +11,7 @@ export async function removeMessageFromStarboard( await pluginData.state.starboardReactions.deleteAllStarboardReactionsForMessageId(msg.message_id).catch(noop); // this code is now Almeida-certified and no longer ugly :ok_hand: :cake: - const channel = pluginData.client.channels.cache.find(c => c.id === msg.starboard_channel_id); + const channel = pluginData.client.channels.cache.find((c) => c.id === msg.starboard_channel_id); if (!channel?.isText()) return; const message = await channel.messages.fetch(msg.starboard_message_id).catch(noop); if (!message?.deletable) return; diff --git a/backend/src/plugins/Tags/TagsPlugin.ts b/backend/src/plugins/Tags/TagsPlugin.ts index 0b5763ff..1d1c7c0c 100644 --- a/backend/src/plugins/Tags/TagsPlugin.ts +++ b/backend/src/plugins/Tags/TagsPlugin.ts @@ -114,10 +114,10 @@ export const TagsPlugin = zeppelinGuildPlugin()({ afterLoad(pluginData) { const { state, guild } = pluginData; - state.onMessageCreateFn = msg => onMessageCreate(pluginData, msg); + state.onMessageCreateFn = (msg) => onMessageCreate(pluginData, msg); state.savedMessages.events.on("create", state.onMessageCreateFn); - state.onMessageDeleteFn = msg => onMessageDelete(pluginData, msg); + state.onMessageDeleteFn = (msg) => onMessageDelete(pluginData, msg); state.savedMessages.events.on("delete", state.onMessageDeleteFn); const timeAndDate = pluginData.getPlugin(TimeAndDatePlugin); @@ -167,10 +167,7 @@ export const TagsPlugin = zeppelinGuildPlugin()({ } const delayMS = convertDelayStringToMS(delay) ?? 0; - return moment - .utc(reference, "x") - .add(delayMS) - .valueOf(); + return moment.utc(reference, "x").add(delayMS).valueOf(); }, timeSub(...args) { @@ -189,10 +186,7 @@ export const TagsPlugin = zeppelinGuildPlugin()({ } const delayMS = convertDelayStringToMS(delay) ?? 0; - return moment - .utc(reference, "x") - .subtract(delayMS) - .valueOf(); + return moment.utc(reference, "x").subtract(delayMS).valueOf(); }, timeAgo(delay) { @@ -210,7 +204,7 @@ export const TagsPlugin = zeppelinGuildPlugin()({ return timeAndDate.inGuildTz(parsed).format("YYYY-MM-DD"); }, - mention: input => { + mention: (input) => { if (typeof input !== "string") { return ""; } @@ -233,7 +227,7 @@ export const TagsPlugin = zeppelinGuildPlugin()({ return ""; }, - isMention: input => { + isMention: (input) => { if (typeof input !== "string") { return false; } diff --git a/backend/src/plugins/Tags/commands/TagListCmd.ts b/backend/src/plugins/Tags/commands/TagListCmd.ts index 41febd5d..c50baaa5 100644 --- a/backend/src/plugins/Tags/commands/TagListCmd.ts +++ b/backend/src/plugins/Tags/commands/TagListCmd.ts @@ -13,7 +13,7 @@ export const TagListCmd = tagsCmd({ } const prefix = (await pluginData.config.getForMessage(msg)).prefix; - const tagNames = tags.map(tag => tag.tag).sort(); + const tagNames = tags.map((tag) => tag.tag).sort(); createChunkedMessage(msg.channel, `Available tags (use with ${prefix}tag): \`\`\`${tagNames.join(", ")}\`\`\``); }, diff --git a/backend/src/plugins/Tags/util/onMessageCreate.ts b/backend/src/plugins/Tags/util/onMessageCreate.ts index 46dcf570..f64906e8 100644 --- a/backend/src/plugins/Tags/util/onMessageCreate.ts +++ b/backend/src/plugins/Tags/util/onMessageCreate.ts @@ -79,7 +79,7 @@ export async function onMessageCreate(pluginData: GuildPluginData pluginData.cooldowns.isOnCooldown(cd[0])); + const isOnCooldown = cooldowns.some((cd) => pluginData.cooldowns.isOnCooldown(cd[0])); if (isOnCooldown) return; for (const cd of cooldowns) { diff --git a/backend/src/plugins/Tags/util/renderTagBody.ts b/backend/src/plugins/Tags/util/renderTagBody.ts index de175d73..5174e7b1 100644 --- a/backend/src/plugins/Tags/util/renderTagBody.ts +++ b/backend/src/plugins/Tags/util/renderTagBody.ts @@ -65,6 +65,6 @@ export async function renderTagBody( return { content: await renderTemplate(body, data) }; } else { // Embed - return renderRecursively(body, str => renderTemplate(str, data)); + return renderRecursively(body, (str) => renderTemplate(str, data)); } } diff --git a/backend/src/plugins/Tags/util/renderTagFromString.ts b/backend/src/plugins/Tags/util/renderTagFromString.ts index 4a22310c..b482741d 100644 --- a/backend/src/plugins/Tags/util/renderTagFromString.ts +++ b/backend/src/plugins/Tags/util/renderTagFromString.ts @@ -17,7 +17,7 @@ export async function renderTagFromString( member: GuildMember, ): Promise { const variableStr = str.slice(prefix.length + tagName.length).trim(); - const tagArgs = parseArguments(variableStr).map(v => v.value); + const tagArgs = parseArguments(variableStr).map((v) => v.value); // Format the string try { diff --git a/backend/src/plugins/Utility/commands/AboutCmd.ts b/backend/src/plugins/Utility/commands/AboutCmd.ts index 219afc15..369c1201 100644 --- a/backend/src/plugins/Utility/commands/AboutCmd.ts +++ b/backend/src/plugins/Utility/commands/AboutCmd.ts @@ -55,10 +55,7 @@ export const AboutCmd = utilityCmd({ ]; const loadedPlugins = Array.from( - pluginData - .getKnubInstance() - .getLoadedGuild(pluginData.guild.id)! - .loadedPlugins.keys(), + pluginData.getKnubInstance().getLoadedGuild(pluginData.guild.id)!.loadedPlugins.keys(), ); loadedPlugins.sort(); @@ -100,9 +97,9 @@ export const AboutCmd = utilityCmd({ // For the embed color, find the highest colored role the bot has - this is their color on the server as well const botMember = await resolveMember(pluginData.client, pluginData.guild, pluginData.client.user!.id); - let botRoles = botMember?.roles.cache.map(r => (msg.channel as GuildChannel).guild.roles.cache.get(r.id)!) || []; - botRoles = botRoles.filter(r => !!r); // Drop any unknown roles - botRoles = botRoles.filter(r => r.color); // Filter to those with a color + let botRoles = botMember?.roles.cache.map((r) => (msg.channel as GuildChannel).guild.roles.cache.get(r.id)!) || []; + botRoles = botRoles.filter((r) => !!r); // Drop any unknown roles + botRoles = botRoles.filter((r) => r.color); // Filter to those with a color botRoles.sort(sorter("position", "DESC")); // Sort by position (highest first) if (botRoles.length) { aboutContent.embeds![0].color = botRoles[0].color; diff --git a/backend/src/plugins/Utility/commands/CleanCmd.ts b/backend/src/plugins/Utility/commands/CleanCmd.ts index 7a852721..60e79f26 100644 --- a/backend/src/plugins/Utility/commands/CleanCmd.ts +++ b/backend/src/plugins/Utility/commands/CleanCmd.ts @@ -30,10 +30,10 @@ export async function cleanMessages( // Delete & archive in ID order savedMessages = Array.from(savedMessages).sort((a, b) => (a.id > b.id ? 1 : -1)); - const idsToDelete = savedMessages.map(m => m.id) as Snowflake[]; + const idsToDelete = savedMessages.map((m) => m.id) as Snowflake[]; // Make sure the deletions aren't double logged - idsToDelete.forEach(id => pluginData.state.logs.ignoreLog(LogType.MESSAGE_DELETE, id)); + idsToDelete.forEach((id) => pluginData.state.logs.ignoreLog(LogType.MESSAGE_DELETE, id)); pluginData.state.logs.ignoreLog(LogType.MESSAGE_DELETE_BULK, idsToDelete[0]); // Actually delete the messages @@ -171,12 +171,12 @@ export async function cleanCmd(pluginData: GuildPluginData, a let responseMsg: Message | undefined; if (messagesToClean.length > 0) { // Save to-be-deleted messages that were missing from the database - const existingStored = await pluginData.state.savedMessages.getMultiple(messagesToClean.map(m => m.id)); - const alreadyStored = existingStored.map(stored => stored.id); - const messagesToStore = messagesToClean.filter(potentialMsg => !alreadyStored.includes(potentialMsg.id)); + const existingStored = await pluginData.state.savedMessages.getMultiple(messagesToClean.map((m) => m.id)); + const alreadyStored = existingStored.map((stored) => stored.id); + const messagesToStore = messagesToClean.filter((potentialMsg) => !alreadyStored.includes(potentialMsg.id)); await pluginData.state.savedMessages.createFromMessages(messagesToStore); - const savedMessagesToClean = await pluginData.state.savedMessages.getMultiple(messagesToClean.map(m => m.id)); + const savedMessagesToClean = await pluginData.state.savedMessages.getMultiple(messagesToClean.map((m) => m.id)); const cleanResult = await cleanMessages(pluginData, targetChannel, savedMessagesToClean, msg.author); let responseText = `Cleaned ${messagesToClean.length} ${messagesToClean.length === 1 ? "message" : "messages"}`; diff --git a/backend/src/plugins/Utility/commands/HelpCmd.ts b/backend/src/plugins/Utility/commands/HelpCmd.ts index 5966cbc9..b03d3aa4 100644 --- a/backend/src/plugins/Utility/commands/HelpCmd.ts +++ b/backend/src/plugins/Utility/commands/HelpCmd.ts @@ -58,10 +58,7 @@ export const HelpCmd = utilityCmd({ const description = command.config!.extra!.blueprint.description; const usage = command.config!.extra!.blueprint.usage; - const commandSlug = trigger - .trim() - .toLowerCase() - .replace(/\s/g, "-"); + const commandSlug = trigger.trim().toLowerCase().replace(/\s/g, "-"); let snippet = `**${prefix}${trigger}**`; if (description) snippet += `\n${description}`; diff --git a/backend/src/plugins/Utility/commands/RolesCmd.ts b/backend/src/plugins/Utility/commands/RolesCmd.ts index 2aa3f459..6734d167 100644 --- a/backend/src/plugins/Utility/commands/RolesCmd.ts +++ b/backend/src/plugins/Utility/commands/RolesCmd.ts @@ -28,7 +28,7 @@ export const RolesCmd = utilityCmd({ if (args.search) { const searchStr = args.search.toLowerCase(); - roles = roles.filter(r => r.name.toLowerCase().includes(searchStr) || r.id === searchStr); + roles = roles.filter((r) => r.name.toLowerCase().includes(searchStr) || r.id === searchStr); } if (args.counts) { @@ -75,7 +75,7 @@ export const RolesCmd = utilityCmd({ } else if (sort === "memberCount" && args.counts) { roles.sort(sorter("_memberCount", sortDir)); } else if (sort === "name") { - roles.sort(sorter(r => r.name.toLowerCase(), sortDir)); + roles.sort(sorter((r) => r.name.toLowerCase(), sortDir)); } else { sendErrorMessage(pluginData, msg.channel, "Unknown sorting method"); return; @@ -85,7 +85,7 @@ export const RolesCmd = utilityCmd({ const chunks = chunkArray(roles, 20); for (const [i, chunk] of chunks.entries()) { - const roleLines = chunk.map(role => { + const roleLines = chunk.map((role) => { const paddedId = role.id.padEnd(longestId, " "); let line = `${paddedId} ${role.name}`; if (role._memberCount != null) { diff --git a/backend/src/plugins/Utility/commands/VcmoveCmd.ts b/backend/src/plugins/Utility/commands/VcmoveCmd.ts index 0f852e14..935fa0b1 100644 --- a/backend/src/plugins/Utility/commands/VcmoveCmd.ts +++ b/backend/src/plugins/Utility/commands/VcmoveCmd.ts @@ -50,7 +50,7 @@ export const VcmoveCmd = utilityCmd({ const voiceChannels = [...pluginData.guild.channels.cache.values()].filter( (c): c is VoiceChannel => c.type === ChannelTypeStrings.VOICE, ); - const closestMatch = simpleClosestStringMatch(args.channel, voiceChannels, ch => ch.name); + const closestMatch = simpleClosestStringMatch(args.channel, voiceChannels, (ch) => ch.name); if (!closestMatch) { sendErrorMessage(pluginData, msg.channel, "No matching voice channels"); return; @@ -129,7 +129,7 @@ export const VcmoveAllCmd = utilityCmd({ const voiceChannels = [...pluginData.guild.channels.cache.values()].filter( (c): c is VoiceChannel => c.type === ChannelTypeStrings.VOICE, ); - const closestMatch = simpleClosestStringMatch(args.channel, voiceChannels, ch => ch.name); + const closestMatch = simpleClosestStringMatch(args.channel, voiceChannels, (ch) => ch.name); if (!closestMatch) { sendErrorMessage(pluginData, msg.channel, "No matching voice channels"); return; diff --git a/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts b/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts index 5052ac11..9d050b3f 100644 --- a/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts @@ -96,8 +96,8 @@ export async function getChannelInfoEmbed( if (channel.type === ChannelTypeStrings.VOICE || channel.type === ChannelTypeStrings.STAGE) { const voiceMembers = Array.from((channel as VoiceChannel | StageChannel).members.values()); - const muted = voiceMembers.filter(vm => vm.voice.mute || vm.voice.selfMute); - const deafened = voiceMembers.filter(vm => vm.voice.deaf || vm.voice.selfDeaf); + const muted = voiceMembers.filter((vm) => vm.voice.mute || vm.voice.selfMute); + const deafened = voiceMembers.filter((vm) => vm.voice.deaf || vm.voice.selfDeaf); const voiceOrStage = channel.type === ChannelTypeStrings.VOICE ? "Voice" : "Stage"; embed.fields.push({ @@ -112,10 +112,10 @@ export async function getChannelInfoEmbed( if (channel.type === ChannelTypeStrings.CATEGORY) { const textChannels = pluginData.guild.channels.cache.filter( - ch => ch.parentId === channel.id && ch.type !== ChannelTypeStrings.VOICE, + (ch) => ch.parentId === channel.id && ch.type !== ChannelTypeStrings.VOICE, ); const voiceChannels = pluginData.guild.channels.cache.filter( - ch => + (ch) => ch.parentId === channel.id && (ch.type === ChannelTypeStrings.VOICE || ch.type === ChannelTypeStrings.STAGE), ); diff --git a/backend/src/plugins/Utility/functions/getEmojiInfoEmbed.ts b/backend/src/plugins/Utility/functions/getEmojiInfoEmbed.ts index 02228924..a97d5310 100644 --- a/backend/src/plugins/Utility/functions/getEmojiInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getEmojiInfoEmbed.ts @@ -7,7 +7,7 @@ export async function getEmojiInfoEmbed( pluginData: GuildPluginData, emojiId: string, ): Promise { - const emoji = pluginData.guild.emojis.cache.find(e => e.id === emojiId); + const emoji = pluginData.guild.emojis.cache.find((e) => e.id === emojiId); if (!emoji) { return null; } diff --git a/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts b/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts index 4a7215ed..a0a987e7 100644 --- a/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts @@ -120,9 +120,7 @@ export async function getInviteInfoEmbed( /*if (invite.channel.icon) { embed.author.icon_url = `https://cdn.discordapp.com/channel-icons/${invite.channel.id}/${invite.channel.icon}.png?size=256`; - }*/ const channelCreatedAtTimestamp = snowflakeToTimestamp( - invite.channel.id, - ); + }*/ const channelCreatedAtTimestamp = snowflakeToTimestamp(invite.channel.id); const channelCreatedAt = moment.utc(channelCreatedAtTimestamp, "x"); const channelAge = humanizeDuration(Date.now() - channelCreatedAtTimestamp, { largest: 2, diff --git a/backend/src/plugins/Utility/functions/getRoleInfoEmbed.ts b/backend/src/plugins/Utility/functions/getRoleInfoEmbed.ts index 4f16c31a..36a664e3 100644 --- a/backend/src/plugins/Utility/functions/getRoleInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getRoleInfoEmbed.ts @@ -35,13 +35,13 @@ export async function getRoleInfoEmbed( round: true, }); - const rolePerms = Object.keys(role.permissions.toJSON()).map(p => + const rolePerms = Object.keys(role.permissions.toJSON()).map((p) => p // Voice channel related permission names start with 'voice' .replace(/^voice/i, "") .replace(/([a-z])([A-Z])/g, "$1 $2") .toLowerCase() - .replace(/(^\w{1})|(\s{1}\w{1})/g, l => l.toUpperCase()), + .replace(/(^\w{1})|(\s{1}\w{1})/g, (l) => l.toUpperCase()), ); // -1 because of the @everyone role @@ -54,10 +54,7 @@ export async function getRoleInfoEmbed( ID: \`${role.id}\` Created: **${roleAge} ago** (\`${prettyCreatedAt}\`) Position: **${role.position} / ${totalGuildRoles}** - Color: **#${role.color - .toString(16) - .toUpperCase() - .padStart(6, "0")}** + Color: **#${role.color.toString(16).toUpperCase().padStart(6, "0")}** Mentionable: **${role.mentionable ? "Yes" : "No"}** Hoisted: **${role.hoist ? "Yes" : "No"}** Permissions: \`${rolePerms.length ? rolePerms.join(", ") : "None"}\` diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index 91728e04..03d7212d 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -134,7 +134,7 @@ export async function getServerInfoEmbed( } if (!onlineMemberCount && thisServer) { - onlineMemberCount = thisServer.members.cache.filter(m => m.presence?.status !== "offline").size; // Extremely inaccurate fallback + onlineMemberCount = thisServer.members.cache.filter((m) => m.presence?.status !== "offline").size; // Extremely inaccurate fallback } const offlineMemberCount = totalMembers - onlineMemberCount; @@ -162,9 +162,9 @@ export async function getServerInfoEmbed( // CHANNEL COUNTS if (thisServer) { const totalChannels = thisServer.channels.cache.size; - const categories = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.CATEGORY); - const textChannels = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.TEXT); - const voiceChannels = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.VOICE); + const categories = thisServer.channels.cache.filter((channel) => channel.type === ChannelTypeStrings.CATEGORY); + const textChannels = thisServer.channels.cache.filter((channel) => channel.type === ChannelTypeStrings.TEXT); + const voiceChannels = thisServer.channels.cache.filter((channel) => channel.type === ChannelTypeStrings.VOICE); embed.fields.push({ name: preEmbedPadding + "Channels", diff --git a/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts b/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts index d4e74637..39cf4166 100644 --- a/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts @@ -102,14 +102,14 @@ export async function getUserInfoEmbed( largest: 2, round: true, }); - const roles = Array.from(member.roles.cache.values()).filter(r => r.id !== pluginData.guild.id); + const roles = Array.from(member.roles.cache.values()).filter((r) => r.id !== pluginData.guild.id); roles.sort(sorter("position", "DESC")); embed.fields.push({ name: preEmbedPadding + "Member information", value: trimLines(` ${user.bot ? "Added" : "Joined"}: **${joinAge} ago** (\`${prettyJoinedAt}\`) - ${roles.length > 0 ? "Roles: " + roles.map(r => `<@&${r.id}>`).join(", ") : ""} + ${roles.length > 0 ? "Roles: " + roles.map((r) => `<@&${r.id}>`).join(", ") : ""} `), }); @@ -130,14 +130,14 @@ export async function getUserInfoEmbed( value: `⚠ ${user.bot ? "Bot" : "User"} is not on the server`, }); } - const cases = (await pluginData.state.cases.getByUserId(user.id)).filter(c => !c.is_hidden); + const cases = (await pluginData.state.cases.getByUserId(user.id)).filter((c) => !c.is_hidden); if (cases.length > 0) { cases.sort((a, b) => { return a.created_at < b.created_at ? 1 : -1; }); - const caseSummary = cases.slice(0, 3).map(c => { + const caseSummary = cases.slice(0, 3).map((c) => { const summaryText = `${CaseTypes[c.type]} (#${c.case_number})`; if (c.log_message_id) { diff --git a/backend/src/plugins/Utility/search.ts b/backend/src/plugins/Utility/search.ts index 4717dd31..b2b417b7 100644 --- a/backend/src/plugins/Utility/search.ts +++ b/backend/src/plugins/Utility/search.ts @@ -90,7 +90,7 @@ export async function displaySearch( const perPage = args.ids ? SEARCH_ID_RESULTS_PER_PAGE : SEARCH_RESULTS_PER_PAGE; - const loadSearchPage = async page => { + const loadSearchPage = async (page) => { if (searching) return; searching = true; @@ -101,7 +101,7 @@ export async function displaySearch( searchMsgPromise = originalSearchMsg.edit("Searching..."); } else { searchMsgPromise = msg.channel.send("Searching..."); - searchMsgPromise.then(m => (originalSearchMsg = m)); + searchMsgPromise.then((m) => (originalSearchMsg = m)); } let searchResult; @@ -182,10 +182,7 @@ export async function displaySearch( .setEmoji("➡") .setCustomId(`nextButton:${idMod}`) .setDisabled(currentPage === searchResult.lastPage), - new MessageButton() - .setStyle("SECONDARY") - .setEmoji("🔄") - .setCustomId(`reloadButton:${idMod}`), + new MessageButton().setStyle("SECONDARY").setEmoji("🔄").setCustomId(`reloadButton:${idMod}`), ); const row = new MessageActionRow().addComponents(buttons); @@ -308,7 +305,7 @@ async function performMemberSearch( if (args.role) { const roleIds = args.role.split(","); - matchingMembers = matchingMembers.filter(member => { + matchingMembers = matchingMembers.filter((member) => { for (const role of roleIds) { if (!member.roles.cache.has(role as Snowflake)) return false; } @@ -318,11 +315,11 @@ async function performMemberSearch( } if (args.voice) { - matchingMembers = matchingMembers.filter(m => m.voice.channelId); + matchingMembers = matchingMembers.filter((m) => m.voice.channelId); } if (args.bot) { - matchingMembers = matchingMembers.filter(m => m.user.bot); + matchingMembers = matchingMembers.filter((m) => m.user.bot); } if (args.query) { @@ -379,7 +376,7 @@ async function performMemberSearch( }); } else { */ - matchingMembers = await asyncFilter(matchingMembers, async member => { + matchingMembers = await asyncFilter(matchingMembers, async (member) => { if (member.nickname && (await execRegExp(queryRegex, member.nickname).catch(allowTimeout))) { return true; } @@ -396,12 +393,12 @@ async function performMemberSearch( const realSortDir = sortDir === "-" ? "DESC" : "ASC"; if (sortBy === "id") { - matchingMembers.sort(sorter(m => BigInt(m.id), realSortDir)); + matchingMembers.sort(sorter((m) => BigInt(m.id), realSortDir)); } else { matchingMembers.sort( multiSorter([ - [m => m.user.username.toLowerCase(), realSortDir], - [m => m.discriminator, realSortDir], + [(m) => m.user.username.toLowerCase(), realSortDir], + [(m) => m.discriminator, realSortDir], ]), ); } @@ -435,7 +432,7 @@ async function performBanSearch( throw new SearchError(`Unable to search bans: missing "Ban Members" permission`); } - let matchingBans = (await pluginData.guild.bans.fetch({ cache: false })).map(x => x.user); + let matchingBans = (await pluginData.guild.bans.fetch({ cache: false })).map((x) => x.user); if (args.query) { let isSafeRegex = true; @@ -450,7 +447,7 @@ async function performBanSearch( } const execRegExp = getOptimizedRegExpRunner(pluginData, isSafeRegex); - matchingBans = await asyncFilter(matchingBans, async user => { + matchingBans = await asyncFilter(matchingBans, async (user) => { const fullUsername = user.tag; if (await execRegExp(queryRegex, fullUsername).catch(allowTimeout)) return true; return false; @@ -461,12 +458,12 @@ async function performBanSearch( const realSortDir = sortDir === "-" ? "DESC" : "ASC"; if (sortBy === "id") { - matchingBans.sort(sorter(m => BigInt(m.id), realSortDir)); + matchingBans.sort(sorter((m) => BigInt(m.id), realSortDir)); } else { matchingBans.sort( multiSorter([ - [m => m.username.toLowerCase(), realSortDir], - [m => m.discriminator, realSortDir], + [(m) => m.username.toLowerCase(), realSortDir], + [(m) => m.discriminator, realSortDir], ]), ); } @@ -491,7 +488,7 @@ async function performBanSearch( function formatSearchResultList(members: Array): string { const longestId = members.reduce((longest, member) => Math.max(longest, member.id.length), 0); - const lines = members.map(member => { + const lines = members.map((member) => { const paddedId = member.id.padEnd(longestId, " "); let line; if (member instanceof GuildMember) { @@ -506,5 +503,5 @@ function formatSearchResultList(members: Array): string { } function formatSearchResultIdList(members: Array): string { - return members.map(m => m.id).join(" "); + return members.map((m) => m.id).join(" "); } diff --git a/backend/src/plugins/ZeppelinPluginBlueprint.ts b/backend/src/plugins/ZeppelinPluginBlueprint.ts index 9bcd3417..0bc7dbce 100644 --- a/backend/src/plugins/ZeppelinPluginBlueprint.ts +++ b/backend/src/plugins/ZeppelinPluginBlueprint.ts @@ -41,7 +41,7 @@ export function zeppelinGuildPlugin(): < - TBlueprint extends ZeppelinGuildPluginBlueprint> + TBlueprint extends ZeppelinGuildPluginBlueprint>, >( blueprint: TBlueprint, ) => TBlueprint & { @@ -50,9 +50,9 @@ export function zeppelinGuildPlugin(): < export function zeppelinGuildPlugin(...args) { if (args.length) { - const blueprint = (typedGuildPlugin( + const blueprint = typedGuildPlugin( ...(args as Parameters), - ) as unknown) as ZeppelinGuildPluginBlueprint; + ) as unknown as ZeppelinGuildPluginBlueprint; blueprint.configPreprocessor = getPluginConfigPreprocessor(blueprint, blueprint.configPreprocessor); return blueprint; } else { @@ -75,7 +75,7 @@ export function zeppelinGlobalPlugin(): < - TBlueprint extends ZeppelinGlobalPluginBlueprint + TBlueprint extends ZeppelinGlobalPluginBlueprint, >( blueprint: TBlueprint, ) => TBlueprint & { @@ -84,9 +84,9 @@ export function zeppelinGlobalPlugin(): < export function zeppelinGlobalPlugin(...args) { if (args.length) { - const blueprint = (typedGlobalPlugin( + const blueprint = typedGlobalPlugin( ...(args as Parameters), - ) as unknown) as ZeppelinGlobalPluginBlueprint; + ) as unknown as ZeppelinGlobalPluginBlueprint; // @ts-ignore FIXME: Check the types here blueprint.configPreprocessor = getPluginConfigPreprocessor(blueprint, blueprint.configPreprocessor); return blueprint; diff --git a/backend/src/templateFormatter.test.ts b/backend/src/templateFormatter.test.ts index 39132731..24aaa881 100644 --- a/backend/src/templateFormatter.test.ts +++ b/backend/src/templateFormatter.test.ts @@ -1,12 +1,12 @@ import test from "ava"; import { parseTemplate, renderParsedTemplate, renderTemplate, TemplateSafeValueContainer } from "./templateFormatter"; -test("Parses plain string templates correctly", t => { +test("Parses plain string templates correctly", (t) => { const result = parseTemplate("foo bar baz"); t.deepEqual(result, ["foo bar baz"]); }); -test("Parses templates with variables correctly", t => { +test("Parses templates with variables correctly", (t) => { const result = parseTemplate("foo {bar} baz"); t.deepEqual(result, [ "foo ", @@ -18,7 +18,7 @@ test("Parses templates with variables correctly", t => { ]); }); -test("Parses templates with function variables correctly", t => { +test("Parses templates with function variables correctly", (t) => { const result = parseTemplate('foo {bar("str", 5.07)} baz'); t.deepEqual(result, [ "foo ", @@ -30,7 +30,7 @@ test("Parses templates with function variables correctly", t => { ]); }); -test("Parses function variables with variable arguments correctly", t => { +test("Parses function variables with variable arguments correctly", (t) => { const result = parseTemplate('foo {bar("str", 5.07, someVar)} baz'); t.deepEqual(result, [ "foo ", @@ -49,7 +49,7 @@ test("Parses function variables with variable arguments correctly", t => { ]); }); -test("Parses function variables with function variable arguments correctly", t => { +test("Parses function variables with function variable arguments correctly", (t) => { const result = parseTemplate('foo {bar("str", 5.07, deeply(nested(8)))} baz'); t.deepEqual(result, [ "foo ", @@ -73,7 +73,7 @@ test("Parses function variables with function variable arguments correctly", t = ]); }); -test("Renders a parsed template correctly", async t => { +test("Renders a parsed template correctly", async (t) => { const parseResult = parseTemplate('foo {bar("str", 5.07, deeply(nested(8)))} baz'); const values = new TemplateSafeValueContainer({ bar(strArg, numArg, varArg) { @@ -91,18 +91,18 @@ test("Renders a parsed template correctly", async t => { t.is(renderResult, "foo str 5.07 !! baz"); }); -test("Supports base values in renderTemplate", async t => { +test("Supports base values in renderTemplate", async (t) => { const result = await renderTemplate('{if("", "+", "-")} {if(1, "+", "-")}'); t.is(result, "- +"); }); -test("Edge case #1", async t => { +test("Edge case #1", async (t) => { const result = await renderTemplate("{foo} {bar()}"); // No "Unclosed function" exception = success t.pass(); }); -test("Parses empty string args as empty strings", async t => { +test("Parses empty string args as empty strings", async (t) => { const result = parseTemplate('{foo("")}'); t.deepEqual(result, [ { diff --git a/backend/src/templateFormatter.ts b/backend/src/templateFormatter.ts index 2ed902d9..0dcb7bde 100644 --- a/backend/src/templateFormatter.ts +++ b/backend/src/templateFormatter.ts @@ -51,7 +51,7 @@ function isTemplateSafeValue(value: unknown): value is TemplateSafeValue { typeof value === "number" || typeof value === "boolean" || typeof value === "function" || - (Array.isArray(value) && value.every(v => isTemplateSafeValue(v))) || + (Array.isArray(value) && value.every((v) => isTemplateSafeValue(v))) || value instanceof TemplateSafeValueContainer ); } @@ -89,7 +89,7 @@ export function createTypedTemplateSafeValueContainer { + arr.forEach((item) => { if (typeof item === "object") { delete item._state; delete item._parent; diff --git a/backend/src/utils.test.ts b/backend/src/utils.test.ts index abd89774..ecf773a3 100644 --- a/backend/src/utils.test.ts +++ b/backend/src/utils.test.ts @@ -5,51 +5,51 @@ import { ErisAllowedMentionFormat } from "./utils/erisAllowedMentionsToDjsMentio type AssertEquals = TActual extends TExpected ? true : false; -test("getUrlsInString(): detects full links", t => { +test("getUrlsInString(): detects full links", (t) => { const urls = getUrlsInString("foo https://google.com/ bar"); t.is(urls.length, 1); t.is(urls[0].hostname, "google.com"); }); -test("getUrlsInString(): detects partial links", t => { +test("getUrlsInString(): detects partial links", (t) => { const urls = getUrlsInString("foo google.com bar"); t.is(urls.length, 1); t.is(urls[0].hostname, "google.com"); }); -test("getUrlsInString(): detects subdomains", t => { +test("getUrlsInString(): detects subdomains", (t) => { const urls = getUrlsInString("foo photos.google.com bar"); t.is(urls.length, 1); t.is(urls[0].hostname, "photos.google.com"); }); -test("delay strings: basic support", t => { +test("delay strings: basic support", (t) => { const delayString = "2w4d7h32m17s"; const expected = 1_582_337_000; t.is(convertDelayStringToMS(delayString), expected); }); -test("delay strings: default unit (minutes)", t => { +test("delay strings: default unit (minutes)", (t) => { t.is(convertDelayStringToMS("10"), 10 * 60 * 1000); }); -test("delay strings: custom default unit", t => { +test("delay strings: custom default unit", (t) => { t.is(convertDelayStringToMS("10", "s"), 10 * 1000); }); -test("delay strings: reverse conversion", t => { +test("delay strings: reverse conversion", (t) => { const ms = 1_582_337_020; const expected = "2w4d7h32m17s20x"; t.is(convertMSToDelayString(ms), expected); }); -test("delay strings: reverse conversion (conservative)", t => { +test("delay strings: reverse conversion (conservative)", (t) => { const ms = 1_209_600_000; const expected = "2w"; t.is(convertMSToDelayString(ms), expected); }); -test("tAllowedMentions matches Eris's AllowedMentions", t => { +test("tAllowedMentions matches Eris's AllowedMentions", (t) => { type TAllowedMentions = ioTs.TypeOf; const typeTest: AssertEquals = true; t.pass(); diff --git a/backend/src/utils.ts b/backend/src/utils.ts index 6e40d666..e5bde6fe 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -106,7 +106,7 @@ export const tNormalizedNullOrUndefined = new t.Type typeof v === "undefined", (v, c) => (v == null ? t.success(undefined) : t.failure(v, c, "Value must be null or undefined")), - s => undefined, + (s) => undefined, ); /** @@ -154,10 +154,10 @@ export function tDeepPartial(type: T): TDeepPartial { } else if (type instanceof t.DictionaryType) { return t.record(type.domain, tDeepPartial(type.codomain)) as TDeepPartial; } else if (type instanceof t.UnionType) { - return t.union(type.types.map(unionType => tDeepPartial(unionType))) as TDeepPartial; + return t.union(type.types.map((unionType) => tDeepPartial(unionType))) as TDeepPartial; } else if (type instanceof t.IntersectionType) { - const types = type.types.map(intersectionType => tDeepPartial(intersectionType)); - return (t.intersection(types as [t.Mixed, t.Mixed]) as unknown) as TDeepPartial; + const types = type.types.map((intersectionType) => tDeepPartial(intersectionType)); + return t.intersection(types as [t.Mixed, t.Mixed]) as unknown as TDeepPartial; } else if (type instanceof t.ArrayType) { return t.array(tDeepPartial(type.type)) as TDeepPartial; } else { @@ -433,7 +433,7 @@ export function validateAndParseMessageContent(input: unknown): StrictMessageCon dropNullValuesRecursively(input); try { - return (zStrictMessageContent.parse(input) as unknown) as StrictMessageContent; + return zStrictMessageContent.parse(input) as unknown as StrictMessageContent; } catch (err) { if (err instanceof ZodError) { // TODO: Allow error to be thrown and handle at use location @@ -492,34 +492,34 @@ export const tAlphanumeric = new t.Type( "tAlphanumeric", (s): s is string => typeof s === "string", (from, to) => - either.chain(t.string.validate(from, to), s => { + either.chain(t.string.validate(from, to), (s) => { return s.match(/\W/) ? t.failure(from, to, "String must be alphanumeric") : t.success(s); }), - s => s, + (s) => s, ); export const tDateTime = new t.Type( "tDateTime", (s): s is string => typeof s === "string", (from, to) => - either.chain(t.string.validate(from, to), s => { + either.chain(t.string.validate(from, to), (s) => { const parsed = s.length === 10 ? moment.utc(s, "YYYY-MM-DD") : s.length === 19 ? moment.utc(s, "YYYY-MM-DD HH:mm:ss") : null; return parsed && parsed.isValid() ? t.success(s) : t.failure(from, to, "Invalid datetime"); }), - s => s, + (s) => s, ); export const tDelayString = new t.Type( "tDelayString", (s): s is string => typeof s === "string", (from, to) => - either.chain(t.string.validate(from, to), s => { + either.chain(t.string.validate(from, to), (s) => { const ms = convertDelayStringToMS(s); return ms === null ? t.failure(from, to, "Invalid delay string") : t.success(s); }), - s => s, + (s) => s, ); // To avoid running into issues with the JS max date vaLue, we cap maximum delay strings *far* below that. @@ -608,8 +608,8 @@ export function stripObjectToScalars(obj, includedNested: string[] = []) { } else if (typeof obj[key] === "object") { const prefix = `${key}.`; const nestedNested = includedNested - .filter(p => p === key || p.startsWith(prefix)) - .map(p => (p === key ? p : p.slice(prefix.length))); + .filter((p) => p === key || p.startsWith(prefix)) + .map((p) => (p === key ? p : p.slice(prefix.length))); if (nestedNested.length) { result[key] = stripObjectToScalars(obj[key], nestedNested); @@ -628,7 +628,7 @@ export function isSnowflake(v: string): boolean { } export function sleep(ms: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, ms); }); } @@ -676,7 +676,7 @@ export async function findRelevantAuditLogEntry( const cutoffTS = Date.now() - 1000 * 60 * 2; - const relevantEntry = entries.find(entry => { + const relevantEntry = entries.find((entry) => { return (entry.target as { id }).id === userId && entry.createdTimestamp >= cutoffTS; }); @@ -744,7 +744,8 @@ export function isNotNull(value): value is Exclude { // discord.gg/invite/ // discord.gg/ // discord.com/friend-invite/ -const quickInviteDetection = /discord(?:app)?\.com\/(?:friend-)?invite\/([a-z0-9\-]+)|discord\.gg\/(?:\S+\/)?([a-z0-9\-]+)/gi; +const quickInviteDetection = + /discord(?:app)?\.com\/(?:friend-)?invite\/([a-z0-9\-]+)|discord\.gg\/(?:\S+\/)?([a-z0-9\-]+)/gi; const isInviteHostRegex = /(?:^|\.)(?:discord.gg|discord.com|discordapp.com)$/i; const longInvitePathRegex = /^\/(?:friend-)?invite\/([a-z0-9\-]+)$/i; @@ -758,19 +759,19 @@ export function getInviteCodesInString(str: string): string[] { // Quick detection const quickDetectionMatch = str.matchAll(quickInviteDetection); if (quickDetectionMatch) { - inviteCodes.push(...[...quickDetectionMatch].map(m => m[1] || m[2])); + inviteCodes.push(...[...quickDetectionMatch].map((m) => m[1] || m[2])); } // Deep detection via URL parsing const linksInString = getUrlsInString(str, true); - const potentialInviteLinks = linksInString.filter(url => isInviteHostRegex.test(url.hostname)); - const withNormalizedPaths = potentialInviteLinks.map(url => { + const potentialInviteLinks = linksInString.filter((url) => isInviteHostRegex.test(url.hostname)); + const withNormalizedPaths = potentialInviteLinks.map((url) => { url.pathname = url.pathname.replace(/\/{2,}/g, "/").replace(/\/+$/g, ""); return url; }); const codesFromInviteLinks = withNormalizedPaths - .map(url => { + .map((url) => { // discord.gg/[anything/] if (url.hostname === "discord.gg") { const parts = url.pathname.split("/").filter(Boolean); @@ -816,7 +817,7 @@ export function trimLines(str: string) { return str .trim() .split("\n") - .map(l => l.trim()) + .map((l) => l.trim()) .join("\n") .trim(); } @@ -824,7 +825,7 @@ export function trimLines(str: string) { export function trimEmptyLines(str: string) { return str .split("\n") - .filter(l => l.trim() !== "") + .filter((l) => l.trim() !== "") .join("\n"); } @@ -860,7 +861,7 @@ export function trimIndents(str: string, indentLength: number) { const regex = new RegExp(`^\\s{0,${indentLength}}`, "g"); return str .split("\n") - .map(line => line.replace(regex, "")) + .map((line) => line.replace(regex, "")) .join("\n"); } @@ -871,7 +872,7 @@ export function indentLine(str: string, indentLength: number) { export function indentLines(str: string, indentLength: number) { return str .split("\n") - .map(line => indentLine(line, indentLength)) + .map((line) => indentLine(line, indentLength)) .join("\n"); } @@ -977,7 +978,7 @@ export function chunkMessageLines(str: string, maxChunkLength = 1990): string[] const chunks = chunkLines(str, maxChunkLength); let openCodeBlock = false; - return chunks.map(chunk => { + return chunks.map((chunk) => { // If the chunk starts with a newline, add an invisible unicode char so Discord doesn't strip it away if (chunk[0] === "\n") chunk = "\u200b" + chunk; // If the chunk ends with a newline, add an invisible unicode char so Discord doesn't strip it away @@ -1019,14 +1020,14 @@ export async function createChunkedMessage( * Downloads the file from the given URL to a temporary file, with retry support */ export function downloadFile(attachmentUrl: string, retries = 3): Promise<{ path: string; deleteFn: () => void }> { - return new Promise(resolve => { + return new Promise((resolve) => { tmp.file((err, path, fd, deleteFn) => { if (err) throw err; const writeStream = fs.createWriteStream(path); https - .get(attachmentUrl, res => { + .get(attachmentUrl, (res) => { res.pipe(writeStream); writeStream.on("finish", () => { writeStream.end(); @@ -1036,7 +1037,7 @@ export function downloadFile(attachmentUrl: string, retries = 3): Promise<{ path }); }); }) - .on("error", httpsErr => { + .on("error", (httpsErr) => { fsp.unlink(path); if (retries === 0) { @@ -1061,7 +1062,7 @@ export function simpleClosestStringMatch(searchStr, haystack, getter?) { const normalizedSearchStr = searchStr.toLowerCase(); // See if any haystack item contains a part of the search string - const itemsWithRankings: Array> = haystack.map(item => { + const itemsWithRankings: Array> = haystack.map((item) => { const itemStr: string = getter ? getter(item) : item; const normalizedItemStr = itemStr.toLowerCase(); @@ -1100,14 +1101,14 @@ type sorterFn = (a: any, b: any) => number; function resolveGetter(getter: sorterGetterResolvable): sorterGetterFn { if (typeof getter === "string") { - return obj => obj[getter]; + return (obj) => obj[getter]; } return getter; } export function multiSorter(getters: Array): sorterFn { - const resolvedGetters: sorterGetterFnWithDirection[] = getters.map(getter => { + const resolvedGetters: sorterGetterFnWithDirection[] = getters.map((getter) => { if (Array.isArray(getter)) { return [resolveGetter(getter[0]), getter[1]] as sorterGetterFnWithDirection; } else { @@ -1288,7 +1289,7 @@ export function resolveUserId(bot: Client, value: string) { // A non-mention, full username? const usernameMatch = value.match(/^@?([^#]+)#(\d{4})$/); if (usernameMatch) { - const user = bot.users.cache.find(u => u.username === usernameMatch[1] && u.discriminator === usernameMatch[2]); + const user = bot.users.cache.find((u) => u.username === usernameMatch[1] && u.discriminator === usernameMatch[2]); if (user) return user.id; } @@ -1403,7 +1404,7 @@ export async function resolveRoleId(bot: Client, guildId: string, value: string) // Role name const roleList = (await bot.guilds.fetch(guildId as Snowflake)).roles.cache; - const role = roleList.filter(x => x.name.toLocaleLowerCase() === value.toLocaleLowerCase()); + const role = roleList.filter((x) => x.name.toLocaleLowerCase() === value.toLocaleLowerCase()); if (role.size >= 1) { return role.firstKey(); } @@ -1459,7 +1460,7 @@ export function messageSummary(msg: SavedMessage) { let result = "```\n" + (msg.data.content ? Util.escapeCodeBlock(msg.data.content) : "") + "```"; // Rich embed - const richEmbed = (msg.data.embeds || []).find(e => (e as MessageEmbed).type === "rich"); + const richEmbed = (msg.data.embeds || []).find((e) => (e as MessageEmbed).type === "rich"); if (richEmbed) result += "Embed:```" + Util.escapeCodeBlock(JSON.stringify(richEmbed)) + "```"; // Attachments @@ -1587,7 +1588,7 @@ export function canUseEmoji(client: Client, emoji: string): boolean { return true; } else if (isSnowflake(emoji)) { for (const guild of client.guilds.cache) { - if (guild[1].emojis.cache.some(e => (e as any).id === emoji)) { + if (guild[1].emojis.cache.some((e) => (e as any).id === emoji)) { return true; } } diff --git a/backend/src/utils/crypt.test.ts b/backend/src/utils/crypt.test.ts index 38b381ca..54417c8b 100644 --- a/backend/src/utils/crypt.test.ts +++ b/backend/src/utils/crypt.test.ts @@ -1,7 +1,7 @@ import test from "ava"; import { decrypt, encrypt } from "./crypt"; -test("encrypt() followed by decrypt()", t => { +test("encrypt() followed by decrypt()", (t) => { const original = "banana 123 👀 💕"; // Includes emojis to verify utf8 stuff works const encrypted = encrypt(original); const decrypted = decrypt(encrypted); diff --git a/backend/src/utils/normalizeText.test.ts b/backend/src/utils/normalizeText.test.ts index 9c9c03be..cd5a139c 100644 --- a/backend/src/utils/normalizeText.test.ts +++ b/backend/src/utils/normalizeText.test.ts @@ -1,25 +1,25 @@ import test from "ava"; import { normalizeText } from "./normalizeText"; -test("Replaces special characters", t => { +test("Replaces special characters", (t) => { const from = "𝗧:regional_indicator_e:ᔕ7 𝗧:regional_indicator_e:ᔕ7 𝗧:regional_indicator_e:ᔕ7"; const to = "test test test"; t.deepEqual(normalizeText(from), to); }); -test("Does not change lowercase ASCII text", t => { +test("Does not change lowercase ASCII text", (t) => { const text = "lorem ipsum dolor sit amet consectetur adipiscing elit"; t.deepEqual(normalizeText(text), text); }); -test("Replaces whitespace", t => { +test("Replaces whitespace", (t) => { const from = "foo bar"; const to = "foo bar"; t.deepEqual(normalizeText(from), to); }); -test("Result is always lowercase", t => { +test("Result is always lowercase", (t) => { const from = "TEST"; const to = "test"; t.deepEqual(normalizeText(from), to); diff --git a/backend/src/utils/parseFuzzyTimezone.ts b/backend/src/utils/parseFuzzyTimezone.ts index ef570e26..d4989681 100644 --- a/backend/src/utils/parseFuzzyTimezone.ts +++ b/backend/src/utils/parseFuzzyTimezone.ts @@ -1,7 +1,7 @@ import escapeStringRegexp from "escape-string-regexp"; import moment from "moment-timezone"; -const normalizeTzName = str => str.replace(/[^a-zA-Z0-9+\-]/g, "").toLowerCase(); +const normalizeTzName = (str) => str.replace(/[^a-zA-Z0-9+\-]/g, "").toLowerCase(); const validTimezones = moment.tz.names(); const normalizedTimezoneMap = validTimezones.reduce((map, tz) => { diff --git a/backend/src/utils/tColor.ts b/backend/src/utils/tColor.ts index ccc4f6a3..f240f7f4 100644 --- a/backend/src/utils/tColor.ts +++ b/backend/src/utils/tColor.ts @@ -8,9 +8,9 @@ export const tColor = new t.Type( "tColor", (s): s is number => typeof s === "number", (from, to) => - either.chain(t.string.validate(from, to), input => { + either.chain(t.string.validate(from, to), (input) => { const parsedColor = parseColor(input); return parsedColor == null ? t.failure(from, to, "Invalid color") : t.success(rgbToInt(parsedColor)); }), - s => intToRgb(s).join(","), + (s) => intToRgb(s).join(","), ); diff --git a/backend/src/utils/tValidTimezone.ts b/backend/src/utils/tValidTimezone.ts index 43c61c3e..35fc97c5 100644 --- a/backend/src/utils/tValidTimezone.ts +++ b/backend/src/utils/tValidTimezone.ts @@ -6,8 +6,8 @@ export const tValidTimezone = new t.Type( "tValidTimezone", (s): s is string => typeof s === "string", (from, to) => - either.chain(t.string.validate(from, to), input => { + either.chain(t.string.validate(from, to), (input) => { return isValidTimezone(input) ? t.success(input) : t.failure(from, to, `Invalid timezone: ${input}`); }), - s => s, + (s) => s, ); diff --git a/backend/src/utils/templateSafeObjects.ts b/backend/src/utils/templateSafeObjects.ts index 14547ff8..d57e1fca 100644 --- a/backend/src/utils/templateSafeObjects.ts +++ b/backend/src/utils/templateSafeObjects.ts @@ -262,7 +262,7 @@ export function memberToTemplateSafeMember(member: GuildMember | PartialGuildMem ...templateSafeUser, user: templateSafeUser, nick: member.nickname ?? "*None*", - roles: [...member.roles.cache.mapValues(r => roleToTemplateSafeRole(r)).values()], + roles: [...member.roles.cache.mapValues((r) => roleToTemplateSafeRole(r)).values()], joinedAt: member.joinedTimestamp ?? undefined, guildName: member.guild.name, }); @@ -322,7 +322,7 @@ export function savedMessageToTemplateSafeSavedMessage(savedMessage: SavedMessag data: new TemplateSafeSavedMessageData({ attachments: (savedMessage.data.attachments ?? []).map( - att => + (att) => new TemplateSafeValueContainer({ id: att.id, contentType: att.contentType, @@ -343,7 +343,7 @@ export function savedMessageToTemplateSafeSavedMessage(savedMessage: SavedMessag content: savedMessage.data.content, embeds: (savedMessage.data.embeds ?? []).map( - embed => + (embed) => new TemplateSafeValueContainer({ title: embed.title, description: embed.description, @@ -352,7 +352,7 @@ export function savedMessageToTemplateSafeSavedMessage(savedMessage: SavedMessag color: embed.color, fields: (embed.fields ?? []).map( - field => + (field) => new TemplateSafeValueContainer({ name: field.name, value: field.value, @@ -407,7 +407,7 @@ export function savedMessageToTemplateSafeSavedMessage(savedMessage: SavedMessag ), stickers: (savedMessage.data.stickers ?? []).map( - sticker => + (sticker) => new TemplateSafeValueContainer({ format: sticker.format, guildId: sticker.guildId, @@ -459,7 +459,7 @@ export function getTemplateSafeMemberLevel(pluginData: GuildPluginData, mem const levels = pluginData.fullConfig.levels ?? {}; for (const [id, level] of Object.entries(levels)) { - if (member.id === id || member.roles?.find(r => r.id === id)) { + if (member.id === id || member.roles?.find((r) => r.id === id)) { return level as number; } } diff --git a/backend/src/utils/typeUtils.ts b/backend/src/utils/typeUtils.ts index 619f6cec..a32aa0e1 100644 --- a/backend/src/utils/typeUtils.ts +++ b/backend/src/utils/typeUtils.ts @@ -1,8 +1,7 @@ // From https://stackoverflow.com/a/56370310/316944 export type Tail = ((...t: T) => void) extends (h: any, ...r: infer R) => void ? R : never; -export declare type WithRequiredProps = T & - { - // https://mariusschulz.com/blog/mapped-type-modifiers-in-typescript#removing-the-mapped-type-modifier - [PK in K]-?: Exclude; - }; +export declare type WithRequiredProps = T & { + // https://mariusschulz.com/blog/mapped-type-modifiers-in-typescript#removing-the-mapped-type-modifier + [PK in K]-?: Exclude; +}; diff --git a/backend/src/utils/validateNoObjectAliases.test.ts b/backend/src/utils/validateNoObjectAliases.test.ts index fe2ff6bf..b418f72b 100644 --- a/backend/src/utils/validateNoObjectAliases.test.ts +++ b/backend/src/utils/validateNoObjectAliases.test.ts @@ -1,7 +1,7 @@ import test from "ava"; import { ObjectAliasError, validateNoObjectAliases } from "./validateNoObjectAliases"; -test("validateNoObjectAliases() disallows object aliases at top level", t => { +test("validateNoObjectAliases() disallows object aliases at top level", (t) => { const obj: any = { objectRef: { foo: "bar", @@ -12,7 +12,7 @@ test("validateNoObjectAliases() disallows object aliases at top level", t => { t.throws(() => validateNoObjectAliases(obj), { instanceOf: ObjectAliasError }); }); -test("validateNoObjectAliases() disallows aliases to nested objects", t => { +test("validateNoObjectAliases() disallows aliases to nested objects", (t) => { const obj: any = { nested: { objectRef: { @@ -25,7 +25,7 @@ test("validateNoObjectAliases() disallows aliases to nested objects", t => { t.throws(() => validateNoObjectAliases(obj), { instanceOf: ObjectAliasError }); }); -test("validateNoObjectAliases() disallows nested object aliases", t => { +test("validateNoObjectAliases() disallows nested object aliases", (t) => { const obj: any = { nested: { objectRef: { diff --git a/backend/src/utils/waitForInteraction.ts b/backend/src/utils/waitForInteraction.ts index e7e4ae7d..d39467c9 100644 --- a/backend/src/utils/waitForInteraction.ts +++ b/backend/src/utils/waitForInteraction.ts @@ -8,7 +8,7 @@ export async function waitForButtonConfirm( toPost: MessageOptions, options?: WaitForOptions, ): Promise { - return new Promise(async resolve => { + return new Promise(async (resolve) => { const idMod = `${channel.guild.id}-${moment.utc().valueOf()}`; const row = new MessageActionRow().addComponents([ new MessageButton() diff --git a/backend/src/validation.test.ts b/backend/src/validation.test.ts index 795e67ff..d41d6c4a 100644 --- a/backend/src/validation.test.ts +++ b/backend/src/validation.test.ts @@ -3,7 +3,7 @@ import * as t from "io-ts"; import { tDeepPartial } from "./utils"; import * as validatorUtils from "./validatorUtils"; -test("tDeepPartial works", ava => { +test("tDeepPartial works", (ava) => { const originalSchema = t.type({ listOfThings: t.record( t.string, diff --git a/backend/src/validatorUtils.ts b/backend/src/validatorUtils.ts index 8a6863f9..7b75637c 100644 --- a/backend/src/validatorUtils.ts +++ b/backend/src/validatorUtils.ts @@ -25,7 +25,7 @@ export const TRegex = new t.Type( "TRegex", (s): s is RegExp => s instanceof RegExp, (from, to) => - either.chain(t.string.validate(from, to), s => { + either.chain(t.string.validate(from, to), (s) => { try { return t.success(inputPatternToRegExp(s)); } catch (err) { @@ -36,7 +36,7 @@ export const TRegex = new t.Type( throw err; } }), - s => `/${s.source}/${s.flags}`, + (s) => `/${s.source}/${s.flags}`, ); // From io-ts/lib/PathReporter @@ -57,7 +57,7 @@ function stringify(v) { // tslint:disable function getContextPath(context) { return context - .map(function(_a) { + .map(function (_a) { var key = _a.key, type = _a.type; return key + ": " + type.name; @@ -80,8 +80,8 @@ export class StrictValidationError extends Error { } const report = fold((errors: any): StrictValidationError | void => { - const errorStrings = errors.map(err => { - const context = err.context.map(c => c.key).filter(k => k && !k.startsWith("{")); + const errorStrings = errors.map((err) => { + const context = err.context.map((c) => c.key).filter((k) => k && !k.startsWith("{")); while (context.length > 0 && !isNaN(context[context.length - 1])) context.splice(-1); const value = stringify(err.value); @@ -99,8 +99,8 @@ export function validate(schema: t.Type, value: any): StrictValidationError pipe( validationResult, fold( - err => report(validationResult), - result => null, + (err) => report(validationResult), + (result) => null, ), ) || null ); @@ -119,8 +119,8 @@ export function decodeAndValidateStrict( return pipe( validationResult, fold( - err => report(validationResult), - result => { + (err) => report(validationResult), + (result) => { // Make sure there are no extra properties if (debug) { console.log( @@ -133,7 +133,7 @@ export function decodeAndValidateStrict( } if (JSON.stringify(value) !== JSON.stringify(result)) { const diff = deepDiff(result, value); - const errors = diff.filter(d => d.kind === "N").map(d => `Unknown property <${d.path.join(".")}>`); + const errors = diff.filter((d) => d.kind === "N").map((d) => `Unknown property <${d.path.join(".")}>`); if (errors.length) return new StrictValidationError(errors); } diff --git a/backend/start-dev.js b/backend/start-dev.js index 5b6c3b44..70c912f2 100644 --- a/backend/start-dev.js +++ b/backend/start-dev.js @@ -5,9 +5,7 @@ const childProcess = require("child_process"); -const cmd = process.platform === "win32" - ? "npm.cmd" - : "npm"; +const cmd = process.platform === "win32" ? "npm.cmd" : "npm"; childProcess.spawn(cmd, ["run", "start-bot-dev"], { stdio: [process.stdin, process.stdout, process.stderr], diff --git a/backend/tsconfig.json b/backend/tsconfig.json index d20c0579..23f838e2 100644 --- a/backend/tsconfig.json +++ b/backend/tsconfig.json @@ -7,17 +7,13 @@ "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "es2020", - "lib": [ - "esnext" - ], + "lib": ["esnext"], "baseUrl": ".", "resolveJsonModule": true, "esModuleInterop": true, "outDir": "./dist", "paths": { - "@shared/*": [ - "../shared/src/*" - ] + "@shared/*": ["../shared/src/*"] }, "sourceMap": true, "alwaysStrict": true, @@ -26,7 +22,5 @@ "strict": true, "strictPropertyInitialization": false }, - "include": [ - "src/**/*.ts" - ] + "include": ["src/**/*.ts"] } diff --git a/dashboard/.htmlnanorc.js b/dashboard/.htmlnanorc.js index 7aeaf2ab..5dff0968 100644 --- a/dashboard/.htmlnanorc.js +++ b/dashboard/.htmlnanorc.js @@ -1,3 +1,3 @@ module.exports = { - collapseWhitespace: false + collapseWhitespace: false, }; diff --git a/dashboard/src/api.ts b/dashboard/src/api.ts index 5782aa47..2a5fa858 100644 --- a/dashboard/src/api.ts +++ b/dashboard/src/api.ts @@ -22,13 +22,13 @@ function buildQueryString(params: QueryParamObject) { return ( "?" + Array.from(Object.entries(params)) - .map(pair => `${encodeURIComponent(pair[0])}=${encodeURIComponent(pair[1] || "")}`) + .map((pair) => `${encodeURIComponent(pair[0])}=${encodeURIComponent(pair[1] || "")}`) .join("&") ); } export function request(resource, fetchOpts: RequestInit = {}) { - return fetch(`${apiUrl}/${resource}`, fetchOpts).then(async res => { + return fetch(`${apiUrl}/${resource}`, fetchOpts).then(async (res) => { if (!res.ok) { if (res.status === 401) { RootStore.dispatch("auth/expiredLogin"); diff --git a/dashboard/src/directives/trim-indents.ts b/dashboard/src/directives/trim-indents.ts index 79f61ba3..eff9b92e 100644 --- a/dashboard/src/directives/trim-indents.ts +++ b/dashboard/src/directives/trim-indents.ts @@ -19,7 +19,7 @@ Vue.directive("trim-indents", { el.innerHTML = withoutStartEndWhitespace .split("\n") - .map(line => line.slice(spacesToTrim)) + .map((line) => line.slice(spacesToTrim)) .join("\n"); }, }); diff --git a/dashboard/src/index.html b/dashboard/src/index.html index b1be5ddf..7151c5b0 100644 --- a/dashboard/src/index.html +++ b/dashboard/src/index.html @@ -1,18 +1,20 @@ - + - - - - - Zeppelin - Moderation bot for Discord - - - + + + + + Zeppelin - Moderation bot for Discord + + + -
- +
+ diff --git a/dashboard/src/splash.html b/dashboard/src/splash.html index 4b2abb9f..18da7ee9 100644 --- a/dashboard/src/splash.html +++ b/dashboard/src/splash.html @@ -2,7 +2,7 @@
- +

Zeppelin

diff --git a/dashboard/src/store/guilds.ts b/dashboard/src/store/guilds.ts index dfe6ac43..10c2eb70 100644 --- a/dashboard/src/store/guilds.ts +++ b/dashboard/src/store/guilds.ts @@ -90,7 +90,7 @@ export const GuildStore: Module = { Vue.set( state.guildPermissionAssignments, guildId, - permissionAssignments.map(p => ({ + permissionAssignments.map((p) => ({ ...p, permissions: new Set(p.permissions), })), @@ -102,12 +102,12 @@ export const GuildStore: Module = { if (permissions.length === 0) { // No permissions -> remove permission assignment guildPermissionAssignments.splice( - guildPermissionAssignments.findIndex(p => p.target_id === targetId && p.type === type), + guildPermissionAssignments.findIndex((p) => p.target_id === targetId && p.type === type), 1, ); } else { // Update/add permission assignment - const itemToEdit = guildPermissionAssignments.find(p => p.target_id === targetId && p.type === type); + const itemToEdit = guildPermissionAssignments.find((p) => p.target_id === targetId && p.type === type); if (itemToEdit) { itemToEdit.permissions = new Set(permissions); } else { diff --git a/dashboard/tailwind.config.js b/dashboard/tailwind.config.js index 800b9f1a..d3fbd401 100644 --- a/dashboard/tailwind.config.js +++ b/dashboard/tailwind.config.js @@ -3,22 +3,22 @@ module.exports = { theme: { extend: { lineHeight: { - zero: '0' + zero: "0", }, flex: { - full: '0 0 100%', - flexible: '1 1 0' - } + full: "0 0 100%", + flexible: "1 1 0", + }, }, screens: { - sm: '640px', - md: '768px', - 'until-lg': { max: '1023px' }, - lg: '1024px', - xl: '1280px', - '2xl': '1536px' - } + sm: "640px", + md: "768px", + "until-lg": { max: "1023px" }, + lg: "1024px", + xl: "1280px", + "2xl": "1536px", + }, }, variants: {}, - plugins: [] -} + plugins: [], +}; diff --git a/dashboard/tsconfig.json b/dashboard/tsconfig.json index 42745a2a..1bd1fd32 100644 --- a/dashboard/tsconfig.json +++ b/dashboard/tsconfig.json @@ -9,10 +9,7 @@ "experimentalDecorators": true, "emitDecoratorMetadata": true, "strict": false, - "lib": [ - "esnext", - "dom" - ], + "lib": ["esnext", "dom"], "baseUrl": ".", "resolveJsonModule": true, "esModuleInterop": true, diff --git a/dashboard/webpack.config.js b/dashboard/webpack.config.js index e9f10e51..e4b78765 100644 --- a/dashboard/webpack.config.js +++ b/dashboard/webpack.config.js @@ -1,42 +1,40 @@ -require('dotenv').config(); +require("dotenv").config(); -const path = require('path'); -const VueLoaderPlugin = require('vue-loader/lib/plugin'); -const HtmlWebpackPlugin = require('html-webpack-plugin'); -const DotenvPlugin = require('dotenv-webpack'); -const merge = require('webpack-merge'); +const path = require("path"); +const VueLoaderPlugin = require("vue-loader/lib/plugin"); +const HtmlWebpackPlugin = require("html-webpack-plugin"); +const DotenvPlugin = require("dotenv-webpack"); +const merge = require("webpack-merge"); -const targetDir = path.normalize(path.join(__dirname, 'dist')); +const targetDir = path.normalize(path.join(__dirname, "dist")); -if (! process.env.NODE_ENV) { - console.error('Please set NODE_ENV'); +if (!process.env.NODE_ENV) { + console.error("Please set NODE_ENV"); process.exit(1); } const babelOpts = { - presets: [ - '@babel/preset-env', - ], + presets: ["@babel/preset-env"], }; -const tsconfig = require('./tsconfig.json'); +const tsconfig = require("./tsconfig.json"); const pathAliases = Object.entries(tsconfig.compilerOptions.paths || []).reduce((aliases, pair) => { let alias = pair[0]; - if (alias.endsWith('/*')) alias = alias.slice(0, -2); + if (alias.endsWith("/*")) alias = alias.slice(0, -2); let aliasPath = pair[1][0]; - if (aliasPath.endsWith('/*')) aliasPath = aliasPath.slice(0, -2); + if (aliasPath.endsWith("/*")) aliasPath = aliasPath.slice(0, -2); aliases[alias] = path.resolve(__dirname, aliasPath); return aliases; }, {}); let config = { - entry: './src/main.ts', + entry: "./src/main.ts", output: { - filename: '[name].[hash].js', + filename: "[name].[hash].js", path: targetDir, - publicPath: '/', + publicPath: "/", }, module: { rules: [ @@ -50,11 +48,11 @@ let config = { exclude: /node_modules/, use: [ { - loader: 'babel-loader', + loader: "babel-loader", options: babelOpts, }, { - loader: 'ts-loader', + loader: "ts-loader", options: { appendTsSuffixTo: [/\.vue$/], }, @@ -65,7 +63,7 @@ let config = { test: /\.m?js$/, exclude: /node_modules/, use: { - loader: 'babel-loader', + loader: "babel-loader", options: babelOpts, }, }, @@ -90,26 +88,23 @@ let config = { loader: "postcss-loader", options: { ident: "postcss", - plugins: loader => { + plugins: (loader) => { const plugins = [ - require('postcss-import')({ + require("postcss-import")({ resolve(id, base, options) { // Since WebStorm doesn't resolve imports from node_modules without a tilde (~) prefix, // strip the tilde here to get the best of both worlds (webstorm support + postcss-import support) - if (id[0] === '~') id = id.slice(1); + if (id[0] === "~") id = id.slice(1); // Call the original resolver after stripping the tilde - return require('postcss-import/lib/resolve-id')(id, base, options); + return require("postcss-import/lib/resolve-id")(id, base, options); }, }), - require('postcss-nesting')(), - require('tailwindcss')(), + require("postcss-nesting")(), + require("tailwindcss")(), ]; if (process.env.NODE_ENV === "production") { - plugins.push( - require('postcss-preset-env')(), - require('cssnano')(), - ); + plugins.push(require("postcss-preset-env")(), require("cssnano")()); } return plugins; @@ -137,9 +132,9 @@ let config = { { loader: "html-loader", options: { - root: path.resolve(__dirname, 'src'), - attrs: ['img:src', 'link:href'], - ...(process.env.NODE_ENV === 'production' && { + root: path.resolve(__dirname, "src"), + attrs: ["img:src", "link:href"], + ...(process.env.NODE_ENV === "production" && { minimize: true, removeComments: true, collapseWhitespace: true, @@ -153,29 +148,29 @@ let config = { plugins: [ new VueLoaderPlugin(), new HtmlWebpackPlugin({ - template: 'src/index.html', + template: "src/index.html", files: { - "css": ["./src/style/initial.pcss"], - "js": ["./src/main.ts"], + css: ["./src/style/initial.pcss"], + js: ["./src/main.ts"], }, }), new DotenvPlugin(), ], resolve: { - extensions: ['.ts', '.tsx', '.js', '.mjs', '.vue'], + extensions: [".ts", ".tsx", ".js", ".mjs", ".vue"], alias: pathAliases, }, }; -if (process.env.NODE_ENV === 'production') { +if (process.env.NODE_ENV === "production") { config = merge(config, { - mode: 'production', - devtool: 'source-map', + mode: "production", + devtool: "source-map", }); } else { config = merge(config, { - mode: 'development', - devtool: 'eval', + mode: "development", + devtool: "eval", devServer: { ...(process.env.DEV_HOST ? { host: process.env.DEV_HOST } : undefined), historyApiFallback: true, diff --git a/presetup-configurator/snowpack.config.js b/presetup-configurator/snowpack.config.js index 0125dd6f..2d15cba7 100644 --- a/presetup-configurator/snowpack.config.js +++ b/presetup-configurator/snowpack.config.js @@ -1,8 +1,6 @@ module.exports = { mount: { - "src": "/", + src: "/", }, - plugins: [ - '@snowpack/plugin-typescript', - ], + plugins: ["@snowpack/plugin-typescript"], }; diff --git a/presetup-configurator/src/App.tsx b/presetup-configurator/src/App.tsx index 5201bdf8..54e9e365 100644 --- a/presetup-configurator/src/App.tsx +++ b/presetup-configurator/src/App.tsx @@ -3,9 +3,11 @@ import { Configurator } from "./Configurator"; import "./App.css"; export function App() { - return
-
- + return ( +
+
+ +
-
; + ); } diff --git a/presetup-configurator/src/Configurator.css b/presetup-configurator/src/Configurator.css index 8bebd777..7d8ba426 100644 --- a/presetup-configurator/src/Configurator.css +++ b/presetup-configurator/src/Configurator.css @@ -1,5 +1,4 @@ .Configurator { - } .Configurator .options { diff --git a/presetup-configurator/src/Configurator.tsx b/presetup-configurator/src/Configurator.tsx index 8e2222de..02fd9d7d 100644 --- a/presetup-configurator/src/Configurator.tsx +++ b/presetup-configurator/src/Configurator.tsx @@ -5,7 +5,7 @@ import yaml from "js-yaml"; import "./Configurator.css"; export function Configurator() { - const [prefix, setPrefix] = useState('!'); + const [prefix, setPrefix] = useState("!"); const [levels, setLevels] = useState([]); const [withModCommands, setWithModCommands] = useState(false); @@ -42,7 +42,7 @@ export function Configurator() { resultObj.plugins.mutes = { config: { mute_role: muteRoleId, - } + }, }; if (dmModActionReasons) { @@ -108,7 +108,7 @@ export function Configurator() { setCopied(true); } - const [copyResetTimeout, setCopyResetTimeout] = useState(null); + const [copyResetTimeout, setCopyResetTimeout] = useState(null); useEffect(() => { if (!copied) { return; @@ -129,8 +129,9 @@ export function Configurator() {

Prefix

@@ -142,24 +143,30 @@ export function Configurator() {

Mod commands

{withModCommands && (
@@ -169,21 +176,23 @@ export function Configurator() {

Logs

- {withLogs && ( - - )} + {withLogs && }
{/* Result */} -