3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-03-16 14:11:50 +00:00

Merge pull request #5 from almeidx/final

Final
This commit is contained in:
Nils 2021-07-29 18:50:01 +02:00 committed by GitHub
commit 16188702f3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 64 additions and 88 deletions

View file

@ -14,7 +14,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"deep-diff": "^1.0.2", "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", "dotenv": "^4.0.0",
"emoji-regex": "^8.0.0", "emoji-regex": "^8.0.0",
"erlpack": "github:discord/erlpack", "erlpack": "github:discord/erlpack",
@ -2159,9 +2159,9 @@
} }
}, },
"node_modules/discord.js": { "node_modules/discord.js": {
"version": "13.0.0-dev.4886ae2.1627214570", "version": "13.0.0-dev.d310e4f.1627560163",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.4886ae2.1627214570.tgz", "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.d310e4f.1627560163.tgz",
"integrity": "sha512-9eqVCQyqqSHJcR1nki9NlaTD7FjvfkjJt8zcmF5wcCs/7P9v27UrPYg9yxvghswDvDhz9ojotYGGcpK7tSypmA==", "integrity": "sha512-qJmQrG4xCnBqYF/WQIOxl4IWY3gYAwK0UyNOAKhRpHzMXYHX99wx3FcGaYrZiqtXxGbN2lgVanBakKNsq/uYYw==",
"dependencies": { "dependencies": {
"@discordjs/builders": "^0.2.0", "@discordjs/builders": "^0.2.0",
"@discordjs/collection": "^0.1.6", "@discordjs/collection": "^0.1.6",
@ -8034,9 +8034,9 @@
"integrity": "sha512-hNC38R9ZF4uaujaZQtQfm5CdQO58uhdkoHQAVvMfIL0LgOSZeW575W8H6upngQOuoxWd8tiRII3LLJm9zuQKYg==" "integrity": "sha512-hNC38R9ZF4uaujaZQtQfm5CdQO58uhdkoHQAVvMfIL0LgOSZeW575W8H6upngQOuoxWd8tiRII3LLJm9zuQKYg=="
}, },
"discord.js": { "discord.js": {
"version": "13.0.0-dev.4886ae2.1627214570", "version": "13.0.0-dev.d310e4f.1627560163",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.4886ae2.1627214570.tgz", "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-13.0.0-dev.d310e4f.1627560163.tgz",
"integrity": "sha512-9eqVCQyqqSHJcR1nki9NlaTD7FjvfkjJt8zcmF5wcCs/7P9v27UrPYg9yxvghswDvDhz9ojotYGGcpK7tSypmA==", "integrity": "sha512-qJmQrG4xCnBqYF/WQIOxl4IWY3gYAwK0UyNOAKhRpHzMXYHX99wx3FcGaYrZiqtXxGbN2lgVanBakKNsq/uYYw==",
"requires": { "requires": {
"@discordjs/builders": "^0.2.0", "@discordjs/builders": "^0.2.0",
"@discordjs/collection": "^0.1.6", "@discordjs/collection": "^0.1.6",

View file

@ -29,7 +29,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"cross-env": "^5.2.0", "cross-env": "^5.2.0",
"deep-diff": "^1.0.2", "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", "dotenv": "^4.0.0",
"emoji-regex": "^8.0.0", "emoji-regex": "^8.0.0",
"erlpack": "github:discord/erlpack", "erlpack": "github:discord/erlpack",

View file

@ -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 { baseCommandParameterTypeHelpers, baseTypeConverters, CommandContext, TypeConversionError } from "knub";
import { createTypeHelper } from "knub-command-manager"; import { createTypeHelper } from "knub-command-manager";
import { import {
channelMentionRegex, channelMentionRegex,
convertDelayStringToMS, convertDelayStringToMS,
disableCodeBlocks,
disableInlineCode,
isValidSnowflake, isValidSnowflake,
resolveMember, resolveMember,
resolveUser, resolveUser,
@ -32,7 +30,7 @@ export const commandTypes = {
async resolvedUser(value, context: CommandContext<any>) { async resolvedUser(value, context: CommandContext<any>) {
const result = await resolveUser(context.pluginData.client, value); const result = await resolveUser(context.pluginData.client, value);
if (result == null || result instanceof UnknownUser) { 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; return result;
}, },
@ -40,7 +38,7 @@ export const commandTypes = {
async resolvedUserLoose(value, context: CommandContext<any>) { async resolvedUserLoose(value, context: CommandContext<any>) {
const result = await resolveUser(context.pluginData.client, value); const result = await resolveUser(context.pluginData.client, value);
if (result == null) { if (result == null) {
throw new TypeConversionError(`Invalid user: \`${disableCodeBlocks(value)}\``); throw new TypeConversionError(`Invalid user: \`${Util.escapeCodeBlock(value)}\``);
} }
return result; return result;
}, },
@ -53,7 +51,7 @@ export const commandTypes = {
const result = await resolveMember(context.pluginData.client, context.message.channel.guild, value); const result = await resolveMember(context.pluginData.client, context.message.channel.guild, value);
if (result == null) { if (result == null) {
throw new TypeConversionError( 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; return result;
@ -64,7 +62,7 @@ export const commandTypes = {
const result = await resolveMessageTarget(context.pluginData, value); const result = await resolveMessageTarget(context.pluginData, value);
if (!result) { if (!result) {
throw new TypeConversionError(`Unknown message \`${disableInlineCode(value)}\``); throw new TypeConversionError(`Unknown message \`${Util.escapeInlineCode(value)}\``);
} }
return result; return result;
@ -84,20 +82,20 @@ export const commandTypes = {
return value as Snowflake; 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<any>): RegExp { regex(value: string, context: CommandContext<any>): RegExp {
try { try {
return inputPatternToRegExp(value); return inputPatternToRegExp(value);
} catch (e) { } 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) { timezone(value: string) {
if (!isValidTimezone(value)) { if (!isValidTimezone(value)) {
throw new TypeConversionError(`Invalid timezone: ${disableInlineCode(value)}`); throw new TypeConversionError(`Invalid timezone: ${Util.escapeInlineCode(value)}`);
} }
return value; return value;

View file

@ -1,6 +1,6 @@
import { Snowflake, TextChannel } from "discord.js"; import { Snowflake, TextChannel, Util } from "discord.js";
import * as t from "io-ts"; import * as t from "io-ts";
import { asSingleLine, disableInlineCode, messageSummary, verboseChannelMention } from "../../../utils"; import { asSingleLine, messageSummary, verboseChannelMention } from "../../../utils";
import { automodTrigger } from "../helpers"; import { automodTrigger } from "../helpers";
interface MatchResultType { interface MatchResultType {
@ -73,7 +73,7 @@ export const MatchAttachmentTypeTrigger = automodTrigger<MatchResultType>()({
return ( return (
asSingleLine(` asSingleLine(`
Matched attachment type \`${disableInlineCode(matchResult.extra.matchedType)}\` Matched attachment type \`${Util.escapeInlineCode(matchResult.extra.matchedType)}\`
(${matchResult.extra.mode === "blacklist" ? "(blacklisted)" : "(not in whitelist)"}) (${matchResult.extra.mode === "blacklist" ? "(blacklisted)" : "(not in whitelist)"})
in message (\`${contexts[0].message!.id}\`) in ${prettyChannel}: in message (\`${contexts[0].message!.id}\`) in ${prettyChannel}:
`) + messageSummary(contexts[0].message!) `) + messageSummary(contexts[0].message!)

View file

@ -1,7 +1,8 @@
import { Util } from "discord.js";
import escapeStringRegexp from "escape-string-regexp"; import escapeStringRegexp from "escape-string-regexp";
import * as t from "io-ts"; import * as t from "io-ts";
import { allowTimeout } from "../../../RegExpRunner"; import { allowTimeout } from "../../../RegExpRunner";
import { disableInlineCode, getUrlsInString, tNullable } from "../../../utils"; import { getUrlsInString, tNullable } from "../../../utils";
import { TRegex } from "../../../validatorUtils"; import { TRegex } from "../../../validatorUtils";
import { getTextMatchPartialSummary } from "../functions/getTextMatchPartialSummary"; import { getTextMatchPartialSummary } from "../functions/getTextMatchPartialSummary";
import { MatchableTextType, matchMultipleTextTypesOnMessage } from "../functions/matchMultipleTextTypesOnMessage"; import { MatchableTextType, matchMultipleTextTypesOnMessage } from "../functions/matchMultipleTextTypesOnMessage";
@ -129,6 +130,6 @@ export const MatchLinksTrigger = automodTrigger<MatchResultType>()({
renderMatchInformation({ pluginData, contexts, matchResult }) { renderMatchInformation({ pluginData, contexts, matchResult }) {
const partialSummary = getTextMatchPartialSummary(pluginData, matchResult.extra.type, contexts[0]); 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}`;
}, },
}); });

View file

@ -1,6 +1,6 @@
import { Util } from "discord.js";
import * as t from "io-ts"; import * as t from "io-ts";
import { allowTimeout } from "../../../RegExpRunner"; import { allowTimeout } from "../../../RegExpRunner";
import { disableInlineCode } from "../../../utils";
import { normalizeText } from "../../../utils/normalizeText"; import { normalizeText } from "../../../utils/normalizeText";
import { stripMarkdown } from "../../../utils/stripMarkdown"; import { stripMarkdown } from "../../../utils/stripMarkdown";
import { TRegex } from "../../../validatorUtils"; import { TRegex } from "../../../validatorUtils";
@ -72,6 +72,6 @@ export const MatchRegexTrigger = automodTrigger<MatchResultType>()({
renderMatchInformation({ pluginData, contexts, matchResult }) { renderMatchInformation({ pluginData, contexts, matchResult }) {
const partialSummary = getTextMatchPartialSummary(pluginData, matchResult.extra.type, contexts[0]); 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}`;
}, },
}); });

View file

@ -1,6 +1,6 @@
import { Util } from "discord.js";
import escapeStringRegexp from "escape-string-regexp"; import escapeStringRegexp from "escape-string-regexp";
import * as t from "io-ts"; import * as t from "io-ts";
import { disableInlineCode } from "../../../utils";
import { normalizeText } from "../../../utils/normalizeText"; import { normalizeText } from "../../../utils/normalizeText";
import { stripMarkdown } from "../../../utils/stripMarkdown"; import { stripMarkdown } from "../../../utils/stripMarkdown";
import { getTextMatchPartialSummary } from "../functions/getTextMatchPartialSummary"; import { getTextMatchPartialSummary } from "../functions/getTextMatchPartialSummary";
@ -89,6 +89,6 @@ export const MatchWordsTrigger = automodTrigger<MatchResultType>()({
renderMatchInformation({ pluginData, contexts, matchResult }) { renderMatchInformation({ pluginData, contexts, matchResult }) {
const partialSummary = getTextMatchPartialSummary(pluginData, matchResult.extra.type, contexts[0]); 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}`;
}, },
}); });

View file

@ -7,7 +7,6 @@ import { GuildSavedMessages } from "../../data/GuildSavedMessages";
import { LogType } from "../../data/LogType"; import { LogType } from "../../data/LogType";
import { logger } from "../../logger"; import { logger } from "../../logger";
import { discardRegExpRunner, getRegExpRunner } from "../../regExpRunners"; import { discardRegExpRunner, getRegExpRunner } from "../../regExpRunners";
import { disableCodeBlocks } from "../../utils";
import { CasesPlugin } from "../Cases/CasesPlugin"; import { CasesPlugin } from "../Cases/CasesPlugin";
import { TimeAndDatePlugin } from "../TimeAndDate/TimeAndDatePlugin"; import { TimeAndDatePlugin } from "../TimeAndDate/TimeAndDatePlugin";
import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint"; import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint";
@ -37,6 +36,7 @@ import { log } from "./util/log";
import { onMessageDelete } from "./util/onMessageDelete"; import { onMessageDelete } from "./util/onMessageDelete";
import { onMessageDeleteBulk } from "./util/onMessageDeleteBulk"; import { onMessageDeleteBulk } from "./util/onMessageDeleteBulk";
import { onMessageUpdate } from "./util/onMessageUpdate"; import { onMessageUpdate } from "./util/onMessageUpdate";
import { Util } from "discord.js";
const defaultOptions: PluginOptions<LogsPluginType> = { const defaultOptions: PluginOptions<LogsPluginType> = {
config: { config: {
@ -147,7 +147,7 @@ export const LogsPlugin = zeppelinGuildPlugin<LogsPluginType>()({
The following regex has taken longer than ${timeoutMs}ms for ${failedTimes} times and has been temporarily disabled: The following regex has taken longer than ${timeoutMs}ms for ${failedTimes} times and has been temporarily disabled:
`.trim() + `.trim() +
"\n```" + "\n```" +
disableCodeBlocks(regexSource) + Util.escapeCodeBlock(regexSource) +
"```", "```",
}); });
}; };

View file

@ -214,11 +214,7 @@ export const MutesCmd = mutesCmd({
const row = new MessageActionRow().addComponents(buttons); const row = new MessageActionRow().addComponents(buttons);
await listMessage.edit({ components: [row] }); await listMessage.edit({ components: [row] });
const filter = (iac: MessageComponentInteraction) => iac.message.id === listMessage.id; const collector = listMessage.createMessageComponentCollector({ time: stopCollectionDebounce });
const collector = listMessage.createMessageComponentCollector({
filter,
time: stopCollectionDebounce,
});
collector.on("collect", async (interaction: MessageComponentInteraction) => { collector.on("collect", async (interaction: MessageComponentInteraction) => {
if (msg.author.id !== interaction.user.id) { if (msg.author.id !== interaction.user.id) {

View file

@ -1,13 +1,7 @@
import { Util } from "discord.js";
import humanizeDuration from "humanize-duration"; import humanizeDuration from "humanize-duration";
import moment from "moment-timezone"; import moment from "moment-timezone";
import { import { createChunkedMessage, DBDateFormat, deactivateMentions, sorter, trimLines } from "../../../utils";
createChunkedMessage,
DBDateFormat,
deactivateMentions,
disableCodeBlocks,
sorter,
trimLines,
} from "../../../utils";
import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin"; import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin";
import { postCmd } from "../types"; import { postCmd } from "../types";
@ -33,7 +27,7 @@ export const ScheduledPostsListCmd = postCmd({
const isTruncated = previewText.length > SCHEDULED_POST_PREVIEW_TEXT_LENGTH; const isTruncated = previewText.length > SCHEDULED_POST_PREVIEW_TEXT_LENGTH;
previewText = disableCodeBlocks(deactivateMentions(previewText)) previewText = Util.escapeCodeBlock(deactivateMentions(previewText))
.replace(/\s+/g, " ") .replace(/\s+/g, " ")
.slice(0, SCHEDULED_POST_PREVIEW_TEXT_LENGTH); .slice(0, SCHEDULED_POST_PREVIEW_TEXT_LENGTH);
@ -61,7 +55,7 @@ export const ScheduledPostsListCmd = postCmd({
const finalMessage = trimLines(` const finalMessage = trimLines(`
${postLines.join("\n")} ${postLines.join("\n")}
Use \`scheduled_posts <num>\` to view a scheduled post in full Use \`scheduled_posts <num>\` to view a scheduled post in full
Use \`scheduled_posts delete <num>\` to delete a scheduled post Use \`scheduled_posts delete <num>\` to delete a scheduled post
`); `);

View file

@ -1,7 +1,8 @@
import { Util } from "discord.js";
import { ChannelTypeStrings } from "src/types"; import { ChannelTypeStrings } from "src/types";
import { commandTypeHelpers as ct } from "../../../commandTypes"; import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { asSingleLine, disableInlineCode } from "../../../utils"; import { asSingleLine } from "../../../utils";
import { getMissingChannelPermissions } from "../../../utils/getMissingChannelPermissions"; import { getMissingChannelPermissions } from "../../../utils/getMissingChannelPermissions";
import { missingPermissionError } from "../../../utils/missingPermissionError"; import { missingPermissionError } from "../../../utils/missingPermissionError";
import { BOT_SLOWMODE_CLEAR_PERMISSIONS } from "../requiredPermissions"; import { BOT_SLOWMODE_CLEAR_PERMISSIONS } from "../requiredPermissions";
@ -57,7 +58,7 @@ export const SlowmodeClearCmd = slowmodeCmd({
msg.channel, msg.channel,
asSingleLine(` asSingleLine(`
Failed to clear slowmode from **${args.user.tag}** in <#${args.channel.id}>: Failed to clear slowmode from **${args.user.tag}** in <#${args.channel.id}>:
\`${disableInlineCode(e.message)}\` \`${Util.escapeInlineCode(e.message)}\`
`), `),
); );
return; return;

View file

@ -27,7 +27,7 @@ export const SlowmodeGetCmd = slowmodeCmd({
} }
if (currentSlowmode) { if (currentSlowmode) {
const humanized = humanizeDuration(channel.rateLimitPerUser * 1000); const humanized = humanizeDuration(currentSlowmode * 1000);
const slowmodeType = isNative ? "native" : "bot-maintained"; const slowmodeType = isNative ? "native" : "bot-maintained";
msg.channel.send(`The current slowmode of <#${channel.id}> is **${humanized}** (${slowmodeType})`); msg.channel.send(`The current slowmode of <#${channel.id}> is **${humanized}** (${slowmodeType})`);
} else { } else {

View file

@ -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 humanizeDuration from "humanize-duration";
import { ChannelTypeStrings } from "src/types"; import { ChannelTypeStrings } from "src/types";
import { commandTypeHelpers as ct } from "../../../commandTypes"; import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; 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 { getMissingPermissions } from "../../../utils/getMissingPermissions";
import { missingPermissionError } from "../../../utils/missingPermissionError"; import { missingPermissionError } from "../../../utils/missingPermissionError";
import { BOT_SLOWMODE_PERMISSIONS, NATIVE_SLOWMODE_PERMISSIONS } from "../requiredPermissions"; import { BOT_SLOWMODE_PERMISSIONS, NATIVE_SLOWMODE_PERMISSIONS } from "../requiredPermissions";
@ -133,7 +133,7 @@ export const SlowmodeSetCmd = slowmodeCmd({
rateLimitPerUser: rateLimitSeconds, rateLimitPerUser: rateLimitSeconds,
}); });
} catch (e) { } 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; return;
} }
} else { } else {

View file

@ -1,6 +1,7 @@
import { Util } from "discord.js";
import { commandTypeHelpers as ct } from "../../../commandTypes"; import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils"; import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { disableInlineCode, trimLines } from "../../../utils"; import { trimLines } from "../../../utils";
import { parseFuzzyTimezone } from "../../../utils/parseFuzzyTimezone"; import { parseFuzzyTimezone } from "../../../utils/parseFuzzyTimezone";
import { timeAndDateCmd } from "../types"; import { timeAndDateCmd } from "../types";
@ -19,7 +20,7 @@ export const SetTimezoneCmd = timeAndDateCmd({
pluginData, pluginData,
message.channel, message.channel,
trimLines(` trimLines(`
Invalid timezone: \`${disableInlineCode(args.timezone)}\` Invalid timezone: \`${Util.escapeInlineCode(args.timezone)}\`
Zeppelin uses timezone locations rather than specific timezone names. Zeppelin uses timezone locations rather than specific timezone names.
See the **TZ database name** column at <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones> for a list of valid options. See the **TZ database name** column at <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones> for a list of valid options.
`), `),

View file

@ -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 humanizeDuration from "humanize-duration";
import { GuildPluginData } from "knub"; import { GuildPluginData } from "knub";
import moment from "moment-timezone"; import moment from "moment-timezone";
import { ChannelTypeStrings } from "../../../types";
import { import {
EmbedWith, EmbedWith,
formatNumber, formatNumber,
@ -82,12 +83,11 @@ export async function getServerInfoEmbed(
}); });
// IMAGE LINKS // IMAGE LINKS
const iconUrl = `[Link](${(restGuild || guildPreview)!.iconURL()})`; const iconUrl = `[Link](${(restGuild || guildPreview)!.iconURL({ dynamic: true, format: "png", size: 2048 })})`;
const bannerUrl = restGuild?.bannerURL() ? `[Link](${restGuild.bannerURL()})` : "None"; const bannerUrl = restGuild?.banner ? `[Link](${restGuild.bannerURL({ format: "png", size: 2048 })})` : "None";
const splashUrl = const splashUrl = (restGuild || guildPreview)!.splash
(restGuild || guildPreview)!.splashURL() != null ? `[Link](${(restGuild || guildPreview)!.splashURL({ format: "png", size: 2048 })})`
? `[Link](${(restGuild || guildPreview)!.splashURL()?.replace("size=128", "size=2048")})` : "None";
: "None";
embed.fields.push( embed.fields.push(
{ {
@ -155,9 +155,9 @@ export async function getServerInfoEmbed(
// CHANNEL COUNTS // CHANNEL COUNTS
if (thisServer) { if (thisServer) {
const totalChannels = thisServer.channels.cache.size; const totalChannels = thisServer.channels.cache.size;
const categories = thisServer.channels.cache.filter(channel => channel instanceof CategoryChannel); const categories = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.CATEGORY);
const textChannels = thisServer.channels.cache.filter(channel => channel instanceof TextChannel); const textChannels = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.TEXT);
const voiceChannels = thisServer.channels.cache.filter(channel => channel instanceof VoiceChannel); const voiceChannels = thisServer.channels.cache.filter(channel => channel.type === ChannelTypeStrings.VOICE);
embed.fields.push({ embed.fields.push({
name: preEmbedPadding + "Channels", name: preEmbedPadding + "Channels",

View file

@ -191,8 +191,7 @@ export async function displaySearch(
const row = new MessageActionRow().addComponents(buttons); const row = new MessageActionRow().addComponents(buttons);
await searchMsg.edit({ content: result, components: [row] }); await searchMsg.edit({ content: result, components: [row] });
const filter = (iac: MessageComponentInteraction) => iac.message.id === searchMsg.id; const collector = searchMsg.createMessageComponentCollector({ time: 2 * MINUTES });
const collector = searchMsg.createMessageComponentCollector({ filter, time: 2 * MINUTES });
collector.on("collect", async (interaction: MessageComponentInteraction) => { collector.on("collect", async (interaction: MessageComponentInteraction) => {
if (msg.author.id !== interaction.user.id) { if (msg.author.id !== interaction.user.id) {

View file

@ -22,6 +22,7 @@ import {
TextChannel, TextChannel,
ThreadChannel, ThreadChannel,
User, User,
Util,
} from "discord.js"; } from "discord.js";
import emojiRegex from "emoji-regex"; import emojiRegex from "emoji-regex";
import { either } from "fp-ts/lib/Either"; import { either } from "fp-ts/lib/Either";
@ -785,21 +786,6 @@ export function deactivateMentions(content: string): string {
return content.replace(/@/g, "@\u200b"); 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 { export function useMediaUrls(content: string): string {
return content.replace(/cdn\.discord(app)?\.com/g, "media.discordapp.net"); return content.replace(/cdn\.discord(app)?\.com/g, "media.discordapp.net");
} }
@ -1282,7 +1268,7 @@ export async function resolveRoleId(bot: Client, guildId: string, value: string)
} }
// Role name // 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()); const role = roleList.filter(x => x.name.toLocaleLowerCase() === value.toLocaleLowerCase());
if (role[0]) { if (role[0]) {
return role[0].id; return role[0].id;
@ -1310,7 +1296,6 @@ export async function resolveInvite<T extends boolean>(
return inviteCache.get(key) as ResolveInviteReturnType<T>; return inviteCache.get(key) as ResolveInviteReturnType<T>;
} }
// @ts-ignore: the getInvite() withCounts typings are blergh
const promise = client.fetchInvite(code).catch(() => null); const promise = client.fetchInvite(code).catch(() => null);
inviteCache.set(key, promise); inviteCache.set(key, promise);
@ -1319,12 +1304,14 @@ export async function resolveInvite<T extends boolean>(
const internalStickerCache: LimitedCollection<Snowflake, Sticker> = new LimitedCollection(500); const internalStickerCache: LimitedCollection<Snowflake, Sticker> = new LimitedCollection(500);
export async function resolveStickerId(bot: Client, id: Snowflake): Promise<Sticker> { export async function resolveStickerId(bot: Client, id: Snowflake): Promise<Sticker | null> {
const cachedSticker = internalStickerCache.get(id); const cachedSticker = internalStickerCache.get(id);
if (cachedSticker) return cachedSticker; if (cachedSticker) return cachedSticker;
const fetchedSticker = await bot.fetchSticker(id).catch(undefined); const fetchedSticker = await bot.fetchSticker(id).catch(() => null);
internalStickerCache.set(id, fetchedSticker); if (fetchedSticker) {
internalStickerCache.set(id, fetchedSticker);
}
return fetchedSticker; return fetchedSticker;
} }
@ -1335,11 +1322,11 @@ export async function confirm(channel: TextChannel, userId: string, content: Mes
export function messageSummary(msg: SavedMessage) { export function messageSummary(msg: SavedMessage) {
// Regular text content // Regular text content
let result = "```\n" + (msg.data.content ? disableCodeBlocks(msg.data.content) : "<no text content>") + "```"; let result = "```\n" + (msg.data.content ? Util.escapeCodeBlock(msg.data.content) : "<no text content>") + "```";
// Rich embed // Rich embed
const richEmbed = (msg.data.embeds || []).find(e => (e as MessageEmbed).type === "rich"); const richEmbed = (msg.data.embeds || []).find(e => (e as MessageEmbed).type === "rich");
if (richEmbed) result += "Embed:```" + disableCodeBlocks(JSON.stringify(richEmbed)) + "```"; if (richEmbed) result += "Embed:```" + Util.escapeCodeBlock(JSON.stringify(richEmbed)) + "```";
// Attachments // Attachments
if (msg.data.attachments) { if (msg.data.attachments) {

View file

@ -22,8 +22,7 @@ export async function waitForButtonConfirm(
]); ]);
const message = await channel.send({ ...toPost, components: [row] }); const message = await channel.send({ ...toPost, components: [row] });
const filter = (iac: MessageComponentInteraction) => iac.message.id === message.id; const collector = message.createMessageComponentCollector({ time: 10000 });
const collector = message.createMessageComponentCollector({ filter, time: 10000 });
collector.on("collect", (interaction: MessageComponentInteraction) => { collector.on("collect", (interaction: MessageComponentInteraction) => {
if (options?.restrictToId && options.restrictToId !== interaction.user.id) { if (options?.restrictToId && options.restrictToId !== interaction.user.id) {