diff --git a/backend/src/Queue.ts b/backend/src/Queue.ts index e6bea62a..41192e0d 100644 --- a/backend/src/Queue.ts +++ b/backend/src/Queue.ts @@ -14,7 +14,7 @@ export class Queue { } public add(fn) { - const promise = new Promise((resolve) => { + const promise = new Promise(resolve => { this.queue.push(async () => { await fn(); resolve(undefined); @@ -35,7 +35,7 @@ export class Queue { } const fn = this.queue.shift()!; - new Promise((resolve) => { + new Promise(resolve => { // Either fn() completes or the timeout is reached fn().then(resolve); setTimeout(resolve, this.timeout); diff --git a/backend/src/QueuedEventEmitter.ts b/backend/src/QueuedEventEmitter.ts index 2402c491..3da957d3 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 1579b08f..0d7848e6 100644 --- a/backend/src/RegExpRunner.ts +++ b/backend/src/RegExpRunner.ts @@ -27,7 +27,7 @@ const INITIAL_REGEX_TIMEOUT = 1000; // ms const INITIAL_REGEX_TIMEOUT_DURATION = 30 * SECONDS; const FINAL_REGEX_TIMEOUT = 750; // ms -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 779d5d7e..d66ae078 100644 --- a/backend/src/api/auth.ts +++ b/backend/src/api/auth.ts @@ -33,17 +33,17 @@ function simpleDiscordAPIRequest(bearerToken, path): Promise { Authorization: `Bearer ${bearerToken}`, }, }, - (res) => { + res => { if (res.statusCode !== 200) { reject(new Error(`Discord API error ${res.statusCode}`)); return; } - res.on("data", (data) => resolve(JSON.parse(data))); + res.on("data", data => resolve(JSON.parse(data))); }, ); - 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 0618e3e5..f8306bd7 100644 --- a/backend/src/api/docs.ts +++ b/backend/src/api/docs.ts @@ -20,21 +20,21 @@ function formatConfigSchema(schema) { if (schema.name.startsWith("Nullable<")) { return `Nullable<${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 } : {}; return { name: plugin.name, @@ -54,7 +54,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/data/ApiLogins.ts b/backend/src/data/ApiLogins.ts index 1fe01f93..22ab35e8 100644 --- a/backend/src/data/ApiLogins.ts +++ b/backend/src/data/ApiLogins.ts @@ -66,7 +66,10 @@ export class ApiLogins extends BaseRepository { token: hashedToken, user_id: userId, logged_in_at: moment.utc().format(DBDateFormat), - expires_at: moment.utc().add(1, "day").format(DBDateFormat), + expires_at: moment + .utc() + .add(1, "day") + .format(DBDateFormat), }); return `${loginId}.${token}`; diff --git a/backend/src/data/ApiUserInfo.ts b/backend/src/data/ApiUserInfo.ts index 7ad8757e..09d9df75 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 2c7fac5e..054ce255 100644 --- a/backend/src/data/Configs.ts +++ b/backend/src/data/Configs.ts @@ -41,7 +41,11 @@ 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) { @@ -61,7 +65,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/GuildCases.ts b/backend/src/data/GuildCases.ts index afb48919..67a1ad41 100644 --- a/backend/src/data/GuildCases.ts +++ b/backend/src/data/GuildCases.ts @@ -132,7 +132,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 a153e90b..3f05972e 100644 --- a/backend/src/data/GuildCounters.ts +++ b/backend/src/data/GuildCounters.ts @@ -45,11 +45,19 @@ const DELETE_UNUSED_COUNTER_TRIGGERS_AFTER = 1 * DAYS; const MAX_COUNTER_VALUE = 2147483647; // 2^31-1, for MySQL INT 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); @@ -110,7 +118,10 @@ export class GuildCounters extends BaseGuildRepository { return; } - 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( { guild_id: this.guildId, @@ -124,7 +135,11 @@ 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(id: number, channelId: string | null, userId: string | null, change: number): Promise { @@ -216,7 +231,10 @@ export class GuildCounters extends BaseGuildRepository { } async markAllTriggersTobeDeleted() { - 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( {}, { @@ -226,7 +244,11 @@ 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( @@ -242,7 +264,7 @@ export class GuildCounters extends BaseGuildRepository { throw new Error(`Invalid comparison value: ${comparisonValue}`); } - return connection.transaction(async (entityManager) => { + return connection.transaction(async entityManager => { const existing = await entityManager.findOne(CounterTrigger, { counter_id: counterId, comparison_op: comparisonOp, @@ -286,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!, @@ -334,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( @@ -351,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, channelId: row.channel_id, userId: row.user_id, @@ -359,7 +381,7 @@ export class GuildCounters extends BaseGuildRepository { ); } - return matchingValues.map((row) => ({ + return matchingValues.map(row => ({ channelId: row.channel_id, userId: row.user_id, })); @@ -385,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 reverseOp = getReverseComparisonOp(counterTrigger.comparison_op); const matchingValue = await entityManager .createQueryBuilder(CounterValue, "cv") @@ -423,7 +445,7 @@ export class GuildCounters extends BaseGuildRepository { async checkAllValuesForReverseTrigger( counterTrigger: CounterTrigger, ): Promise> { - return connection.transaction(async (entityManager) => { + return connection.transaction(async entityManager => { const reverseOp = getReverseComparisonOp(counterTrigger.comparison_op); const matchingValues: Array<{ id: string; @@ -450,11 +472,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 b324984e..457beec6 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 e3e6cea9..9e1a1b68 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 741e0d2b..93fcfdc5 100644 --- a/backend/src/data/GuildMutes.ts +++ b/backend/src/data/GuildMutes.ts @@ -35,7 +35,12 @@ 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, @@ -48,7 +53,12 @@ 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( @@ -79,7 +89,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 4ad899f8..60f8f419 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/GuildScheduledPosts.ts b/backend/src/data/GuildScheduledPosts.ts index ccfa2d2a..af621434 100644 --- a/backend/src/data/GuildScheduledPosts.ts +++ b/backend/src/data/GuildScheduledPosts.ts @@ -11,7 +11,10 @@ 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 6027e8fd..9e4281db 100644 --- a/backend/src/data/GuildSlowmodes.ts +++ b/backend/src/data/GuildSlowmodes.ts @@ -67,7 +67,10 @@ 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 987c3936..76e126c5 100644 --- a/backend/src/data/GuildTempbans.ts +++ b/backend/src/data/GuildTempbans.ts @@ -31,7 +31,10 @@ 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, @@ -45,7 +48,10 @@ 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 9781f7b3..6acc35e9 100644 --- a/backend/src/data/GuildVCAlerts.ts +++ b/backend/src/data/GuildVCAlerts.ts @@ -19,7 +19,10 @@ 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 95fd0bba..bcc5647a 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 fc0cc1eb..04c76044 100644 --- a/backend/src/data/cleanup/configs.ts +++ b/backend/src/data/cleanup/configs.ts @@ -13,7 +13,10 @@ 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( ` @@ -43,7 +46,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)), }); } @@ -51,7 +54,10 @@ 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( ` @@ -81,7 +87,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 35af60bf..1b9f8427 100644 --- a/backend/src/data/cleanup/messages.ts +++ b/backend/src/data/cleanup/messages.ts @@ -18,9 +18,18 @@ 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 @@ -51,7 +60,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 d37f169c..e48b2670 100644 --- a/backend/src/data/cleanup/nicknames.ts +++ b/backend/src/data/cleanup/nicknames.ts @@ -11,7 +11,10 @@ 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; @@ -28,7 +31,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 605565e8..6bcca3d2 100644 --- a/backend/src/data/cleanup/usernames.ts +++ b/backend/src/data/cleanup/usernames.ts @@ -11,7 +11,10 @@ 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; @@ -28,7 +31,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 8fa418aa..30383b14 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 0cc35f39..25f2405a 100644 --- a/backend/src/data/entities/ApiLogin.ts +++ b/backend/src/data/entities/ApiLogin.ts @@ -19,7 +19,10 @@ 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 bd3a1a43..fcea7595 100644 --- a/backend/src/data/entities/ApiPermissionAssignment.ts +++ b/backend/src/data/entities/ApiPermissionAssignment.ts @@ -18,7 +18,10 @@ export class ApiPermissionAssignment { @Column("simple-array") permissions: string[]; - @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 b6146b23..32c3a1b0 100644 --- a/backend/src/data/entities/ApiUserInfo.ts +++ b/backend/src/data/entities/ApiUserInfo.ts @@ -20,9 +20,15 @@ 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 84d24618..f8980b33 100644 --- a/backend/src/data/entities/Case.ts +++ b/backend/src/data/entities/Case.ts @@ -35,6 +35,9 @@ 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 f883d79f..3f2e8125 100644 --- a/backend/src/data/entities/CaseNote.ts +++ b/backend/src/data/entities/CaseNote.ts @@ -15,7 +15,10 @@ 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 d5e391b4..8e16514e 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 2d8839e6..405222c1 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 c2cb0258..8e04a8fb 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 1fde6f4d..5e1f82a3 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -139,8 +139,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; @@ -175,7 +175,7 @@ connect().then(async () => { }); client.setMaxListeners(200); - client.on("debug", (message) => { + client.on("debug", message => { if (message.includes(" 429 ")) { logger.info(`[429] ${message}`); } @@ -209,9 +209,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; }); diff --git a/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts b/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts index 63136720..691167f9 100644 --- a/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts +++ b/backend/src/migrations/1556909512501-MigrateUsernamesToNewHistoryTable.ts @@ -9,23 +9,23 @@ 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("result", (row) => { + stream.on("result", row => { migratedUsernames.add(row.key); }); stream.on("end", resolve); }); const migrateNextBatch = (): Promise<{ finished: boolean; migrated?: number }> => { - return new Promise(async (resolve) => { + return new Promise(async resolve => { const toInsert: any[][] = []; const toDelete: number[] = []; const stream = await queryRunner.stream( `SELECT * FROM name_history WHERE type=1 ORDER BY timestamp ASC LIMIT ${BATCH_SIZE}`, ); - stream.on("result", (row) => { + stream.on("result", row => { const key = `${row.user_id}-${row.value}`; if (!migratedUsernames.has(key)) { diff --git a/backend/src/migrations/1617410382003-AFKStatus.ts b/backend/src/migrations/1617410382003-AFKStatus.ts index 8ee4e94e..b179785d 100644 --- a/backend/src/migrations/1617410382003-AFKStatus.ts +++ b/backend/src/migrations/1617410382003-AFKStatus.ts @@ -1,33 +1,34 @@ import { MigrationInterface, QueryRunner, Table } from "typeorm"; export class AFKStatus1617410382003 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.createTable( - new Table({ - name: "afk", - columns: [ - { - name: "id", - type: "int", - isPrimary: true, - isGenerated: true, - generationStrategy: "increment", - }, - { - name: "user_id", - type: "bigint", - }, - { - name: "status", - type: "varchar", - length: "255", - }, - ], - }), - ); - } - public async down(queryRunner: QueryRunner): Promise { - return queryRunner.dropTable("afk"); - } + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.createTable( + new Table({ + name: "afk", + columns: [ + { + name: "id", + type: "int", + isPrimary: true, + isGenerated: true, + generationStrategy: "increment", + }, + { + name: "user_id", + type: "bigint", + }, + { + name: "status", + type: "varchar", + length: "255", + } + ] + }) + ); + } + + public async down(queryRunner: QueryRunner): Promise { + return queryRunner.dropTable("afk"); + } } diff --git a/backend/src/pluginUtils.ts b/backend/src/pluginUtils.ts index e16a6ad9..cae48714 100644 --- a/backend/src/pluginUtils.ts +++ b/backend/src/pluginUtils.ts @@ -61,7 +61,7 @@ export function strictValidationErrorToConfigValidationError(err: StrictValidati return new ConfigValidationError( err .getErrors() - .map((e) => e.toString()) + .map(e => e.toString()) .join("\n"), ); } @@ -150,7 +150,7 @@ export function sendSuccessMessage( : { content: formattedBody }; return channel .createMessage(content) // Force line break - .catch((err) => { + .catch(err => { const channelInfo = (channel as GuildTextableChannel).guild ? `${channel.id} (${(channel as GuildTextableChannel).guild.id})` : `${channel.id}`; @@ -172,7 +172,7 @@ export function sendErrorMessage( : { content: formattedBody }; return channel .createMessage(content) // Force line break - .catch((err) => { + .catch(err => { const channelInfo = (channel as GuildTextableChannel).guild ? `${channel.id} (${(channel as GuildTextableChannel).guild.id})` : `${channel.id}`; @@ -206,7 +206,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/AFK/AFKPlugin.ts b/backend/src/plugins/AFK/AFKPlugin.ts index ed66d0b6..839d6650 100644 --- a/backend/src/plugins/AFK/AFKPlugin.ts +++ b/backend/src/plugins/AFK/AFKPlugin.ts @@ -1,5 +1,5 @@ import { PluginOptions } from "knub"; -import { AFKPluginType, ConfigSchema } from "./types"; +import { AFKPluginType, ConfigSchema } from './types'; import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint"; import { AFK } from "src/data/AFK"; @@ -7,39 +7,40 @@ import { AfkSetCmd } from "./commands/AFKCmd"; import { AFKNotificationEvt } from "./events/AFKNotificationEvt"; const defaultOptions: PluginOptions = { - config: { - can_afk: false, - allow_links: false, - allow_invites: false, - }, - overrides: [ - { - level: ">=50", - config: { - can_afk: true, - allow_links: true, - allow_invites: true, - }, + config: { + can_afk: false, + allow_links: false, + allow_invites: false, }, - ], -}; + overrides: [ + { + level: '>=50', + config: { + can_afk: true, + allow_links: true, + allow_invites: true, + } + } + ] +} export const AFKPlugin = zeppelinGuildPlugin()("afk", { - showInDocs: true, - info: { - prettyName: "AFK", - description: "Allows you to set your AFK Status.", - }, + showInDocs: true, + info: { + prettyName: "AFK", + description: "Allows you to set your AFK Status.", + }, - configSchema: ConfigSchema, - defaultOptions, + configSchema: ConfigSchema, + defaultOptions, - commands: [AfkSetCmd], - events: [AFKNotificationEvt], + commands: [AfkSetCmd], + events: [AFKNotificationEvt], - onLoad(pluginData) { - const { state } = pluginData; + onLoad(pluginData) { + const { state } = pluginData; + + state.afkUsers = new AFK(); + } +}) - state.afkUsers = new AFK(); - }, -}); diff --git a/backend/src/plugins/AFK/commands/AFKCmd.ts b/backend/src/plugins/AFK/commands/AFKCmd.ts index 9105db23..ee34a235 100644 --- a/backend/src/plugins/AFK/commands/AFKCmd.ts +++ b/backend/src/plugins/AFK/commands/AFKCmd.ts @@ -4,40 +4,43 @@ import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; import { parseStatusMessage } from "../functions/parseStatusMessage"; export const AfkSetCmd = afkCmd({ - trigger: ["afk", "afk set"], - permission: "can_afk", + trigger: ['afk', 'afk set'], + permission: 'can_afk', - signature: { - status: ct.string({ rest: true, required: true }), - }, + signature: { + status: ct.string({ rest: true, required: true }), + }, - async run({ message: msg, args, pluginData }) { - // Checks if the user is AFK, if so, return. - const isAfk = await pluginData.state.afkUsers.getUserAFKStatus(msg.author.id); - if (isAfk) return; + async run({ message: msg, args, pluginData }) { + // Checks if the user is AFK, if so, return. + const isAfk = await pluginData.state.afkUsers.getUserAFKStatus(msg.author.id); + if (isAfk) return; + + const status = args.status.join(" "); - const status = args.status.join(" "); + // Check status length + if (status.length > 124) { + sendErrorMessage(pluginData, msg.channel, "Status length is above **124** characters."); + return; + } - // Check status length - if (status.length > 124) { - sendErrorMessage(pluginData, msg.channel, "Status length is above **124** characters."); - return; + // Checks status based on configuration options + const parsed = parseStatusMessage(pluginData, msg.member, status); + if (typeof parsed === 'string') { + sendErrorMessage(pluginData, msg.channel, parsed); + return; + } + + // Set user status + const afk = await pluginData.state.afkUsers.setAfkStatus( + msg.author.id, + status, + ); + + sendSuccessMessage(pluginData, msg.channel, `AFK Status set to: **${afk.status}**`, { + roles: false, + everyone: false, + users: false, + }); } - - // Checks status based on configuration options - const parsed = parseStatusMessage(pluginData, msg.member, status); - if (typeof parsed === "string") { - sendErrorMessage(pluginData, msg.channel, parsed); - return; - } - - // Set user status - const afk = await pluginData.state.afkUsers.setAfkStatus(msg.author.id, status); - - sendSuccessMessage(pluginData, msg.channel, `AFK Status set to: **${afk.status}**`, { - roles: false, - everyone: false, - users: false, - }); - }, -}); +}) \ No newline at end of file diff --git a/backend/src/plugins/AFK/events/AFKNotificationEvt.ts b/backend/src/plugins/AFK/events/AFKNotificationEvt.ts index 9f4dd8bc..626a4bd7 100644 --- a/backend/src/plugins/AFK/events/AFKNotificationEvt.ts +++ b/backend/src/plugins/AFK/events/AFKNotificationEvt.ts @@ -2,27 +2,27 @@ import { sendUserMentionMessage, sendWelcomeBackMessage } from "../functions/bui import { afkEvt } from "../types"; export const AFKNotificationEvt = afkEvt({ - event: "messageCreate", + event: 'messageCreate', - listener: async ({ pluginData, args: { message } }) => { - // Mention Check (if someone mentions the AFK user) - if (message.mentions.length) { - const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.mentions[0].id); - if (!afk) return; + listener: async ({ pluginData, args: { message } }) => { + // Mention Check (if someone mentions the AFK user) + if (message.mentions.length) { + const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.mentions[0].id); + if (!afk) return; + + sendUserMentionMessage(message, afk.status); - sendUserMentionMessage(message, afk.status); + return; + } - return; + // Self AFK Check (if user is the one that's AFK) + const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.author.id); + if (!afk) return; + + try { + await pluginData.state.afkUsers.clearAFKStatus(message.author.id); + } catch (err) {} + + sendWelcomeBackMessage(message); } - - // Self AFK Check (if user is the one that's AFK) - const afk = await pluginData.state.afkUsers.getUserAFKStatus(message.author.id); - if (!afk) return; - - try { - await pluginData.state.afkUsers.clearAFKStatus(message.author.id); - } catch (err) {} - - sendWelcomeBackMessage(message); - }, -}); +}); \ No newline at end of file diff --git a/backend/src/plugins/AFK/functions/buildAFKMessages.ts b/backend/src/plugins/AFK/functions/buildAFKMessages.ts index 12de8e06..8d858744 100644 --- a/backend/src/plugins/AFK/functions/buildAFKMessages.ts +++ b/backend/src/plugins/AFK/functions/buildAFKMessages.ts @@ -1,23 +1,23 @@ import { Message } from "eris"; export function sendUserMentionMessage(message: Message, status: string) { - return message.channel.createMessage({ - allowedMentions: { - users: [message.author.id], - everyone: false, - roles: false, - }, - content: `<@!${message.author.id}>, the user mentioned is currently AFK: **${status}**`, - }); + return message.channel.createMessage({ + allowedMentions: { + users: [message.author.id], + everyone: false, + roles: false, + }, + content: `<@!${message.author.id}>, the user mentioned is currently AFK: **${status}**`, + }); } export function sendWelcomeBackMessage(message: Message) { - return message.channel.createMessage({ - allowedMentions: { - users: [message.author.id], - everyone: false, - roles: false, - }, - content: `<@!${message.author.id}>, welcome back!`, - }); -} + return message.channel.createMessage({ + allowedMentions: { + users: [message.author.id], + everyone: false, + roles: false, + }, + content: `<@!${message.author.id}>, welcome back!`, + }); +} \ No newline at end of file diff --git a/backend/src/plugins/AFK/functions/parseStatusMessage.ts b/backend/src/plugins/AFK/functions/parseStatusMessage.ts index 4d77c665..ca41790e 100644 --- a/backend/src/plugins/AFK/functions/parseStatusMessage.ts +++ b/backend/src/plugins/AFK/functions/parseStatusMessage.ts @@ -10,9 +10,9 @@ const HttpUrlRegex = /^(https?):\/\/[^\s$.?#].[^\s]*$/; const DiscordInviteLinkRegex = /^(?:https?:\/\/)?(?:www\.)?(?:discord\.gg\/|discord(?:app)?\.com\/invite\/)?(?[\w\d-]{2,})$/i; export function parseStatusMessage(pluginData: GuildPluginData, member: Member, status: string) { - const allow_links = hasPermission(pluginData, "allow_links", { member }); - const allow_invites = hasPermission(pluginData, "allow_invites", { member }); + const allow_links = hasPermission(pluginData, "allow_links", { member }); + const allow_invites = hasPermission(pluginData, "allow_invites", { member }); - if (!allow_links && HttpUrlRegex.test(status)) return "Links are not allowed in an AFK status!"; - if (!allow_invites && DiscordInviteLinkRegex.test(status)) return "Invites are not allowed in an AFK status!"; -} + if (!allow_links && HttpUrlRegex.test(status)) return "Links are not allowed in an AFK status!"; + if (!allow_invites && DiscordInviteLinkRegex.test(status)) return "Invites are not allowed in an AFK status!"; +} \ No newline at end of file diff --git a/backend/src/plugins/AFK/types.ts b/backend/src/plugins/AFK/types.ts index 9d97e41a..bf80a3f4 100644 --- a/backend/src/plugins/AFK/types.ts +++ b/backend/src/plugins/AFK/types.ts @@ -1,20 +1,20 @@ -import * as t from "io-ts"; -import { BasePluginType, guildCommand, guildEventListener } from "knub"; -import { AFK } from "../../data/AFK"; +import * as t from 'io-ts'; +import { BasePluginType, guildCommand, guildEventListener } from 'knub'; +import { AFK } from '../../data/AFK'; export const ConfigSchema = t.type({ - can_afk: t.boolean, - allow_links: t.boolean, - allow_invites: t.boolean, + can_afk: t.boolean, + allow_links: t.boolean, + allow_invites: t.boolean, }); export type TConfigSchema = t.TypeOf; export interface AFKPluginType extends BasePluginType { - config: TConfigSchema; - state: { - afkUsers: AFK; - }; + config: TConfigSchema; + state: { + afkUsers: AFK; + } } export const afkCmd = guildCommand(); -export const afkEvt = guildEventListener(); +export const afkEvt = guildEventListener(); \ No newline at end of file diff --git a/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts b/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts index ba3acc8c..ed8aa590 100644 --- a/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts +++ b/backend/src/plugins/AutoDelete/AutoDeletePlugin.ts @@ -39,13 +39,13 @@ export const AutoDeletePlugin = zeppelinGuildPlugin()("aut state.maxDelayWarningSent = false; - 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/onMessageDelete.ts b/backend/src/plugins/AutoDelete/util/onMessageDelete.ts index 2e5deab9..98eb2816 100644 --- a/backend/src/plugins/AutoDelete/util/onMessageDelete.ts +++ b/backend/src/plugins/AutoDelete/util/onMessageDelete.ts @@ -4,7 +4,7 @@ import { SavedMessage } from "../../../data/entities/SavedMessage"; 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 e9ef9864..9cd380c2 100644 --- a/backend/src/plugins/Automod/AutomodPlugin.ts +++ b/backend/src/plugins/Automod/AutomodPlugin.ts @@ -61,7 +61,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)) { @@ -217,10 +217,10 @@ export const AutomodPlugin = zeppelinGuildPlugin()("automod", pluginData.state.antiraidLevels = GuildAntiraidLevels.getGuildInstance(pluginData.guild.id); pluginData.state.archives = GuildArchives.getGuildInstance(pluginData.guild.id); - 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); pluginData.state.cachedAntiraidLevel = await pluginData.state.antiraidLevels.get(); diff --git a/backend/src/plugins/Automod/actions/addRoles.ts b/backend/src/plugins/Automod/actions/addRoles.ts index 51114673..4da915e7 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.get(pluginData.client.user.id)!; const missingPermissions = getMissingPermissions(me.permission, p.manageRoles); @@ -41,7 +41,7 @@ export const AddRolesAction = automodAction({ if (rolesWeCannotAssign.length) { const roleNamesWeCannotAssign = rolesWeCannotAssign.map( - (roleId) => pluginData.guild.roles.get(roleId)?.name || roleId, + roleId => pluginData.guild.roles.get(roleId)?.name || roleId, ); const logs = pluginData.getPlugin(LogsPlugin); logs.log(LogType.BOT_ALERT, { @@ -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); for (const roleId of rolesToAssign) { memberRoles.add(roleId); diff --git a/backend/src/plugins/Automod/actions/alert.ts b/backend/src/plugins/Automod/actions/alert.ts index 766adf0b..f4a098c9 100644 --- a/backend/src/plugins/Automod/actions/alert.ts +++ b/backend/src/plugins/Automod/actions/alert.ts @@ -33,7 +33,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 && stripObjectToScalars(c.user)).filter(Boolean); + const safeUsers = contexts.map(c => c.user && stripObjectToScalars(c.user)).filter(Boolean); const safeUser = safeUsers[0]; const actionsTaken = Object.keys(pluginData.config.get().rules[ruleName].actions).join(", "); diff --git a/backend/src/plugins/Automod/actions/ban.ts b/backend/src/plugins/Automod/actions/ban.ts index 9ee5ea45..0b53aff7 100644 --- a/backend/src/plugins/Automod/actions/ban.ts +++ b/backend/src/plugins/Automod/actions/ban.ts @@ -27,7 +27,7 @@ export const BanAction = automodAction({ extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [], }; - 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 2fada47e..7225f794 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).log(LogType.BOT_ALERT, { 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 3d678ea5..26f0dcc7 100644 --- a/backend/src/plugins/Automod/actions/kick.ts +++ b/backend/src/plugins/Automod/actions/kick.ts @@ -25,8 +25,8 @@ export const KickAction = automodAction({ extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [], }; - 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 548122d7..5390fe12 100644 --- a/backend/src/plugins/Automod/actions/log.ts +++ b/backend/src/plugins/Automod/actions/log.ts @@ -9,9 +9,9 @@ export const LogAction = automodAction({ defaultConfig: true, async apply({ pluginData, contexts, ruleName, matchResult }) { - const safeUsers = unique(contexts.map((c) => c.user)) + const safeUsers = unique(contexts.map(c => c.user)) .filter(Boolean) - .map((user) => stripObjectToScalars(user)); + .map(user => stripObjectToScalars(user)); const safeUser = safeUsers[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 8e590c67..6115a042 100644 --- a/backend/src/plugins/Automod/actions/mute.ts +++ b/backend/src/plugins/Automod/actions/mute.ts @@ -42,7 +42,7 @@ export const MuteAction = automodAction({ extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [], }; - 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 1057da67..6049cbf2 100644 --- a/backend/src/plugins/Automod/actions/removeRoles.ts +++ b/backend/src/plugins/Automod/actions/removeRoles.ts @@ -19,7 +19,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.get(pluginData.client.user.id)!; const missingPermissions = getMissingPermissions(me.permission, p.manageRoles); @@ -43,7 +43,7 @@ export const RemoveRolesAction = automodAction({ if (rolesWeCannotRemove.length) { const roleNamesWeCannotRemove = rolesWeCannotRemove.map( - (roleId) => pluginData.guild.roles.get(roleId)?.name || roleId, + roleId => pluginData.guild.roles.get(roleId)?.name || roleId, ); const logs = pluginData.getPlugin(LogsPlugin); logs.log(LogType.BOT_ALERT, { @@ -54,7 +54,7 @@ export const RemoveRolesAction = automodAction({ } await Promise.all( - members.map(async (member) => { + members.map(async member => { const memberRoles = new Set(member.roles); for (const roleId of rolesToRemove) { memberRoles.delete(roleId); diff --git a/backend/src/plugins/Automod/actions/reply.ts b/backend/src/plugins/Automod/actions/reply.ts index 5e25459a..0a451d00 100644 --- a/backend/src/plugins/Automod/actions/reply.ts +++ b/backend/src/plugins/Automod/actions/reply.ts @@ -27,8 +27,8 @@ export const ReplyAction = automodAction({ async apply({ pluginData, contexts, actionConfig }) { const contextsWithTextChannels = contexts - .filter((c) => c.message?.channel_id) - .filter((c) => pluginData.guild.channels.get(c.message!.channel_id) instanceof TextChannel); + .filter(c => c.message?.channel_id) + .filter(c => pluginData.guild.channels.get(c.message!.channel_id) instanceof TextChannel); const contextsByChannelId = contextsWithTextChannels.reduce((map: Map, context) => { if (!map.has(context.message!.channel_id)) { @@ -40,10 +40,10 @@ 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)))); + const users = unique(Array.from(new Set(_contexts.map(c => c.user).filter(Boolean)))); const user = users[0]; - const renderReplyText = async (str) => + const renderReplyText = async str => renderTemplate(str, { user: stripObjectToScalars(user), }); diff --git a/backend/src/plugins/Automod/actions/warn.ts b/backend/src/plugins/Automod/actions/warn.ts index feb3fa55..31a898b6 100644 --- a/backend/src/plugins/Automod/actions/warn.ts +++ b/backend/src/plugins/Automod/actions/warn.ts @@ -25,8 +25,8 @@ export const WarnAction = automodAction({ extraNotes: matchResult.fullSummary ? [matchResult.fullSummary] : [], }; - 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 b2372722..e1ee2fe5 100644 --- a/backend/src/plugins/Automod/functions/clearOldRecentActions.ts +++ b/backend/src/plugins/Automod/functions/clearOldRecentActions.ts @@ -4,7 +4,7 @@ import { RECENT_ACTION_EXPIRY_TIME } from "../constants"; 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 108552e8..7fcec63e 100644 --- a/backend/src/plugins/Automod/functions/clearOldRecentSpam.ts +++ b/backend/src/plugins/Automod/functions/clearOldRecentSpam.ts @@ -4,7 +4,7 @@ import { RECENT_SPAM_EXPIRY_TIME } from "../constants"; 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 33039320..03af6c9d 100644 --- a/backend/src/plugins/Automod/functions/clearRecentActionsForMessage.ts +++ b/backend/src/plugins/Automod/functions/clearRecentActionsForMessage.ts @@ -8,7 +8,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 be4063e7..09f4af78 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 1adcc9f9..6ec8a59f 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 fc74d176..56d251c2 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/triggers/exampleTrigger.ts b/backend/src/plugins/Automod/triggers/exampleTrigger.ts index bf0880a9..7098e713 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 a7b8d383..45f29697 100644 --- a/backend/src/plugins/Automod/triggers/matchAttachmentType.ts +++ b/backend/src/plugins/Automod/triggers/matchAttachmentType.ts @@ -37,10 +37,13 @@ export const MatchAttachmentTypeTrigger = automodTrigger()({ const attachments: any[] = context.message.data.attachments; for (const attachment of attachments) { - const attachmentType = attachment.filename.split(".").pop().toLowerCase(); + const attachmentType = attachment.filename + .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)) { @@ -53,7 +56,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/matchWords.ts b/backend/src/plugins/Automod/triggers/matchWords.ts index c04a3240..b5a2da97 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 d6d19fcf..f0f9b704 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 f89921af..5bda2423 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({ } const userNameList = args.users.map( - (user) => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, + user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, ); sendSuccessMessage( pluginData, diff --git a/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts b/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts index 6615e2eb..5c856275 100644 --- a/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts +++ b/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts @@ -23,9 +23,9 @@ export const ListDashboardUsersCmd = botControlCmd({ } const dashboardUsers = await pluginData.state.apiPermissionAssignments.getByGuildId(guild.id); - const users = await Promise.all(dashboardUsers.map((perm) => resolveUser(pluginData.client, perm.target_id))); + const users = await Promise.all(dashboardUsers.map(perm => resolveUser(pluginData.client, perm.target_id))); const userNameList = users.map( - (user) => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, + user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, ); sendSuccessMessage( diff --git a/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts b/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts index 9d386a60..078c189c 100644 --- a/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts +++ b/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts @@ -35,7 +35,7 @@ export const RemoveDashboardUserCmd = botControlCmd({ } const userNameList = args.users.map( - (user) => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, + user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, ); sendSuccessMessage( pluginData, diff --git a/backend/src/plugins/BotControl/commands/ServersCmd.ts b/backend/src/plugins/BotControl/commands/ServersCmd.ts index 1107cbd1..7d4be31c 100644 --- a/backend/src/plugins/BotControl/commands/ServersCmd.ts +++ b/backend/src/plugins/BotControl/commands/ServersCmd.ts @@ -21,7 +21,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.values()); const loadedGuilds = pluginData.getKnubInstance().getLoadedGuilds(); @@ -31,21 +31,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.username}#${owner.discriminator}** \`${owner.id}\`)`; @@ -56,7 +56,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.createMessage( diff --git a/backend/src/plugins/Cases/functions/createCaseNote.ts b/backend/src/plugins/Cases/functions/createCaseNote.ts index df2cc898..34db8758 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 eaa3fc54..60752242 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 b9d32139..b7fd5575 100644 --- a/backend/src/plugins/Censor/CensorPlugin.ts +++ b/backend/src/plugins/Censor/CensorPlugin.ts @@ -65,10 +65,10 @@ export const CensorPlugin = zeppelinGuildPlugin()("censor", { state.regexRunner = getRegExpRunner(`guild-${pluginData.guild.id}`); - 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 8bbe59a3..7a12639b 100644 --- a/backend/src/plugins/Censor/util/applyFiltersToMsg.ts +++ b/backend/src/plugins/Censor/util/applyFiltersToMsg.ts @@ -20,7 +20,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 Embed[]).map((e) => cloneDeep(e)); + const embeds = (savedMessage.data.embeds as Embed[]).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 @@ -53,7 +53,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/commands/ArchiveChannelCmd.ts b/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts index 30046ea2..373f2aa4 100644 --- a/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts +++ b/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts @@ -66,9 +66,9 @@ export const ArchiveChannelCmd = channelArchiverCmd({ for (const message of messages) { const ts = moment.utc(message.timestamp).format("YYYY-MM-DD HH:mm:ss"); - let content = `[${ts}] [${message.author.id}] [${message.author.username}#${message.author.discriminator}]: ${ - message.content || "" - }`; + let content = `[${ts}] [${message.author.id}] [${message.author.username}#${ + message.author.discriminator + }]: ${message.content || ""}`; if (message.attachments.length) { if (args["attachment-channel"]) { diff --git a/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts b/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts index 7dc08c0d..9287b080 100644 --- a/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts +++ b/backend/src/plugins/CompanionChannels/functions/getCompanionChannelOptsForVoiceChannelId.ts @@ -14,9 +14,9 @@ export function getCompanionChannelOptsForVoiceChannelId( const config = 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/Counters/CountersPlugin.ts b/backend/src/plugins/Counters/CountersPlugin.ts index becc7078..56af0f96 100644 --- a/backend/src/plugins/Counters/CountersPlugin.ts +++ b/backend/src/plugins/Counters/CountersPlugin.ts @@ -44,7 +44,7 @@ const defaultOptions: PluginOptions = { ], }; -const configPreprocessor: ConfigPreprocessorFn = (options) => { +const configPreprocessor: ConfigPreprocessorFn = options => { for (const counter of Object.values(options.config?.counters || {})) { counter.per_user = counter.per_user ?? false; counter.per_channel = counter.per_channel ?? false; diff --git a/backend/src/plugins/Counters/functions/changeCounterValue.ts b/backend/src/plugins/Counters/functions/changeCounterValue.ts index 23fdf8cd..be214eb7 100644 --- a/backend/src/plugins/Counters/functions/changeCounterValue.ts +++ b/backend/src/plugins/Counters/functions/changeCounterValue.ts @@ -37,10 +37,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 bc34e4ca..175cb158 100644 --- a/backend/src/plugins/Counters/functions/decayCounter.ts +++ b/backend/src/plugins/Counters/functions/decayCounter.ts @@ -24,8 +24,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 97ceb82b..2eefed8f 100644 --- a/backend/src/plugins/Counters/functions/setCounterValue.ts +++ b/backend/src/plugins/Counters/functions/setCounterValue.ts @@ -34,10 +34,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/LocateUser/events/BanRemoveAlertsEvt.ts b/backend/src/plugins/LocateUser/events/BanRemoveAlertsEvt.ts index 5dd503ad..cc6c155f 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.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 3648ec8b..e426e704 100644 --- a/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts +++ b/backend/src/plugins/LocateUser/events/SendAlertsEvts.ts @@ -29,7 +29,7 @@ export const ChannelLeaveAlertsEvt = locateUserEvt({ const triggeredAlerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.member.id); const voiceChannel = meta.args.oldChannel as VoiceChannel; - triggeredAlerts.forEach((alert) => { + triggeredAlerts.forEach(alert => { const txtChannel = meta.pluginData.client.getChannel(alert.channel_id) as TextableChannel; txtChannel.createMessage( `🔴 <@!${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 56e4315f..3c5c90d1 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 49f68450..df49c3d1 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.client.getChannel(alert.channel_id) as TextableChannel; sendWhere(pluginData, member, txtChannel, prepend); diff --git a/backend/src/plugins/Logs/LogsPlugin.ts b/backend/src/plugins/Logs/LogsPlugin.ts index 1c297bba..3173c507 100644 --- a/backend/src/plugins/Logs/LogsPlugin.ts +++ b/backend/src/plugins/Logs/LogsPlugin.ts @@ -97,10 +97,10 @@ export const LogsPlugin = zeppelinGuildPlugin()("logs", { state.batches = new Map(); - 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/LogsGuildMemberAddEvt.ts b/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts index 025d465e..b7a731f7 100644 --- a/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts +++ b/backend/src/plugins/Logs/events/LogsGuildMemberAddEvt.ts @@ -24,7 +24,7 @@ export const LogsGuildMemberAddEvt = logsEvt({ account_age: accountAge, }); - const cases = (await pluginData.state.cases.with("notes").getByUserId(member.id)).filter((c) => !c.is_hidden); + const cases = (await pluginData.state.cases.with("notes").getByUserId(member.id)).filter(c => !c.is_hidden); cases.sort((a, b) => (a.created_at > b.created_at ? -1 : 1)); if (cases.length) { diff --git a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts index 99993132..46228646 100644 --- a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts +++ b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts @@ -61,12 +61,12 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ { member: logMember, addedRoles: addedRoles - .map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) - .map((r) => r.name) + .map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(r => r.name) .join(", "), removedRoles: removedRoles - .map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) - .map((r) => r.name) + .map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(r => r.name) .join(", "), mod: stripObjectToScalars(mod), }, @@ -79,8 +79,8 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ { member: logMember, roles: addedRoles - .map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) - .map((r) => r.name) + .map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(r => r.name) .join(", "), mod: stripObjectToScalars(mod), }, @@ -93,8 +93,8 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ { member: logMember, roles: removedRoles - .map((roleId) => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) - .map((r) => r.name) + .map(roleId => pluginData.guild.roles.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(r => r.name) .join(", "), mod: stripObjectToScalars(mod), }, diff --git a/backend/src/plugins/Logs/util/getLogMessage.ts b/backend/src/plugins/Logs/util/getLogMessage.ts index 651c892b..41fc369b 100644 --- a/backend/src/plugins/Logs/util/getLogMessage.ts +++ b/backend/src/plugins/Logs/util/getLogMessage.ts @@ -41,7 +41,7 @@ export async function getLogMessage( const values = { ...data, timestamp, - userMention: async (inputUserOrMember) => { + userMention: async inputUserOrMember => { if (!inputUserOrMember) return ""; const usersOrMembers = Array.isArray(inputUserOrMember) ? inputUserOrMember : [inputUserOrMember]; @@ -71,7 +71,7 @@ export async function getLogMessage( return mentions.join(", "); }, - channelMention: (channel) => { + channelMention: channel => { if (!channel) return ""; return verboseChannelMention(channel); }, @@ -83,12 +83,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/onMessageDeleteBulk.ts b/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts index 8a55873c..f7b7e571 100644 --- a/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts +++ b/backend/src/plugins/Logs/util/onMessageDeleteBulk.ts @@ -8,7 +8,7 @@ export async function onMessageDeleteBulk(pluginData: GuildPluginData `\`${item.user_id}\``))).join(", "); + const authorIds = Array.from(new Set(savedMessages.map(item => `\`${item.user_id}\``))).join(", "); pluginData.state.guildLogs.log( LogType.MESSAGE_DELETE_BULK, diff --git a/backend/src/plugins/Logs/util/onMessageUpdate.ts b/backend/src/plugins/Logs/util/onMessageUpdate.ts index 54c6a39d..91eb7abb 100644 --- a/backend/src/plugins/Logs/util/onMessageUpdate.ts +++ b/backend/src/plugins/Logs/util/onMessageUpdate.ts @@ -15,12 +15,12 @@ export async function onMessageUpdate( let logUpdate = false; const oldEmbedsToCompare = ((oldSavedMessage.data.embeds || []) as Embed[]) - .map((e) => cloneDeep(e)) - .filter((e) => (e as Embed).type === "rich"); + .map(e => cloneDeep(e)) + .filter(e => (e as Embed).type === "rich"); const newEmbedsToCompare = ((savedMessage.data.embeds || []) as Embed[]) - .map((e) => cloneDeep(e)) - .filter((e) => (e as Embed).type === "rich"); + .map(e => cloneDeep(e)) + .filter(e => (e as Embed).type === "rich"); for (const embed of [...oldEmbedsToCompare, ...newEmbedsToCompare]) { if (embed.thumbnail) { diff --git a/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts b/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts index 1bfa568e..2ecbf8e0 100644 --- a/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts +++ b/backend/src/plugins/MessageSaver/commands/SavePinsToDB.ts @@ -19,7 +19,7 @@ export const SavePinsToDBCmd = messageSaverCmd({ const { savedCount, failed } = await saveMessagesToDB( pluginData, args.channel, - pins.map((m) => m.id), + pins.map(m => m.id), ); if (failed.length) { diff --git a/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts b/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts index 18965260..00d83fcd 100644 --- a/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts +++ b/backend/src/plugins/MessageSaver/events/SaveMessagesEvts.ts @@ -51,7 +51,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 6b7e0335..6d84fc77 100644 --- a/backend/src/plugins/ModActions/commands/CasesModCmd.ts +++ b/backend/src/plugins/ModActions/commands/CasesModCmd.ts @@ -47,9 +47,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 0f870689..12fdf125 100644 --- a/backend/src/plugins/ModActions/commands/CasesUserCmd.ts +++ b/backend/src/plugins/ModActions/commands/CasesUserCmd.ts @@ -42,8 +42,8 @@ export const CasesUserCmd = modActionsCmd({ } const cases = await pluginData.state.cases.with("notes").getByUserId(user.id); - 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 @@ -70,7 +70,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/MassBanCmd.ts b/backend/src/plugins/ModActions/commands/MassBanCmd.ts index 9a28ad89..bd79f7f3 100644 --- a/backend/src/plugins/ModActions/commands/MassBanCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassBanCmd.ts @@ -52,7 +52,7 @@ export const MassbanCmd = modActionsCmd({ // Ignore automatic ban cases and logs for these users // We'll create our own cases below and post a single "mass banned" log instead - args.userIds.forEach((userId) => { + args.userIds.forEach(userId => { // Use longer timeouts since this can take a while ignoreEvent(pluginData, IgnoredEventType.Ban, userId, 120 * 1000); pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_BAN, userId, 120 * 1000); diff --git a/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts b/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts index 51d5c545..897cc25f 100644 --- a/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts @@ -41,7 +41,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); @@ -90,19 +90,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 605c6439..73e329d0 100644 --- a/backend/src/plugins/ModActions/commands/MassmuteCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassmuteCmd.ts @@ -52,7 +52,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 c16dabcf..cbcf082f 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 96653daf..d8a6b4e4 100644 --- a/backend/src/plugins/ModActions/functions/formatReasonWithAttachments.ts +++ b/backend/src/plugins/ModActions/functions/formatReasonWithAttachments.ts @@ -1,6 +1,6 @@ import { Attachment } from "eris"; export function formatReasonWithAttachments(reason: string, attachments: Attachment[]) { - 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/isBanned.ts b/backend/src/plugins/ModActions/functions/isBanned.ts index 4d6ce1a3..c809a30c 100644 --- a/backend/src/plugins/ModActions/functions/isBanned.ts +++ b/backend/src/plugins/ModActions/functions/isBanned.ts @@ -5,7 +5,7 @@ import { isDiscordHTTPError } from "../../../utils"; export async function isBanned(pluginData: GuildPluginData, userId: string): Promise { try { const bans = await pluginData.guild.getBans(); - return bans.some((b) => b.user.id === userId); + return bans.some(b => b.user.id === userId); } catch (e) { if (isDiscordHTTPError(e) && e.code === 500) { return false; diff --git a/backend/src/plugins/ModActions/functions/isEventIgnored.ts b/backend/src/plugins/ModActions/functions/isEventIgnored.ts index 8ec27baf..32ae4acf 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 d504d551..b59f1165 100644 --- a/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts @@ -14,7 +14,7 @@ export const ClearBannedMutesCmd = mutesCmd({ // Mismatch in Eris docs and actual result here, based on Eris's code comments anyway const bans: Array<{ reason: string; user: User }> = (await pluginData.guild.getBans()) as any; - const bannedIds = bans.map((b) => b.user.id); + const bannedIds = bans.map(b => b.user.id); await msg.channel.createMessage( `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 7e7ee622..9636141a 100644 --- a/backend/src/plugins/Mutes/commands/MutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/MutesCmd.ts @@ -47,12 +47,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: Member[] = []; const muteRole = pluginData.config.get().mute_role; if (muteRole) { - pluginData.guild.members.forEach((member) => { + pluginData.guild.members.forEach(member => { if (muteUserIds.has(member.id)) return; if (member.roles.includes(muteRole)) manuallyMutedMembers.push(member); }); @@ -60,7 +60,7 @@ export const MutesCmd = mutesCmd({ totalMutes = manuallyMutedMembers.length; - lines = manuallyMutedMembers.map((member) => { + lines = manuallyMutedMembers.map(member => { return `<@!${member.id}> (**${member.user.username}#${member.user.discriminator}**, \`${member.id}\`) 🔧 Manual mute`; }); } else { @@ -70,8 +70,11 @@ 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; } @@ -84,7 +87,7 @@ export const MutesCmd = mutesCmd({ if (!member) { if (!bannedIds) { const bans = await pluginData.guild.getBans(); - bannedIds = bans.map((u) => u.user.id); + bannedIds = bans.map(u => u.user.id); } muteWithDetails.banned = bannedIds.includes(mute.user_id); @@ -97,18 +100,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.get(mute.user_id); const username = user ? `${user.username}#${user.discriminator}` : "Unknown#0000"; const theCase = muteCasesById.get(mute.case_id); @@ -143,7 +146,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; diff --git a/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts b/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts index fef577fa..e99f2b73 100644 --- a/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts +++ b/backend/src/plugins/Mutes/functions/clearExpiredMutes.ts @@ -19,7 +19,7 @@ export async function clearExpiredMutes(pluginData: GuildPluginData x !== muteRole && guildRoles.has(x))]), + new Set([...mute.roles_to_restore, ...member.roles.filter(x => x !== muteRole && guildRoles.has(x))]), ); member.edit(memberOptions); } diff --git a/backend/src/plugins/Mutes/functions/muteUser.ts b/backend/src/plugins/Mutes/functions/muteUser.ts index 83f3a73f..2f8e4e28 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.filter((x) => x.managed).map((y) => y.id); - memberOptions.roles = managedRoles.filter((x) => member.roles.includes(x)); + const managedRoles = pluginData.guild.roles.filter(x => x.managed).map(y => y.id); + memberOptions.roles = managedRoles.filter(x => member.roles.includes(x)); await member.edit(memberOptions); } } else { - memberOptions.roles = currentUserRoles.filter((x) => !(removeRoles).includes(x)); + memberOptions.roles = currentUserRoles.filter(x => !(removeRoles).includes(x)); await member.edit(memberOptions); } @@ -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 @@ -90,7 +90,7 @@ export async function muteUser( try { await member.addRole(muteRole); } catch (e) { - const actualMuteRole = pluginData.guild.roles.find((x) => x.id === muteRole); + const actualMuteRole = pluginData.guild.roles.find(x => x.id === muteRole); if (!actualMuteRole) { lock.unlock(); logs.log(LogType.BOT_ALERT, { @@ -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.filter((x) => zep!.roles.includes(x.id)); + const zepRoles = pluginData.guild.roles.filter(x => zep!.roles.includes(x.id)); // If we have roles and one of them is above the muted role, throw generic error - if (zepRoles.length >= 0 && zepRoles.some((zepRole) => zepRole.position > actualMuteRole.position)) { + if (zepRoles.length >= 0 && zepRoles.some(zepRole => zepRole.position > actualMuteRole.position)) { lock.unlock(); logs.log(LogType.BOT_ALERT, { 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 07a00f8a..dce5cc06 100644 --- a/backend/src/plugins/Mutes/functions/unmuteUser.ts +++ b/backend/src/plugins/Mutes/functions/unmuteUser.ts @@ -40,10 +40,7 @@ export async function unmuteUser( const memberOptions: MemberOptions = {}; const guildRoles = pluginData.guild.roles; memberOptions.roles = Array.from( - new Set([ - ...existingMute.roles_to_restore, - ...member.roles.filter((x) => x !== muteRole && guildRoles.has(x)), - ]), + new Set([...existingMute.roles_to_restore, ...member.roles.filter(x => x !== muteRole && guildRoles.has(x))]), ); member.edit(memberOptions); } diff --git a/backend/src/plugins/NameHistory/commands/NamesCmd.ts b/backend/src/plugins/NameHistory/commands/NamesCmd.ts index 20a4dbd1..78456820 100644 --- a/backend/src/plugins/NameHistory/commands/NamesCmd.ts +++ b/backend/src/plugins/NameHistory/commands/NamesCmd.ts @@ -25,9 +25,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 = pluginData.client.users.get(args.userId); const currentUsername = user ? `${user.username}#${user.discriminator}` : args.userId; diff --git a/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts b/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts index 13997b81..bc61a4ba 100644 --- a/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts +++ b/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts @@ -27,7 +27,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.embed && (p.content.embed.description || p.content.embed.title)) || ""; diff --git a/backend/src/plugins/Post/util/actualPostCmd.ts b/backend/src/plugins/Post/util/actualPostCmd.ts index ab30344f..b8c8cbc8 100644 --- a/backend/src/plugins/Post/util/actualPostCmd.ts +++ b/backend/src/plugins/Post/util/actualPostCmd.ts @@ -125,10 +125,18 @@ export async function actualPostCmd( channel_id: targetChannel.id, content, attachments: msg.attachments, - 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/commands/InitReactionRolesCmd.ts b/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts index 34dd5cca..119b7b27 100644 --- a/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts +++ b/backend/src/plugins/ReactionRoles/commands/InitReactionRolesCmd.ts @@ -59,7 +59,7 @@ 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(v => v.split(/[\s=,]+/).map(v => v.trim())) // tslint:disable-line .map( (pair): TReactionRolePair => { const customEmojiMatch = pair[0].match(/^$/); diff --git a/backend/src/plugins/ReactionRoles/events/AddReactionRoleEvt.ts b/backend/src/plugins/ReactionRoles/events/AddReactionRoleEvt.ts index 57e37716..296c5038 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 27500df6..7de45269 100644 --- a/backend/src/plugins/ReactionRoles/util/applyReactionRoleReactionsToMessage.ts +++ b/backend/src/plugins/ReactionRoles/util/applyReactionRoleReactionsToMessage.ts @@ -66,7 +66,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 c1d2b42a..c365c18f 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 0f967707..67a2cfc1 100644 --- a/backend/src/plugins/Reminders/commands/RemindCmd.ts +++ b/backend/src/plugins/Reminders/commands/RemindCmd.ts @@ -53,7 +53,10 @@ 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 87694741..b2e3000f 100644 --- a/backend/src/plugins/Roles/commands/MassAddRoleCmd.ts +++ b/backend/src/plugins/Roles/commands/MassAddRoleCmd.ts @@ -58,7 +58,7 @@ export const MassAddRoleCmd = rolesCmd({ return; } - const membersWithoutTheRole = members.filter((m) => !m.roles.includes(roleId)); + const membersWithoutTheRole = members.filter(m => !m.roles.includes(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 c31b90ba..966f2e4a 100644 --- a/backend/src/plugins/Roles/commands/MassRemoveRoleCmd.ts +++ b/backend/src/plugins/Roles/commands/MassRemoveRoleCmd.ts @@ -58,7 +58,7 @@ export const MassRemoveRoleCmd = rolesCmd({ return; } - const membersWithTheRole = members.filter((m) => m.roles.includes(roleId)); + const membersWithTheRole = members.filter(m => m.roles.includes(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 9299ac73..9b1e5b2c 100644 --- a/backend/src/plugins/SelfGrantableRoles/SelfGrantableRolesPlugin.ts +++ b/backend/src/plugins/SelfGrantableRoles/SelfGrantableRolesPlugin.ts @@ -69,7 +69,7 @@ export const SelfGrantableRolesPlugin = zeppelinGuildPlugin { + configPreprocessor: options => { const config = options.config; for (const [key, entry] of Object.entries(config.entries)) { // Apply default entry config @@ -78,7 +78,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 038290d6..2c9a1d0f 100644 --- a/backend/src/plugins/SelfGrantableRoles/commands/RoleAddCmd.ts +++ b/backend/src/plugins/SelfGrantableRoles/commands/RoleAddCmd.ts @@ -30,7 +30,7 @@ export const RoleAddCmd = selfGrantableRolesCmd({ const hasUnknownRoles = matchedRoleIds.length !== roleNames.length; const rolesToAdd: Map = Array.from(matchedRoleIds.values()) - .map((id) => pluginData.guild.roles.get(id)!) + .map(id => pluginData.guild.roles.get(id)!) .filter(Boolean) .reduce((map, role) => { map.set(role.id, role); @@ -91,7 +91,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[] = []; @@ -101,11 +101,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 c0a438d4..7cabb3c4 100644 --- a/backend/src/plugins/SelfGrantableRoles/commands/RoleRemoveCmd.ts +++ b/backend/src/plugins/SelfGrantableRoles/commands/RoleRemoveCmd.ts @@ -26,19 +26,19 @@ export const RoleRemoveCmd = selfGrantableRolesCmd({ const roleNames = normalizeRoleNames(splitRoleNames(args.roleNames)); const matchedRoleIds = findMatchingRoles(roleNames, applyingEntries); - const rolesToRemove = Array.from(matchedRoleIds.values()).map((id) => pluginData.guild.roles.get(id)!); - const roleIdsToRemove = rolesToRemove.map((r) => r.id); + const rolesToRemove = Array.from(matchedRoleIds.values()).map(id => pluginData.guild.roles.get(id)!); + const roleIdsToRemove = rolesToRemove.map(r => r.id); // Remove the roles if (rolesToRemove.length) { - const newRoleIds = msg.member.roles.filter((roleId) => !roleIdsToRemove.includes(roleId)); + const newRoleIds = msg.member.roles.filter(roleId => !roleIdsToRemove.includes(roleId)); 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 42a6dd34..69daae02 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 47331c65..d921002d 100644 --- a/backend/src/plugins/SelfGrantableRoles/util/getApplyingEntries.ts +++ b/backend/src/plugins/SelfGrantableRoles/util/getApplyingEntries.ts @@ -11,5 +11,5 @@ export 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 d0c6d6d2..7f19a7bb 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 3baefee5..efd460d3 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 ef35e4b9..1983a6a7 100644 --- a/backend/src/plugins/Slowmode/SlowmodePlugin.ts +++ b/backend/src/plugins/Slowmode/SlowmodePlugin.ts @@ -62,7 +62,7 @@ export const SlowmodePlugin = zeppelinGuildPlugin()("slowmod state.logs = new GuildLogs(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 c7aa322e..136ff277 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 23f8e2a4..a09261bd 100644 --- a/backend/src/plugins/Spam/SpamPlugin.ts +++ b/backend/src/plugins/Spam/SpamPlugin.ts @@ -77,7 +77,7 @@ export const SpamPlugin = zeppelinGuildPlugin()("spam", { state.spamDetectionQueue = Promise.resolve(); - 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 1c0857b3..4f42211c 100644 --- a/backend/src/plugins/Spam/util/clearOldRecentActions.ts +++ b/backend/src/plugins/Spam/util/clearOldRecentActions.ts @@ -6,7 +6,5 @@ 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 43010aca..839ac107 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 484c2462..765a1300 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 e652dc57..d5cc946e 100644 --- a/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts +++ b/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts @@ -108,8 +108,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( @@ -117,11 +117,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.client.deleteMessages(savedMessage.channel_id, msgIds).catch(noop); } @@ -129,7 +129,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; }); @@ -191,7 +191,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 a2b3c437..c3374e56 100644 --- a/backend/src/plugins/Starboard/StarboardPlugin.ts +++ b/backend/src/plugins/Starboard/StarboardPlugin.ts @@ -139,7 +139,7 @@ export const StarboardPlugin = zeppelinGuildPlugin()("starb state.starboardMessages = GuildStarboardMessages.getGuildInstance(guild.id); state.starboardReactions = GuildStarboardReactions.getGuildInstance(guild.id); - 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 1a6a107f..b6142655 100644 --- a/backend/src/plugins/Starboard/events/StarboardReactionAddEvt.ts +++ b/backend/src/plugins/Starboard/events/StarboardReactionAddEvt.ts @@ -39,11 +39,11 @@ export const StarboardReactionAddEvt = starboardEvt({ const boardLock = await pluginData.locks.acquire(`starboards`); 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 64260592..d63b519c 100644 --- a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts +++ b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts @@ -53,7 +53,10 @@ export function createStarboardEmbedFromMessage(msg: Message, copyFullEmbed: boo // If there are no embeds, add the first image attachment explicitly else if (msg.attachments.length) { for (const attachment of msg.attachments) { - const ext = path.extname(attachment.filename).slice(1).toLowerCase(); + const ext = path + .extname(attachment.filename) + .slice(1) + .toLowerCase(); if (imageAttachmentExtensions.includes(ext)) { embed.image = { url: attachment.url }; diff --git a/backend/src/plugins/Tags/TagsPlugin.ts b/backend/src/plugins/Tags/TagsPlugin.ts index 450c72db..e8bb8541 100644 --- a/backend/src/plugins/Tags/TagsPlugin.ts +++ b/backend/src/plugins/Tags/TagsPlugin.ts @@ -103,10 +103,10 @@ export const TagsPlugin = zeppelinGuildPlugin()("tags", { state.savedMessages = GuildSavedMessages.getGuildInstance(guild.id); state.logs = new GuildLogs(guild.id); - 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); @@ -155,7 +155,10 @@ export const TagsPlugin = zeppelinGuildPlugin()("tags", { } const delayMS = convertDelayStringToMS(delay) ?? 0; - return moment.utc(reference, "x").add(delayMS).valueOf(); + return moment + .utc(reference, "x") + .add(delayMS) + .valueOf(); }, timeSub(...args) { @@ -173,7 +176,10 @@ export const TagsPlugin = zeppelinGuildPlugin()("tags", { } const delayMS = convertDelayStringToMS(delay) ?? 0; - return moment.utc(reference, "x").subtract(delayMS).valueOf(); + return moment + .utc(reference, "x") + .subtract(delayMS) + .valueOf(); }, timeAgo(delay) { @@ -191,7 +197,7 @@ export const TagsPlugin = zeppelinGuildPlugin()("tags", { return timeAndDate.inGuildTz(parsed).format("YYYY-MM-DD"); }, - mention: (input) => { + mention: input => { if (typeof input !== "string") { return ""; } diff --git a/backend/src/plugins/Tags/commands/TagListCmd.ts b/backend/src/plugins/Tags/commands/TagListCmd.ts index 71dbce06..ed22e4a1 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 = 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 4c761abe..d7d8530b 100644 --- a/backend/src/plugins/Tags/util/onMessageCreate.ts +++ b/backend/src/plugins/Tags/util/onMessageCreate.ts @@ -77,7 +77,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 065413f2..dfde7a71 100644 --- a/backend/src/plugins/Tags/util/renderTagBody.ts +++ b/backend/src/plugins/Tags/util/renderTagBody.ts @@ -53,6 +53,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 7298f911..5c9986ac 100644 --- a/backend/src/plugins/Tags/util/renderTagFromString.ts +++ b/backend/src/plugins/Tags/util/renderTagFromString.ts @@ -19,7 +19,7 @@ export async function renderTagFromString( member: Member, ): 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 3e2a113f..3f1285b4 100644 --- a/backend/src/plugins/Utility/commands/AboutCmd.ts +++ b/backend/src/plugins/Utility/commands/AboutCmd.ts @@ -57,7 +57,10 @@ 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(); @@ -84,23 +87,23 @@ export const AboutCmd = utilityCmd({ const supporters = await pluginData.state.supporters.getAll(); supporters.sort( multiSorter([ - [(r) => r.amount, "DESC"], - [(r) => r.name.toLowerCase(), "ASC"], + [r => r.amount, "DESC"], + [r => r.name.toLowerCase(), "ASC"], ]), ); if (supporters.length) { aboutContent.embed.fields.push({ name: "Zeppelin supporters 🎉", - value: supporters.map((s) => `**${s.name}** ${s.amount ? `${s.amount}€/mo` : ""}`.trim()).join("\n"), + value: supporters.map(s => `**${s.name}** ${s.amount ? `${s.amount}€/mo` : ""}`.trim()).join("\n"), }); } // 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.map((r) => (msg.channel as GuildChannel).guild.roles.get(r)!) || []; - 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.map(r => (msg.channel as GuildChannel).guild.roles.get(r)!) || []; + 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.embed.color = botRoles[0].color; diff --git a/backend/src/plugins/Utility/commands/CleanCmd.ts b/backend/src/plugins/Utility/commands/CleanCmd.ts index a2e9555b..e75da2f8 100644 --- a/backend/src/plugins/Utility/commands/CleanCmd.ts +++ b/backend/src/plugins/Utility/commands/CleanCmd.ts @@ -24,10 +24,10 @@ 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); + const idsToDelete = savedMessages.map(m => m.id); // 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 @@ -119,7 +119,7 @@ export const CleanCmd = utilityCmd({ const contentString = message.data.content || ""; if (args.user && message.user_id !== args.user) continue; if (args.bots && !message.is_bot) continue; - if (!deletePins && pins.find((x) => x.id === message.id) != null) continue; + if (!deletePins && pins.find(x => x.id === message.id) != null) continue; if (args["has-invites"] && getInviteCodesInString(contentString).length === 0) continue; if (upToMsgId != null && message.id < upToMsgId) { foundId = true; diff --git a/backend/src/plugins/Utility/commands/HelpCmd.ts b/backend/src/plugins/Utility/commands/HelpCmd.ts index c9be23df..8d4af9cc 100644 --- a/backend/src/plugins/Utility/commands/HelpCmd.ts +++ b/backend/src/plugins/Utility/commands/HelpCmd.ts @@ -57,7 +57,10 @@ 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/PingCmd.ts b/backend/src/plugins/Utility/commands/PingCmd.ts index 73d713cc..b8304182 100644 --- a/backend/src/plugins/Utility/commands/PingCmd.ts +++ b/backend/src/plugins/Utility/commands/PingCmd.ts @@ -46,7 +46,7 @@ export const PingCmd = utilityCmd({ pluginData.client .deleteMessages( messages[0].channel.id, - messages.map((m) => m.id), + messages.map(m => m.id), ) .catch(noop); }, diff --git a/backend/src/plugins/Utility/commands/RolesCmd.ts b/backend/src/plugins/Utility/commands/RolesCmd.ts index 69a9274f..5aa52452 100644 --- a/backend/src/plugins/Utility/commands/RolesCmd.ts +++ b/backend/src/plugins/Utility/commands/RolesCmd.ts @@ -26,7 +26,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) { @@ -77,7 +77,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; @@ -87,7 +87,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 dfc7defc..aa9a9131 100644 --- a/backend/src/plugins/Utility/commands/VcmoveCmd.ts +++ b/backend/src/plugins/Utility/commands/VcmoveCmd.ts @@ -47,10 +47,10 @@ export const VcmoveCmd = utilityCmd({ channel = potentialChannel; } else { // Search string -> find closest matching voice channel name - const voiceChannels = pluginData.guild.channels.filter((theChannel) => { + const voiceChannels = pluginData.guild.channels.filter(theChannel => { return theChannel instanceof VoiceChannel; }) as VoiceChannel[]; - 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; @@ -130,10 +130,10 @@ export const VcmoveAllCmd = utilityCmd({ channel = potentialChannel; } else { // Search string -> find closest matching voice channel name - const voiceChannels = pluginData.guild.channels.filter((theChannel) => { + const voiceChannels = pluginData.guild.channels.filter(theChannel => { return theChannel instanceof VoiceChannel; }) as VoiceChannel[]; - 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 a9367940..1795cf3d 100644 --- a/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts @@ -84,8 +84,8 @@ export async function getChannelInfoEmbed( if (channel.type === Constants.ChannelTypes.GUILD_VOICE) { const voiceMembers = Array.from(channel.voiceMembers.values()); - const muted = voiceMembers.filter((vm) => vm.voiceState.mute || vm.voiceState.selfMute); - const deafened = voiceMembers.filter((vm) => vm.voiceState.deaf || vm.voiceState.selfDeaf); + const muted = voiceMembers.filter(vm => vm.voiceState.mute || vm.voiceState.selfMute); + const deafened = voiceMembers.filter(vm => vm.voiceState.deaf || vm.voiceState.selfDeaf); embed.fields.push({ name: preEmbedPadding + "Voice information", @@ -99,10 +99,10 @@ export async function getChannelInfoEmbed( if (channel.type === Constants.ChannelTypes.GUILD_CATEGORY) { const textChannels = pluginData.guild.channels.filter( - (ch) => ch.parentID === channel.id && ch.type !== Constants.ChannelTypes.GUILD_VOICE, + ch => ch.parentID === channel.id && ch.type !== Constants.ChannelTypes.GUILD_VOICE, ); const voiceChannels = pluginData.guild.channels.filter( - (ch) => ch.parentID === channel.id && ch.type === Constants.ChannelTypes.GUILD_VOICE, + ch => ch.parentID === channel.id && ch.type === Constants.ChannelTypes.GUILD_VOICE, ); embed.fields.push({ diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index f49ba904..3022a250 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -126,7 +126,7 @@ export async function getServerInfoEmbed( } if (!onlineMemberCount && thisServer) { - onlineMemberCount = thisServer.members.filter((m) => m.status !== "offline").length; // Extremely inaccurate fallback + onlineMemberCount = thisServer.members.filter(m => m.status !== "offline").length; // Extremely inaccurate fallback } const offlineMemberCount = totalMembers - onlineMemberCount; @@ -154,9 +154,9 @@ export async function getServerInfoEmbed( // CHANNEL COUNTS if (thisServer) { const totalChannels = thisServer.channels.size; - const categories = thisServer.channels.filter((channel) => channel instanceof CategoryChannel); - const textChannels = thisServer.channels.filter((channel) => channel instanceof TextChannel); - const voiceChannels = thisServer.channels.filter((channel) => channel instanceof VoiceChannel); + const categories = thisServer.channels.filter(channel => channel instanceof CategoryChannel); + const textChannels = thisServer.channels.filter(channel => channel instanceof TextChannel); + const voiceChannels = thisServer.channels.filter(channel => channel instanceof VoiceChannel); 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 45521e65..c3acdda3 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 = member.roles.map((id) => pluginData.guild.roles.get(id)).filter((r) => r != null) as Role[]; + const roles = member.roles.map(id => pluginData.guild.roles.get(id)).filter(r => r != null) as Role[]; roles.sort(sorter("position", "DESC")); embed.fields.push({ name: preEmbedPadding + "Member information", value: trimLines(` Joined: **${joinAge} ago** (\`${prettyJoinedAt}\`) - ${roles.length > 0 ? "Roles: " + roles.map((r) => `<@&${r.id}>`).join(", ") : ""} + ${roles.length > 0 ? "Roles: " + roles.map(r => `<@&${r.id}>`).join(", ") : ""} `), }); @@ -132,14 +132,14 @@ export async function getUserInfoEmbed( value: "⚠ 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 3391b23e..c369e7ba 100644 --- a/backend/src/plugins/Utility/search.ts +++ b/backend/src/plugins/Utility/search.ts @@ -57,7 +57,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; @@ -68,7 +68,7 @@ export async function displaySearch( searchMsgPromise = originalSearchMsg.edit("Searching..."); } else { searchMsgPromise = msg.channel.createMessage("Searching..."); - searchMsgPromise.then((m) => (originalSearchMsg = m)); + searchMsgPromise.then(m => (originalSearchMsg = m)); } let searchResult; @@ -252,7 +252,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.includes(role)) return false; } @@ -262,11 +262,11 @@ async function performMemberSearch( } if (args.voice) { - matchingMembers = matchingMembers.filter((m) => m.voiceState.channelID != null); + matchingMembers = matchingMembers.filter(m => m.voiceState.channelID != null); } if (args.bot) { - matchingMembers = matchingMembers.filter((m) => m.bot); + matchingMembers = matchingMembers.filter(m => m.bot); } if (args.query) { @@ -280,7 +280,7 @@ async function performMemberSearch( } if (args["status-search"]) { - matchingMembers = await asyncFilter(matchingMembers, async (member) => { + matchingMembers = await asyncFilter(matchingMembers, async member => { if (member.game) { if ( member.game.name && @@ -329,7 +329,7 @@ async function performMemberSearch( return false; }); } else { - matchingMembers = await asyncFilter(matchingMembers, async (member) => { + matchingMembers = await asyncFilter(matchingMembers, async member => { if (member.nick && (await pluginData.state.regexRunner.exec(queryRegex, member.nick).catch(allowTimeout))) { return true; } @@ -346,12 +346,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.username.toLowerCase(), realSortDir], - [(m) => m.discriminator, realSortDir], + [m => m.username.toLowerCase(), realSortDir], + [m => m.discriminator, realSortDir], ]), ); } @@ -380,7 +380,7 @@ async function performBanSearch( page = 1, perPage = SEARCH_RESULTS_PER_PAGE, ): Promise<{ results: User[]; totalResults: number; page: number; lastPage: number; from: number; to: number }> { - let matchingBans = (await pluginData.guild.getBans()).map((x) => x.user); + let matchingBans = (await pluginData.guild.getBans()).map(x => x.user); if (args.query) { let queryRegex: RegExp; @@ -392,7 +392,7 @@ async function performBanSearch( queryRegex = new RegExp(escapeStringRegexp(args.query.trimStart()), args["case-sensitive"] ? "" : "i"); } - matchingBans = await asyncFilter(matchingBans, async (user) => { + matchingBans = await asyncFilter(matchingBans, async user => { const fullUsername = `${user.username}#${user.discriminator}`; if (await pluginData.state.regexRunner.exec(queryRegex, fullUsername).catch(allowTimeout)) return true; return false; @@ -403,12 +403,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], ]), ); } @@ -433,7 +433,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 Member) { @@ -448,5 +448,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/availablePlugins.ts b/backend/src/plugins/availablePlugins.ts index dfaa6688..8e406bb8 100644 --- a/backend/src/plugins/availablePlugins.ts +++ b/backend/src/plugins/availablePlugins.ts @@ -33,7 +33,7 @@ import { BotControlPlugin } from "./BotControl/BotControlPlugin"; import { GuildAccessMonitorPlugin } from "./GuildAccessMonitor/GuildAccessMonitorPlugin"; import { TimeAndDatePlugin } from "./TimeAndDate/TimeAndDatePlugin"; import { CountersPlugin } from "./Counters/CountersPlugin"; -import { AFKPlugin } from "./AFK/AFKPlugin"; +import { AFKPlugin } from './AFK/AFKPlugin'; // prettier-ignore export const guildPlugins: Array> = [ diff --git a/backend/src/templateFormatter.test.ts b/backend/src/templateFormatter.test.ts index 0679f535..93a804b9 100644 --- a/backend/src/templateFormatter.test.ts +++ b/backend/src/templateFormatter.test.ts @@ -1,12 +1,12 @@ import { parseTemplate, renderParsedTemplate, renderTemplate } from "./templateFormatter"; import test from "ava"; -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 = { 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 496a2748..1963c816 100644 --- a/backend/src/templateFormatter.ts +++ b/backend/src/templateFormatter.ts @@ -35,7 +35,7 @@ function newTemplateVar(): ITemplateVar { type ParsedTemplate = Array; function cleanUpParseResult(arr) { - arr.forEach((item) => { + 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 c311405f..345c32a3 100644 --- a/backend/src/utils.test.ts +++ b/backend/src/utils.test.ts @@ -2,45 +2,45 @@ import { convertDelayStringToMS, convertMSToDelayString, getUrlsInString } from import test from "ava"; -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); diff --git a/backend/src/utils.ts b/backend/src/utils.ts index 71c0fc83..b78a29c7 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -130,9 +130,9 @@ 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)); + 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; @@ -278,34 +278,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. @@ -394,8 +394,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); @@ -414,7 +414,7 @@ export function isSnowflake(v: string): boolean { } export function sleep(ms: number): Promise { - return new Promise((resolve) => { + return new Promise(resolve => { setTimeout(resolve, ms); }); } @@ -462,7 +462,7 @@ export async function findRelevantAuditLogEntry( const cutoffTS = Date.now() - 1000 * 60 * 2; - const relevantEntry = entries.find((entry) => { + const relevantEntry = entries.find(entry => { return entry.targetID === userId && entry.createdAt >= cutoffTS; }); @@ -523,7 +523,7 @@ export function parseInviteCodeInput(str: string): string { export function getInviteCodesInString(str: string): string[] { const inviteCodeRegex = /(?:discord.gg|discordapp.com\/invite|discord.com\/invite)\/([a-z0-9\-]+)/gi; - return Array.from(str.matchAll(inviteCodeRegex)).map((m) => m[1]); + return Array.from(str.matchAll(inviteCodeRegex)).map(m => m[1]); } export const unicodeEmojiRegex = emojiRegex(); @@ -547,7 +547,7 @@ export function trimLines(str: string) { return str .trim() .split("\n") - .map((l) => l.trim()) + .map(l => l.trim()) .join("\n") .trim(); } @@ -555,7 +555,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"); } @@ -590,7 +590,7 @@ export function trimEmptyStartEndLines(str: string) { export function trimIndents(str: string, indentLength: number) { return str .split("\n") - .map((line) => line.slice(indentLength)) + .map(line => line.slice(indentLength)) .join("\n"); } @@ -601,7 +601,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"); } @@ -722,7 +722,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 @@ -764,14 +764,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(); @@ -781,7 +781,7 @@ export function downloadFile(attachmentUrl: string, retries = 3): Promise<{ path }); }); }) - .on("error", (httpsErr) => { + .on("error", httpsErr => { fsp.unlink(path); if (retries === 0) { @@ -806,7 +806,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(); @@ -845,14 +845,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 { @@ -1029,7 +1029,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.find((u) => u.username === usernameMatch[1] && u.discriminator === usernameMatch[2]); + const user = bot.users.find(u => u.username === usernameMatch[1] && u.discriminator === usernameMatch[2]); if (user) return user.id; } @@ -1140,7 +1140,7 @@ export async function resolveRoleId(bot: Client, guildId: string, value: string) // Role name const roleList = await bot.getRESTGuildRoles(guildId); - const role = roleList.filter((x) => x.name.toLocaleLowerCase() === value.toLocaleLowerCase()); + const role = roleList.filter(x => x.name.toLocaleLowerCase() === value.toLocaleLowerCase()); if (role[0]) { return role[0].id; } @@ -1186,7 +1186,7 @@ export function messageSummary(msg: SavedMessage) { let result = "```\n" + (msg.data.content ? disableCodeBlocks(msg.data.content) : "") + "```"; // Rich embed - const richEmbed = (msg.data.embeds || []).find((e) => (e as Embed).type === "rich"); + const richEmbed = (msg.data.embeds || []).find(e => (e as Embed).type === "rich"); if (richEmbed) result += "Embed:```" + disableCodeBlocks(JSON.stringify(richEmbed)) + "```"; // Attachments @@ -1308,7 +1308,7 @@ export function canUseEmoji(client: Client, emoji: string): boolean { return true; } else if (isSnowflake(emoji)) { for (const guild of client.guilds.values()) { - if (guild.emojis.some((e) => (e as any).id === emoji)) { + if (guild.emojis.some(e => (e as any).id === emoji)) { return true; } } diff --git a/backend/src/utils/canAssignRole.ts b/backend/src/utils/canAssignRole.ts index b431ac7d..f42778bd 100644 --- a/backend/src/utils/canAssignRole.ts +++ b/backend/src/utils/canAssignRole.ts @@ -16,7 +16,7 @@ export function canAssignRole(guild: Guild, member: Member, roleId: string) { return false; } - const memberRoles = member.roles.map((_roleId) => guild.roles.get(_roleId)!); + const memberRoles = member.roles.map(_roleId => guild.roles.get(_roleId)!); const highestRoleWithManageRoles = memberRoles.reduce((highest, role) => { if (!hasDiscordPermissions(role.permissions, Constants.Permissions.manageRoles)) return highest; if (highest == null) return role; diff --git a/backend/src/utils/crypt.test.ts b/backend/src/utils/crypt.test.ts index 3394e57d..00619645 100644 --- a/backend/src/utils/crypt.test.ts +++ b/backend/src/utils/crypt.test.ts @@ -2,7 +2,7 @@ import test from "ava"; import { encrypt, decrypt } 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/getPermissionNames.ts b/backend/src/utils/getPermissionNames.ts index 42ed5112..48e057bc 100644 --- a/backend/src/utils/getPermissionNames.ts +++ b/backend/src/utils/getPermissionNames.ts @@ -1,10 +1,10 @@ import { Constants } from "eris"; -const camelCaseToTitleCase = (str) => +const camelCaseToTitleCase = str => str .replace(/([a-z])([A-Z])/g, "$1 $2") .split(" ") - .map((w) => w[0].toUpperCase() + w.slice(1)) + .map(w => w[0].toUpperCase() + w.slice(1)) .join(" "); const permissionNumberToName: Map = new Map(); diff --git a/backend/src/utils/normalizeText.test.ts b/backend/src/utils/normalizeText.test.ts index cd5a139c..9c9c03be 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 e1edf492..05d3b1c7 100644 --- a/backend/src/utils/parseFuzzyTimezone.ts +++ b/backend/src/utils/parseFuzzyTimezone.ts @@ -1,7 +1,7 @@ import moment from "moment-timezone"; import escapeStringRegexp from "escape-string-regexp"; -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 0a931df1..df61f579 100644 --- a/backend/src/utils/tColor.ts +++ b/backend/src/utils/tColor.ts @@ -9,9 +9,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 46059e3a..9922bd96 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/validation.test.ts b/backend/src/validation.test.ts index 74c1a970..e1019a85 100644 --- a/backend/src/validation.test.ts +++ b/backend/src/validation.test.ts @@ -3,7 +3,7 @@ import * as t from "io-ts"; import * as validatorUtils from "./validatorUtils"; import test from "ava"; -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 80b3cc44..1db917c0 100644 --- a/backend/src/validatorUtils.ts +++ b/backend/src/validatorUtils.ts @@ -26,10 +26,10 @@ 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 => { return t.success(inputPatternToRegExp(s)); }), - (s) => `/${s.source}/${s.flags}`, + s => `/${s.source}/${s.flags}`, ); // From io-ts/lib/PathReporter @@ -50,7 +50,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; @@ -73,8 +73,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); @@ -92,8 +92,8 @@ export function validate(schema: t.Type, value: any): StrictValidationError pipe( validationResult, fold( - (err) => report(validationResult), - (result) => null, + err => report(validationResult), + result => null, ), ) || null ); @@ -108,12 +108,12 @@ export function decodeAndValidateStrict(schema: T, value: return pipe( validationResult, fold( - (err) => report(validationResult), - (result) => { + err => report(validationResult), + result => { // Make sure there are no extra properties 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); }