From bc1330bf332f664dc59401be4d3b6e23866f35e4 Mon Sep 17 00:00:00 2001 From: Dark <7890309+DarkView@users.noreply.github.com> Date: Tue, 27 Jul 2021 04:19:11 +0200 Subject: [PATCH 01/40] Various bugfixes and change ct.anyId return to Snowflake --- backend/src/commandTypes.ts | 12 ++++++------ .../plugins/BotControl/commands/ReloadServerCmd.ts | 2 +- .../functions/reloadChangedGuilds.ts | 3 ++- .../src/plugins/LocateUser/events/SendAlertsEvts.ts | 7 ++++--- .../plugins/LocateUser/utils/createOrReuseInvite.ts | 2 +- .../ReactionRoles/events/ButtonInteractionEvt.ts | 4 ++++ .../ReactionRoles/util/buttonCustomIdFunctions.ts | 2 +- 7 files changed, 19 insertions(+), 13 deletions(-) diff --git a/backend/src/commandTypes.ts b/backend/src/commandTypes.ts index 04ca71fa..29a69d11 100644 --- a/backend/src/commandTypes.ts +++ b/backend/src/commandTypes.ts @@ -1,4 +1,4 @@ -import { GuildChannel, GuildMember, User } from "discord.js"; +import { GuildChannel, GuildMember, Snowflake, User } from "discord.js"; import { baseCommandParameterTypeHelpers, baseTypeConverters, CommandContext, TypeConversionError } from "knub"; import { createTypeHelper } from "knub-command-manager"; import { @@ -72,16 +72,16 @@ export const commandTypes = { async anyId(value: string, context: CommandContext) { const userId = resolveUserId(context.pluginData.client, value); - if (userId) return userId; + if (userId) return userId as Snowflake; const channelIdMatch = value.match(channelMentionRegex); - if (channelIdMatch) return channelIdMatch[1]; + if (channelIdMatch) return channelIdMatch[1] as Snowflake; const roleIdMatch = value.match(roleMentionRegex); - if (roleIdMatch) return roleIdMatch[1]; + if (roleIdMatch) return roleIdMatch[1] as Snowflake; if (isValidSnowflake(value)) { - return value; + return value as Snowflake; } throw new TypeConversionError(`Could not parse ID: \`${disableInlineCode(value)}\``); @@ -112,7 +112,7 @@ export const commandTypeHelpers = { resolvedUserLoose: createTypeHelper>(commandTypes.resolvedUserLoose), resolvedMember: createTypeHelper>(commandTypes.resolvedMember), messageTarget: createTypeHelper>(commandTypes.messageTarget), - anyId: createTypeHelper>(commandTypes.anyId), + anyId: createTypeHelper>(commandTypes.anyId), regex: createTypeHelper(commandTypes.regex), timezone: createTypeHelper(commandTypes.timezone), }; diff --git a/backend/src/plugins/BotControl/commands/ReloadServerCmd.ts b/backend/src/plugins/BotControl/commands/ReloadServerCmd.ts index fb652b65..88193fba 100644 --- a/backend/src/plugins/BotControl/commands/ReloadServerCmd.ts +++ b/backend/src/plugins/BotControl/commands/ReloadServerCmd.ts @@ -11,7 +11,7 @@ export const ReloadServerCmd = botControlCmd({ }, signature: { - guildId: ct.string(), + guildId: ct.anyId(), }, async run({ pluginData, message: msg, args }) { diff --git a/backend/src/plugins/GuildConfigReloader/functions/reloadChangedGuilds.ts b/backend/src/plugins/GuildConfigReloader/functions/reloadChangedGuilds.ts index 65571b46..bc7eb6e9 100644 --- a/backend/src/plugins/GuildConfigReloader/functions/reloadChangedGuilds.ts +++ b/backend/src/plugins/GuildConfigReloader/functions/reloadChangedGuilds.ts @@ -1,3 +1,4 @@ +import { Snowflake } from "discord.js"; import { GlobalPluginData } from "knub"; import { SECONDS } from "../../../utils"; import { GuildConfigReloaderPluginType } from "../types"; @@ -11,7 +12,7 @@ export async function reloadChangedGuilds(pluginData: GlobalPluginData { const txtChannel = meta.pluginData.guild.channels.resolve(alert.channel_id as Snowflake) as TextChannel; - txtChannel.send( - `🔴 <@!${alert.requestor_id}> the user <@!${alert.user_id}> disconnected out of \`<#!${voiceChannel.id}>\``, - ); + txtChannel.send({ + content: `🔴 <@!${alert.requestor_id}> the user <@!${alert.user_id}> disconnected out of \`${voiceChannel.name}\``, + allowedMentions: { users: [alert.requestor_id as Snowflake] }, + }); }); } }, diff --git a/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts b/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts index 2853c7f0..3ac5dd1d 100644 --- a/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts +++ b/backend/src/plugins/LocateUser/utils/createOrReuseInvite.ts @@ -4,7 +4,7 @@ export async function createOrReuseInvite(vc: VoiceChannel) { const existingInvites = await vc.fetchInvites(); if (existingInvites.size !== 0) { - return existingInvites[0]; + return existingInvites.first()!; } else { return vc.createInvite(); } diff --git a/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts b/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts index 704b0b6a..7f366140 100644 --- a/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts +++ b/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts @@ -32,6 +32,10 @@ export const ButtonInteractionEvt = reactionRolesEvt({ }; if (context.stateless) { + if (context.roleOrMenu == null) { + // Not reaction from this plugin + return; + } const timeSinceCreation = moment.utc().valueOf() - idToTimestamp(int.message.id)!; if (timeSinceCreation >= BUTTON_INVALIDATION_TIME) { sendEphemeralReply( diff --git a/backend/src/plugins/ReactionRoles/util/buttonCustomIdFunctions.ts b/backend/src/plugins/ReactionRoles/util/buttonCustomIdFunctions.ts index ce1a9c3b..fa3644da 100644 --- a/backend/src/plugins/ReactionRoles/util/buttonCustomIdFunctions.ts +++ b/backend/src/plugins/ReactionRoles/util/buttonCustomIdFunctions.ts @@ -3,7 +3,7 @@ import { GuildPluginData } from "knub"; import { ReactionRolesPluginType } from "../types"; import { ButtonMenuActions } from "./buttonMenuActions"; -export const BUTTON_CONTEXT_SEPARATOR = "::"; +export const BUTTON_CONTEXT_SEPARATOR = ":rb:"; export async function getButtonAction(pluginData: GuildPluginData, roleOrMenu: string) { if (await pluginData.guild.roles.fetch(roleOrMenu as Snowflake).catch(() => false)) { From 12d2724256c9135acc0804852097e6c4ce9737f4 Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 16:08:36 +0100 Subject: [PATCH 02/40] fix: updated some properties that were renamed on the discord.js side --- backend/src/data/DefaultLogMessages.json | 4 ++-- backend/src/plugins/Logs/util/log.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/data/DefaultLogMessages.json b/backend/src/data/DefaultLogMessages.json index fccdb1ed..af22228f 100644 --- a/backend/src/data/DefaultLogMessages.json +++ b/backend/src/data/DefaultLogMessages.json @@ -26,8 +26,8 @@ "CHANNEL_DELETE": "🗑 Channel {channelMention(channel)} was deleted", "CHANNEL_UPDATE": "✏ Channel {channelMention(newChannel)} was edited. Changes:\n{differenceString}", - "THREAD_CREATE": "🖊 Thread {channelMention(thread)} was created in channel <#{thread.parentID}>", - "THREAD_DELETE": "🗑 Thread {channelMention(thread)} was deleted/archived from channel <#{thread.parentID}>", + "THREAD_CREATE": "🖊 Thread {channelMention(thread)} was created in channel <#{thread.parentId}>", + "THREAD_DELETE": "🗑 Thread {channelMention(thread)} was deleted/archived from channel <#{thread.parentId}>", "THREAD_UPDATE": "✏ Thread {channelMention(newThread)} was edited. Changes:\n{differenceString}", "ROLE_CREATE": "🖊 Role **{role.name}** (`{role.id}`) was created", diff --git a/backend/src/plugins/Logs/util/log.ts b/backend/src/plugins/Logs/util/log.ts index 0fdce60e..b8e6eed0 100644 --- a/backend/src/plugins/Logs/util/log.ts +++ b/backend/src/plugins/Logs/util/log.ts @@ -94,7 +94,7 @@ export async function log(pluginData: GuildPluginData, type: Log type === LogType.CENSOR || type === LogType.CLEAN ) { - if (data.channel.parentID && opts.excluded_categories.includes(data.channel.parentID)) { + if (data.channel.parentId && opts.excluded_categories.includes(data.channel.parentId)) { continue logChannelLoop; } } From 77b33c18584b444edbb8c7d4edc682b8d75320a0 Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 16:43:31 +0100 Subject: [PATCH 03/40] renamed ErisError to DiscordJSError, use rateLimit event instead of debug, renamed the TOKEN variable back --- backend/src/{ErisError.ts => DiscordJSError.ts} | 4 ++-- backend/src/index.ts | 17 ++++++----------- 2 files changed, 8 insertions(+), 13 deletions(-) rename backend/src/{ErisError.ts => DiscordJSError.ts} (65%) diff --git a/backend/src/ErisError.ts b/backend/src/DiscordJSError.ts similarity index 65% rename from backend/src/ErisError.ts rename to backend/src/DiscordJSError.ts index 732fa53b..26a3b8ed 100644 --- a/backend/src/ErisError.ts +++ b/backend/src/DiscordJSError.ts @@ -1,6 +1,6 @@ import util from "util"; -export class ErisError extends Error { +export class DiscordJSError extends Error { code: number | string | undefined; shardId: number; @@ -11,6 +11,6 @@ export class ErisError extends Error { } [util.inspect.custom]() { - return `[ERIS] [ERROR CODE ${this.code || "?"}] [SHARD ${this.shardId}] ${this.message}`; + return `[DISCORDJS] [ERROR CODE ${this.code ?? "?"}] [SHARD ${this.shardId}] ${this.message}`; } } diff --git a/backend/src/index.ts b/backend/src/index.ts index 163ba459..70bf4d2e 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -1,5 +1,4 @@ import { Client, Intents, TextChannel } from "discord.js"; -import fs from "fs"; import yaml from "js-yaml"; import { Knub, PluginError } from "knub"; import { PluginLoadError } from "knub/dist/plugins/PluginLoadError"; @@ -11,7 +10,7 @@ import { Configs } from "./data/Configs"; import { connect } from "./data/db"; import { GuildLogs } from "./data/GuildLogs"; import { LogType } from "./data/LogType"; -import { ErisError } from "./ErisError"; +import { DiscordJSError } from "./DiscordJSError"; import "./loadEnv"; import { logger } from "./logger"; import { baseGuildPlugins, globalPlugins, guildPlugins } from "./plugins/availablePlugins"; @@ -21,8 +20,6 @@ import { ZeppelinGlobalConfig, ZeppelinGuildConfig } from "./types"; import { startUptimeCounter } from "./uptime"; import { errorMessage, isDiscordAPIError, isDiscordHTTPError, successMessage } from "./utils"; -const fsp = fs.promises; - if (!process.env.KEY) { // tslint:disable-next-line:no-console console.error("Project root .env with KEY is required!"); @@ -81,7 +78,7 @@ function errorHandler(err) { return; } - if (err instanceof ErisError) { + if (err instanceof DiscordJSError) { if (err.code && SAFE_TO_IGNORE_ERIS_ERROR_CODES.includes(err.code)) { return; } @@ -176,14 +173,12 @@ connect().then(async () => { }); client.setMaxListeners(200); - client.on("debug", message => { - if (message.includes(" 429 ")) { - logger.info(`[429] ${message}`); - } + client.on("rateLimit", rateLimitData => { + logger.info(`[429] ${rateLimitData}`); }); client.on("error", err => { - errorHandler(new ErisError(err.message, (err as any).code, 0)); + errorHandler(new DiscordJSError(err.message, (err as any).code, 0)); }); const allowedGuilds = new AllowedGuilds(); @@ -266,5 +261,5 @@ connect().then(async () => { bot.initialize(); logger.info("Bot Initialized"); logger.info("Logging in..."); - await client.login(process.env.token); + await client.login(process.env.TOKEN); }); From 88f53b4af9a39bed956ef0895368dda6b951631e Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 22:29:52 +0100 Subject: [PATCH 04/40] removed unnecessary non-null operator --- backend/src/plugins/Automod/events/runAutomodOnMessage.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/plugins/Automod/events/runAutomodOnMessage.ts b/backend/src/plugins/Automod/events/runAutomodOnMessage.ts index 34d14a74..7181b257 100644 --- a/backend/src/plugins/Automod/events/runAutomodOnMessage.ts +++ b/backend/src/plugins/Automod/events/runAutomodOnMessage.ts @@ -12,7 +12,7 @@ export function runAutomodOnMessage( message: SavedMessage, isEdit: boolean, ) { - const user = pluginData.client.users.cache!.get(message.user_id as Snowflake); + const user = pluginData.client.users.cache.get(message.user_id as Snowflake); const member = pluginData.guild.members.cache.get(message.user_id as Snowflake); const context: AutomodContext = { From 4047b7f921e4a9d244daf227c5ca20bbdc8292bf Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 23:15:40 +0100 Subject: [PATCH 05/40] removed unnecessary assertion --- .../src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts b/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts index 84e26317..c1b3a871 100644 --- a/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts +++ b/backend/src/plugins/ChannelArchiver/commands/ArchiveChannelCmd.ts @@ -60,10 +60,10 @@ export const ArchiveChannelCmd = channelArchiverCmd({ while (archivedMessages < maxMessagesToArchive) { const messagesToFetch = Math.min(MAX_MESSAGES_PER_FETCH, maxMessagesToArchive - archivedMessages); - const messages = (await args.channel.messages.fetch({ + const messages = await args.channel.messages.fetch({ limit: messagesToFetch, before: previousId as Snowflake, - })) as Collection; + }); if (messages.size === 0) break; for (const message of messages.values()) { From 60caa3153b7d10f4f0f5aea050c1119458b723e4 Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 23:27:07 +0100 Subject: [PATCH 06/40] simplified ternary --- backend/src/plugins/Logs/events/LogsGuildBanEvts.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts b/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts index 7e8d8eb9..580ce85e 100644 --- a/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts +++ b/backend/src/plugins/Logs/events/LogsGuildBanEvts.ts @@ -16,7 +16,7 @@ export const LogsGuildBanAddEvt = logsEvt({ GuildAuditLogs.Actions.MEMBER_BAN_ADD as number, user.id, ); - const mod = relevantAuditLogEntry ? relevantAuditLogEntry.executor : null; + const mod = relevantAuditLogEntry?.executor ?? null; pluginData.state.guildLogs.log( LogType.MEMBER_BAN, @@ -41,7 +41,7 @@ export const LogsGuildBanRemoveEvt = logsEvt({ GuildAuditLogs.Actions.MEMBER_BAN_REMOVE as number, user.id, ); - const mod = relevantAuditLogEntry ? relevantAuditLogEntry.executor : null; + const mod = relevantAuditLogEntry?.executor ?? null; pluginData.state.guildLogs.log( LogType.MEMBER_UNBAN, From b4ba1daa762256e879f86aefa827e67e61f03df9 Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 23:30:52 +0100 Subject: [PATCH 07/40] simplify --- backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts | 10 +++++----- .../ModActions/events/CreateBanCaseOnManualBanEvt.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts index 5b29e3f0..1f37a360 100644 --- a/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts +++ b/backend/src/plugins/Logs/events/LogsUserUpdateEvts.ts @@ -52,7 +52,7 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ GuildAuditLogs.Actions.MEMBER_ROLE_UPDATE as number, member.id, ); - const mod = relevantAuditLogEntry ? relevantAuditLogEntry.executor : null; + const mod = relevantAuditLogEntry?.executor ?? null; if (addedRoles.length && removedRoles.length) { // Roles added *and* removed @@ -61,11 +61,11 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ { member: logMember, addedRoles: addedRoles - .map(roleId => pluginData.guild.roles.cache.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }) .map(r => r.name) .join(", "), removedRoles: removedRoles - .map(roleId => pluginData.guild.roles.cache.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }) .map(r => r.name) .join(", "), mod: mod ? userToConfigAccessibleUser(mod) : {}, @@ -79,7 +79,7 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ { member: logMember, roles: addedRoles - .map(roleId => pluginData.guild.roles.cache.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }) .map(r => r.name) .join(", "), mod: mod ? userToConfigAccessibleUser(mod) : {}, @@ -93,7 +93,7 @@ export const LogsGuildMemberUpdateEvt = logsEvt({ { member: logMember, roles: removedRoles - .map(roleId => pluginData.guild.roles.cache.get(roleId) || { id: roleId, name: `Unknown (${roleId})` }) + .map(roleId => pluginData.guild.roles.cache.get(roleId) ?? { id: roleId, name: `Unknown (${roleId})` }) .map(r => r.name) .join(", "), mod: mod ? userToConfigAccessibleUser(mod) : {}, diff --git a/backend/src/plugins/ModActions/events/CreateBanCaseOnManualBanEvt.ts b/backend/src/plugins/ModActions/events/CreateBanCaseOnManualBanEvt.ts index 57790912..875f8cd7 100644 --- a/backend/src/plugins/ModActions/events/CreateBanCaseOnManualBanEvt.ts +++ b/backend/src/plugins/ModActions/events/CreateBanCaseOnManualBanEvt.ts @@ -44,7 +44,7 @@ export const CreateBanCaseOnManualBanEvt = modActionsEvt({ const config = mod instanceof UnknownUser ? pluginData.config.get() : await pluginData.config.getForUser(mod); if (config.create_cases_for_manual_actions) { - reason = relevantAuditLogEntry.reason || ""; + reason = relevantAuditLogEntry.reason ?? ""; createdCase = await casesPlugin.createCase({ userId: user.id, modId, From f9e134300301f670b2a5bad3d468333130bfbe4a Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 23:40:20 +0100 Subject: [PATCH 08/40] use User#displayAvatarURL and dont encode reason --- backend/src/plugins/ModActions/commands/CasesModCmd.ts | 2 +- backend/src/plugins/ModActions/commands/CasesUserCmd.ts | 2 +- backend/src/plugins/ModActions/commands/ForcebanCmd.ts | 2 +- backend/src/plugins/ModActions/commands/UnbanCmd.ts | 2 +- backend/src/plugins/ModActions/functions/banUserId.ts | 2 +- backend/src/plugins/ModActions/functions/kickMember.ts | 2 +- .../src/plugins/ModActions/functions/outdatedTempbansLoop.ts | 5 +---- backend/src/plugins/Utility/commands/AvatarCmd.ts | 2 +- backend/src/plugins/Utility/functions/getUserInfoEmbed.ts | 2 +- 9 files changed, 9 insertions(+), 12 deletions(-) diff --git a/backend/src/plugins/ModActions/commands/CasesModCmd.ts b/backend/src/plugins/ModActions/commands/CasesModCmd.ts index 6b06c56c..9569e859 100644 --- a/backend/src/plugins/ModActions/commands/CasesModCmd.ts +++ b/backend/src/plugins/ModActions/commands/CasesModCmd.ts @@ -57,7 +57,7 @@ export const CasesModCmd = modActionsCmd({ const embed: MessageEmbedOptions = { author: { name: title, - iconURL: mod instanceof User ? mod.avatarURL() || mod.defaultAvatarURL : undefined, + iconURL: mod instanceof User ? mod.displayAvatarURL() : undefined, }, fields: [ ...getChunkedEmbedFields(emptyEmbedValue, lines.join("\n")), diff --git a/backend/src/plugins/ModActions/commands/CasesUserCmd.ts b/backend/src/plugins/ModActions/commands/CasesUserCmd.ts index ac1d2eb5..f551369f 100644 --- a/backend/src/plugins/ModActions/commands/CasesUserCmd.ts +++ b/backend/src/plugins/ModActions/commands/CasesUserCmd.ts @@ -119,7 +119,7 @@ export const CasesUserCmd = modActionsCmd({ lineChunks.length === 1 ? `Cases for ${userName} (${lines.length} total)` : `Cases ${chunkStart}–${chunkEnd} of ${lines.length} for ${userName}`, - icon_url: user instanceof User ? user.avatarURL() || user.defaultAvatarURL : undefined, + icon_url: user instanceof User ? user.displayAvatarURL() : undefined, }, fields: [ ...getChunkedEmbedFields(emptyEmbedValue, linesInChunk.join("\n")), diff --git a/backend/src/plugins/ModActions/commands/ForcebanCmd.ts b/backend/src/plugins/ModActions/commands/ForcebanCmd.ts index b7ff84da..67df9ece 100644 --- a/backend/src/plugins/ModActions/commands/ForcebanCmd.ts +++ b/backend/src/plugins/ModActions/commands/ForcebanCmd.ts @@ -70,7 +70,7 @@ export const ForcebanCmd = modActionsCmd({ // FIXME: Use banUserId()? await pluginData.guild.bans.create(user.id as Snowflake, { days: 1, - reason: reason != null ? encodeURIComponent(reason) : undefined, + reason: reason ?? undefined, }); } catch { sendErrorMessage(pluginData, msg.channel, "Failed to forceban member"); diff --git a/backend/src/plugins/ModActions/commands/UnbanCmd.ts b/backend/src/plugins/ModActions/commands/UnbanCmd.ts index e425ddee..38bb49f0 100644 --- a/backend/src/plugins/ModActions/commands/UnbanCmd.ts +++ b/backend/src/plugins/ModActions/commands/UnbanCmd.ts @@ -51,7 +51,7 @@ export const UnbanCmd = modActionsCmd({ try { ignoreEvent(pluginData, IgnoredEventType.Unban, user.id); - await pluginData.guild.bans.remove(user.id as Snowflake, reason != null ? encodeURIComponent(reason) : undefined); + await pluginData.guild.bans.remove(user.id as Snowflake, reason ?? undefined); } catch { sendErrorMessage(pluginData, msg.channel, "Failed to unban member; are you sure they're banned?"); return; diff --git a/backend/src/plugins/ModActions/functions/banUserId.ts b/backend/src/plugins/ModActions/functions/banUserId.ts index 25613f7d..3462842d 100644 --- a/backend/src/plugins/ModActions/functions/banUserId.ts +++ b/backend/src/plugins/ModActions/functions/banUserId.ts @@ -80,7 +80,7 @@ export async function banUserId( const deleteMessageDays = Math.min(30, Math.max(0, banOptions.deleteMessageDays ?? 1)); await pluginData.guild.bans.create(userId as Snowflake, { days: deleteMessageDays, - reason: reason != null ? encodeURIComponent(reason) : undefined, + reason: reason ?? undefined, }); } catch (e) { let errorMessage; diff --git a/backend/src/plugins/ModActions/functions/kickMember.ts b/backend/src/plugins/ModActions/functions/kickMember.ts index 5aa3d853..3ffcab6b 100644 --- a/backend/src/plugins/ModActions/functions/kickMember.ts +++ b/backend/src/plugins/ModActions/functions/kickMember.ts @@ -49,7 +49,7 @@ export async function kickMember( pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_KICK, member.id); ignoreEvent(pluginData, IgnoredEventType.Kick, member.id); try { - await member.kick(reason != null ? encodeURIComponent(reason) : undefined); + await member.kick(reason ?? undefined); } catch (e) { return { status: "failed", diff --git a/backend/src/plugins/ModActions/functions/outdatedTempbansLoop.ts b/backend/src/plugins/ModActions/functions/outdatedTempbansLoop.ts index fdf957ea..935e16a4 100644 --- a/backend/src/plugins/ModActions/functions/outdatedTempbansLoop.ts +++ b/backend/src/plugins/ModActions/functions/outdatedTempbansLoop.ts @@ -32,10 +32,7 @@ export async function outdatedTempbansLoop(pluginData: GuildPluginData Date: Wed, 28 Jul 2021 23:50:25 +0100 Subject: [PATCH 09/40] removed unnecessary encodeURIComponent on reasons --- backend/src/plugins/ModActions/commands/MassBanCmd.ts | 2 +- backend/src/plugins/ModActions/commands/MassUnbanCmd.ts | 5 +---- .../src/plugins/ModActions/functions/actualKickMemberCmd.ts | 4 ++-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/backend/src/plugins/ModActions/commands/MassBanCmd.ts b/backend/src/plugins/ModActions/commands/MassBanCmd.ts index 899d8ca3..7e61bb48 100644 --- a/backend/src/plugins/ModActions/commands/MassBanCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassBanCmd.ts @@ -95,7 +95,7 @@ export const MassbanCmd = modActionsCmd({ await pluginData.guild.bans.create(userId as Snowflake, { days: deleteDays, - reason: banReason != null ? encodeURIComponent(banReason) : undefined, + reason: banReason ?? undefined, }); await casesPlugin.createCase({ diff --git a/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts b/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts index 059f85a7..1141c26c 100644 --- a/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts +++ b/backend/src/plugins/ModActions/commands/MassUnbanCmd.ts @@ -60,10 +60,7 @@ export const MassunbanCmd = modActionsCmd({ } try { - await pluginData.guild.bans.remove( - userId as Snowflake, - unbanReason != null ? encodeURIComponent(unbanReason) : undefined, - ); + await pluginData.guild.bans.remove(userId as Snowflake, unbanReason ?? undefined); await casesPlugin.createCase({ userId, diff --git a/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts b/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts index a957696c..0ed86ded 100644 --- a/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts +++ b/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts @@ -82,7 +82,7 @@ export async function actualKickMemberCmd( ignoreEvent(pluginData, IgnoredEventType.Ban, memberToKick.id); try { - await memberToKick.ban({ days: 1, reason: encodeURIComponent("kick -clean") }); + await memberToKick.ban({ days: 1, reason: "kick -clean" }); } catch { sendErrorMessage(pluginData, msg.channel, "Failed to ban the user to clean messages (-clean)"); } @@ -91,7 +91,7 @@ export async function actualKickMemberCmd( ignoreEvent(pluginData, IgnoredEventType.Unban, memberToKick.id); try { - await pluginData.guild.bans.remove(memberToKick.id, encodeURIComponent("kick -clean")); + await pluginData.guild.bans.remove(memberToKick.id, "kick -clean"); } catch { sendErrorMessage(pluginData, msg.channel, "Failed to unban the user after banning them (-clean)"); } From d9d1793e5907cba16e2153ebec0d515dce16f0a2 Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 23:54:34 +0100 Subject: [PATCH 10/40] removed unnecessary type annotation --- backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts b/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts index 77fc0f85..ad5b9666 100644 --- a/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/ClearBannedMutesCmd.ts @@ -12,7 +12,7 @@ export const ClearBannedMutesCmd = mutesCmd({ const activeMutes = await pluginData.state.mutes.getActiveMutes(); - const bans: Array<{ reason: string; user: User }> = (await pluginData.guild.bans.fetch({ cache: true })) as any; + const bans = await pluginData.guild.bans.fetch({ cache: true }); const bannedIds = bans.map(b => b.user.id); await msg.channel.send(`Found ${activeMutes.length} mutes and ${bannedIds.length} bans, cross-referencing...`); From 9ddfc48bb2fb98d5586fdef3bb777aa0612267d6 Mon Sep 17 00:00:00 2001 From: almeidx Date: Wed, 28 Jul 2021 23:57:29 +0100 Subject: [PATCH 11/40] simplify --- backend/src/plugins/Mutes/commands/MutesCmd.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/backend/src/plugins/Mutes/commands/MutesCmd.ts b/backend/src/plugins/Mutes/commands/MutesCmd.ts index 74e2dc84..27b33523 100644 --- a/backend/src/plugins/Mutes/commands/MutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/MutesCmd.ts @@ -225,14 +225,11 @@ export const MutesCmd = mutesCmd({ interaction.reply({ content: `You are not permitted to use these buttons.`, ephemeral: true }); } else { collector.resetTimer(); + await interaction.deferUpdate(); if (interaction.customId === `previousButton:${idMod}` && currentPage > 1) { - await interaction.deferUpdate(); await drawListPage(currentPage - 1); } else if (interaction.customId === `nextButton:${idMod}` && currentPage < totalPages) { - await interaction.deferUpdate(); await drawListPage(currentPage + 1); - } else { - await interaction.deferUpdate(); } } }); From 3886d2d1dd33b09f19f46cf3f86cc740505333da Mon Sep 17 00:00:00 2001 From: Dark <7890309+DarkView@users.noreply.github.com> Date: Thu, 29 Jul 2021 01:02:29 +0200 Subject: [PATCH 12/40] Include Sticker and Emoji events in Logs --- backend/src/data/DefaultLogMessages.json | 8 ++ backend/src/data/LogType.ts | 8 ++ backend/src/plugins/Logs/LogsPlugin.ts | 14 ++++ .../Logs/events/LogsStickerEmojiModifyEvts.ts | 82 +++++++++++++++++++ backend/src/utils.ts | 2 +- backend/src/utils/configAccessibleObjects.ts | 50 +++++++++++ presetup-configurator/src/LogChannels.tsx | 6 ++ 7 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts diff --git a/backend/src/data/DefaultLogMessages.json b/backend/src/data/DefaultLogMessages.json index af22228f..c666ff43 100644 --- a/backend/src/data/DefaultLogMessages.json +++ b/backend/src/data/DefaultLogMessages.json @@ -50,6 +50,14 @@ "STAGE_INSTANCE_DELETE": "📣 Stage Instance `{stageInstance.topic}` was deleted in Stage Channel <#{stageChannel.id}>", "STAGE_INSTANCE_UPDATE": "📣 Stage Instance `{newStageInstance.topic}` was edited in Stage Channel <#{stageChannel.id}>. Changes:\n{differenceString}", + "EMOJI_CREATE": "<{emoji.identifier}> Emoji `{emoji.name} ({emoji.id})` was created", + "EMOJI_DELETE": "👋 Emoji `{emoji.name} ({emoji.id})` was deleted", + "EMOJI_UPDATE": "<{newEmoji.identifier}> Emoji `{newEmoji.name} ({newEmoji.id})` was updated. Changes:\n{differenceString}", + + "STICKER_CREATE": "🖼️ Sticker `{sticker.name} ({sticker.id})` was created. Description: `{sticker.description}` Format: {emoji.format}", + "STICKER_DELETE": "🖼️ Sticker `{sticker.name} ({sticker.id})` was deleted.", + "STICKER_UPDATE": "🖼️ Sticker `{newSticker.name} ({sticker.id})` was updated. Changes:\n{differenceString}", + "COMMAND": "🤖 {userMention(member)} used command in {channelMention(channel)}:\n`{command}`", "MESSAGE_SPAM_DETECTED": "🛑 {userMention(member)} spam detected in {channelMention(channel)}: {description} (more than {limit} in {interval}s)\n{archiveUrl}", diff --git a/backend/src/data/LogType.ts b/backend/src/data/LogType.ts index eb6e66e5..90c81173 100644 --- a/backend/src/data/LogType.ts +++ b/backend/src/data/LogType.ts @@ -41,6 +41,14 @@ export enum LogType { STAGE_INSTANCE_DELETE, STAGE_INSTANCE_UPDATE, + EMOJI_CREATE, + EMOJI_DELETE, + EMOJI_UPDATE, + + STICKER_CREATE, + STICKER_DELETE, + STICKER_UPDATE, + COMMAND, MESSAGE_SPAM_DETECTED, diff --git a/backend/src/plugins/Logs/LogsPlugin.ts b/backend/src/plugins/Logs/LogsPlugin.ts index 64c62444..3f65e9bc 100644 --- a/backend/src/plugins/Logs/LogsPlugin.ts +++ b/backend/src/plugins/Logs/LogsPlugin.ts @@ -20,6 +20,14 @@ import { LogsStageInstanceDeleteEvt, LogsStageInstanceUpdateEvt, } from "./events/LogsStageInstanceModifyEvts"; +import { + LogsEmojiCreateEvt, + LogsEmojiDeleteEvt, + LogsEmojiUpdateEvt, + LogsStickerCreateEvt, + LogsStickerDeleteEvt, + LogsStickerUpdateEvt, +} from "./events/LogsStickerEmojiModifyEvts"; import { LogsThreadCreateEvt, LogsThreadDeleteEvt, LogsThreadUpdateEvt } from "./events/LogsThreadModifyEvts"; import { LogsGuildMemberUpdateEvt } from "./events/LogsUserUpdateEvts"; import { LogsVoiceStateUpdateEvt } from "./events/LogsVoiceChannelEvts"; @@ -81,6 +89,12 @@ export const LogsPlugin = zeppelinGuildPlugin()({ LogsThreadCreateEvt, LogsThreadDeleteEvt, LogsThreadUpdateEvt, + LogsEmojiCreateEvt, + LogsEmojiDeleteEvt, + LogsEmojiUpdateEvt, + LogsStickerCreateEvt, + LogsStickerDeleteEvt, + LogsStickerUpdateEvt, ], public: { diff --git a/backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts b/backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts new file mode 100644 index 00000000..3535174c --- /dev/null +++ b/backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts @@ -0,0 +1,82 @@ +import { LogType } from "../../../data/LogType"; +import { differenceToString, getScalarDifference } from "../../../utils"; +import { + channelToConfigAccessibleChannel, + emojiToConfigAccessibleEmoji, + stickerToConfigAccessibleSticker, +} from "../../../utils/configAccessibleObjects"; +import { logsEvt } from "../types"; + +export const LogsEmojiCreateEvt = logsEvt({ + event: "emojiCreate", + + async listener(meta) { + meta.pluginData.state.guildLogs.log(LogType.EMOJI_CREATE, { + emoji: emojiToConfigAccessibleEmoji(meta.args.emoji), + }); + }, +}); + +export const LogsEmojiDeleteEvt = logsEvt({ + event: "emojiDelete", + + async listener(meta) { + meta.pluginData.state.guildLogs.log(LogType.EMOJI_DELETE, { + emoji: emojiToConfigAccessibleEmoji(meta.args.emoji), + }); + }, +}); + +export const LogsEmojiUpdateEvt = logsEvt({ + event: "emojiUpdate", + + async listener(meta) { + const diff = getScalarDifference(meta.args.oldEmoji, meta.args.newEmoji); + const differenceString = differenceToString(diff); + + meta.pluginData.state.guildLogs.log(LogType.EMOJI_UPDATE, { + oldEmoji: emojiToConfigAccessibleEmoji(meta.args.oldEmoji), + newEmoji: emojiToConfigAccessibleEmoji(meta.args.newEmoji), + differenceString, + }); + }, +}); + +export const LogsStickerCreateEvt = logsEvt({ + event: "stickerCreate", + + async listener(meta) { + meta.pluginData.state.guildLogs.log(LogType.STICKER_CREATE, { + thread: stickerToConfigAccessibleSticker(meta.args.sticker), + }); + }, +}); + +export const LogsStickerDeleteEvt = logsEvt({ + event: "stickerDelete", + + async listener(meta) { + meta.pluginData.state.guildLogs.log(LogType.STICKER_DELETE, { + thread: stickerToConfigAccessibleSticker(meta.args.sticker), + }); + }, +}); + +export const LogsStickerUpdateEvt = logsEvt({ + event: "stickerUpdate", + + async listener(meta) { + const diff = getScalarDifference(meta.args.oldSticker, meta.args.newSticker); + const differenceString = differenceToString(diff); + + meta.pluginData.state.guildLogs.log( + LogType.STICKER_UPDATE, + { + oldThread: stickerToConfigAccessibleSticker(meta.args.oldSticker), + newThread: stickerToConfigAccessibleSticker(meta.args.newSticker), + differenceString, + }, + meta.args.newSticker.id, + ); + }, +}); diff --git a/backend/src/utils.ts b/backend/src/utils.ts index c4464f97..a1e10430 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -212,7 +212,7 @@ export function differenceToString(diff: Map): st let toReturn = ""; diff = prettyDifference(diff); for (const [key, difference] of diff) { - toReturn += `${key[0].toUpperCase() + key.slice(1)}: \`${difference.was}\` ➜ \`${difference.is}\`\n`; + toReturn += `**${key[0].toUpperCase() + key.slice(1)}**: \`${difference.was}\` ➜ \`${difference.is}\`\n`; } return toReturn; } diff --git a/backend/src/utils/configAccessibleObjects.ts b/backend/src/utils/configAccessibleObjects.ts index 1c281ed6..e28c61a5 100644 --- a/backend/src/utils/configAccessibleObjects.ts +++ b/backend/src/utils/configAccessibleObjects.ts @@ -1,10 +1,12 @@ import { + Emoji, GuildChannel, GuildMember, PartialGuildMember, Role, Snowflake, StageInstance, + Sticker, ThreadChannel, User, } from "discord.js"; @@ -127,3 +129,51 @@ export function stageToConfigAccessibleStage(stage: StageInstance): IConfigAcces return toReturn; } + +export interface IConfigAccessibleEmoji { + id: Snowflake; + name: string; + createdAt?: number; + animated: boolean; + identifier: string; +} + +export function emojiToConfigAccessibleEmoji(emoji: Emoji): IConfigAccessibleEmoji { + const toReturn: IConfigAccessibleEmoji = { + id: emoji.id!, + name: emoji.name!, + createdAt: emoji.createdTimestamp ?? undefined, + animated: emoji.animated ?? false, + identifier: emoji.identifier, + }; + + return toReturn; +} + +export interface IConfigAccessibleSticker { + id: Snowflake; + guildId?: Snowflake; + packId?: Snowflake; + name: string; + description: string; + tags: string; + format: string; + animated: boolean; + url: string; +} + +export function stickerToConfigAccessibleSticker(sticker: Sticker): IConfigAccessibleSticker { + const toReturn: IConfigAccessibleSticker = { + id: sticker.id, + guildId: sticker.guildId ?? undefined, + packId: sticker.packId ?? undefined, + name: sticker.name, + description: sticker.description ?? "", + tags: sticker.tags?.join(", ") ?? "", + format: sticker.format, + animated: sticker.format === "PNG" ? false : true, + url: sticker.url, + }; + + return toReturn; +} diff --git a/presetup-configurator/src/LogChannels.tsx b/presetup-configurator/src/LogChannels.tsx index 928d4c99..85300d37 100644 --- a/presetup-configurator/src/LogChannels.tsx +++ b/presetup-configurator/src/LogChannels.tsx @@ -37,6 +37,12 @@ const LOG_TYPES = { "STAGE_INSTANCE_CREATE": "Stage created", "STAGE_INSTANCE_DELETE": "Stage deleted", "STAGE_INSTANCE_UPDATE": "Stage updated", + "EMOJI_CREATE": "Emoji created", + "EMOJI_DELETE": "Emoji deleted", + "EMOJI_UPDATE": "Emoji updated", + "STICKER_CREATE": "Sticker created", + "STICKER_DELETE": "Sticker deleted", + "STICKER_UPDATE": "Sticker updated", "COMMAND": "Command used", "MESSAGE_SPAM_DETECTED": "Message spam detected", "CENSOR": "Message censored", From 3d29963b871eb4081bf8202d45b8395ff253cda1 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 00:03:25 +0100 Subject: [PATCH 13/40] perf --- backend/src/plugins/Mutes/functions/muteUser.ts | 2 +- backend/src/plugins/NameHistory/events/UpdateNameEvts.ts | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/backend/src/plugins/Mutes/functions/muteUser.ts b/backend/src/plugins/Mutes/functions/muteUser.ts index 78d0e4bd..cbfa3870 100644 --- a/backend/src/plugins/Mutes/functions/muteUser.ts +++ b/backend/src/plugins/Mutes/functions/muteUser.ts @@ -90,7 +90,7 @@ export async function muteUser( try { await member.roles.add(muteRole as Snowflake); } catch (e) { - const actualMuteRole = pluginData.guild.roles.cache.find(x => x.id === muteRole); + const actualMuteRole = pluginData.guild.roles.cache.get(muteRole as Snowflake); if (!actualMuteRole) { lock.unlock(); logs.log(LogType.BOT_ALERT, { diff --git a/backend/src/plugins/NameHistory/events/UpdateNameEvts.ts b/backend/src/plugins/NameHistory/events/UpdateNameEvts.ts index c41e2cc9..0d644663 100644 --- a/backend/src/plugins/NameHistory/events/UpdateNameEvts.ts +++ b/backend/src/plugins/NameHistory/events/UpdateNameEvts.ts @@ -6,10 +6,7 @@ export const ChannelJoinEvt = nameHistoryEvt({ async listener(meta) { meta.pluginData.state.updateQueue.add(() => - updateNickname( - meta.pluginData, - meta.args.newState.member ? meta.args.newState.member : meta.args.oldState.member!, - ), + updateNickname(meta.pluginData, meta.args.newState.member ?? meta.args.oldState.member!), ); }, }); From e5985e8776b5b6e155ca8bd1d2b71cd1b8a2907a Mon Sep 17 00:00:00 2001 From: Dark <7890309+DarkView@users.noreply.github.com> Date: Thu, 29 Jul 2021 01:14:21 +0200 Subject: [PATCH 14/40] Allow =0 condition in counter triggers --- backend/src/data/entities/CounterTrigger.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/data/entities/CounterTrigger.ts b/backend/src/data/entities/CounterTrigger.ts index 71b6bf52..91cbf995 100644 --- a/backend/src/data/entities/CounterTrigger.ts +++ b/backend/src/data/entities/CounterTrigger.ts @@ -17,7 +17,7 @@ export function getReverseCounterComparisonOp(op: TriggerComparisonOp): TriggerC return REVERSE_OPS[op]; } -const comparisonStringRegex = new RegExp(`^(${TRIGGER_COMPARISON_OPS.join("|")})([1-9]\\d*)$`); +const comparisonStringRegex = new RegExp(`^(${TRIGGER_COMPARISON_OPS.join("|")})(\\d*)$`); /** * @return Parsed comparison op and value, or null if the comparison string was invalid From 74a676913ee781df2ef0ce856aa12987dd835832 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 00:37:19 +0100 Subject: [PATCH 15/40] user.tag --- backend/src/plugins/Automod/triggers/roleAdded.ts | 2 +- .../src/plugins/Automod/triggers/roleRemoved.ts | 2 +- .../BotControl/commands/AddDashboardUserCmd.ts | 4 +--- .../BotControl/commands/ListDashboardPermsCmd.ts | 6 ++---- .../BotControl/commands/ListDashboardUsersCmd.ts | 4 +--- .../BotControl/commands/RemoveDashboardUserCmd.ts | 4 +--- .../src/plugins/BotControl/commands/ServersCmd.ts | 2 +- backend/src/plugins/Cases/functions/createCase.ts | 6 +++--- .../src/plugins/Cases/functions/createCaseNote.ts | 2 +- .../src/plugins/ModActions/commands/AddCaseCmd.ts | 6 +----- backend/src/plugins/ModActions/commands/BanCmd.ts | 2 +- .../src/plugins/ModActions/commands/CasesModCmd.ts | 2 +- .../plugins/ModActions/commands/CasesUserCmd.ts | 5 +---- .../plugins/ModActions/commands/DeleteCaseCmd.ts | 2 +- backend/src/plugins/ModActions/commands/NoteCmd.ts | 2 +- backend/src/plugins/ModActions/commands/WarnCmd.ts | 2 +- .../ModActions/events/PostAlertOnMemberJoinEvt.ts | 2 +- .../ModActions/functions/actualKickMemberCmd.ts | 2 +- .../ModActions/functions/actualMuteUserCmd.ts | 8 ++++---- .../ModActions/functions/actualUnmuteUserCmd.ts | 4 ++-- backend/src/plugins/Mutes/commands/MutesCmd.ts | 4 ++-- .../src/plugins/NameHistory/commands/NamesCmd.ts | 2 +- backend/src/plugins/Post/util/actualPostCmd.ts | 2 +- .../util/addMemberPendingRoleChange.ts | 4 +--- .../plugins/Slowmode/commands/SlowmodeClearCmd.ts | 10 +++------- .../util/createStarboardEmbedFromMessage.ts | 2 +- .../src/plugins/UsernameSaver/updateUsername.ts | 2 +- backend/src/plugins/Utility/commands/AvatarCmd.ts | 2 +- backend/src/plugins/Utility/commands/LevelCmd.ts | 4 +--- .../plugins/Utility/commands/VcdisconnectCmd.ts | 6 +----- backend/src/plugins/Utility/commands/VcmoveCmd.ts | 14 +++----------- .../Utility/functions/getInviteInfoEmbed.ts | 4 ++-- .../Utility/functions/getMessageInfoEmbed.ts | 2 +- .../Utility/functions/getServerInfoEmbed.ts | 2 +- .../plugins/Utility/functions/getUserInfoEmbed.ts | 4 ++-- backend/src/plugins/Utility/search.ts | 8 ++++---- backend/src/utils.ts | 9 +++++---- backend/src/utils/configAccessibleObjects.ts | 2 +- 38 files changed, 59 insertions(+), 93 deletions(-) diff --git a/backend/src/plugins/Automod/triggers/roleAdded.ts b/backend/src/plugins/Automod/triggers/roleAdded.ts index d3fd0cf9..387f4d9b 100644 --- a/backend/src/plugins/Automod/triggers/roleAdded.ts +++ b/backend/src/plugins/Automod/triggers/roleAdded.ts @@ -37,7 +37,7 @@ export const RoleAddedTrigger = automodTrigger()({ const role = pluginData.guild.roles.cache.get(matchResult.extra.matchedRoleId as Snowflake); const roleName = role?.name || "Unknown"; const member = contexts[0].member!; - const memberName = `**${member.user.username}#${member.user.discriminator}** (\`${member.id}\`)`; + const memberName = `**${member.user.tag}** (\`${member.id}\`)`; return `Role ${roleName} (\`${matchResult.extra.matchedRoleId}\`) was added to ${memberName}`; }, }); diff --git a/backend/src/plugins/Automod/triggers/roleRemoved.ts b/backend/src/plugins/Automod/triggers/roleRemoved.ts index 45360086..46b68376 100644 --- a/backend/src/plugins/Automod/triggers/roleRemoved.ts +++ b/backend/src/plugins/Automod/triggers/roleRemoved.ts @@ -37,7 +37,7 @@ export const RoleRemovedTrigger = automodTrigger()({ const role = pluginData.guild.roles.cache.get(matchResult.extra.matchedRoleId as Snowflake); const roleName = role?.name || "Unknown"; const member = contexts[0].member!; - const memberName = `**${member.user.username}#${member.user.discriminator}** (\`${member.id}\`)`; + const memberName = `**${member.user.tag}** (\`${member.id}\`)`; return `Role ${roleName} (\`${matchResult.extra.matchedRoleId}\`) was removed from ${memberName}`; }, }); diff --git a/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts b/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts index 156606da..84cce432 100644 --- a/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts +++ b/backend/src/plugins/BotControl/commands/AddDashboardUserCmd.ts @@ -35,9 +35,7 @@ export const AddDashboardUserCmd = botControlCmd({ await pluginData.state.apiPermissionAssignments.addUser(args.guildId, user.id, [ApiPermissions.EditConfig]); } - const userNameList = args.users.map( - user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, - ); + const userNameList = args.users.map(user => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); sendSuccessMessage( pluginData, msg.channel as TextChannel, diff --git a/backend/src/plugins/BotControl/commands/ListDashboardPermsCmd.ts b/backend/src/plugins/BotControl/commands/ListDashboardPermsCmd.ts index d9310906..4a8a609c 100644 --- a/backend/src/plugins/BotControl/commands/ListDashboardPermsCmd.ts +++ b/backend/src/plugins/BotControl/commands/ListDashboardPermsCmd.ts @@ -46,7 +46,7 @@ export const ListDashboardPermsCmd = botControlCmd({ // If we have user, always display which guilds they have permissions in (or only specified guild permissions) if (args.user) { - const userInfo = `**${args.user.username}#${args.user.discriminator}** (\`${args.user.id}\`)`; + const userInfo = `**${args.user.tag}** (\`${args.user.id}\`)`; for (const assignment of existingUserAssignment!) { if (guild != null && assignment.guild_id !== args.guildId) continue; @@ -82,9 +82,7 @@ export const ListDashboardPermsCmd = botControlCmd({ finalMessage += `The server ${guildInfo} has the following assigned permissions:\n`; // Double \n for consistency with AddDashboardUserCmd for (const assignment of existingGuildAssignment) { const user = await resolveUser(pluginData.client, assignment.target_id); - finalMessage += `\n**${user.username}#${user.discriminator}**, \`${ - assignment.target_id - }\`: ${assignment.permissions.join(", ")}`; + finalMessage += `\n**${user.tag}**, \`${assignment.target_id}\`: ${assignment.permissions.join(", ")}`; } } diff --git a/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts b/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts index 81e58fb7..52c3083f 100644 --- a/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts +++ b/backend/src/plugins/BotControl/commands/ListDashboardUsersCmd.ts @@ -24,9 +24,7 @@ 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 userNameList = users.map( - user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, - ); + const userNameList = users.map(user => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); sendSuccessMessage( pluginData, diff --git a/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts b/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts index 75085491..3dfafb42 100644 --- a/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts +++ b/backend/src/plugins/BotControl/commands/RemoveDashboardUserCmd.ts @@ -34,9 +34,7 @@ export const RemoveDashboardUserCmd = botControlCmd({ await pluginData.state.apiPermissionAssignments.removeUser(args.guildId, user.id); } - const userNameList = args.users.map( - user => `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`, - ); + const userNameList = args.users.map(user => `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`); sendSuccessMessage( pluginData, msg.channel as TextChannel, diff --git a/backend/src/plugins/BotControl/commands/ServersCmd.ts b/backend/src/plugins/BotControl/commands/ServersCmd.ts index 39938e3a..d226e14c 100644 --- a/backend/src/plugins/BotControl/commands/ServersCmd.ts +++ b/backend/src/plugins/BotControl/commands/ServersCmd.ts @@ -49,7 +49,7 @@ export const ServersCmd = botControlCmd({ 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}\`)`; + return `\`${paddedId}\` **${g.name}** (${g.memberCount} members) (owner **${owner.tag}** \`${owner.id}\`)`; }); createChunkedMessage(msg.channel as TextChannel, lines.join("\n")); } else { diff --git a/backend/src/plugins/Cases/functions/createCase.ts b/backend/src/plugins/Cases/functions/createCase.ts index 0d66c71e..5a03c1c2 100644 --- a/backend/src/plugins/Cases/functions/createCase.ts +++ b/backend/src/plugins/Cases/functions/createCase.ts @@ -7,15 +7,15 @@ import { postCaseToCaseLogChannel } from "./postToCaseLogChannel"; export async function createCase(pluginData: GuildPluginData, args: CaseArgs) { const user = await resolveUser(pluginData.client, args.userId); - const userName = `${user.username}#${user.discriminator}`; + const userName = `${user.tag}`; const mod = await resolveUser(pluginData.client, args.modId); - const modName = `${mod.username}#${mod.discriminator}`; + const modName = `${mod.tag}`; let ppName: string | null = null; if (args.ppId) { const pp = await resolveUser(pluginData.client, args.ppId); - ppName = `${pp.username}#${pp.discriminator}`; + ppName = `${pp.tag}`; } if (args.auditLogId) { diff --git a/backend/src/plugins/Cases/functions/createCaseNote.ts b/backend/src/plugins/Cases/functions/createCaseNote.ts index ed95e7a7..2f9d801c 100644 --- a/backend/src/plugins/Cases/functions/createCaseNote.ts +++ b/backend/src/plugins/Cases/functions/createCaseNote.ts @@ -16,7 +16,7 @@ export async function createCaseNote(pluginData: GuildPluginData !c.is_hidden); const hiddenCases = cases.filter(c => c.is_hidden); - const userName = - user instanceof UnknownUser && cases.length - ? cases[cases.length - 1].user_name - : `${user.username}#${user.discriminator}`; + const userName = user instanceof UnknownUser && cases.length ? cases[cases.length - 1].user_name : `${user.tag}`; if (cases.length === 0) { msg.channel.send(`No cases found for **${userName}**`); diff --git a/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts b/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts index 09fbb8d0..b783fbbd 100644 --- a/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts +++ b/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts @@ -68,7 +68,7 @@ export const DeleteCaseCmd = modActionsCmd({ } } - const deletedByName = `${message.author.username}#${message.author.discriminator}`; + const deletedByName = `${message.author.tag}`; const timeAndDate = pluginData.getPlugin(TimeAndDatePlugin); const deletedAt = timeAndDate.inGuildTz().format(timeAndDate.getDateFormat("pretty_datetime")); diff --git a/backend/src/plugins/ModActions/commands/NoteCmd.ts b/backend/src/plugins/ModActions/commands/NoteCmd.ts index efdb5adc..0fbd1dbd 100644 --- a/backend/src/plugins/ModActions/commands/NoteCmd.ts +++ b/backend/src/plugins/ModActions/commands/NoteCmd.ts @@ -30,7 +30,7 @@ export const NoteCmd = modActionsCmd({ return; } - const userName = `${user.username}#${user.discriminator}`; + const userName = `${user.tag}`; const reason = formatReasonWithAttachments(args.note, msg.attachments.array()); const casesPlugin = pluginData.getPlugin(CasesPlugin); diff --git a/backend/src/plugins/ModActions/commands/WarnCmd.ts b/backend/src/plugins/ModActions/commands/WarnCmd.ts index f85e1bdb..d06f91b8 100644 --- a/backend/src/plugins/ModActions/commands/WarnCmd.ts +++ b/backend/src/plugins/ModActions/commands/WarnCmd.ts @@ -107,7 +107,7 @@ export const WarnCmd = modActionsCmd({ sendSuccessMessage( pluginData, msg.channel, - `Warned **${memberToWarn.user.username}#${memberToWarn.user.discriminator}** (Case #${warnResult.case.case_number})${messageResultText}`, + `Warned **${memberToWarn.user.tag}** (Case #${warnResult.case.case_number})${messageResultText}`, ); }, }); diff --git a/backend/src/plugins/ModActions/events/PostAlertOnMemberJoinEvt.ts b/backend/src/plugins/ModActions/events/PostAlertOnMemberJoinEvt.ts index b8925aa1..136e41cc 100644 --- a/backend/src/plugins/ModActions/events/PostAlertOnMemberJoinEvt.ts +++ b/backend/src/plugins/ModActions/events/PostAlertOnMemberJoinEvt.ts @@ -47,7 +47,7 @@ export const PostAlertOnMemberJoinEvt = modActionsEvt({ } await alertChannel.send( - `<@!${member.id}> (${member.user.username}#${member.user.discriminator} \`${member.id}\`) joined with ${actions.length} prior record(s)`, + `<@!${member.id}> (${member.user.tag} \`${member.id}\`) joined with ${actions.length} prior record(s)`, ); } }, diff --git a/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts b/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts index 0ed86ded..92178edc 100644 --- a/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts +++ b/backend/src/plugins/ModActions/functions/actualKickMemberCmd.ts @@ -103,7 +103,7 @@ export async function actualKickMemberCmd( } // Confirm the action to the moderator - let response = `Kicked **${memberToKick.user.username}#${memberToKick.user.discriminator}** (Case #${kickResult.case.case_number})`; + let response = `Kicked **${memberToKick.user.tag}** (Case #${kickResult.case.case_number})`; if (kickResult.notifyResult.text) response += ` (${kickResult.notifyResult.text})`; sendSuccessMessage(pluginData, msg.channel, response); diff --git a/backend/src/plugins/ModActions/functions/actualMuteUserCmd.ts b/backend/src/plugins/ModActions/functions/actualMuteUserCmd.ts index 4dc16209..64fd30df 100644 --- a/backend/src/plugins/ModActions/functions/actualMuteUserCmd.ts +++ b/backend/src/plugins/ModActions/functions/actualMuteUserCmd.ts @@ -85,24 +85,24 @@ export async function actualMuteUserCmd( if (args.time) { if (muteResult.updatedExistingMute) { response = asSingleLine(` - Updated **${user.username}#${user.discriminator}**'s + Updated **${user.tag}**'s mute to ${timeUntilUnmute} (Case #${muteResult.case.case_number}) `); } else { response = asSingleLine(` - Muted **${user.username}#${user.discriminator}** + Muted **${user.tag}** for ${timeUntilUnmute} (Case #${muteResult.case.case_number}) `); } } else { if (muteResult.updatedExistingMute) { response = asSingleLine(` - Updated **${user.username}#${user.discriminator}**'s + Updated **${user.tag}**'s mute to indefinite (Case #${muteResult.case.case_number}) `); } else { response = asSingleLine(` - Muted **${user.username}#${user.discriminator}** + Muted **${user.tag}** indefinitely (Case #${muteResult.case.case_number}) `); } diff --git a/backend/src/plugins/ModActions/functions/actualUnmuteUserCmd.ts b/backend/src/plugins/ModActions/functions/actualUnmuteUserCmd.ts index 9f95b417..fb7465c7 100644 --- a/backend/src/plugins/ModActions/functions/actualUnmuteUserCmd.ts +++ b/backend/src/plugins/ModActions/functions/actualUnmuteUserCmd.ts @@ -48,7 +48,7 @@ export async function actualUnmuteCmd( pluginData, msg.channel as TextChannel, asSingleLine(` - Unmuting **${user.username}#${user.discriminator}** + Unmuting **${user.tag}** in ${timeUntilUnmute} (Case #${result.case.case_number}) `), ); @@ -57,7 +57,7 @@ export async function actualUnmuteCmd( pluginData, msg.channel as TextChannel, asSingleLine(` - Unmuted **${user.username}#${user.discriminator}** + Unmuted **${user.tag}** (Case #${result.case.case_number}) `), ); diff --git a/backend/src/plugins/Mutes/commands/MutesCmd.ts b/backend/src/plugins/Mutes/commands/MutesCmd.ts index 27b33523..4ee88e74 100644 --- a/backend/src/plugins/Mutes/commands/MutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/MutesCmd.ts @@ -67,7 +67,7 @@ export const MutesCmd = mutesCmd({ totalMutes = manuallyMutedMembers.length; lines = manuallyMutedMembers.map(member => { - return `<@!${member.id}> (**${member.user.username}#${member.user.discriminator}**, \`${member.id}\`) 🔧 Manual mute`; + return `<@!${member.id}> (**${member.user.tag}**, \`${member.id}\`) 🔧 Manual mute`; }); } else { // Show filtered active mutes (but not manual mutes) @@ -119,7 +119,7 @@ export const MutesCmd = mutesCmd({ lines = filteredMutes.map(mute => { const user = pluginData.client.users.resolve(mute.user_id as Snowflake); - const username = user ? `${user.username}#${user.discriminator}` : "Unknown#0000"; + const username = user ? `${user.tag}` : "Unknown#0000"; const theCase = muteCasesById.get(mute.case_id); const caseName = theCase ? `Case #${theCase.case_number}` : "No case"; diff --git a/backend/src/plugins/NameHistory/commands/NamesCmd.ts b/backend/src/plugins/NameHistory/commands/NamesCmd.ts index f2a7348a..0ee42166 100644 --- a/backend/src/plugins/NameHistory/commands/NamesCmd.ts +++ b/backend/src/plugins/NameHistory/commands/NamesCmd.ts @@ -31,7 +31,7 @@ export const NamesCmd = nameHistoryCmd({ const usernameRows = usernames.map(r => `\`[${r.timestamp}]\` **${disableCodeBlocks(r.username)}**`); const user = await pluginData.client.users.fetch(args.userId as Snowflake); - const currentUsername = user ? `${user.username}#${user.discriminator}` : args.userId; + const currentUsername = user ? `${user.tag}` : args.userId; const nicknameDays = Math.round(NICKNAME_RETENTION_PERIOD / DAYS); const usernameDays = Math.round(NICKNAME_RETENTION_PERIOD / DAYS); diff --git a/backend/src/plugins/Post/util/actualPostCmd.ts b/backend/src/plugins/Post/util/actualPostCmd.ts index 88135f38..db8f51a4 100644 --- a/backend/src/plugins/Post/util/actualPostCmd.ts +++ b/backend/src/plugins/Post/util/actualPostCmd.ts @@ -138,7 +138,7 @@ export async function actualPostCmd( await pluginData.state.scheduledPosts.create({ author_id: msg.author.id, - author_name: `${msg.author.username}#${msg.author.discriminator}`, + author_name: `${msg.author.tag}`, channel_id: targetChannel.id, content, attachments: msg.attachments.array(), diff --git a/backend/src/plugins/ReactionRoles/util/addMemberPendingRoleChange.ts b/backend/src/plugins/ReactionRoles/util/addMemberPendingRoleChange.ts index 41ec5710..f4e4bfcb 100644 --- a/backend/src/plugins/ReactionRoles/util/addMemberPendingRoleChange.ts +++ b/backend/src/plugins/ReactionRoles/util/addMemberPendingRoleChange.ts @@ -38,9 +38,7 @@ export async function addMemberPendingRoleChange( "Reaction roles", ); } catch (e) { - logger.warn( - `Failed to apply role changes to ${member.user.username}#${member.user.discriminator} (${member.id}): ${e.message}`, - ); + logger.warn(`Failed to apply role changes to ${member.user.tag} (${member.id}): ${e.message}`); } } lock.unlock(); diff --git a/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts b/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts index 3f67b710..75835e6b 100644 --- a/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts +++ b/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts @@ -45,7 +45,7 @@ export const SlowmodeClearCmd = slowmodeCmd({ pluginData, msg.channel, asSingleLine(` - Failed to clear slowmode from **${args.user.username}#${args.user.discriminator}** in <#${args.channel.id}>: + Failed to clear slowmode from **${args.user.tag}** in <#${args.channel.id}>: Threads cannot have Bot Slowmode `), ); @@ -56,17 +56,13 @@ export const SlowmodeClearCmd = slowmodeCmd({ pluginData, msg.channel, asSingleLine(` - Failed to clear slowmode from **${args.user.username}#${args.user.discriminator}** in <#${args.channel.id}>: + Failed to clear slowmode from **${args.user.tag}** in <#${args.channel.id}>: \`${disableInlineCode(e.message)}\` `), ); return; } - sendSuccessMessage( - pluginData, - msg.channel, - `Slowmode cleared from **${args.user.username}#${args.user.discriminator}** in <#${args.channel.id}>`, - ); + sendSuccessMessage(pluginData, msg.channel, `Slowmode cleared from **${args.user.tag}** in <#${args.channel.id}>`); }, }); diff --git a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts index a66f09f8..209d8ca8 100644 --- a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts +++ b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts @@ -18,7 +18,7 @@ export function createStarboardEmbedFromMessage( text: `#${(msg.channel as GuildChannel).name}`, }, author: { - name: `${msg.author.username}#${msg.author.discriminator}`, + name: `${msg.author.tag}`, }, fields: [], timestamp: msg.createdAt, diff --git a/backend/src/plugins/UsernameSaver/updateUsername.ts b/backend/src/plugins/UsernameSaver/updateUsername.ts index 56debeac..baaa3bd1 100644 --- a/backend/src/plugins/UsernameSaver/updateUsername.ts +++ b/backend/src/plugins/UsernameSaver/updateUsername.ts @@ -4,7 +4,7 @@ import { UsernameSaverPluginType } from "./types"; export async function updateUsername(pluginData: GuildPluginData, user: User) { if (!user) return; - const newUsername = `${user.username}#${user.discriminator}`; + const newUsername = `${user.tag}`; const latestEntry = await pluginData.state.usernameHistory.getLastEntry(user.id); if (!latestEntry || newUsername !== latestEntry.username) { await pluginData.state.usernameHistory.addEntry(user.id, newUsername); diff --git a/backend/src/plugins/Utility/commands/AvatarCmd.ts b/backend/src/plugins/Utility/commands/AvatarCmd.ts index 7fe01bb9..cf8714b1 100644 --- a/backend/src/plugins/Utility/commands/AvatarCmd.ts +++ b/backend/src/plugins/Utility/commands/AvatarCmd.ts @@ -24,7 +24,7 @@ export const AvatarCmd = utilityCmd({ const embed: MessageEmbedOptions = { image: { url: avatarUrl + `${extension}?size=2048` }, }; - embed.title = `Avatar of ${user.username}#${user.discriminator}:`; + embed.title = `Avatar of ${user.tag}:`; msg.channel.send({ embeds: [embed] }); } else { sendErrorMessage(pluginData, msg.channel, "Invalid user ID"); diff --git a/backend/src/plugins/Utility/commands/LevelCmd.ts b/backend/src/plugins/Utility/commands/LevelCmd.ts index 404412b5..e0be2605 100644 --- a/backend/src/plugins/Utility/commands/LevelCmd.ts +++ b/backend/src/plugins/Utility/commands/LevelCmd.ts @@ -17,8 +17,6 @@ export const LevelCmd = utilityCmd({ run({ message, args, pluginData }) { const member = args.member || message.member; const level = getMemberLevel(pluginData, member); - message.channel.send( - `The permission level of ${member.user.username}#${member.user.discriminator} is **${level}**`, - ); + message.channel.send(`The permission level of ${member.user.tag} is **${level}**`); }, }); diff --git a/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts b/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts index 8c20adc4..d473b491 100644 --- a/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts +++ b/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts @@ -44,10 +44,6 @@ export const VcdisconnectCmd = utilityCmd({ oldChannel: channelToConfigAccessibleChannel(channel), }); - sendSuccessMessage( - pluginData, - msg.channel, - `**${args.member.user.username}#${args.member.user.discriminator}** disconnected from **${channel.name}**`, - ); + sendSuccessMessage(pluginData, msg.channel, `**${args.member.user.tag}** disconnected from **${channel.name}**`); }, }); diff --git a/backend/src/plugins/Utility/commands/VcmoveCmd.ts b/backend/src/plugins/Utility/commands/VcmoveCmd.ts index adb56d96..0e7bface 100644 --- a/backend/src/plugins/Utility/commands/VcmoveCmd.ts +++ b/backend/src/plugins/Utility/commands/VcmoveCmd.ts @@ -85,11 +85,7 @@ export const VcmoveCmd = utilityCmd({ newChannel: channelToConfigAccessibleChannel(channel), }); - sendSuccessMessage( - pluginData, - msg.channel, - `**${args.member.user.username}#${args.member.user.discriminator}** moved to **${channel.name}**`, - ); + sendSuccessMessage(pluginData, msg.channel, `**${args.member.user.tag}** moved to **${channel.name}**`); }, }); @@ -162,7 +158,7 @@ export const VcmoveAllCmd = utilityCmd({ sendErrorMessage( pluginData, msg.channel, - `Failed to move ${currMember.user.username}#${currMember.user.discriminator} (${currMember.id}): You cannot act on this member`, + `Failed to move ${currMember.user.tag} (${currMember.id}): You cannot act on this member`, ); errAmt++; continue; @@ -177,11 +173,7 @@ export const VcmoveAllCmd = utilityCmd({ sendErrorMessage(pluginData, msg.channel, "Unknown error when trying to move members"); return; } - sendErrorMessage( - pluginData, - msg.channel, - `Failed to move ${currMember.user.username}#${currMember.user.discriminator} (${currMember.id})`, - ); + sendErrorMessage(pluginData, msg.channel, `Failed to move ${currMember.user.tag} (${currMember.id})`); errAmt++; continue; } diff --git a/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts b/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts index c8ddfad8..a95de14b 100644 --- a/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getInviteInfoEmbed.ts @@ -96,7 +96,7 @@ export async function getInviteInfoEmbed( embed.fields.push({ name: preEmbedPadding + "Invite creator", value: trimLines(` - Name: **${invite.inviter.username}#${invite.inviter.discriminator}** + Name: **${invite.inviter.tag}** ID: \`${invite.inviter.id}\` Mention: <@!${invite.inviter.id}> `), @@ -143,7 +143,7 @@ export async function getInviteInfoEmbed( embed.fields.push({ name: preEmbedPadding + "Invite creator", value: trimLines(` - Name: **${invite.inviter.username}#${invite.inviter.discriminator}** + Name: **${invite.inviter.tag}** ID: \`${invite.inviter.id}\` Mention: <@!${invite.inviter.id}> `), diff --git a/backend/src/plugins/Utility/functions/getMessageInfoEmbed.ts b/backend/src/plugins/Utility/functions/getMessageInfoEmbed.ts index 5b8fc4bc..17e2c63f 100644 --- a/backend/src/plugins/Utility/functions/getMessageInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getMessageInfoEmbed.ts @@ -112,7 +112,7 @@ export async function getMessageInfoEmbed( embed.fields.push({ name: preEmbedPadding + "Author information", value: trimLines(` - Name: **${message.author.username}#${message.author.discriminator}** + Name: **${message.author.tag}** ID: \`${message.author.id}\` Created: **${authorAccountAge} ago** (\`${prettyAuthorCreatedAt}\`) ${authorJoinedAt ? `Joined: **${authorServerAge} ago** (\`${prettyAuthorJoinedAt}\`)` : ""} diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index 2eb04a60..93b4d45e 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -65,7 +65,7 @@ export async function getServerInfoEmbed( if (thisServer) { const owner = await resolveUser(pluginData.client, thisServer.ownerId); - const ownerName = `${owner.username}#${owner.discriminator}`; + const ownerName = `${owner.tag}`; basicInformation.push(`Owner: **${ownerName}** (\`${thisServer.ownerId}\`)`); // basicInformation.push(`Voice region: **${thisServer.region}**`); Outdated, as automatic voice regions are fully live diff --git a/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts b/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts index 581193fb..4f87dabc 100644 --- a/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts @@ -36,7 +36,7 @@ export async function getUserInfoEmbed( const timeAndDate = pluginData.getPlugin(TimeAndDatePlugin); embed.author = { - name: `User: ${user.username}#${user.discriminator}`, + name: `User: ${user.tag}`, }; const avatarURL = user.displayAvatarURL(); @@ -84,7 +84,7 @@ export async function getUserInfoEmbed( embed.fields.push({ name: preEmbedPadding + "User information", value: trimLines(` - Name: **${user.username}#${user.discriminator}** + Name: **${user.tag}** ID: \`${user.id}\` Created: **${accountAge} ago** (\`${prettyCreatedAt}\`) Mention: <@!${user.id}> diff --git a/backend/src/plugins/Utility/search.ts b/backend/src/plugins/Utility/search.ts index 40bd1d1b..97bc1bd4 100644 --- a/backend/src/plugins/Utility/search.ts +++ b/backend/src/plugins/Utility/search.ts @@ -391,7 +391,7 @@ async function performMemberSearch( return true; } - const fullUsername = `${member.user.username}#${member.user.discriminator}`; + const fullUsername = `${member.user.tag}`; if (await execRegExp(queryRegex, fullUsername).catch(allowTimeout)) return true; return false; @@ -458,7 +458,7 @@ async function performBanSearch( const execRegExp = getOptimizedRegExpRunner(pluginData, isSafeRegex); matchingBans = await asyncFilter(matchingBans, async user => { - const fullUsername = `${user.username}#${user.discriminator}`; + const fullUsername = `${user.tag}`; if (await execRegExp(queryRegex, fullUsername).catch(allowTimeout)) return true; return false; }); @@ -502,10 +502,10 @@ function formatSearchResultList(members: Array): string { const paddedId = member.id.padEnd(longestId, " "); let line; if (member instanceof GuildMember) { - line = `${paddedId} ${member.user.username}#${member.user.discriminator}`; + line = `${paddedId} ${member.user.tag}`; if (member.nickname) line += ` (${member.nickname})`; } else { - line = `${paddedId} ${member.username}#${member.discriminator}`; + line = `${paddedId} ${member.tag}`; } return line; }); diff --git a/backend/src/utils.ts b/backend/src/utils.ts index c4464f97..99d46617 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -1099,6 +1099,7 @@ export class UnknownUser { public id: string; public username = "Unknown"; public discriminator = "0000"; + public tag = "Unknown#0000"; constructor(props = {}) { for (const key in props) { @@ -1353,18 +1354,18 @@ export function messageSummary(msg: SavedMessage) { export function verboseUserMention(user: User | UnknownUser): string { if (user.id == null) { - return `**${user.username}#${user.discriminator}**`; + return `**${user.tag}**`; } - return `<@!${user.id}> (**${user.username}#${user.discriminator}**, \`${user.id}\`)`; + return `<@!${user.id}> (**${user.tag}**, \`${user.id}\`)`; } export function verboseUserName(user: User | UnknownUser): string { if (user.id == null) { - return `**${user.username}#${user.discriminator}**`; + return `**${user.tag}**`; } - return `**${user.username}#${user.discriminator}** (\`${user.id}\`)`; + return `**${user.tag}** (\`${user.id}\`)`; } export function verboseChannelMention(channel: GuildChannel): string { diff --git a/backend/src/utils/configAccessibleObjects.ts b/backend/src/utils/configAccessibleObjects.ts index 1c281ed6..638fb6ca 100644 --- a/backend/src/utils/configAccessibleObjects.ts +++ b/backend/src/utils/configAccessibleObjects.ts @@ -38,7 +38,7 @@ export interface IConfigAccessibleMember extends IConfigAccessibleUser { } export function userToConfigAccessibleUser(user: User | UnknownUser): IConfigAccessibleUser { - if (`${user.username}#${user.discriminator}` === "Unknown#0000") { + if (`${user.tag}` === "Unknown#0000") { const toReturnPartial: IConfigAccessibleUser = { id: user.id, username: "Unknown", From bd5e5100a597a50a963dde8c6f10b931588b6742 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 00:50:41 +0100 Subject: [PATCH 16/40] typo and return --- .../ReactionRoles/events/ButtonInteractionEvt.ts | 4 ++-- .../ReactionRoles/util/buttonActionHandlers.ts | 12 ++++-------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts b/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts index 7f366140..a08e4579 100644 --- a/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts +++ b/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts @@ -55,7 +55,7 @@ export const ButtonInteractionEvt = reactionRolesEvt({ .getPlugin(LogsPlugin) .log( LogType.BOT_ALERT, - `**A configuration error occured** on buttons for message ${int.message.id}, group **${context.groupName}** not found in config`, + `**A configuration error occurred** on buttons for message ${int.message.id}, group **${context.groupName}** not found in config`, ); return; } @@ -67,7 +67,7 @@ export const ButtonInteractionEvt = reactionRolesEvt({ .getPlugin(LogsPlugin) .log( LogType.BOT_ALERT, - `**A internal error occured** on buttons for message ${int.message.id}, action **${context.action}** is not known`, + `**A internal error occurred** on buttons for message ${int.message.id}, action **${context.action}** is not known`, ); return; } diff --git a/backend/src/plugins/ReactionRoles/util/buttonActionHandlers.ts b/backend/src/plugins/ReactionRoles/util/buttonActionHandlers.ts index 314516b6..446cc0ee 100644 --- a/backend/src/plugins/ReactionRoles/util/buttonActionHandlers.ts +++ b/backend/src/plugins/ReactionRoles/util/buttonActionHandlers.ts @@ -22,7 +22,7 @@ export async function handleOpenMenu( .getPlugin(LogsPlugin) .log( LogType.BOT_ALERT, - `**A configuration error occured** on buttons for message ${int.message.id}, no menus found in config`, + `**A configuration error occurred** on buttons for message ${int.message.id}, no menus found in config`, ); return; } @@ -52,14 +52,13 @@ export async function handleOpenMenu( .getPlugin(LogsPlugin) .log( LogType.BOT_ALERT, - `**A configuration error occured** on buttons for message ${int.message.id}, menu **${context.roleOrMenu}** not found in config`, + `**A configuration error occurred** on buttons for message ${int.message.id}, menu **${context.roleOrMenu}** not found in config`, ); return; } const rows = splitButtonsIntoRows(menuButtons, Object.values(group.button_menus[context.roleOrMenu])); // new MessageActionRow().addComponents(menuButtons); int.reply({ content: `Click to add/remove a role`, components: rows, ephemeral: true }); - return; } export async function handleModifyRole( @@ -78,7 +77,7 @@ export async function handleModifyRole( .getPlugin(LogsPlugin) .log( LogType.BOT_ALERT, - `**A configuration error occured** on buttons for message ${int.message.id}, role **${context.roleOrMenu}** not found on server`, + `**A configuration error occurred** on buttons for message ${int.message.id}, role **${context.roleOrMenu}** not found on server`, ); return; } @@ -101,10 +100,7 @@ export async function handleModifyRole( .getPlugin(LogsPlugin) .log( LogType.BOT_ALERT, - `**A configuration error occured** on buttons for message ${int.message.id}, error: ${e}. We might be missing permissions!`, + `**A configuration error occurred** on buttons for message ${int.message.id}, error: ${e}. We might be missing permissions!`, ); - return; } - - return; } From de7c721c0e2f63234ed52a7f0d51f205d3ce1e92 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 00:52:19 +0100 Subject: [PATCH 17/40] simplify ternary --- backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts b/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts index ce4894e0..22bc74d7 100644 --- a/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts +++ b/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts @@ -89,7 +89,7 @@ export const SlowmodeSetCmd = slowmodeCmd({ if (mode === "native") { const missingPermissions = getMissingPermissions( - channelPermissions ? channelPermissions : new Permissions(), + channelPermissions ?? new Permissions(), NATIVE_SLOWMODE_PERMISSIONS, ); if (missingPermissions) { @@ -104,7 +104,7 @@ export const SlowmodeSetCmd = slowmodeCmd({ if (mode === "bot") { const missingPermissions = getMissingPermissions( - channelPermissions ? channelPermissions : new Permissions(), + channelPermissions ?? new Permissions(), BOT_SLOWMODE_PERMISSIONS, ); if (missingPermissions) { From cfe3bff74289291b5656b8afb35f63a701b35e4b Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 00:55:03 +0100 Subject: [PATCH 18/40] fetch fix --- backend/src/plugins/Slowmode/util/applyBotSlowmodeToUserId.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/plugins/Slowmode/util/applyBotSlowmodeToUserId.ts b/backend/src/plugins/Slowmode/util/applyBotSlowmodeToUserId.ts index 208f628a..3a29a711 100644 --- a/backend/src/plugins/Slowmode/util/applyBotSlowmodeToUserId.ts +++ b/backend/src/plugins/Slowmode/util/applyBotSlowmodeToUserId.ts @@ -21,7 +21,7 @@ export async function applyBotSlowmodeToUserId( await channel.permissionOverwrites.create(userId as Snowflake, { SEND_MESSAGES: false }, { type: 1 }); } } catch (e) { - const user = (await pluginData.client.users.fetch(userId as Snowflake)) || new UnknownUser({ id: userId }); + const user = await pluginData.client.users.fetch(userId as Snowflake).catch(() => new UnknownUser({ id: userId })); if (isDiscordAPIError(e) && e.code === 50013) { logger.warn( From c98de0f554e95608632b211f16a89ebba92976a6 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 00:58:11 +0100 Subject: [PATCH 19/40] fetch fix --- backend/src/plugins/Slowmode/util/clearExpiredSlowmodes.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/Slowmode/util/clearExpiredSlowmodes.ts b/backend/src/plugins/Slowmode/util/clearExpiredSlowmodes.ts index 0d22bca8..f8490e4d 100644 --- a/backend/src/plugins/Slowmode/util/clearExpiredSlowmodes.ts +++ b/backend/src/plugins/Slowmode/util/clearExpiredSlowmodes.ts @@ -21,8 +21,9 @@ export async function clearExpiredSlowmodes(pluginData: GuildPluginData new UnknownUser({ id: user.user_id })); pluginData.state.logs.log(LogType.BOT_ALERT, { body: `Failed to clear slowmode permissions from {userMention(user)} in {channelMention(channel)}`, From 9539c5a7de1d355d83bf33a7dc93b766bc553e0b Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:08:00 +0100 Subject: [PATCH 20/40] corrected type assertion --- backend/src/plugins/Starboard/util/saveMessageToStarboard.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/Starboard/util/saveMessageToStarboard.ts b/backend/src/plugins/Starboard/util/saveMessageToStarboard.ts index 12e2785a..ed2bd3f9 100644 --- a/backend/src/plugins/Starboard/util/saveMessageToStarboard.ts +++ b/backend/src/plugins/Starboard/util/saveMessageToStarboard.ts @@ -1,4 +1,4 @@ -import { Message, MessageEmbed, Snowflake, TextChannel } from "discord.js"; +import { Message, MessageEmbedOptions, Snowflake, TextChannel } from "discord.js"; import { GuildPluginData } from "knub"; import { StarboardPluginType, TStarboardOpts } from "../types"; import { createStarboardEmbedFromMessage } from "./createStarboardEmbedFromMessage"; @@ -16,6 +16,6 @@ export async function saveMessageToStarboard( const embed = createStarboardEmbedFromMessage(msg, Boolean(starboard.copy_full_embed), starboard.color); embed.fields!.push(createStarboardPseudoFooterForMessage(starboard, msg, starboard.star_emoji![0], starCount)); - const starboardMessage = await (channel as TextChannel).send({ embeds: [embed as MessageEmbed] }); + const starboardMessage = await (channel as TextChannel).send({ embeds: [embed as MessageEmbedOptions] }); await pluginData.state.starboardMessages.createStarboardMessage(channel.id, msg.id, starboardMessage.id); } From 87cc461c79a87efe9d065b9d27a31480e8978317 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:10:53 +0100 Subject: [PATCH 21/40] always set author icon url using dynamic --- .../plugins/Starboard/util/createStarboardEmbedFromMessage.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts index 209d8ca8..0cc579a9 100644 --- a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts +++ b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts @@ -28,9 +28,7 @@ export function createStarboardEmbedFromMessage( embed.color = color; } - if (msg.author.avatarURL()) { - embed.author.icon_url = msg.author.avatarURL()!; - } + embed.author.icon_url = msg.author.displayAvatarURL({ dynamic: true }); // The second condition here checks for messages with only an image link that is then embedded. // The message content in that case is hidden by the Discord client, so we hide it here too. From 3a59f772ae0668d4b1f1e5706fb2d254679d0a9d Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:18:06 +0100 Subject: [PATCH 22/40] use optional chaining and createdTimestamp on embed --- backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts | 4 ++-- .../plugins/Starboard/util/createStarboardEmbedFromMessage.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts b/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts index b5f9bbba..e34b34c2 100644 --- a/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts +++ b/backend/src/plugins/Spam/util/logAndDetectMessageSpam.ts @@ -120,8 +120,8 @@ export async function logAndDetectMessageSpam( // Then, if enabled, remove the spam messages if (spamConfig.clean !== false) { msgIds.forEach(id => pluginData.state.logs.ignoreLog(LogType.MESSAGE_DELETE, id)); - (pluginData.guild.channels.cache.get(savedMessage.channel_id as Snowflake)! as TextChannel) - .bulkDelete(msgIds as Snowflake[]) + (pluginData.guild.channels.cache.get(savedMessage.channel_id as Snowflake)! as TextChannel | undefined) + ?.bulkDelete(msgIds as Snowflake[]) .catch(noop); } diff --git a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts index 0cc579a9..e1fe0aed 100644 --- a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts +++ b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts @@ -21,7 +21,7 @@ export function createStarboardEmbedFromMessage( name: `${msg.author.tag}`, }, fields: [], - timestamp: msg.createdAt, + timestamp: msg.createdTimestamp, }; if (color != null) { From 0f5162ee21b9ed4e9e47ee752acf7dc0c0da9e25 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:20:40 +0100 Subject: [PATCH 23/40] ping in about cmd --- backend/src/plugins/Utility/commands/AboutCmd.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/backend/src/plugins/Utility/commands/AboutCmd.ts b/backend/src/plugins/Utility/commands/AboutCmd.ts index 8c7d4db5..0d6f8493 100644 --- a/backend/src/plugins/Utility/commands/AboutCmd.ts +++ b/backend/src/plugins/Utility/commands/AboutCmd.ts @@ -39,8 +39,6 @@ export const AboutCmd = utilityCmd({ version = "?"; } - // const shard = pluginData.client.shards.get(pluginData.client.guildShardMap[pluginData.guild.id])!; FIXME Sharding stuff - const lastReload = humanizeDuration(Date.now() - pluginData.state.lastReload, { largest: 2, round: true, @@ -51,7 +49,7 @@ export const AboutCmd = utilityCmd({ ["Last reload", `${lastReload} ago`], ["Last update", lastUpdate], ["Version", version], - // ["API latency", `${shard.latency}ms`], + ["API latency", `${pluginData.client.ws.ping}ms`], ["Server timezone", timeAndDate.getGuildTz()], ]; @@ -70,11 +68,7 @@ export const AboutCmd = utilityCmd({ fields: [ { name: "Status", - value: basicInfoRows - .map(([label, value]) => { - return `${label}: **${value}**`; - }) - .join("\n"), + value: basicInfoRows.map(([label, value]) => `${label}: **${value}**`).join("\n"), }, { name: `Loaded plugins on this server (${loadedPlugins.length})`, From 80f2dacb7f3f98efd18d661163f6b8cce9b8b435 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:22:37 +0100 Subject: [PATCH 24/40] simplified avatar cmd --- backend/src/plugins/Utility/commands/AvatarCmd.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/backend/src/plugins/Utility/commands/AvatarCmd.ts b/backend/src/plugins/Utility/commands/AvatarCmd.ts index cf8714b1..d503bc97 100644 --- a/backend/src/plugins/Utility/commands/AvatarCmd.ts +++ b/backend/src/plugins/Utility/commands/AvatarCmd.ts @@ -16,15 +16,12 @@ export const AvatarCmd = utilityCmd({ async run({ message: msg, args, pluginData }) { const user = args.user || msg.author; if (!(user instanceof UnknownUser)) { - const avatar = user.displayAvatarURL(); - let extension = avatar.slice(avatar.lastIndexOf("."), avatar.lastIndexOf("?")); - // Some pngs can have the .jpg extention for some reason, so we always use .png for static images - extension = extension === ".gif" ? extension : ".png"; - const avatarUrl = avatar.slice(0, avatar.lastIndexOf(".")); const embed: MessageEmbedOptions = { - image: { url: avatarUrl + `${extension}?size=2048` }, + image: { + url: user.displayAvatarURL({ dynamic: true, format: "png", size: 2048 }), + }, + title: `Avatar of ${user.tag}:`, }; - embed.title = `Avatar of ${user.tag}:`; msg.channel.send({ embeds: [embed] }); } else { sendErrorMessage(pluginData, msg.channel, "Invalid user ID"); From a8298d4faa38d7720fd3af0949070bb454fd4ce2 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:43:50 +0100 Subject: [PATCH 25/40] fixed jumbo cmd, simplified checks and fixed ping cmd --- .../src/plugins/Utility/commands/JumboCmd.ts | 35 +++++++++---------- .../src/plugins/Utility/commands/PingCmd.ts | 5 ++- .../Utility/commands/VcdisconnectCmd.ts | 2 +- .../src/plugins/Utility/commands/VcmoveCmd.ts | 2 +- 4 files changed, 20 insertions(+), 24 deletions(-) diff --git a/backend/src/plugins/Utility/commands/JumboCmd.ts b/backend/src/plugins/Utility/commands/JumboCmd.ts index 4e2e99a7..bc117d45 100644 --- a/backend/src/plugins/Utility/commands/JumboCmd.ts +++ b/backend/src/plugins/Utility/commands/JumboCmd.ts @@ -1,3 +1,4 @@ +import { MessageAttachment } from "discord.js"; import fs from "fs"; import sharp from "sharp"; import twemoji from "twemoji"; @@ -39,8 +40,8 @@ export const JumboCmd = utilityCmd({ const size = config.jumbo_size > 2048 ? 2048 : config.jumbo_size; const emojiRegex = new RegExp(`(<.*:).*:(\\d+)`); const results = emojiRegex.exec(args.emoji); - let extention = ".png"; - let file; + let extension = ".png"; + let file: MessageAttachment | undefined; if (!isEmoji(args.emoji)) { sendErrorMessage(pluginData, msg.channel, "Invalid emoji"); @@ -50,25 +51,19 @@ export const JumboCmd = utilityCmd({ if (results) { let url = "https://cdn.discordapp.com/emojis/"; if (results[1] === " total + ms, 0) / times.length); - // const shard = pluginData.client.shards.get(pluginData.client.guildShardMap[pluginData.guild.id])!; FIXME sharding stuff - msg.channel.send( trimLines(` **Ping:** @@ -38,7 +36,8 @@ export const PingCmd = utilityCmd({ Highest: **${highest}ms** Mean: **${mean}ms** Time between ping command and first reply: **${msgToMsgDelay!}ms** - `), // Omitted line: Shard latency: **${shard.latency}ms** + Shard latency: **${pluginData.client.ws.ping}ms** + `), ); // Clean up test messages diff --git a/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts b/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts index d473b491..c5d4b14d 100644 --- a/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts +++ b/backend/src/plugins/Utility/commands/VcdisconnectCmd.ts @@ -25,7 +25,7 @@ export const VcdisconnectCmd = utilityCmd({ return; } - if (!args.member.voice || !args.member.voice.channelId) { + if (!args.member.voice?.channelId) { sendErrorMessage(pluginData, msg.channel, "Member is not in a voice channel"); return; } diff --git a/backend/src/plugins/Utility/commands/VcmoveCmd.ts b/backend/src/plugins/Utility/commands/VcmoveCmd.ts index 0e7bface..9e51dd5b 100644 --- a/backend/src/plugins/Utility/commands/VcmoveCmd.ts +++ b/backend/src/plugins/Utility/commands/VcmoveCmd.ts @@ -57,7 +57,7 @@ export const VcmoveCmd = utilityCmd({ channel = closestMatch; } - if (!args.member.voice || !args.member.voice.channelId) { + if (!args.member.voice?.channelId) { sendErrorMessage(pluginData, msg.channel, "Member is not in a voice channel"); return; } From a3e6e4f31992db5ac31c8c8fb67163c672e19bf2 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 01:51:11 +0100 Subject: [PATCH 26/40] removed unnecessary conditional --- backend/src/index.ts | 2 +- .../src/plugins/Utility/events/AutoJoinThreadEvt.ts | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 70bf4d2e..7ab1032d 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -174,7 +174,7 @@ connect().then(async () => { client.setMaxListeners(200); client.on("rateLimit", rateLimitData => { - logger.info(`[429] ${rateLimitData}`); + logger.info(`[429] ${JSON.stringify(rateLimitData)}`); }); client.on("error", err => { diff --git a/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts b/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts index 6789073c..84c36768 100644 --- a/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts +++ b/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts @@ -5,7 +5,7 @@ export const AutoJoinThreadEvt = utilityEvt({ async listener(meta) { const config = meta.pluginData.config.get(); - if (config.autojoin_threads && meta.args.thread.joinable && !meta.args.thread.joined) { + if (config.autojoin_threads && meta.args.thread.joinable) { await meta.args.thread.join(); } }, @@ -16,11 +16,10 @@ export const AutoJoinThreadSyncEvt = utilityEvt({ async listener(meta) { const config = meta.pluginData.config.get(); - if (config.autojoin_threads) { - for (const thread of meta.args.threads.values()) { - if (!thread.joined && thread.joinable) { - await thread.join(); - } + if (config.autojoin_threads) return; + for (const thread of meta.args.threads.values()) { + if (!thread.joined && thread.joinable) { + await thread.join(); } } }, From 30010247b19c9395ae415b24532bb96e56fb742c Mon Sep 17 00:00:00 2001 From: Dark <7890309+DarkView@users.noreply.github.com> Date: Thu, 29 Jul 2021 03:02:00 +0200 Subject: [PATCH 27/40] Fix object names --- backend/src/plugins/Logs/LogsPlugin.ts | 2 +- ...mojiModifyEvts.ts => LogsEmojiAndStickerModifyEvts.ts} | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) rename backend/src/plugins/Logs/events/{LogsStickerEmojiModifyEvts.ts => LogsEmojiAndStickerModifyEvts.ts} (87%) diff --git a/backend/src/plugins/Logs/LogsPlugin.ts b/backend/src/plugins/Logs/LogsPlugin.ts index 3f65e9bc..e61d0857 100644 --- a/backend/src/plugins/Logs/LogsPlugin.ts +++ b/backend/src/plugins/Logs/LogsPlugin.ts @@ -27,7 +27,7 @@ import { LogsStickerCreateEvt, LogsStickerDeleteEvt, LogsStickerUpdateEvt, -} from "./events/LogsStickerEmojiModifyEvts"; +} from "./events/LogsEmojiAndStickerModifyEvts"; import { LogsThreadCreateEvt, LogsThreadDeleteEvt, LogsThreadUpdateEvt } from "./events/LogsThreadModifyEvts"; import { LogsGuildMemberUpdateEvt } from "./events/LogsUserUpdateEvts"; import { LogsVoiceStateUpdateEvt } from "./events/LogsVoiceChannelEvts"; diff --git a/backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts b/backend/src/plugins/Logs/events/LogsEmojiAndStickerModifyEvts.ts similarity index 87% rename from backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts rename to backend/src/plugins/Logs/events/LogsEmojiAndStickerModifyEvts.ts index 3535174c..4f8ce433 100644 --- a/backend/src/plugins/Logs/events/LogsStickerEmojiModifyEvts.ts +++ b/backend/src/plugins/Logs/events/LogsEmojiAndStickerModifyEvts.ts @@ -47,7 +47,7 @@ export const LogsStickerCreateEvt = logsEvt({ async listener(meta) { meta.pluginData.state.guildLogs.log(LogType.STICKER_CREATE, { - thread: stickerToConfigAccessibleSticker(meta.args.sticker), + sticker: stickerToConfigAccessibleSticker(meta.args.sticker), }); }, }); @@ -57,7 +57,7 @@ export const LogsStickerDeleteEvt = logsEvt({ async listener(meta) { meta.pluginData.state.guildLogs.log(LogType.STICKER_DELETE, { - thread: stickerToConfigAccessibleSticker(meta.args.sticker), + sticker: stickerToConfigAccessibleSticker(meta.args.sticker), }); }, }); @@ -72,8 +72,8 @@ export const LogsStickerUpdateEvt = logsEvt({ meta.pluginData.state.guildLogs.log( LogType.STICKER_UPDATE, { - oldThread: stickerToConfigAccessibleSticker(meta.args.oldSticker), - newThread: stickerToConfigAccessibleSticker(meta.args.newSticker), + oldSticker: stickerToConfigAccessibleSticker(meta.args.oldSticker), + newSticker: stickerToConfigAccessibleSticker(meta.args.newSticker), differenceString, }, meta.args.newSticker.id, From afe0ec1194e7f7f765ad7fc52f84e88c4e416111 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 10:08:55 +0100 Subject: [PATCH 28/40] removed unnecessary string literal and simplified stuff --- backend/src/pluginUtils.ts | 4 ++-- backend/src/plugins/Cases/functions/createCase.ts | 6 +++--- backend/src/plugins/Cases/functions/createCaseNote.ts | 2 +- backend/src/plugins/ModActions/commands/CasesModCmd.ts | 2 +- backend/src/plugins/ModActions/commands/CasesUserCmd.ts | 2 +- backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts | 2 +- backend/src/plugins/ModActions/commands/NoteCmd.ts | 2 +- backend/src/plugins/Mutes/commands/MutesCmd.ts | 2 +- backend/src/plugins/NameHistory/commands/NamesCmd.ts | 4 ++-- backend/src/plugins/Post/util/actualPostCmd.ts | 2 +- .../plugins/ReactionRoles/events/ButtonInteractionEvt.ts | 6 ++---- .../Starboard/util/createStarboardEmbedFromMessage.ts | 2 +- backend/src/plugins/UsernameSaver/updateUsername.ts | 2 +- backend/src/plugins/Utility/commands/HelpCmd.ts | 2 +- backend/src/plugins/Utility/functions/getServerInfoEmbed.ts | 2 +- backend/src/plugins/Utility/search.ts | 4 ++-- backend/src/utils/configAccessibleObjects.ts | 2 +- 17 files changed, 23 insertions(+), 25 deletions(-) diff --git a/backend/src/pluginUtils.ts b/backend/src/pluginUtils.ts index 733ba59a..14dcf85e 100644 --- a/backend/src/pluginUtils.ts +++ b/backend/src/pluginUtils.ts @@ -198,7 +198,7 @@ export async function sendSuccessMessage( return channel .send({ ...content }) // Force line break .catch(err => { - const channelInfo = channel.guild ? `${channel.id} (${channel.guild.id})` : `${channel.id}`; + const channelInfo = channel.guild ? `${channel.id} (${channel.guild.id})` : channel.id; logger.warn(`Failed to send success message to ${channelInfo}): ${err.code} ${err.message}`); return undefined; }); @@ -219,7 +219,7 @@ export async function sendErrorMessage( return channel .send({ ...content }) // Force line break .catch(err => { - const channelInfo = channel.guild ? `${channel.id} (${channel.guild.id})` : `${channel.id}`; + const channelInfo = channel.guild ? `${channel.id} (${channel.guild.id})` : channel.id; logger.warn(`Failed to send error message to ${channelInfo}): ${err.code} ${err.message}`); return undefined; }); diff --git a/backend/src/plugins/Cases/functions/createCase.ts b/backend/src/plugins/Cases/functions/createCase.ts index 5a03c1c2..9df38f26 100644 --- a/backend/src/plugins/Cases/functions/createCase.ts +++ b/backend/src/plugins/Cases/functions/createCase.ts @@ -7,15 +7,15 @@ import { postCaseToCaseLogChannel } from "./postToCaseLogChannel"; export async function createCase(pluginData: GuildPluginData, args: CaseArgs) { const user = await resolveUser(pluginData.client, args.userId); - const userName = `${user.tag}`; + const userName = user.tag; const mod = await resolveUser(pluginData.client, args.modId); - const modName = `${mod.tag}`; + const modName = mod.tag; let ppName: string | null = null; if (args.ppId) { const pp = await resolveUser(pluginData.client, args.ppId); - ppName = `${pp.tag}`; + ppName = pp.tag; } if (args.auditLogId) { diff --git a/backend/src/plugins/Cases/functions/createCaseNote.ts b/backend/src/plugins/Cases/functions/createCaseNote.ts index 2f9d801c..c03a5b3c 100644 --- a/backend/src/plugins/Cases/functions/createCaseNote.ts +++ b/backend/src/plugins/Cases/functions/createCaseNote.ts @@ -16,7 +16,7 @@ export async function createCaseNote(pluginData: GuildPluginData !c.is_hidden); const hiddenCases = cases.filter(c => c.is_hidden); - const userName = user instanceof UnknownUser && cases.length ? cases[cases.length - 1].user_name : `${user.tag}`; + const userName = user instanceof UnknownUser && cases.length ? cases[cases.length - 1].user_name : user.tag; if (cases.length === 0) { msg.channel.send(`No cases found for **${userName}**`); diff --git a/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts b/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts index b783fbbd..925d97c6 100644 --- a/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts +++ b/backend/src/plugins/ModActions/commands/DeleteCaseCmd.ts @@ -68,7 +68,7 @@ export const DeleteCaseCmd = modActionsCmd({ } } - const deletedByName = `${message.author.tag}`; + const deletedByName = message.author.tag; const timeAndDate = pluginData.getPlugin(TimeAndDatePlugin); const deletedAt = timeAndDate.inGuildTz().format(timeAndDate.getDateFormat("pretty_datetime")); diff --git a/backend/src/plugins/ModActions/commands/NoteCmd.ts b/backend/src/plugins/ModActions/commands/NoteCmd.ts index 0fbd1dbd..3ed21806 100644 --- a/backend/src/plugins/ModActions/commands/NoteCmd.ts +++ b/backend/src/plugins/ModActions/commands/NoteCmd.ts @@ -30,7 +30,7 @@ export const NoteCmd = modActionsCmd({ return; } - const userName = `${user.tag}`; + const userName = user.tag; const reason = formatReasonWithAttachments(args.note, msg.attachments.array()); const casesPlugin = pluginData.getPlugin(CasesPlugin); diff --git a/backend/src/plugins/Mutes/commands/MutesCmd.ts b/backend/src/plugins/Mutes/commands/MutesCmd.ts index 4ee88e74..5de51a3d 100644 --- a/backend/src/plugins/Mutes/commands/MutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/MutesCmd.ts @@ -119,7 +119,7 @@ export const MutesCmd = mutesCmd({ lines = filteredMutes.map(mute => { const user = pluginData.client.users.resolve(mute.user_id as Snowflake); - const username = user ? `${user.tag}` : "Unknown#0000"; + const username = user ? user.tag : "Unknown#0000"; const theCase = muteCasesById.get(mute.case_id); const caseName = theCase ? `Case #${theCase.case_number}` : "No case"; diff --git a/backend/src/plugins/NameHistory/commands/NamesCmd.ts b/backend/src/plugins/NameHistory/commands/NamesCmd.ts index 0ee42166..710e7ba6 100644 --- a/backend/src/plugins/NameHistory/commands/NamesCmd.ts +++ b/backend/src/plugins/NameHistory/commands/NamesCmd.ts @@ -30,8 +30,8 @@ export const NamesCmd = nameHistoryCmd({ ); const usernameRows = usernames.map(r => `\`[${r.timestamp}]\` **${disableCodeBlocks(r.username)}**`); - const user = await pluginData.client.users.fetch(args.userId as Snowflake); - const currentUsername = user ? `${user.tag}` : args.userId; + const user = await pluginData.client.users.fetch(args.userId as Snowflake).catch(() => null); + const currentUsername = user ? user.tag : args.userId; const nicknameDays = Math.round(NICKNAME_RETENTION_PERIOD / DAYS); const usernameDays = Math.round(NICKNAME_RETENTION_PERIOD / DAYS); diff --git a/backend/src/plugins/Post/util/actualPostCmd.ts b/backend/src/plugins/Post/util/actualPostCmd.ts index db8f51a4..54492c10 100644 --- a/backend/src/plugins/Post/util/actualPostCmd.ts +++ b/backend/src/plugins/Post/util/actualPostCmd.ts @@ -138,7 +138,7 @@ export async function actualPostCmd( await pluginData.state.scheduledPosts.create({ author_id: msg.author.id, - author_name: `${msg.author.tag}`, + author_name: msg.author.tag, channel_id: targetChannel.id, content, attachments: msg.attachments.array(), diff --git a/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts b/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts index a08e4579..3d7fb3d5 100644 --- a/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts +++ b/backend/src/plugins/ReactionRoles/events/ButtonInteractionEvt.ts @@ -17,10 +17,8 @@ export const ButtonInteractionEvt = reactionRolesEvt({ event: "interactionCreate", async listener(meta) { - const int = meta.args.interaction.isMessageComponent() - ? (meta.args.interaction as MessageComponentInteraction) - : null; - if (!int) return; + const int = meta.args.interaction; + if (!int.isMessageComponent()) return; const cfg = meta.pluginData.config.get(); const split = int.customId.split(BUTTON_CONTEXT_SEPARATOR); diff --git a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts index e1fe0aed..dc6e8781 100644 --- a/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts +++ b/backend/src/plugins/Starboard/util/createStarboardEmbedFromMessage.ts @@ -18,7 +18,7 @@ export function createStarboardEmbedFromMessage( text: `#${(msg.channel as GuildChannel).name}`, }, author: { - name: `${msg.author.tag}`, + name: msg.author.tag, }, fields: [], timestamp: msg.createdTimestamp, diff --git a/backend/src/plugins/UsernameSaver/updateUsername.ts b/backend/src/plugins/UsernameSaver/updateUsername.ts index baaa3bd1..207e6540 100644 --- a/backend/src/plugins/UsernameSaver/updateUsername.ts +++ b/backend/src/plugins/UsernameSaver/updateUsername.ts @@ -4,7 +4,7 @@ import { UsernameSaverPluginType } from "./types"; export async function updateUsername(pluginData: GuildPluginData, user: User) { if (!user) return; - const newUsername = `${user.tag}`; + const newUsername = user.tag; const latestEntry = await pluginData.state.usernameHistory.getLastEntry(user.id); if (!latestEntry || newUsername !== latestEntry.username) { await pluginData.state.usernameHistory.addEntry(user.id, newUsername); diff --git a/backend/src/plugins/Utility/commands/HelpCmd.ts b/backend/src/plugins/Utility/commands/HelpCmd.ts index d53f19b4..112e932e 100644 --- a/backend/src/plugins/Utility/commands/HelpCmd.ts +++ b/backend/src/plugins/Utility/commands/HelpCmd.ts @@ -80,7 +80,7 @@ export const HelpCmd = utilityCmd({ ? `Results (${totalResults} total, showing first ${limitedResults.length}):\n\n` : ""; - message += `${commandSnippets.join("\n\n")}`; + message += commandSnippets.join("\n\n"); createChunkedMessage(msg.channel, message); }, }); diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index 93b4d45e..13e0652f 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -65,7 +65,7 @@ export async function getServerInfoEmbed( if (thisServer) { const owner = await resolveUser(pluginData.client, thisServer.ownerId); - const ownerName = `${owner.tag}`; + const ownerName = owner.tag; basicInformation.push(`Owner: **${ownerName}** (\`${thisServer.ownerId}\`)`); // basicInformation.push(`Voice region: **${thisServer.region}**`); Outdated, as automatic voice regions are fully live diff --git a/backend/src/plugins/Utility/search.ts b/backend/src/plugins/Utility/search.ts index 97bc1bd4..45f77cd4 100644 --- a/backend/src/plugins/Utility/search.ts +++ b/backend/src/plugins/Utility/search.ts @@ -391,7 +391,7 @@ async function performMemberSearch( return true; } - const fullUsername = `${member.user.tag}`; + const fullUsername = member.user.tag; if (await execRegExp(queryRegex, fullUsername).catch(allowTimeout)) return true; return false; @@ -458,7 +458,7 @@ async function performBanSearch( const execRegExp = getOptimizedRegExpRunner(pluginData, isSafeRegex); matchingBans = await asyncFilter(matchingBans, async user => { - const fullUsername = `${user.tag}`; + const fullUsername = user.tag; if (await execRegExp(queryRegex, fullUsername).catch(allowTimeout)) return true; return false; }); diff --git a/backend/src/utils/configAccessibleObjects.ts b/backend/src/utils/configAccessibleObjects.ts index 14f13fec..379aaea0 100644 --- a/backend/src/utils/configAccessibleObjects.ts +++ b/backend/src/utils/configAccessibleObjects.ts @@ -40,7 +40,7 @@ export interface IConfigAccessibleMember extends IConfigAccessibleUser { } export function userToConfigAccessibleUser(user: User | UnknownUser): IConfigAccessibleUser { - if (`${user.tag}` === "Unknown#0000") { + if (user.tag === "Unknown#0000") { const toReturnPartial: IConfigAccessibleUser = { id: user.id, username: "Unknown", From e12f37bb6acafe6f58b1afb7c29bbe9316488c72 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 10:26:05 +0100 Subject: [PATCH 29/40] show created timestamp and sticker info on server info --- backend/src/plugins/Utility/functions/getServerInfoEmbed.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index 13e0652f..753d4d7c 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -1,4 +1,4 @@ -import { CategoryChannel, MessageEmbedOptions, Snowflake, TextChannel, VoiceChannel } from "discord.js"; +import { CategoryChannel, MessageEmbedOptions, Snowflake, SnowflakeUtil, TextChannel, VoiceChannel } from "discord.js"; import humanizeDuration from "humanize-duration"; import { GuildPluginData } from "knub"; import moment from "moment-timezone"; @@ -50,7 +50,7 @@ export async function getServerInfoEmbed( // BASIC INFORMATION const timeAndDate = pluginData.getPlugin(TimeAndDatePlugin); - const createdAt = moment.utc((guildPreview || restGuild)!.id, "x"); // FIXME ID -> Timestamp + const createdAt = moment.utc(SnowflakeUtil.deconstruct((guildPreview || restGuild)!.id).timestamp, "x"); const tzCreatedAt = requestMemberId ? await timeAndDate.inMemberTz(requestMemberId, createdAt) : timeAndDate.inGuildTz(createdAt); @@ -194,7 +194,7 @@ export async function getServerInfoEmbed( }[restGuild.premiumTier] || 0; otherStats.push(`Emojis: **${restGuild.emojis.cache.size}** / ${maxEmojis * 2}`); - otherStats.push(`Stickers: ? / ${maxStickers}`); // Wait on DJS: **${restGuild.stickers.cache.size}** + otherStats.push(`Stickers: **${restGuild.stickers.cache.size}** / ${maxStickers}`); } else { otherStats.push(`Emojis: **${guildPreview!.emojis.size}**`); // otherStats.push(`Stickers: **${guildPreview!.stickers.size}**`); Wait on DJS From f4b4747d086bd831f8d9c20384e953f32ab39e71 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 10:47:47 +0100 Subject: [PATCH 30/40] simplified --- backend/src/plugins/Utility/functions/getUserInfoEmbed.ts | 4 ++-- backend/src/plugins/Utility/search.ts | 8 +------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts b/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts index 4f87dabc..78970a0e 100644 --- a/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getUserInfoEmbed.ts @@ -103,7 +103,7 @@ export async function getUserInfoEmbed( }); const roles = member.roles.cache .map(role => pluginData.guild.roles.cache.get(role.id)) - .filter(r => r != null) as Role[]; + .filter((r): r is Role => !!r); roles.sort(sorter("position", "DESC")); embed.fields.push({ @@ -119,7 +119,7 @@ export async function getUserInfoEmbed( embed.fields.push({ name: preEmbedPadding + "Voice information", value: trimLines(` - ${voiceChannel ? `Current voice channel: **${voiceChannel ? voiceChannel.name : "None"}**` : ""} + ${voiceChannel ? `Current voice channel: **${voiceChannel.name ?? "None"}**` : ""} ${member.voice.mute ? "Server voice muted: **Yes**" : ""} ${member.voice.deaf ? "Server voice deafened: **Yes**" : ""} `), diff --git a/backend/src/plugins/Utility/search.ts b/backend/src/plugins/Utility/search.ts index 45f77cd4..788eadc7 100644 --- a/backend/src/plugins/Utility/search.ts +++ b/backend/src/plugins/Utility/search.ts @@ -177,17 +177,11 @@ export async function displaySearch( .setEmoji("⬅") .setCustomId(`previousButton:${idMod}`) .setDisabled(currentPage === 1), - ); - - buttons.push( new MessageButton() .setStyle("SECONDARY") .setEmoji("➡") .setCustomId(`nextButton:${idMod}`) .setDisabled(currentPage === searchResult.lastPage), - ); - - buttons.push( new MessageButton() .setStyle("SECONDARY") .setEmoji("🔄") @@ -325,7 +319,7 @@ async function performMemberSearch( } if (args.voice) { - matchingMembers = matchingMembers.filter(m => m.voice.channelId != null); + matchingMembers = matchingMembers.filter(m => m.voice.channelId); } if (args.bot) { From afab564628b28ec4ab59a0b0fad3df6847cacff4 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 13:00:32 +0100 Subject: [PATCH 31/40] remove camelcase permission stuff --- backend/src/utils/getPermissionNames.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/backend/src/utils/getPermissionNames.ts b/backend/src/utils/getPermissionNames.ts index 47202c96..bc05ee64 100644 --- a/backend/src/utils/getPermissionNames.ts +++ b/backend/src/utils/getPermissionNames.ts @@ -1,18 +1,11 @@ import { Permissions } from "discord.js"; -const camelCaseToTitleCase = str => - str - .replace(/([a-z])([A-Z])/g, "$1 $2") - .split(" ") - .map(w => w[0].toUpperCase() + w.slice(1)) - .join(" "); - const permissionNumberToName: Map = new Map(); const ignoredPermissionConstants = ["all", "allGuild", "allText", "allVoice"]; for (const key in Permissions.FLAGS) { if (ignoredPermissionConstants.includes(key)) continue; - permissionNumberToName.set(BigInt(Permissions.FLAGS[key]), camelCaseToTitleCase(key)); + permissionNumberToName.set(BigInt(Permissions.FLAGS[key]), key); } /** From 71cc3176f683a7cead6d346ffd14a7a2bb920d95 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 13:14:45 +0100 Subject: [PATCH 32/40] Use SnowflakeUtil.deconstruct --- backend/src/utils/idToTimestamp.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/backend/src/utils/idToTimestamp.ts b/backend/src/utils/idToTimestamp.ts index 62dd4743..10b964a5 100644 --- a/backend/src/utils/idToTimestamp.ts +++ b/backend/src/utils/idToTimestamp.ts @@ -1,10 +1,6 @@ -import moment from "moment"; - -const EPOCH = 1420070400000; +import { Snowflake, SnowflakeUtil } from "discord.js"; export function idToTimestamp(id: string) { if (typeof id === "number") return null; - return moment(+id / 4194304 + EPOCH) - .utc() - .valueOf(); + return SnowflakeUtil.deconstruct(id as Snowflake).timestamp; } From 72893e7f7d441157be89e83034df863955644570 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 16:34:11 +0100 Subject: [PATCH 33/40] fix autojoin threads --- backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts b/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts index 84c36768..7dddcedf 100644 --- a/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts +++ b/backend/src/plugins/Utility/events/AutoJoinThreadEvt.ts @@ -16,7 +16,7 @@ export const AutoJoinThreadSyncEvt = utilityEvt({ async listener(meta) { const config = meta.pluginData.config.get(); - if (config.autojoin_threads) return; + if (!config.autojoin_threads) return; for (const thread of meta.args.threads.values()) { if (!thread.joined && thread.joinable) { await thread.join(); From 35bf6e5b82a1b2ee3c7ce36c7b017e2308efc68a Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 16:36:00 +0100 Subject: [PATCH 34/40] use idToTimestamp method --- backend/src/plugins/Utility/functions/getServerInfoEmbed.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index 753d4d7c..89e601fe 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -1,4 +1,4 @@ -import { CategoryChannel, MessageEmbedOptions, Snowflake, SnowflakeUtil, TextChannel, VoiceChannel } from "discord.js"; +import { CategoryChannel, MessageEmbedOptions, Snowflake, TextChannel, VoiceChannel } from "discord.js"; import humanizeDuration from "humanize-duration"; import { GuildPluginData } from "knub"; import moment from "moment-timezone"; @@ -13,6 +13,7 @@ import { resolveUser, trimLines, } from "../../../utils"; +import { idToTimestamp } from "../../../utils/idToTimestamp"; import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin"; import { UtilityPluginType } from "../types"; import { getGuildPreview } from "./getGuildPreview"; @@ -50,7 +51,7 @@ export async function getServerInfoEmbed( // BASIC INFORMATION const timeAndDate = pluginData.getPlugin(TimeAndDatePlugin); - const createdAt = moment.utc(SnowflakeUtil.deconstruct((guildPreview || restGuild)!.id).timestamp, "x"); + const createdAt = moment.utc(idToTimestamp((guildPreview || restGuild)!.id)!, "x"); const tzCreatedAt = requestMemberId ? await timeAndDate.inMemberTz(requestMemberId, createdAt) : timeAndDate.inGuildTz(createdAt); From 5fad488a635b0045d5d8cf2c1bcfb7175f02cb37 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 17:18:49 +0100 Subject: [PATCH 35/40] changes to serverinfo and fixes in utils --- .../Utility/functions/getServerInfoEmbed.ts | 20 +++++++++---------- backend/src/utils.ts | 11 +++++----- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts index 89e601fe..a0922399 100644 --- a/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getServerInfoEmbed.ts @@ -1,7 +1,8 @@ -import { CategoryChannel, MessageEmbedOptions, Snowflake, TextChannel, VoiceChannel } from "discord.js"; +import { MessageEmbedOptions, Snowflake } from "discord.js"; import humanizeDuration from "humanize-duration"; import { GuildPluginData } from "knub"; import moment from "moment-timezone"; +import { ChannelTypeStrings } from "../../../types"; import { EmbedWith, formatNumber, @@ -82,12 +83,11 @@ export async function getServerInfoEmbed( }); // IMAGE LINKS - const iconUrl = `[Link](${(restGuild || guildPreview)!.iconURL()})`; - const bannerUrl = restGuild?.bannerURL() ? `[Link](${restGuild.bannerURL()})` : "None"; - const splashUrl = - (restGuild || guildPreview)!.splashURL() != null - ? `[Link](${(restGuild || guildPreview)!.splashURL()?.replace("size=128", "size=2048")})` - : "None"; + const iconUrl = `[Link](${(restGuild || guildPreview)!.iconURL({ dynamic: true, format: "png", size: 2048 })})`; + const bannerUrl = restGuild?.banner ? `[Link](${restGuild.bannerURL({ format: "png", size: 2048 })})` : "None"; + const splashUrl = (restGuild || guildPreview)!.splash + ? `[Link](${(restGuild || guildPreview)!.splashURL({ format: "png", size: 2048 })})` + : "None"; embed.fields.push( { @@ -155,9 +155,9 @@ export async function getServerInfoEmbed( // CHANNEL COUNTS if (thisServer) { const totalChannels = thisServer.channels.cache.size; - const categories = thisServer.channels.cache.filter(channel => channel instanceof CategoryChannel); - const textChannels = thisServer.channels.cache.filter(channel => channel instanceof TextChannel); - const voiceChannels = thisServer.channels.cache.filter(channel => channel instanceof VoiceChannel); + const categories = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.CATEGORY); + const textChannels = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.TEXT); + const voiceChannels = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.VOICE); embed.fields.push({ name: preEmbedPadding + "Channels", diff --git a/backend/src/utils.ts b/backend/src/utils.ts index 350fd830..a2ea3005 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -1282,7 +1282,7 @@ export async function resolveRoleId(bot: Client, guildId: string, value: string) } // Role name - const roleList = await (await bot.guilds.fetch(guildId as Snowflake)).roles.cache; + const roleList = (await bot.guilds.fetch(guildId as Snowflake)).roles.cache; const role = roleList.filter(x => x.name.toLocaleLowerCase() === value.toLocaleLowerCase()); if (role[0]) { return role[0].id; @@ -1310,7 +1310,6 @@ export async function resolveInvite( return inviteCache.get(key) as ResolveInviteReturnType; } - // @ts-ignore: the getInvite() withCounts typings are blergh const promise = client.fetchInvite(code).catch(() => null); inviteCache.set(key, promise); @@ -1319,12 +1318,14 @@ export async function resolveInvite( const internalStickerCache: LimitedCollection = new LimitedCollection(500); -export async function resolveStickerId(bot: Client, id: Snowflake): Promise { +export async function resolveStickerId(bot: Client, id: Snowflake): Promise { const cachedSticker = internalStickerCache.get(id); if (cachedSticker) return cachedSticker; - const fetchedSticker = await bot.fetchSticker(id).catch(undefined); - internalStickerCache.set(id, fetchedSticker); + const fetchedSticker = await bot.fetchSticker(id).catch(() => null); + if (fetchedSticker) { + internalStickerCache.set(id, fetchedSticker); + } return fetchedSticker; } From 5e91a9fed361885d559a2ba3e7dc67953a3ac6be Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 17:24:53 +0100 Subject: [PATCH 36/40] removed unnecessary collector filters --- backend/src/plugins/Mutes/commands/MutesCmd.ts | 6 +----- backend/src/plugins/Utility/search.ts | 3 +-- backend/src/utils/waitForInteraction.ts | 3 +-- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/backend/src/plugins/Mutes/commands/MutesCmd.ts b/backend/src/plugins/Mutes/commands/MutesCmd.ts index 5de51a3d..99356e54 100644 --- a/backend/src/plugins/Mutes/commands/MutesCmd.ts +++ b/backend/src/plugins/Mutes/commands/MutesCmd.ts @@ -214,11 +214,7 @@ export const MutesCmd = mutesCmd({ const row = new MessageActionRow().addComponents(buttons); await listMessage.edit({ components: [row] }); - const filter = (iac: MessageComponentInteraction) => iac.message.id === listMessage.id; - const collector = listMessage.createMessageComponentCollector({ - filter, - time: stopCollectionDebounce, - }); + const collector = listMessage.createMessageComponentCollector({ time: stopCollectionDebounce }); collector.on("collect", async (interaction: MessageComponentInteraction) => { if (msg.author.id !== interaction.user.id) { diff --git a/backend/src/plugins/Utility/search.ts b/backend/src/plugins/Utility/search.ts index 788eadc7..4717dd31 100644 --- a/backend/src/plugins/Utility/search.ts +++ b/backend/src/plugins/Utility/search.ts @@ -191,8 +191,7 @@ export async function displaySearch( const row = new MessageActionRow().addComponents(buttons); await searchMsg.edit({ content: result, components: [row] }); - const filter = (iac: MessageComponentInteraction) => iac.message.id === searchMsg.id; - const collector = searchMsg.createMessageComponentCollector({ filter, time: 2 * MINUTES }); + const collector = searchMsg.createMessageComponentCollector({ time: 2 * MINUTES }); collector.on("collect", async (interaction: MessageComponentInteraction) => { if (msg.author.id !== interaction.user.id) { diff --git a/backend/src/utils/waitForInteraction.ts b/backend/src/utils/waitForInteraction.ts index f984cdd4..afc3641f 100644 --- a/backend/src/utils/waitForInteraction.ts +++ b/backend/src/utils/waitForInteraction.ts @@ -22,8 +22,7 @@ export async function waitForButtonConfirm( ]); const message = await channel.send({ ...toPost, components: [row] }); - const filter = (iac: MessageComponentInteraction) => iac.message.id === message.id; - const collector = message.createMessageComponentCollector({ filter, time: 10000 }); + const collector = message.createMessageComponentCollector({ time: 10000 }); collector.on("collect", (interaction: MessageComponentInteraction) => { if (options?.restrictToId && options.restrictToId !== interaction.user.id) { From 5de35f711d7b83e74f8aa4ecc66b22380b660ec3 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 17:35:27 +0100 Subject: [PATCH 37/40] use Util methods for escaping inline code and code blocks --- backend/src/commandTypes.ts | 18 ++++++++--------- .../Automod/triggers/matchAttachmentType.ts | 6 +++--- .../plugins/Automod/triggers/matchLinks.ts | 5 +++-- .../plugins/Automod/triggers/matchRegex.ts | 4 ++-- .../plugins/Automod/triggers/matchWords.ts | 4 ++-- backend/src/plugins/Logs/LogsPlugin.ts | 4 ++-- .../Post/commands/ScheduledPostsListCmd.ts | 14 ++++--------- .../Slowmode/commands/SlowmodeClearCmd.ts | 5 +++-- .../Slowmode/commands/SlowmodeSetCmd.ts | 6 +++--- .../TimeAndDate/commands/SetTimezoneCmd.ts | 5 +++-- backend/src/utils.ts | 20 +++---------------- 11 files changed, 36 insertions(+), 55 deletions(-) diff --git a/backend/src/commandTypes.ts b/backend/src/commandTypes.ts index 29a69d11..e3f1ece3 100644 --- a/backend/src/commandTypes.ts +++ b/backend/src/commandTypes.ts @@ -1,11 +1,9 @@ -import { GuildChannel, GuildMember, Snowflake, User } from "discord.js"; +import { GuildChannel, GuildMember, Snowflake, Util, User } from "discord.js"; import { baseCommandParameterTypeHelpers, baseTypeConverters, CommandContext, TypeConversionError } from "knub"; import { createTypeHelper } from "knub-command-manager"; import { channelMentionRegex, convertDelayStringToMS, - disableCodeBlocks, - disableInlineCode, isValidSnowflake, resolveMember, resolveUser, @@ -32,7 +30,7 @@ export const commandTypes = { async resolvedUser(value, context: CommandContext) { const result = await resolveUser(context.pluginData.client, value); if (result == null || result instanceof UnknownUser) { - throw new TypeConversionError(`User \`${disableCodeBlocks(value)}\` was not found`); + throw new TypeConversionError(`User \`${Util.escapeCodeBlock(value)}\` was not found`); } return result; }, @@ -40,7 +38,7 @@ export const commandTypes = { async resolvedUserLoose(value, context: CommandContext) { const result = await resolveUser(context.pluginData.client, value); if (result == null) { - throw new TypeConversionError(`Invalid user: \`${disableCodeBlocks(value)}\``); + throw new TypeConversionError(`Invalid user: \`${Util.escapeCodeBlock(value)}\``); } return result; }, @@ -53,7 +51,7 @@ export const commandTypes = { const result = await resolveMember(context.pluginData.client, context.message.channel.guild, value); if (result == null) { throw new TypeConversionError( - `Member \`${disableCodeBlocks(value)}\` was not found or they have left the server`, + `Member \`${Util.escapeCodeBlock(value)}\` was not found or they have left the server`, ); } return result; @@ -64,7 +62,7 @@ export const commandTypes = { const result = await resolveMessageTarget(context.pluginData, value); if (!result) { - throw new TypeConversionError(`Unknown message \`${disableInlineCode(value)}\``); + throw new TypeConversionError(`Unknown message \`${Util.escapeInlineCode(value)}\``); } return result; @@ -84,20 +82,20 @@ export const commandTypes = { return value as Snowflake; } - throw new TypeConversionError(`Could not parse ID: \`${disableInlineCode(value)}\``); + throw new TypeConversionError(`Could not parse ID: \`${Util.escapeInlineCode(value)}\``); }, regex(value: string, context: CommandContext): RegExp { try { return inputPatternToRegExp(value); } catch (e) { - throw new TypeConversionError(`Could not parse RegExp: \`${disableInlineCode(e.message)}\``); + throw new TypeConversionError(`Could not parse RegExp: \`${Util.escapeInlineCode(e.message)}\``); } }, timezone(value: string) { if (!isValidTimezone(value)) { - throw new TypeConversionError(`Invalid timezone: ${disableInlineCode(value)}`); + throw new TypeConversionError(`Invalid timezone: ${Util.escapeInlineCode(value)}`); } return value; diff --git a/backend/src/plugins/Automod/triggers/matchAttachmentType.ts b/backend/src/plugins/Automod/triggers/matchAttachmentType.ts index d69cc9a8..ba8e4e59 100644 --- a/backend/src/plugins/Automod/triggers/matchAttachmentType.ts +++ b/backend/src/plugins/Automod/triggers/matchAttachmentType.ts @@ -1,6 +1,6 @@ -import { Snowflake, TextChannel } from "discord.js"; +import { Snowflake, TextChannel, Util } from "discord.js"; import * as t from "io-ts"; -import { asSingleLine, disableInlineCode, messageSummary, verboseChannelMention } from "../../../utils"; +import { asSingleLine, messageSummary, verboseChannelMention } from "../../../utils"; import { automodTrigger } from "../helpers"; interface MatchResultType { @@ -73,7 +73,7 @@ export const MatchAttachmentTypeTrigger = automodTrigger()({ return ( asSingleLine(` - Matched attachment type \`${disableInlineCode(matchResult.extra.matchedType)}\` + Matched attachment type \`${Util.escapeInlineCode(matchResult.extra.matchedType)}\` (${matchResult.extra.mode === "blacklist" ? "(blacklisted)" : "(not in whitelist)"}) in message (\`${contexts[0].message!.id}\`) in ${prettyChannel}: `) + messageSummary(contexts[0].message!) diff --git a/backend/src/plugins/Automod/triggers/matchLinks.ts b/backend/src/plugins/Automod/triggers/matchLinks.ts index 193a184c..2c70387c 100644 --- a/backend/src/plugins/Automod/triggers/matchLinks.ts +++ b/backend/src/plugins/Automod/triggers/matchLinks.ts @@ -1,7 +1,8 @@ +import { Util } from "discord.js"; import escapeStringRegexp from "escape-string-regexp"; import * as t from "io-ts"; import { allowTimeout } from "../../../RegExpRunner"; -import { disableInlineCode, getUrlsInString, tNullable } from "../../../utils"; +import { getUrlsInString, tNullable } from "../../../utils"; import { TRegex } from "../../../validatorUtils"; import { getTextMatchPartialSummary } from "../functions/getTextMatchPartialSummary"; import { MatchableTextType, matchMultipleTextTypesOnMessage } from "../functions/matchMultipleTextTypesOnMessage"; @@ -129,6 +130,6 @@ export const MatchLinksTrigger = automodTrigger()({ renderMatchInformation({ pluginData, contexts, matchResult }) { const partialSummary = getTextMatchPartialSummary(pluginData, matchResult.extra.type, contexts[0]); - return `Matched link \`${disableInlineCode(matchResult.extra.link)}\` in ${partialSummary}`; + return `Matched link \`${Util.escapeInlineCode(matchResult.extra.link)}\` in ${partialSummary}`; }, }); diff --git a/backend/src/plugins/Automod/triggers/matchRegex.ts b/backend/src/plugins/Automod/triggers/matchRegex.ts index 5d585f08..3e0b2e38 100644 --- a/backend/src/plugins/Automod/triggers/matchRegex.ts +++ b/backend/src/plugins/Automod/triggers/matchRegex.ts @@ -1,6 +1,6 @@ +import { Util } from "discord.js"; import * as t from "io-ts"; import { allowTimeout } from "../../../RegExpRunner"; -import { disableInlineCode } from "../../../utils"; import { normalizeText } from "../../../utils/normalizeText"; import { stripMarkdown } from "../../../utils/stripMarkdown"; import { TRegex } from "../../../validatorUtils"; @@ -72,6 +72,6 @@ export const MatchRegexTrigger = automodTrigger()({ renderMatchInformation({ pluginData, contexts, matchResult }) { const partialSummary = getTextMatchPartialSummary(pluginData, matchResult.extra.type, contexts[0]); - return `Matched regex \`${disableInlineCode(matchResult.extra.pattern)}\` in ${partialSummary}`; + return `Matched regex \`${Util.escapeInlineCode(matchResult.extra.pattern)}\` in ${partialSummary}`; }, }); diff --git a/backend/src/plugins/Automod/triggers/matchWords.ts b/backend/src/plugins/Automod/triggers/matchWords.ts index 2a011546..387f2208 100644 --- a/backend/src/plugins/Automod/triggers/matchWords.ts +++ b/backend/src/plugins/Automod/triggers/matchWords.ts @@ -1,6 +1,6 @@ +import { Util } from "discord.js"; import escapeStringRegexp from "escape-string-regexp"; import * as t from "io-ts"; -import { disableInlineCode } from "../../../utils"; import { normalizeText } from "../../../utils/normalizeText"; import { stripMarkdown } from "../../../utils/stripMarkdown"; import { getTextMatchPartialSummary } from "../functions/getTextMatchPartialSummary"; @@ -89,6 +89,6 @@ export const MatchWordsTrigger = automodTrigger()({ renderMatchInformation({ pluginData, contexts, matchResult }) { const partialSummary = getTextMatchPartialSummary(pluginData, matchResult.extra.type, contexts[0]); - return `Matched word \`${disableInlineCode(matchResult.extra.word)}\` in ${partialSummary}`; + return `Matched word \`${Util.escapeInlineCode(matchResult.extra.word)}\` in ${partialSummary}`; }, }); diff --git a/backend/src/plugins/Logs/LogsPlugin.ts b/backend/src/plugins/Logs/LogsPlugin.ts index e61d0857..d4285de8 100644 --- a/backend/src/plugins/Logs/LogsPlugin.ts +++ b/backend/src/plugins/Logs/LogsPlugin.ts @@ -7,7 +7,6 @@ import { GuildSavedMessages } from "../../data/GuildSavedMessages"; import { LogType } from "../../data/LogType"; import { logger } from "../../logger"; import { discardRegExpRunner, getRegExpRunner } from "../../regExpRunners"; -import { disableCodeBlocks } from "../../utils"; import { CasesPlugin } from "../Cases/CasesPlugin"; import { TimeAndDatePlugin } from "../TimeAndDate/TimeAndDatePlugin"; import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint"; @@ -37,6 +36,7 @@ import { log } from "./util/log"; import { onMessageDelete } from "./util/onMessageDelete"; import { onMessageDeleteBulk } from "./util/onMessageDeleteBulk"; import { onMessageUpdate } from "./util/onMessageUpdate"; +import { Util } from "discord.js"; const defaultOptions: PluginOptions = { config: { @@ -147,7 +147,7 @@ export const LogsPlugin = zeppelinGuildPlugin()({ The following regex has taken longer than ${timeoutMs}ms for ${failedTimes} times and has been temporarily disabled: `.trim() + "\n```" + - disableCodeBlocks(regexSource) + + Util.escapeCodeBlock(regexSource) + "```", }); }; diff --git a/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts b/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts index 65e76041..7ac59698 100644 --- a/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts +++ b/backend/src/plugins/Post/commands/ScheduledPostsListCmd.ts @@ -1,13 +1,7 @@ +import { Util } from "discord.js"; import humanizeDuration from "humanize-duration"; import moment from "moment-timezone"; -import { - createChunkedMessage, - DBDateFormat, - deactivateMentions, - disableCodeBlocks, - sorter, - trimLines, -} from "../../../utils"; +import { createChunkedMessage, DBDateFormat, deactivateMentions, sorter, trimLines } from "../../../utils"; import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin"; import { postCmd } from "../types"; @@ -33,7 +27,7 @@ export const ScheduledPostsListCmd = postCmd({ const isTruncated = previewText.length > SCHEDULED_POST_PREVIEW_TEXT_LENGTH; - previewText = disableCodeBlocks(deactivateMentions(previewText)) + previewText = Util.escapeCodeBlock(deactivateMentions(previewText)) .replace(/\s+/g, " ") .slice(0, SCHEDULED_POST_PREVIEW_TEXT_LENGTH); @@ -61,7 +55,7 @@ export const ScheduledPostsListCmd = postCmd({ const finalMessage = trimLines(` ${postLines.join("\n")} - + Use \`scheduled_posts \` to view a scheduled post in full Use \`scheduled_posts delete \` to delete a scheduled post `); diff --git a/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts b/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts index 75835e6b..c9a31ddd 100644 --- a/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts +++ b/backend/src/plugins/Slowmode/commands/SlowmodeClearCmd.ts @@ -1,7 +1,8 @@ +import { Util } from "discord.js"; import { ChannelTypeStrings } from "src/types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; -import { asSingleLine, disableInlineCode } from "../../../utils"; +import { asSingleLine } from "../../../utils"; import { getMissingChannelPermissions } from "../../../utils/getMissingChannelPermissions"; import { missingPermissionError } from "../../../utils/missingPermissionError"; import { BOT_SLOWMODE_CLEAR_PERMISSIONS } from "../requiredPermissions"; @@ -57,7 +58,7 @@ export const SlowmodeClearCmd = slowmodeCmd({ msg.channel, asSingleLine(` Failed to clear slowmode from **${args.user.tag}** in <#${args.channel.id}>: - \`${disableInlineCode(e.message)}\` + \`${Util.escapeInlineCode(e.message)}\` `), ); return; diff --git a/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts b/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts index 22bc74d7..3b316c6f 100644 --- a/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts +++ b/backend/src/plugins/Slowmode/commands/SlowmodeSetCmd.ts @@ -1,9 +1,9 @@ -import { Permissions, TextChannel, ThreadChannel } from "discord.js"; +import { Permissions, TextChannel, ThreadChannel, Util } from "discord.js"; import humanizeDuration from "humanize-duration"; import { ChannelTypeStrings } from "src/types"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; -import { asSingleLine, DAYS, disableInlineCode, HOURS, MINUTES } from "../../../utils"; +import { asSingleLine, DAYS, HOURS, MINUTES } from "../../../utils"; import { getMissingPermissions } from "../../../utils/getMissingPermissions"; import { missingPermissionError } from "../../../utils/missingPermissionError"; import { BOT_SLOWMODE_PERMISSIONS, NATIVE_SLOWMODE_PERMISSIONS } from "../requiredPermissions"; @@ -133,7 +133,7 @@ export const SlowmodeSetCmd = slowmodeCmd({ rateLimitPerUser: rateLimitSeconds, }); } catch (e) { - sendErrorMessage(pluginData, msg.channel, `Failed to set native slowmode: ${disableInlineCode(e.message)}`); + sendErrorMessage(pluginData, msg.channel, `Failed to set native slowmode: ${Util.escapeInlineCode(e.message)}`); return; } } else { diff --git a/backend/src/plugins/TimeAndDate/commands/SetTimezoneCmd.ts b/backend/src/plugins/TimeAndDate/commands/SetTimezoneCmd.ts index 1786bd34..d88a0740 100644 --- a/backend/src/plugins/TimeAndDate/commands/SetTimezoneCmd.ts +++ b/backend/src/plugins/TimeAndDate/commands/SetTimezoneCmd.ts @@ -1,6 +1,7 @@ +import { Util } from "discord.js"; import { commandTypeHelpers as ct } from "../../../commandTypes"; import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; -import { disableInlineCode, trimLines } from "../../../utils"; +import { trimLines } from "../../../utils"; import { parseFuzzyTimezone } from "../../../utils/parseFuzzyTimezone"; import { timeAndDateCmd } from "../types"; @@ -19,7 +20,7 @@ export const SetTimezoneCmd = timeAndDateCmd({ pluginData, message.channel, trimLines(` - Invalid timezone: \`${disableInlineCode(args.timezone)}\` + Invalid timezone: \`${Util.escapeInlineCode(args.timezone)}\` Zeppelin uses timezone locations rather than specific timezone names. See the **TZ database name** column at for a list of valid options. `), diff --git a/backend/src/utils.ts b/backend/src/utils.ts index a2ea3005..a3dcec39 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -22,6 +22,7 @@ import { TextChannel, ThreadChannel, User, + Util, } from "discord.js"; import emojiRegex from "emoji-regex"; import { either } from "fp-ts/lib/Either"; @@ -785,21 +786,6 @@ export function deactivateMentions(content: string): string { return content.replace(/@/g, "@\u200b"); } -/** - * Disable inline code in the given string by replacing backticks/grave accents with acute accents - * FIXME: Find a better way that keeps the grave accents? Can't use the code block approach here since it's just 1 character. - */ -export function disableInlineCode(content: string): string { - return content.replace(/`/g, "\u00b4"); -} - -/** - * Disable code blocks in the given string by adding invisible unicode characters between backticks - */ -export function disableCodeBlocks(content: string): string { - return content.replace(/`/g, "`\u200b"); -} - export function useMediaUrls(content: string): string { return content.replace(/cdn\.discord(app)?\.com/g, "media.discordapp.net"); } @@ -1336,11 +1322,11 @@ export async function confirm(channel: TextChannel, userId: string, content: Mes export function messageSummary(msg: SavedMessage) { // Regular text content - let result = "```\n" + (msg.data.content ? disableCodeBlocks(msg.data.content) : "") + "```"; + let result = "```\n" + (msg.data.content ? Util.escapeCodeBlock(msg.data.content) : "") + "```"; // Rich embed const richEmbed = (msg.data.embeds || []).find(e => (e as MessageEmbed).type === "rich"); - if (richEmbed) result += "Embed:```" + disableCodeBlocks(JSON.stringify(richEmbed)) + "```"; + if (richEmbed) result += "Embed:```" + Util.escapeCodeBlock(JSON.stringify(richEmbed)) + "```"; // Attachments if (msg.data.attachments) { From b5ea866e62ff6a3166576b7d7789f11e0d2a9410 Mon Sep 17 00:00:00 2001 From: almeidx Date: Thu, 29 Jul 2021 17:45:45 +0100 Subject: [PATCH 38/40] upgraded discord.js --- backend/package-lock.json | 14 +++++++------- backend/package.json | 2 +- .../plugins/Slowmode/commands/SlowmodeGetCmd.ts | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/backend/package-lock.json b/backend/package-lock.json index ad535f14..bbc5e4e7 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -14,7 +14,7 @@ "cors": "^2.8.5", "cross-env": "^5.2.0", "deep-diff": "^1.0.2", - "discord.js": "^13.0.0-dev.4886ae2.1627214570", + "discord.js": "^13.0.0-dev.d310e4f.1627560163", "dotenv": "^4.0.0", "emoji-regex": "^8.0.0", "erlpack": "github:discord/erlpack", @@ -2159,9 +2159,9 @@ } }, "node_modules/discord.js": { - "version": "13.0.0-dev.4886ae2.1627214570", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.4886ae2.1627214570.tgz", - "integrity": "sha512-9eqVCQyqqSHJcR1nki9NlaTD7FjvfkjJt8zcmF5wcCs/7P9v27UrPYg9yxvghswDvDhz9ojotYGGcpK7tSypmA==", + "version": "13.0.0-dev.d310e4f.1627560163", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.d310e4f.1627560163.tgz", + "integrity": "sha512-qJmQrG4xCnBqYF/WQIOxl4IWY3gYAwK0UyNOAKhRpHzMXYHX99wx3FcGaYrZiqtXxGbN2lgVanBakKNsq/uYYw==", "dependencies": { "@discordjs/builders": "^0.2.0", "@discordjs/collection": "^0.1.6", @@ -8034,9 +8034,9 @@ "integrity": "sha512-hNC38R9ZF4uaujaZQtQfm5CdQO58uhdkoHQAVvMfIL0LgOSZeW575W8H6upngQOuoxWd8tiRII3LLJm9zuQKYg==" }, "discord.js": { - "version": "13.0.0-dev.4886ae2.1627214570", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.4886ae2.1627214570.tgz", - "integrity": "sha512-9eqVCQyqqSHJcR1nki9NlaTD7FjvfkjJt8zcmF5wcCs/7P9v27UrPYg9yxvghswDvDhz9ojotYGGcpK7tSypmA==", + "version": "13.0.0-dev.d310e4f.1627560163", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.d310e4f.1627560163.tgz", + "integrity": "sha512-qJmQrG4xCnBqYF/WQIOxl4IWY3gYAwK0UyNOAKhRpHzMXYHX99wx3FcGaYrZiqtXxGbN2lgVanBakKNsq/uYYw==", "requires": { "@discordjs/builders": "^0.2.0", "@discordjs/collection": "^0.1.6", diff --git a/backend/package.json b/backend/package.json index 65ca54f0..8c917b27 100644 --- a/backend/package.json +++ b/backend/package.json @@ -29,7 +29,7 @@ "cors": "^2.8.5", "cross-env": "^5.2.0", "deep-diff": "^1.0.2", - "discord.js": "^13.0.0-dev.4886ae2.1627214570", + "discord.js": "^13.0.0-dev.d310e4f.1627560163", "dotenv": "^4.0.0", "emoji-regex": "^8.0.0", "erlpack": "github:discord/erlpack", diff --git a/backend/src/plugins/Slowmode/commands/SlowmodeGetCmd.ts b/backend/src/plugins/Slowmode/commands/SlowmodeGetCmd.ts index d3f743d0..e1302464 100644 --- a/backend/src/plugins/Slowmode/commands/SlowmodeGetCmd.ts +++ b/backend/src/plugins/Slowmode/commands/SlowmodeGetCmd.ts @@ -27,7 +27,7 @@ export const SlowmodeGetCmd = slowmodeCmd({ } if (currentSlowmode) { - const humanized = humanizeDuration(channel.rateLimitPerUser * 1000); + const humanized = humanizeDuration(currentSlowmode * 1000); const slowmodeType = isNative ? "native" : "bot-maintained"; msg.channel.send(`The current slowmode of <#${channel.id}> is **${humanized}** (${slowmodeType})`); } else { From 0053f55576f2fbc5d56247329d108b14d2356f85 Mon Sep 17 00:00:00 2001 From: Dark <7890309+DarkView@users.noreply.github.com> Date: Thu, 29 Jul 2021 18:46:52 +0200 Subject: [PATCH 39/40] Fix role member counts, add threads to channel info command --- .../src/plugins/Utility/commands/RolesCmd.ts | 10 ++--- .../Utility/functions/getChannelInfoEmbed.ts | 45 ++++++++++++++----- 2 files changed, 38 insertions(+), 17 deletions(-) diff --git a/backend/src/plugins/Utility/commands/RolesCmd.ts b/backend/src/plugins/Utility/commands/RolesCmd.ts index 8aa7e85a..2aa3f459 100644 --- a/backend/src/plugins/Utility/commands/RolesCmd.ts +++ b/backend/src/plugins/Utility/commands/RolesCmd.ts @@ -34,13 +34,9 @@ export const RolesCmd = utilityCmd({ if (args.counts) { await refreshMembersIfNeeded(guild); - // If the user requested role member counts as well, calculate them and sort the roles by their member count - const roleCounts: Map = Array.from(guild.members.cache.values()).reduce((map, member) => { - for (const roleId of member.roles.cache) { - if (!map.has(roleId)) map.set(roleId, 0); - map.set(roleId, map.get(roleId) + 1); - } - + // If the user requested role member counts as well, fetch them and sort the roles by their member count + const roleCounts: Map = Array.from(guild.roles.cache.values()).reduce((map, role) => { + map.set(role.id, role.members.size); return map; }, new Map()); diff --git a/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts b/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts index fa2ea87d..c1dcc7d8 100644 --- a/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts +++ b/backend/src/plugins/Utility/functions/getChannelInfoEmbed.ts @@ -1,9 +1,9 @@ -import { MessageEmbedOptions, Snowflake, StageChannel, VoiceChannel } from "discord.js"; +import { MessageEmbedOptions, Snowflake, StageChannel, ThreadChannel, VoiceChannel } from "discord.js"; import humanizeDuration from "humanize-duration"; import { GuildPluginData } from "knub"; import moment from "moment-timezone"; import { ChannelTypeStrings } from "src/types"; -import { EmbedWith, formatNumber, preEmbedPadding, trimLines } from "../../../utils"; +import { EmbedWith, formatNumber, MINUTES, preEmbedPadding, trimLines, verboseUserMention } from "../../../utils"; import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin"; import { UtilityPluginType } from "../types"; @@ -15,6 +15,10 @@ const ANNOUNCEMENT_CHANNEL_ICON = "https://cdn.discordapp.com/attachments/740650744830623756/740656841687564348/announcement-channel.png"; const STAGE_CHANNEL_ICON = "https://cdn.discordapp.com/attachments/740650744830623756/839930647711186995/stage-channel.png"; +const PUBLIC_THREAD_ICON = + "https://cdn.discordapp.com/attachments/740650744830623756/870343055855738921/public-thread.png"; +const PRIVATE_THREAD_UCON = + "https://cdn.discordapp.com/attachments/740650744830623756/870343402447839242/private-thread.png"; export async function getChannelInfoEmbed( pluginData: GuildPluginData, @@ -30,14 +34,14 @@ export async function getChannelInfoEmbed( fields: [], }; - let icon = TEXT_CHANNEL_ICON; - if (channel.type === ChannelTypeStrings.VOICE) { - icon = VOICE_CHANNEL_ICON; - } else if (channel.type === ChannelTypeStrings.NEWS) { - icon = ANNOUNCEMENT_CHANNEL_ICON; - } else if (channel.type === ChannelTypeStrings.STAGE) { - icon = STAGE_CHANNEL_ICON; - } + const icon = + { + [ChannelTypeStrings.VOICE]: VOICE_CHANNEL_ICON, + [ChannelTypeStrings.NEWS]: ANNOUNCEMENT_CHANNEL_ICON, + [ChannelTypeStrings.STAGE]: STAGE_CHANNEL_ICON, + [ChannelTypeStrings.PUBLIC_THREAD]: PUBLIC_THREAD_ICON, + [ChannelTypeStrings.PRIVATE_THREAD]: PRIVATE_THREAD_UCON, + }[channel.type] || TEXT_CHANNEL_ICON; const channelType = { @@ -47,6 +51,9 @@ export async function getChannelInfoEmbed( [ChannelTypeStrings.NEWS]: "Announcement channel", [ChannelTypeStrings.STORE]: "Store channel", [ChannelTypeStrings.STAGE]: "Stage channel", + [ChannelTypeStrings.PUBLIC_THREAD]: "Public Thread channel", + [ChannelTypeStrings.PRIVATE_THREAD]: "Private Thread channel", + [ChannelTypeStrings.NEWS_THREAD]: "News Thread channel", }[channel.type] || "Channel"; embed.author = { @@ -121,5 +128,23 @@ export async function getChannelInfoEmbed( }); } + if (channel.type === ChannelTypeStrings.PRIVATE_THREAD || channel.type === ChannelTypeStrings.PUBLIC_THREAD) { + const thread = channel as ThreadChannel; + const parentChannelName = thread.parent?.name ? thread.parent.name : `<#${thread.parentId}>`; + const memberCount = thread.memberCount ?? thread.members.cache.size; + const owner = await pluginData.guild.members.fetch(thread.ownerId).catch(() => null); + const ownerMention = owner ? verboseUserMention(owner.user) : "Unknown#0000"; + const humanizedArchiveTime = `Archive duration: **${humanizeDuration(thread.autoArchiveDuration * MINUTES)}**`; + + embed.fields.push({ + name: preEmbedPadding + "Thread information", + value: trimLines(` + Parent channel: **#${parentChannelName}** + Member count: **${memberCount}** + Thread creator: ${ownerMention} + ${thread.archived ? "Archived: **True**" : humanizedArchiveTime}`), + }); + } + return embed; } From 036d46f08a613408a5e500acda553cd498ae7a2a Mon Sep 17 00:00:00 2001 From: Dark <7890309+DarkView@users.noreply.github.com> Date: Thu, 29 Jul 2021 19:08:22 +0200 Subject: [PATCH 40/40] Fix log bugs --- backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts | 4 ++-- backend/src/utils/configAccessibleObjects.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts b/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts index 727fa160..935c7847 100644 --- a/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts +++ b/backend/src/plugins/Logs/events/LogsVoiceChannelEvts.ts @@ -17,13 +17,13 @@ export const LogsVoiceStateUpdateEvt = logsEvt({ // Leave evt meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_LEAVE, { member: memberToConfigAccessibleMember(member), - oldChannel: channelToConfigAccessibleChannel(oldChannel!), + channel: channelToConfigAccessibleChannel(oldChannel!), }); } else if (!oldChannel && newChannel) { // Join Evt meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_JOIN, { member: memberToConfigAccessibleMember(member), - newChannel: channelToConfigAccessibleChannel(newChannel), + channel: channelToConfigAccessibleChannel(newChannel), }); } else { meta.pluginData.state.guildLogs.log(LogType.VOICE_CHANNEL_MOVE, { diff --git a/backend/src/utils/configAccessibleObjects.ts b/backend/src/utils/configAccessibleObjects.ts index 379aaea0..5904e48d 100644 --- a/backend/src/utils/configAccessibleObjects.ts +++ b/backend/src/utils/configAccessibleObjects.ts @@ -17,6 +17,7 @@ export interface IConfigAccessibleUser { username: string; discriminator: string; mention: string; + tag: string; avatarURL?: string; bot?: boolean; createdAt?: number; @@ -46,6 +47,7 @@ export function userToConfigAccessibleUser(user: User | UnknownUser): IConfigAcc username: "Unknown", discriminator: "0000", mention: `<@${user.id}>`, + tag: "Unknown#0000", }; return toReturnPartial; @@ -57,6 +59,7 @@ export function userToConfigAccessibleUser(user: User | UnknownUser): IConfigAcc username: properUser.username, discriminator: properUser.discriminator, mention: `<@${properUser.id}>`, + tag: properUser.tag, avatarURL: properUser.displayAvatarURL({ dynamic: true }), bot: properUser.bot, createdAt: properUser.createdTimestamp,