From b7f254cd426138880318d2ba6a06e8e86ae407bf Mon Sep 17 00:00:00 2001 From: IRONM00N <64110067+IRONM00N@users.noreply.github.com> Date: Thu, 26 Aug 2021 13:43:22 -0400 Subject: finished feature command and did some refactoring --- src/commands/config/features.ts | 72 +++++++---- .../extensions/discord-akairo/BushClientUtil.ts | 2 +- src/lib/models/ActivePunishment.ts | 2 +- src/lib/models/BaseModel.ts | 3 +- src/lib/models/Global.ts | 65 ++-------- src/lib/models/Guild.ts | 140 +++++++-------------- src/lib/models/Level.ts | 3 +- src/lib/models/ModLog.ts | 3 +- src/lib/models/StickyRole.ts | 14 +-- src/lib/models/__helpers.ts | 23 ++++ src/listeners/message/autoPublisher.ts | 2 +- src/listeners/message/autoThread.ts | 44 +++++++ src/listeners/message/automodCreate.ts | 4 +- src/listeners/message/blacklistedFile.ts | 8 +- src/listeners/message/booster.ts | 20 --- src/listeners/message/boosterMessage.ts | 21 ++++ src/listeners/message/level.ts | 9 +- src/listeners/message/supportThreads.ts | 44 ------- src/listeners/message/verbose.ts | 2 +- 19 files changed, 204 insertions(+), 277 deletions(-) create mode 100644 src/lib/models/__helpers.ts create mode 100644 src/listeners/message/autoThread.ts delete mode 100644 src/listeners/message/booster.ts create mode 100644 src/listeners/message/boosterMessage.ts delete mode 100644 src/listeners/message/supportThreads.ts (limited to 'src') diff --git a/src/commands/config/features.ts b/src/commands/config/features.ts index a694483..31facfc 100644 --- a/src/commands/config/features.ts +++ b/src/commands/config/features.ts @@ -1,4 +1,4 @@ -import { BushCommand, BushMessage, BushSlashMessage, GuildFeatures, guildFeatures } from '@lib'; +import { BushCommand, BushMessage, BushSlashMessage, GuildFeatures, guildFeaturesArr, guildFeaturesObj } from '@lib'; import { Message, MessageActionRow, MessageEmbed, MessageSelectMenu, SelectMenuInteraction } from 'discord.js'; //todo: fix this so that it doesn't just select one feature but instead toggles it @@ -24,42 +24,68 @@ export default class FeaturesCommand extends BushCommand { const featureEmbed = new MessageEmbed().setTitle(`${message.guild!.name}'s Features`).setColor(util.colors.default); const enabledFeatures = await message.guild!.getSetting('enabledFeatures'); - let featureList = guildFeatures.map( - (feature) => `**${feature}:** ${enabledFeatures.includes(feature) ? util.emojis.check : util.emojis.cross}` - ); - featureEmbed.setDescription(featureList.join('\n')); - const components = new MessageActionRow().addComponents( - new MessageSelectMenu() - .addOptions(...guildFeatures.map((f) => ({ label: f, value: f }))) - .setPlaceholder('Select A Feature to Toggle') - .setMaxValues(1) - .setMinValues(1) - .setCustomId('featureCommand_selectFeature') - ); - const x = (await message.util.reply({ embeds: [featureEmbed], components: [components] })) as Message; - const collector = x.createMessageComponentCollector({ + this.generateDescription(guildFeaturesArr, enabledFeatures, featureEmbed); + const components = this.generateComponents(guildFeaturesArr, false); + const msg = (await message.util.reply({ embeds: [featureEmbed], components: [components] })) as Message; + const collector = msg.createMessageComponentCollector({ channel: message.channel ?? undefined, guild: message.guild, componentType: 'SELECT_MENU', message: message as Message, time: 300_000 }); + collector.on('collect', async (interaction: SelectMenuInteraction) => { if (interaction.user.id == message.author.id || client.config.owners.includes(interaction.user.id)) { if (!message.guild) throw new Error('message.guild is null'); - const [selected] = interaction.values; - if (!guildFeatures.includes(selected)) throw new Error('Invalid guild feature selected'); - await message.guild.toggleFeature(selected as GuildFeatures); - const enabledFeatures = await message.guild!.getSetting('enabledFeatures'); - featureList = guildFeatures.map( - (feature) => `**${feature}:** ${enabledFeatures.includes(feature) ? util.emojis.check : util.emojis.cross}` - ); - featureEmbed.setDescription(featureList.join('\n')); + + const [selected]: GuildFeatures[] = interaction.values as GuildFeatures[]; + + if (!guildFeaturesArr.includes(selected)) throw new Error('Invalid guild feature selected'); + + const newEnabledFeatures = await message.guild.toggleFeature(selected); + + this.generateDescription(guildFeaturesArr, newEnabledFeatures, featureEmbed); + await interaction.update({ embeds: [featureEmbed] }).catch(() => undefined); + return; } else { return await interaction?.deferUpdate().catch(() => undefined); } }); + + collector.on('end', async () => { + await msg.edit({ components: [this.generateComponents(guildFeaturesArr, false)] }).catch(() => undefined); + }); + } + + public generateDescription(allFeatures: GuildFeatures[], currentFeatures: GuildFeatures[], embed: MessageEmbed): void { + embed.setDescription( + allFeatures + .map( + (feature) => + `${currentFeatures.includes(feature) ? util.emojis.check : util.emojis.cross} **${guildFeaturesObj[feature].name}**` + ) + .join('\n') + ); + } + + public generateComponents(guildFeatures: GuildFeatures[], disable: boolean): MessageActionRow { + return new MessageActionRow().addComponents( + new MessageSelectMenu() + .addOptions( + ...guildFeatures.map((f) => ({ + label: guildFeaturesObj[f].name, + value: f, + description: guildFeaturesObj[f].description + })) + ) + .setPlaceholder('Select A Feature to Toggle') + .setMaxValues(1) + .setMinValues(1) + .setCustomId('featureCommand_selectFeature') + .setDisabled(disable) + ); } } diff --git a/src/lib/extensions/discord-akairo/BushClientUtil.ts b/src/lib/extensions/discord-akairo/BushClientUtil.ts index 26f890a..da98dac 100644 --- a/src/lib/extensions/discord-akairo/BushClientUtil.ts +++ b/src/lib/extensions/discord-akairo/BushClientUtil.ts @@ -1000,7 +1000,7 @@ export class BushClientUtil extends ClientUtil { * Add or remove an item from an array. All duplicates will be removed. */ public addOrRemoveFromArray(action: 'add' | 'remove', array: any[], value: any): any[] { - const set = new Set(...array); + const set = new Set(array); action === 'add' ? set.add(value) : set.delete(value); return [...set]; } diff --git a/src/lib/models/ActivePunishment.ts b/src/lib/models/ActivePunishment.ts index 62bb73e..10ae766 100644 --- a/src/lib/models/ActivePunishment.ts +++ b/src/lib/models/ActivePunishment.ts @@ -147,7 +147,7 @@ export class ActivePunishment } } }, - { sequelize: sequelize } + { sequelize } ); } } diff --git a/src/lib/models/BaseModel.ts b/src/lib/models/BaseModel.ts index 8ed5ed3..555bf7d 100644 --- a/src/lib/models/BaseModel.ts +++ b/src/lib/models/BaseModel.ts @@ -1,6 +1,5 @@ import { Model } from 'sequelize'; - -const NEVER_USED = 'This should never be executed'; +import { NEVER_USED } from './__helpers'; export abstract class BaseModel extends Model { /** diff --git a/src/lib/models/Global.ts b/src/lib/models/Global.ts index 36c72d8..17bd570 100644 --- a/src/lib/models/Global.ts +++ b/src/lib/models/Global.ts @@ -1,6 +1,7 @@ import { Snowflake } from 'discord.js'; import { DataTypes, Sequelize } from 'sequelize'; import { BaseModel } from './BaseModel'; +import { jsonArrayInit, NEVER_USED } from './__helpers'; export interface GlobalModel { environment: 'production' | 'development' | 'beta'; @@ -20,8 +21,6 @@ export interface GlobalModelCreationAttributes { blacklistedChannels?: Snowflake[]; } -const NEVER_USED = 'This should never be executed'; - export class Global extends BaseModel implements GlobalModel { /** * The bot's environment. @@ -90,63 +89,13 @@ export class Global extends BaseModel implements GuildModel { /** @@ -164,10 +194,10 @@ export class Guild extends BaseModel i /** * The features enabled in a guild */ - public get enabledFeatures(): string[] { + public get enabledFeatures(): GuildFeatures[] { throw new Error(NEVER_USED); } - public set enabledFeatures(_: string[]) { + public set enabledFeatures(_: GuildFeatures[]) { throw new Error(NEVER_USED); } @@ -193,39 +223,9 @@ export class Guild extends BaseModel i allowNull: false, defaultValue: client.config.prefix }, - autoPublishChannels: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('autoPublishChannels') as unknown as string); - }, - set: function (val: Snowflake[]) { - return this.setDataValue('autoPublishChannels', JSON.stringify(val) as unknown as Snowflake[]); - }, - allowNull: false, - defaultValue: '[]' - }, - blacklistedChannels: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('blacklistedChannels') as unknown as string); - }, - set: function (val: Snowflake[]) { - return this.setDataValue('blacklistedChannels', JSON.stringify(val) as unknown as Snowflake[]); - }, - allowNull: false, - defaultValue: '[]' - }, - blacklistedUsers: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('blacklistedUsers') as unknown as string); - }, - set: function (val: Snowflake[]) { - return this.setDataValue('blacklistedUsers', JSON.stringify(val) as unknown as Snowflake[]); - }, - allowNull: false, - defaultValue: '[]' - }, + autoPublishChannels: jsonArrayInit('autoPublishChannels'), + blacklistedChannels: jsonArrayInit('blacklistedChannels'), + blacklistedUsers: jsonArrayInit('blacklistedChannels'), welcomeChannel: { type: DataTypes.STRING, allowNull: true @@ -238,61 +238,11 @@ export class Guild extends BaseModel i type: DataTypes.TEXT, allowNull: true }, - disabledCommands: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('disabledCommands') as unknown as string); - }, - set: function (val: string[]) { - return this.setDataValue('disabledCommands', JSON.stringify(val) as unknown as string[]); - }, - allowNull: false, - defaultValue: '[]' - }, - lockdownChannels: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('lockdownChannels') as unknown as string); - }, - set: function (val: Snowflake[]) { - return this.setDataValue('lockdownChannels', JSON.stringify(val) as unknown as Snowflake[]); - }, - allowNull: false, - defaultValue: '[]' - }, - autoModPhases: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('autoModPhases') as unknown as string); - }, - set: function (val: string[]) { - return this.setDataValue('autoModPhases', JSON.stringify(val) as unknown as string[]); - }, - allowNull: false, - defaultValue: '[]' - }, - enabledFeatures: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('enabledFeatures') as unknown as string); - }, - set: function (val: string[]) { - return this.setDataValue('enabledFeatures', JSON.stringify(val) as unknown as string[]); - }, - allowNull: false, - defaultValue: '[]' - }, - joinRoles: { - type: DataTypes.TEXT, - get: function () { - return JSON.parse(this.getDataValue('joinRoles') as unknown as string); - }, - set: function (val: string[]) { - return this.setDataValue('joinRoles', JSON.stringify(val) as unknown as string[]); - }, - allowNull: false, - defaultValue: '[]' - } + disabledCommands: jsonArrayInit('disabledCommands'), + lockdownChannels: jsonArrayInit('lockdownChannels'), + autoModPhases: jsonArrayInit('autoModPhases'), + enabledFeatures: jsonArrayInit('enabledFeatures'), + joinRoles: jsonArrayInit('joinRoles') }, { sequelize: sequelize } ); diff --git a/src/lib/models/Level.ts b/src/lib/models/Level.ts index ad64747..0960d4f 100644 --- a/src/lib/models/Level.ts +++ b/src/lib/models/Level.ts @@ -1,6 +1,7 @@ import { Snowflake } from 'discord.js'; import { DataTypes, Sequelize } from 'sequelize'; import { BaseModel } from './BaseModel'; +import { NEVER_USED } from './__helpers'; export interface LevelModel { user: Snowflake; @@ -14,8 +15,6 @@ export interface LevelModelCreationAttributes { xp?: number; } -const NEVER_USED = 'This should never be executed'; - export class Level extends BaseModel { /** * The user's id. diff --git a/src/lib/models/ModLog.ts b/src/lib/models/ModLog.ts index 50d142a..7787375 100644 --- a/src/lib/models/ModLog.ts +++ b/src/lib/models/ModLog.ts @@ -2,6 +2,7 @@ import { Snowflake } from 'discord.js'; import { DataTypes, Sequelize } from 'sequelize'; import { v4 as uuidv4 } from 'uuid'; import { BaseModel } from './BaseModel'; +import { NEVER_USED } from './__helpers'; export enum ModLogType { PERM_BAN = 'PERM_BAN', @@ -42,8 +43,6 @@ export interface ModLogModelCreationAttributes { evidence?: string; } -const NEVER_USED = 'This should never be executed'; - export class ModLog extends BaseModel implements ModLogModel { /** * The primary key of the modlog entry. diff --git a/src/lib/models/StickyRole.ts b/src/lib/models/StickyRole.ts index d304370..4c06b32 100644 --- a/src/lib/models/StickyRole.ts +++ b/src/lib/models/StickyRole.ts @@ -1,6 +1,7 @@ import { Snowflake } from 'discord.js'; import { DataTypes, Sequelize } from 'sequelize'; import { BaseModel } from './BaseModel'; +import { jsonArrayInit, NEVER_USED } from './__helpers'; export interface StickyRoleModel { user: Snowflake; @@ -15,8 +16,6 @@ export interface StickyRoleModelCreationAttributes { nickname?: string; } -const NEVER_USED = 'This should never be executed'; - export class StickyRole extends BaseModel implements StickyRoleModel { /** * The id of the user the roles belongs to @@ -69,16 +68,7 @@ export class StickyRole extends BaseModel { - if (!message.guild) return; + if (!message.guild || !(await message.guild.hasFeature('autoPublish'))) return; const autoPublishChannels = await message.guild.getSetting('autoPublishChannels'); if (autoPublishChannels) { if (message.channel.type === 'GUILD_NEWS' && autoPublishChannels.some((x) => message.channel.id.includes(x))) { diff --git a/src/listeners/message/autoThread.ts b/src/listeners/message/autoThread.ts new file mode 100644 index 0000000..eb54554 --- /dev/null +++ b/src/listeners/message/autoThread.ts @@ -0,0 +1,44 @@ +import { GuildTextBasedChannels } from 'discord-akairo'; +import { MessageEmbed } from 'discord.js'; +import { BushListener, BushTextChannel } from '../../lib'; +import { BushClientEvents } from '../../lib/extensions/discord.js/BushClientEvents'; + +export default class autoThreadListener extends BushListener { + public constructor() { + super('autoThread', { + emitter: 'client', + event: 'messageCreate', + category: 'message' + }); + } + + public override async exec(...[message]: BushClientEvents['messageCreate']): Promise | undefined> { + if (client.config.isDevelopment) return; + if (!message.guild || !message.channel) return; + // todo: make these configurable etc... + if (message.guild.id !== '516977525906341928') return; // mb + if (message.channel.id !== '714332750156660756') return; // neu-support-1 + if (!(message.channel as BushTextChannel).permissionsFor(message.guild.me!).has('USE_PUBLIC_THREADS')) return; + const thread = await message.startThread({ + name: `Support - ${message.author.username}#${message.author.discriminator}`, + autoArchiveDuration: 60, + reason: 'Support Thread' + }); + const embed = new MessageEmbed() + .setTitle('NotEnoughUpdates Support') + .setDescription( + `Welcome to Moulberry Bush Support:tm:\n\nPlease make sure you have the latest prerelease found in <#693586404256645231>.\nAdditionally if you need help installing the mod be sure to read <#737444942724726915> for a guide on how to do so.` + ) + .setColor('BLURPLE'); + void thread + .send({ embeds: [embed] }) + .then(() => + client.console.info( + 'supportThread', + `opened a support thread for <<${message.author.tag}>> in <<${ + (message.channel as GuildTextBasedChannels).name + }>> in <<${message.guild!.name}>>.` + ) + ); + } +} diff --git a/src/listeners/message/automodCreate.ts b/src/listeners/message/automodCreate.ts index ca61dd0..f78efec 100644 --- a/src/listeners/message/automodCreate.ts +++ b/src/listeners/message/automodCreate.ts @@ -22,8 +22,8 @@ export default class AutomodMessageCreateListener extends BushListener { } public static async automod(message: BushMessage): Promise { - if (message.channel.type === 'DM') return; - if (message.guild?.id !== client.consts.mappings.guilds.bush) return; // just temporary + if (message.channel.type === 'DM' || !message.guild) return; + if (!(await message.guild.hasFeature('automod'))) return; /* await message.guild.getSetting('autoModPhases'); */ const badLinks: { [key: string]: number } = {}; let temp = _badLinks; diff --git a/src/listeners/message/blacklistedFile.ts b/src/listeners/message/blacklistedFile.ts index a9c5c46..5aa5477 100644 --- a/src/listeners/message/blacklistedFile.ts +++ b/src/listeners/message/blacklistedFile.ts @@ -66,13 +66,7 @@ export default class BlacklistedFileListener extends BushListener { } public override async exec(...[message]: BushClientEvents['messageCreate']): Promise { - if (!message.guild) return; - const guildWhitelist = [ - client.consts.mappings.guilds.bush, - client.consts.mappings.guilds.tree, - client.consts.mappings.guilds.space_ship - ]; - if (!guildWhitelist.includes(message.guild!.id)) return; + if (!message.guild || !(await message.guild.hasFeature('blacklistedFile'))) return; const embedAttachments = message.embeds.filter((e) => ['image', 'video', 'gifv'].includes(e.type)); const foundEmojis = [...message.content.matchAll(/<(?a?):\w+:(?\d+)>/g)]; if (message.attachments.size + embedAttachments.length + foundEmojis.length < 1) return; diff --git a/src/listeners/message/booster.ts b/src/listeners/message/booster.ts deleted file mode 100644 index 603e535..0000000 --- a/src/listeners/message/booster.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { BushListener } from '../../lib'; -import { BushClientEvents } from '../../lib/extensions/discord.js/BushClientEvents'; - -export default class BoosterMessageListener extends BushListener { - public constructor() { - super('boosterMessage', { - emitter: 'client', - event: 'messageCreate', - category: 'message' - }); - } - - public override async exec(...[message]: BushClientEvents['messageCreate']): Promise { - if (message.type === 'USER_PREMIUM_GUILD_SUBSCRIPTION' && message.guild!.id === this.client.consts.mappings.guilds.bush) { - return await message.react('<:nitroboost:785160348885975062>').catch(() => { - void this.client.console.warn('BoosterMessage', `Failed to react to <<${message.id}>>.`); - }); - } - } -} diff --git a/src/listeners/message/boosterMessage.ts b/src/listeners/message/boosterMessage.ts new file mode 100644 index 0000000..5d49661 --- /dev/null +++ b/src/listeners/message/boosterMessage.ts @@ -0,0 +1,21 @@ +import { BushListener } from '../../lib'; +import { BushClientEvents } from '../../lib/extensions/discord.js/BushClientEvents'; + +export default class BoosterMessageListener extends BushListener { + public constructor() { + super('boosterMessage', { + emitter: 'client', + event: 'messageCreate', + category: 'message' + }); + } + + public override async exec(...[message]: BushClientEvents['messageCreate']): Promise { + if (!message.guild || !(await message.guild?.hasFeature('boosterMessageReact'))) return; + if (message.type === 'USER_PREMIUM_GUILD_SUBSCRIPTION') { + return await message.react('<:nitroboost:785160348885975062>').catch(() => { + void this.client.console.warn('BoosterMessage', `Failed to react to <<${message.id}>>.`); + }); + } + } +} diff --git a/src/listeners/message/level.ts b/src/listeners/message/level.ts index 0077276..33e7b08 100644 --- a/src/listeners/message/level.ts +++ b/src/listeners/message/level.ts @@ -12,10 +12,7 @@ export default class LevelListener extends BushListener { }); } public override async exec(...[message]: BushCommandHandlerEvents['messageInvalid']): Promise { - if (message.author.bot) return; - if (!message.author) return; - if (!message.guild) return; - if (message.util?.parsed?.command) return; + if (message.author.bot || !message.author || !message.guild) return; if (this.#levelCooldowns.has(`${message.guild.id}-${message.author.id}`)) return; if (this.#blacklistedChannels.includes(message.channel.id)) return; const allowedMessageTypes: MessageType[] = ['DEFAULT', 'REPLY']; // this is so ts will yell at me when discord.js makes some unnecessary breaking change @@ -33,12 +30,12 @@ export default class LevelListener extends BushListener { }); const xpToGive = Level.genRandomizedXp(); const success = await user.increment('xp', { by: xpToGive }).catch((e) => { - void client.logger.error('LevelMessageListener', e?.stack || e); + void client.logger.error('levelMessageListener', e?.stack || e); return false; }); if (success) void client.logger.verbose( - `LevelMessageListener`, + `levelMessageListener`, `Gave <<${xpToGive}>> XP to <<${message.author.tag}>> in <<${message.guild}>>.` ); this.#levelCooldowns.add(`${message.guild.id}-${message.author.id}`); diff --git a/src/listeners/message/supportThreads.ts b/src/listeners/message/supportThreads.ts deleted file mode 100644 index 9b3ea3e..0000000 --- a/src/listeners/message/supportThreads.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { GuildTextBasedChannels } from 'discord-akairo'; -import { MessageEmbed } from 'discord.js'; -import { BushListener, BushTextChannel } from '../../lib'; -import { BushClientEvents } from '../../lib/extensions/discord.js/BushClientEvents'; - -export default class SupportThreadListener extends BushListener { - public constructor() { - super('supportThreads', { - emitter: 'client', - event: 'messageCreate', - category: 'message' - }); - } - - public override async exec(...[message]: BushClientEvents['messageCreate']): Promise | undefined> { - if (client.config.isDevelopment) return; - if (!message.guild || !message.channel) return; - // todo: make these configurable etc... - if (message.guild.id !== '516977525906341928') return; // mb - if (message.channel.id !== '714332750156660756') return; // neu-support-1 - if (!(message.channel as BushTextChannel).permissionsFor(message.guild.me!).has('USE_PUBLIC_THREADS')) return; - const thread = await message.startThread({ - name: `Support - ${message.author.username}#${message.author.discriminator}`, - autoArchiveDuration: 60, - reason: 'Support Thread' - }); - const embed = new MessageEmbed() - .setTitle('NotEnoughUpdates Support') - .setDescription( - `Welcome to Moulberry Bush Support:tm:\n\nPlease make sure you have the latest prerelease found in <#693586404256645231>.\nAdditionally if you need help installing the mod be sure to read <#737444942724726915> for a guide on how to do so.` - ) - .setColor('BLURPLE'); - void thread - .send({ embeds: [embed] }) - .then(() => - client.console.info( - 'supportThread', - `opened a support thread for <<${message.author.tag}>> in <<${ - (message.channel as GuildTextBasedChannels).name - }>> in <<${message.guild!.name}>>.` - ) - ); - } -} diff --git a/src/listeners/message/verbose.ts b/src/listeners/message/verbose.ts index f1530ce..9404412 100644 --- a/src/listeners/message/verbose.ts +++ b/src/listeners/message/verbose.ts @@ -13,7 +13,7 @@ export default class MessageVerboseListener extends BushListener { public override exec(...[message]: BushClientEvents['messageCreate']): Promise | undefined { if (message.channel?.type === 'DM') return; void this.client.console.verbose( - 'Message', + 'messageVerbose', `A message was sent by <<${message.author.tag}>> in <<${message.channel.name}>> in <<${message.guild!.name}>>.` ); } -- cgit