From 4036abdbf1a505af70a59f60b67d872e5b3cf68b Mon Sep 17 00:00:00 2001 From: dev-737 <73829355+dev-737@users.noreply.github.com> Date: Sat, 30 Sep 2023 20:24:29 +0530 Subject: [PATCH] fix(blacklist duration): Use `hmds`format instead --- package-lock.json | 14 ++- package.json | 7 +- src/Commands/Apps/blacklist.ts | 49 ++++------ src/Commands/Network/blacklist.ts | 60 ++++++------ src/Events/messageReactionAdd.ts | 8 +- src/Scripts/blacklist/server.ts | 88 +++++++++-------- src/Scripts/blacklist/user.ts | 93 +++++++----------- src/Scripts/hub/browse.ts | 2 +- src/Scripts/hub/join.ts | 8 +- src/Scripts/hub/leave.ts | 2 +- src/Scripts/message/checks.ts | 6 +- src/Scripts/network/onboarding.ts | 13 +-- src/Scripts/reactions/reactionButton.ts | 6 +- src/Scripts/reactions/viewReactionsMenu.ts | 6 +- src/Utils/blacklist.ts | 4 +- src/Utils/deploy-commands.ts | 48 +++------- src/index.ts | 37 +++---- tsconfig.json | 106 +++------------------ 18 files changed, 212 insertions(+), 345 deletions(-) diff --git a/package-lock.json b/package-lock.json index a4c97c4d..f9f03782 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,12 +18,13 @@ "dotenv": "^16.3.1", "lodash": "^4.17.21", "node-schedule": "^2.1.1", + "parse-duration": "^1.1.0", "winston": "^3.10.0" }, "devDependencies": { "@types/common-tags": "^1.8.2", "@types/lodash": "^4.14.199", - "@types/node": "^20.7.1", + "@types/node": "^20.8.0", "@types/node-schedule": "^2.1.1", "@typescript-eslint/eslint-plugin": "^6.7.3", "@typescript-eslint/parser": "^6.7.3", @@ -982,9 +983,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.7.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.7.1.tgz", - "integrity": "sha512-LT+OIXpp2kj4E2S/p91BMe+VgGX2+lfO+XTpfXhh+bCk2LkQtHZSub8ewFBMGP5ClysPjTDFa4sMI8Q3n4T0wg==" + "version": "20.8.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.0.tgz", + "integrity": "sha512-LzcWltT83s1bthcvjBmiBvGJiiUe84NWRHkw+ZV6Fr41z2FbIzvc815dk2nQ3RAKMuN2fkenM/z3Xv2QzEpYxQ==" }, "node_modules/@types/node-schedule": { "version": "2.1.1", @@ -5138,6 +5139,11 @@ "node": ">=6" } }, + "node_modules/parse-duration": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/parse-duration/-/parse-duration-1.1.0.tgz", + "integrity": "sha512-z6t9dvSJYaPoQq7quMzdEagSFtpGu+utzHqqxmpVWNNZRIXnvqyCvn9XsTdh7c/w0Bqmdz3RB3YnRaKtpRtEXQ==" + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", diff --git a/package.json b/package.json index 55b1865f..eec16014 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "interchat", "version": "3.13.0", "description": "A growing Discord bot which provides inter-server chat!", - "main": "build/src/index.js", + "main": "build/index.js", "maintainers": [ { "name": "Supreme1707" @@ -22,7 +22,7 @@ "start": "node .", "build": "tsc --build", "dev": "tsc-watch --outDir ./build --onSuccess \"node .\"", - "deploy": "node build/src/Utils/deploy-commands.js", + "deploy": "node build/Utils/deploy-commands.js", "release": "standard-version", "lint": "eslint --cache --fix .", "prepare": "husky install" @@ -41,12 +41,13 @@ "dotenv": "^16.3.1", "lodash": "^4.17.21", "node-schedule": "^2.1.1", + "parse-duration": "^1.1.0", "winston": "^3.10.0" }, "devDependencies": { "@types/common-tags": "^1.8.2", "@types/lodash": "^4.14.199", - "@types/node": "^20.7.1", + "@types/node": "^20.8.0", "@types/node-schedule": "^2.1.1", "@typescript-eslint/eslint-plugin": "^6.7.3", "@typescript-eslint/parser": "^6.7.3", diff --git a/src/Commands/Apps/blacklist.ts b/src/Commands/Apps/blacklist.ts index f5bff6e3..b8c34c9c 100644 --- a/src/Commands/Apps/blacklist.ts +++ b/src/Commands/Apps/blacklist.ts @@ -3,6 +3,7 @@ import { getDb } from '../../Utils/utils'; import { captureException } from '@sentry/node'; import { addServerBlacklist, addUserBlacklist, notifyBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; import emojis from '../../Utils/JSON/emoji.json'; +import parse from 'parse-duration'; export default { description: 'Blacklist the user or server that sent the message from the hub.', @@ -23,11 +24,18 @@ export default { }, }); - if (!messageInDb) return interaction.reply({ content: 'This message was not sent in the network or has expired.', ephemeral: true }); + if (!messageInDb) { + interaction.reply({ + content: + 'This message was not sent in a network, has expired or you lack required permissions to perform this action.', + ephemeral: true, + }); + return; + } const embed = new EmbedBuilder() .setTitle('Blacklist') - .setDescription('Blacklist a user or server from this hub. This will prevent them from sending messages in this hub.') + .setDescription('Blacklist this server or user from this hub, preventing their messages from being sent.') .setColor('Blurple'); const buttons = new ActionRowBuilder() @@ -64,29 +72,11 @@ export default { ), new ActionRowBuilder().addComponents( new TextInputBuilder() - .setCustomId('minutes') - .setLabel('Minutes') - .setPlaceholder('How many minutes should this blacklist last?') + .setCustomId('duration') + .setLabel('Duration') + .setPlaceholder('Duration of the blacklist. Eg. 1d 2h 3m') .setStyle(TextInputStyle.Short) - .setMaxLength(2) - .setRequired(false), - ), - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId('hours') - .setLabel('Hours') - .setPlaceholder('How many hours should this blacklist last?') - .setStyle(TextInputStyle.Short) - .setMaxLength(2) - .setRequired(false), - ), - new ActionRowBuilder().addComponents( - new TextInputBuilder() - .setCustomId('days') - .setLabel('Days') - .setPlaceholder('How many days should this blacklist last?') - .setStyle(TextInputStyle.Short) - .setMaxLength(2) + .setMinLength(2) .setRequired(false), ), ); @@ -104,15 +94,8 @@ export default { await modalResp.deferUpdate(); const reason = modalResp.fields.getTextInputValue('reason'); - const mins = parseInt(modalResp.fields.getTextInputValue('minutes')) || 0; - const hours = parseInt(modalResp.fields.getTextInputValue('hours')) || 0; - const days = parseInt(modalResp.fields.getTextInputValue('days')) || 0; - - let expires = undefined; - if (mins || hours || days) expires = new Date(); - if (mins) expires?.setMinutes(expires.getMinutes() + mins); - if (hours) expires?.setHours(expires.getHours() + hours); - if (days) expires?.setDate(expires.getDate() + days); + const duration = parse(modalResp.fields.getTextInputValue('duration')); + const expires = duration ? new Date(Date.now() + duration) : undefined; const successEmbed = new EmbedBuilder() .setColor('Green') diff --git a/src/Commands/Network/blacklist.ts b/src/Commands/Network/blacklist.ts index b60a3407..7ffd8762 100644 --- a/src/Commands/Network/blacklist.ts +++ b/src/Commands/Network/blacklist.ts @@ -32,16 +32,10 @@ export default { .setName('reason') .setDescription('The reason for blacklisting the user.') .setRequired(true)) - .addNumberOption(option => option - .setName('minutes') - .setDescription('The number of minutes the user will be blakclisted for.') - .setMinValue(1)) - .addNumberOption(option => option - .setName('hours') - .setDescription('The number of hours the user will be blacklisted for.')) - .addNumberOption(option => option - .setName('days') - .setDescription('The number of hours the user will be blacklisted for.')), + .addStringOption(option => option + .setName('duration') + .setDescription('The duration of the blacklist.') + .setMinLength(2)), ) .addSubcommand(subcommand => subcommand @@ -66,16 +60,10 @@ export default { .setDescription('The reason for blacklisting the server.') .setRequired(true), ) - .addNumberOption(option => option - .setName('minutes') - .setDescription('The number of minutes the user will be blakclisted for.') - .setMinValue(1)) - .addNumberOption(option => option - .setName('hours') - .setDescription('The number of hours the user will be blacklisted for.')) - .addNumberOption(option => option - .setName('days') - .setDescription('The number of hours the user will be blacklisted for.')), + .addStringOption(option => option + .setName('duration') + .setDescription('The duration of the blacklist.') + .setMinLength(2)), ), ) .addSubcommandGroup(subcommandGroup => @@ -126,29 +114,34 @@ export default { subcommand .setName('list') .setDescription('List all blacklists.') + .addStringOption(string => + string + .setName('type') + .setDescription('The type of blacklist to list.') + .addChoices({ name: 'User', value: 'user' }, { name: 'Server', value: 'server' }) + .setRequired(true), + ) .addStringOption(hubOption => hubOption .setName('hub') - .setDescription('The name of the hub to blacklist the user from.') + .setDescription('The name of the hub to list from.') .setAutocomplete(true) .setRequired(true), - ) - .addStringOption(string => - string - .setName('type') - .setDescription('The type of blacklist to list.') - .setRequired(true) - .addChoices( - { name: 'User', value: 'user' }, - { name: 'Server', value: 'server' }), ), ), async execute(interaction: ChatInputCommandInteraction) { - const subCommand = interaction.options.getSubcommand(); const hub = interaction.options.getString('hub', true); + const subcommand = interaction.options.getSubcommand(true); const db = getDb(); - const hubInDb = await db.hubs.findFirst({ where: { name: hub } }); + const hubInDb = await db.hubs.findFirst({ where: { + name: hub, + OR: [ + { ownerId: interaction.user.id }, + { moderators: { some: { userId: interaction.user.id } } }, + ], + }, + }); if (!hubInDb) { return await interaction.reply({ @@ -163,7 +156,7 @@ export default { }); } - (await import(`../../Scripts/blacklist/${subCommand}`)).default.execute(interaction, hubInDb); + (await import(`../../Scripts/blacklist/${subcommand}`)).default.execute(interaction, hubInDb); }, async autocomplete(interaction: AutocompleteInteraction) { @@ -221,6 +214,7 @@ export default { interaction.respond(choices); break; } + case 'server': { const serverOpt = interaction.options.get('server', true); const serverHubMod = await db.hubs.findFirst({ diff --git a/src/Events/messageReactionAdd.ts b/src/Events/messageReactionAdd.ts index 62850c58..911fec45 100644 --- a/src/Events/messageReactionAdd.ts +++ b/src/Events/messageReactionAdd.ts @@ -2,11 +2,11 @@ import { MessageReaction, PartialMessageReaction, PartialUser, User } from 'disc import { getDb } from '../Utils/utils'; import updateMessageReactions from '../Scripts/reactions/updateMessage'; import { HubSettingsBitField } from '../Utils/hubSettingsBitfield'; -import { findBlacklistedServer, findBlacklistedUser } from '../Utils/blacklist'; +import { fetchServerBlacklist, fetchUserBlacklist } from '../Utils/blacklist'; export default { name: 'messageReactionAdd', - async execute(reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser) { // user: User | PartialUser + async execute(reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser) { if (user.bot || user.system) return; const db = getDb(); @@ -22,8 +22,8 @@ export default { !reaction.message.inGuild() ) return; - const userBlacklisted = await findBlacklistedUser(messageInDb.hubId, user.id); - const serverBlacklisted = await findBlacklistedServer(messageInDb.hubId, reaction.message.guild.id); + const userBlacklisted = await fetchUserBlacklist(messageInDb.hubId, user.id); + const serverBlacklisted = await fetchServerBlacklist(messageInDb.hubId, reaction.message.guild.id); if (userBlacklisted || serverBlacklisted) return; const cooldown = reaction.client.reactionCooldowns.get(user.id); diff --git a/src/Scripts/blacklist/server.ts b/src/Scripts/blacklist/server.ts index 7ed4c7a7..f9137df6 100644 --- a/src/Scripts/blacklist/server.ts +++ b/src/Scripts/blacklist/server.ts @@ -1,77 +1,81 @@ +import { ChatInputCommandInteraction, EmbedBuilder } from 'discord.js'; +import { getDb } from '../../Utils/utils'; +import { addServerBlacklist, fetchServerBlacklist, notifyBlacklist, removeBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; import { hubs } from '@prisma/client'; import { captureException } from '@sentry/node'; -import { logger } from '@sentry/utils'; -import { ChatInputCommandInteraction } from 'discord.js'; -import { getDb } from '../../Utils/utils'; -import { modActions } from '../networkLogs/modActions'; -import { addServerBlacklist, notifyBlacklist, removeBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; +import parse from 'parse-duration'; +import logger from '../../Utils/logger'; +import emojis from '../../Utils/JSON/emoji.json'; export default { async execute(interaction: ChatInputCommandInteraction, hub: hubs) { - const serverOpt = interaction.options.getString('server', true); - const subCommandGroup = interaction.options.getSubcommandGroup(); + // defer the reply as it may take a while to fetch and stuff + await interaction.deferReply(); - const { blacklistedServers, connectedList } = getDb(); - const serverInBlacklist = await blacklistedServers.findFirst({ - where: { serverId: serverOpt }, - }); + const db = getDb(); + const subCommandGroup = interaction.options.getSubcommandGroup(); + const serverOpt = interaction.options.getString('server', true); if (subCommandGroup == 'add') { - await interaction.deferReply(); const reason = interaction.options.getString('reason', true); + const duration = parse(`${interaction.options.getString('duration')}`); + const expires = duration ? new Date(Date.now() + duration) : undefined; + const serverInBlacklist = await fetchServerBlacklist(hub.id, serverOpt); if (serverInBlacklist) return await interaction.followUp('The server is already blacklisted.'); const server = await interaction.client.guilds.fetch(serverOpt).catch(() => null); - if (!server) return interaction.followUp('Invalid server ID.'); - - const serverSetup = await connectedList.findFirst({ where: { serverId: serverOpt, hubId: hub.id } }); - - let expires: Date | undefined; - const mins = interaction.options.getNumber('minutes'); - const hours = interaction.options.getNumber('hours'); - const days = interaction.options.getNumber('days'); - - if (mins || hours || days) { - expires = new Date(); - mins ? expires.setMinutes(expires.getMinutes() + mins) : null; - hours ? expires.setHours(expires.getHours() + hours) : null; - days ? expires.setDate(expires.getDate() + days) : null; - } + if (!server) return interaction.followUp('You have inputted an invalid server ID.'); try { await addServerBlacklist(server.id, interaction.user, hub.id, reason, expires); - await connectedList.delete({ where: { channelId: serverSetup?.channelId } }); } catch (err) { logger.error(err); captureException(err); interaction.followUp(`Failed to blacklist **${server.name}**. Enquire with the bot developer for more information.`); + return; } if (expires && interaction.guildId) scheduleUnblacklist('server', interaction.client, interaction.guildId, hub.id, expires); - await interaction.followUp(`Blacklisted **${server.name}** for reason \`${reason}\`.`); + const successEmbed = new EmbedBuilder() + .setDescription(`${emojis.normal.tick} **${server.name}** has been successfully blacklisted!`) + .setColor('Green') + .addFields( + { + name: 'Reason', + value: reason ? reason : 'No reason provided.', + inline: true, + }, + { + name: 'Expires', + value: expires ? `` : 'Never.', + inline: true, + }, + ); - // TODO: Use embeds for notifications? - if (serverSetup) { - const channel = await interaction.client.channels.fetch(serverSetup.channelId); + await interaction.followUp({ embeds: [successEmbed] }); + + const connected = await db.connectedList.findFirst({ where: { serverId: serverOpt, hubId: hub.id } }); + if (connected) { + // notify the server that they have been blacklisted + const channel = await interaction.client.channels.fetch(connected.channelId).catch(() => null); if (channel?.isTextBased()) notifyBlacklist(channel, hub.id, expires, reason).catch(() => null); + + // delete the connected channel from db so they can't reconnect + await db.connectedList.delete({ where: { channelId: connected.channelId } }); } } + else if (subCommandGroup == 'remove') { - if (!serverInBlacklist) return await interaction.reply({ content: 'The server is not blacklisted.', ephemeral: true }); - await removeBlacklist('server', hub.id, serverInBlacklist.serverId); + const blacklistedServer = await db.blacklistedServers.findFirst({ where: { serverId: serverOpt } }); + if (!blacklistedServer) return await interaction.followUp({ content: 'The server is not blacklisted.', ephemeral: true }); - // Using name from DB since the bot can't access server through API. - interaction.reply(`The server **${serverInBlacklist.serverName}** has been removed from the blacklist.`); + await removeBlacklist('server', hub.id, blacklistedServer.serverId); - modActions(interaction.user, { - action: 'unblacklistServer', - oldBlacklist: serverInBlacklist, - hubId: hub.id, - timestamp: new Date(), - }); + // Using name from DB since the bot can't access server through API. + interaction.followUp(`The server **${blacklistedServer.serverName}** has been removed from the blacklist.`); } }, }; diff --git a/src/Scripts/blacklist/user.ts b/src/Scripts/blacklist/user.ts index 01e7baab..9416ecaa 100644 --- a/src/Scripts/blacklist/user.ts +++ b/src/Scripts/blacklist/user.ts @@ -1,67 +1,41 @@ +import { hubs } from '@prisma/client'; import { ChatInputCommandInteraction, EmbedBuilder } from 'discord.js'; -import { getDb } from '../../Utils/utils'; import { modActions } from '../networkLogs/modActions'; -import { addUserBlacklist, notifyBlacklist, removeBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; +import { addUserBlacklist, fetchUserBlacklist, notifyBlacklist, removeBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; import emojis from '../../Utils/JSON/emoji.json'; +import parse from 'parse-duration'; export default { - async execute(interaction: ChatInputCommandInteraction) { + async execute(interaction: ChatInputCommandInteraction, hub: hubs) { + await interaction.deferReply(); + const subcommandGroup = interaction.options.getSubcommandGroup(); - const hubName = interaction.options.getString('hub', true); + const userId = interaction.options.getString('user', true); const reason = interaction.options.getString('reason'); - let userOpt = interaction.options.getString('user', true); - let user; - - - try { - userOpt = userOpt.replaceAll(/<@|!|>/g, ''); - user = interaction.client.users.cache.find(u => u.tag === userOpt); - if (user === undefined) user = await interaction.client.users.fetch(userOpt); - } - catch { - return interaction.reply('Could not find user. Use an ID instead.'); - } - - const db = getDb(); - const hubInDb = await db.hubs.findFirst({ - where: { - name: hubName, - OR: [ - { moderators: { some: { userId: interaction.user.id } } }, - { ownerId: interaction.user.id }, - ], - }, - }); - if (!hubInDb) return await interaction.reply('Hub with that name not found. Or you are not a moderator of that hub.'); - const userInBlacklist = await db.blacklistedUsers.findFirst({ where: { userId: user.id, hubs: { some: { hubId: hubInDb.id } } } }); + const duration = parse(`${interaction.options.getString('duration')}`); + const expires = duration ? new Date(Date.now() + duration) : undefined; if (subcommandGroup == 'add') { - await interaction.deferReply(); + // get ID if user inputted a @ mention + const userOpt = userId.replaceAll(/<@|!|>/g, ''); + // find user through username if they are cached or fetch them using ID + const user = interaction.client.users.cache.find((u) => u.username === userOpt) ?? + await interaction.client.users.fetch(userOpt).catch(() => null); - let expires: Date | undefined; - const mins = interaction.options.getNumber('minutes'); - const hours = interaction.options.getNumber('hours'); - const days = interaction.options.getNumber('days'); + if (!user) return interaction.followUp('Could not find user. Use an ID instead.'); + if (user.id === interaction.user.id) return interaction.followUp('You cannot blacklist yourself.'); + if (user.id === interaction.client.user?.id) return interaction.followUp('You cannot blacklist the bot wtf.'); + const userInBlacklist = await fetchUserBlacklist(hub.id, userOpt); if (userInBlacklist) { interaction.followUp(`**${user.username}** is already blacklisted.`); return; } - if (user.id === interaction.user.id) return interaction.followUp('You cannot blacklist yourself.'); - if (user.id === interaction.client.user?.id) return interaction.followUp('You cannot blacklist the bot wtf.'); - - if (mins || hours || days) { - expires = new Date(); - mins ? expires.setMinutes(expires.getMinutes() + mins) : null; - hours ? expires.setHours(expires.getHours() + hours) : null; - days ? expires.setDate(expires.getDate() + days) : null; - } - await addUserBlacklist(hubInDb.id, interaction.user, user, String(reason), expires); - if (expires) scheduleUnblacklist('user', interaction.client, user.id, hubInDb.id, expires); - - await notifyBlacklist(user, hubInDb.id, expires, String(reason)); + await addUserBlacklist(hub.id, interaction.user, user, String(reason), expires); + if (expires) scheduleUnblacklist('user', interaction.client, user.id, hub.id, expires); + notifyBlacklist(user, hub.id, expires, String(reason)); const successEmbed = new EmbedBuilder() .setDescription(`${emojis.normal.tick} **${user.username}** has been successfully blacklisted!`) @@ -78,23 +52,28 @@ export default { inline: true, }, ); + await interaction.followUp({ embeds: [successEmbed] }); } else if (subcommandGroup == 'remove') { - if (!userInBlacklist) return interaction.reply(`The user **@${user.username}** is not blacklisted.`); - const userBeforeUnblacklist = await db.blacklistedUsers.findFirst({ where: { userId: user.id } }); + const blacklistedUser = await fetchUserBlacklist(hub.id, userId); + const user = await interaction.client.users.fetch(userId).catch(() => null); - await removeBlacklist('user', hubInDb.id, user.id); - await interaction.reply(`**${user.username}** has been removed from the blacklist.`); + if (!blacklistedUser) return interaction.followUp('The inputted user is not blacklisted.'); - modActions(interaction.user, { - user, - action: 'unblacklistUser', - blacklistedFor: userBeforeUnblacklist?.hubs.find(({ hubId }) => hubId === hubInDb.id)?.reason, - hubId: hubInDb.id, - }); + await removeBlacklist('user', hub.id, blacklistedUser.userId); + await interaction.followUp(`**${user?.username || blacklistedUser?.username}** has been removed from the blacklist.`); + + if (user) { + modActions(interaction.user, { + user, + action: 'unblacklistUser', + blacklistedFor: blacklistedUser.hubs.find(({ hubId }) => hubId === hub.id)?.reason, + hubId: hub.id, + }); + } } }, }; diff --git a/src/Scripts/hub/browse.ts b/src/Scripts/hub/browse.ts index 44bfeaab..e2785fa8 100644 --- a/src/Scripts/hub/browse.ts +++ b/src/Scripts/hub/browse.ts @@ -268,7 +268,7 @@ export default { // Show new users rules & info about network const onboardingStatus = await onboarding.execute(response, hubDetails.name, channel.id, true); // if user cancelled onboarding or didn't click any buttons, stop here - if (!onboardingStatus) return; + if (!onboardingStatus) return interaction.deleteReply().catch(() => null); createConnection.execute(response, hubDetails, channel).then((success) => { if (success) { diff --git a/src/Scripts/hub/join.ts b/src/Scripts/hub/join.ts index c2517207..13edbcab 100644 --- a/src/Scripts/hub/join.ts +++ b/src/Scripts/hub/join.ts @@ -4,7 +4,7 @@ import createConnection from '../network/createConnection'; import displaySettings from '../network/displaySettings'; import emojis from '../../Utils/JSON/emoji.json'; import onboarding from '../network/onboarding'; -import { findBlacklistedServer, findBlacklistedUser } from '../../Utils/blacklist'; +import { fetchServerBlacklist, fetchUserBlacklist } from '../../Utils/blacklist'; export default { async execute(interaction: ChatInputCommandInteraction) { @@ -93,19 +93,19 @@ export default { if (!hubExists) return interaction.reply({ content: 'An error occured.', ephemeral: true }); - const serverInBlacklist = await findBlacklistedServer(hubExists.id, channel.guildId); + const serverInBlacklist = await fetchServerBlacklist(hubExists.id, channel.guildId); if (serverInBlacklist) { await interaction.reply('This server is blacklisted from joining this hub.'); return; } - const userInBlacklist = await findBlacklistedUser(hubExists.id, interaction.user.id); + const userInBlacklist = await fetchUserBlacklist(hubExists.id, interaction.user.id); if (userInBlacklist) { await interaction.reply('You have been blacklisted from joining this hub.'); return; } - if (!onboarding.execute(interaction, hubExists.name, channel.id)) return; + if (!await onboarding.execute(interaction, hubExists.name, channel.id)) return interaction.deleteReply().catch(() => null); const created = await createConnection.execute(interaction, hubExists, channel); if (created) await displaySettings.execute(interaction, created.channelId); diff --git a/src/Scripts/hub/leave.ts b/src/Scripts/hub/leave.ts index 1a51ee4f..233a919e 100644 --- a/src/Scripts/hub/leave.ts +++ b/src/Scripts/hub/leave.ts @@ -47,7 +47,7 @@ export default { content: `${normal.yes} Deleted network connection from <#${channelId}> and left the hub!`, embeds: [], components: [], - }); + }).catch(() => null); }); resetCollector.on('end', () => { diff --git a/src/Scripts/message/checks.ts b/src/Scripts/message/checks.ts index de05c813..c16df490 100644 --- a/src/Scripts/message/checks.ts +++ b/src/Scripts/message/checks.ts @@ -6,13 +6,13 @@ import { slurs } from '../../Utils/JSON/badwords.json'; import { replaceLinks } from '../../Utils/utils'; import { connectedList } from '@prisma/client'; import { HubSettingsBitField } from '../../Utils/hubSettingsBitfield'; -import { addUserBlacklist, findBlacklistedServer, findBlacklistedUser, notifyBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; +import { addUserBlacklist, fetchServerBlacklist, fetchUserBlacklist, notifyBlacklist, scheduleUnblacklist } from '../../Utils/blacklist'; export default { async execute(message: Message, networkData: connectedList, settings: HubSettingsBitField) { // true = pass, false = fail (checks) - const userBlacklisted = await findBlacklistedUser(networkData.hubId, message.author.id); - const serverBlacklisted = await findBlacklistedServer(networkData.hubId, message.guildId || ''); + const userBlacklisted = await fetchUserBlacklist(networkData.hubId, message.author.id); + const serverBlacklisted = await fetchServerBlacklist(networkData.hubId, message.guildId || ''); if (userBlacklisted || serverBlacklisted) return false; if (settings.has('SpamFilter')) { diff --git a/src/Scripts/network/onboarding.ts b/src/Scripts/network/onboarding.ts index 490b61d5..2ef50962 100644 --- a/src/Scripts/network/onboarding.ts +++ b/src/Scripts/network/onboarding.ts @@ -28,16 +28,12 @@ export default { onboardingInProgress.set(channelId, channelId); const embed = new EmbedBuilder() - .setTitle(`👋 Hey there! Welcome to ${hubName}!`) + .setTitle(`👋 Hey there, welcome to ${hubName}!`) .setDescription( stripIndents` To keep things organized, it's recommended to use a separate channel for just for this hub. But don't worry, you can always change this later. - Before we dive in, take a moment to review our rules. We want everyone to have a smooth and fun experience. - - **How it works:** the InterChat Network is like a magic bridge that links channels on different servers that are with us in this hub. So, you can chat with people from all over! - - Developer Note: And hey, if you have any cool ideas for new features, let us know! We're always looking to improve. + **How it works:** The InterChat Network is like a magic bridge that links channels on different servers that are with us in this hub. Learn more at our [guide](https://discord-interchat.github.io/docs). `, ) .setColor(constants.colors.interchatBlue) @@ -69,10 +65,7 @@ export default { }) .catch(() => null); - if (!response || response?.customId === 'cancel') { - await interaction.deleteReply(); - } - else if (response.customId === 'next') { + if (response?.customId === 'next') { const acceptButton = new ActionRowBuilder().addComponents( new ButtonBuilder().setCustomId('cancel').setLabel('Cancel').setStyle(ButtonStyle.Danger), new ButtonBuilder().setCustomId('accept').setLabel('Accept').setStyle(ButtonStyle.Success), diff --git a/src/Scripts/reactions/reactionButton.ts b/src/Scripts/reactions/reactionButton.ts index a0116cd2..17f74edd 100644 --- a/src/Scripts/reactions/reactionButton.ts +++ b/src/Scripts/reactions/reactionButton.ts @@ -2,7 +2,7 @@ import { ButtonInteraction } from 'discord.js'; import { getDb } from '../../Utils/utils'; import updateMessageReactions from '../reactions/updateMessage'; import { HubSettingsBitField } from '../../Utils/hubSettingsBitfield'; -import { findBlacklistedServer, findBlacklistedUser } from '../../Utils/blacklist'; +import { fetchServerBlacklist, fetchUserBlacklist } from '../../Utils/blacklist'; export default { async execute(interaction: ButtonInteraction) { @@ -19,8 +19,8 @@ export default { !interaction.inCachedGuild() ) return interaction.reply({ content: 'This hub does not have reactions enabled.', ephemeral: true }); - const userBlacklisted = await findBlacklistedUser(messageInDb.hubId, interaction.user.id); - const serverBlacklisted = await findBlacklistedServer(messageInDb.hubId, interaction.guild.id); + const userBlacklisted = await fetchUserBlacklist(messageInDb.hubId, interaction.user.id); + const serverBlacklisted = await fetchServerBlacklist(messageInDb.hubId, interaction.guild.id); if (userBlacklisted || serverBlacklisted) { await interaction.reply({ diff --git a/src/Scripts/reactions/viewReactionsMenu.ts b/src/Scripts/reactions/viewReactionsMenu.ts index bd2c0a96..a5d3c5e5 100644 --- a/src/Scripts/reactions/viewReactionsMenu.ts +++ b/src/Scripts/reactions/viewReactionsMenu.ts @@ -5,7 +5,7 @@ import sortReactions from './sortReactions'; import updateMessageReactions from './updateMessage'; import { HubSettingsBitField } from '../../Utils/hubSettingsBitfield'; import emojis from '../../Utils/JSON/emoji.json'; -import { findBlacklistedServer, findBlacklistedUser } from '../../Utils/blacklist'; +import { fetchServerBlacklist, fetchUserBlacklist } from '../../Utils/blacklist'; export default { async execute(interaction: ButtonInteraction) { @@ -27,8 +27,8 @@ export default { return; } - const userBlacklisted = await findBlacklistedUser(networkMessage.hubId, interaction.user.id); - const serverBlacklisted = await findBlacklistedServer(networkMessage.hubId, interaction.guildId || ''); + const userBlacklisted = await fetchUserBlacklist(networkMessage.hubId, interaction.user.id); + const serverBlacklisted = await fetchServerBlacklist(networkMessage.hubId, interaction.guildId || ''); if (userBlacklisted || serverBlacklisted) { await interaction.reply({ diff --git a/src/Utils/blacklist.ts b/src/Utils/blacklist.ts index f7580e56..744a7e84 100644 --- a/src/Utils/blacklist.ts +++ b/src/Utils/blacklist.ts @@ -6,7 +6,7 @@ import emojis from './JSON/emoji.json'; import { blacklistedServers, blacklistedUsers } from '@prisma/client'; -export async function findBlacklistedUser(hubId: string, userId: string) { +export async function fetchUserBlacklist(hubId: string, userId: string) { const db = getDb(); const userBlacklisted = await db.blacklistedUsers.findFirst({ where: { userId, hubs: { some: { hubId } } }, @@ -14,7 +14,7 @@ export async function findBlacklistedUser(hubId: string, userId: string) { return userBlacklisted; } -export async function findBlacklistedServer(hubId: string, serverId: string) { +export async function fetchServerBlacklist(hubId: string, serverId: string) { const db = getDb(); const userBlacklisted = await db.blacklistedServers.findFirst({ where: { serverId, hubs: { some: { hubId } } }, diff --git a/src/Utils/deploy-commands.ts b/src/Utils/deploy-commands.ts index 1a2220ea..5eab932d 100644 --- a/src/Utils/deploy-commands.ts +++ b/src/Utils/deploy-commands.ts @@ -6,18 +6,22 @@ import { constants } from './utils'; import fs from 'fs'; import logger from './logger'; import 'dotenv/config'; +import { InterchatCommand } from '../../typings/discord'; const clientID = process.env.CLIENT_ID as string; const server = process.argv[3]?.toLowerCase() || constants.guilds.cbhq; const staffCommands = ['Developer', 'Staff']; -const commandsPath = 'build/src/Commands'; +const commandsPath = 'build/Commands'; const rest = new REST({ version: '10' }).setToken(process.env.TOKEN as string); -function deployCommands() { - const commands: unknown[] = []; +function deployCommands(staff = false) { + const commands: InterchatCommand[] = []; fs.readdirSync(commandsPath).forEach((dir) => { + // Only proceed if dir is inside staffCommands array (for deploying only staff commands) + if (staff && !staffCommands.includes(dir)) return; + if (!staffCommands.includes(dir) && fs.statSync(`${commandsPath}/${dir}`).isDirectory()) { const commandFiles = fs.readdirSync(`${commandsPath}/${dir}`).filter(file => file.endsWith('.js')); @@ -28,50 +32,28 @@ function deployCommands() { } }); - rest.put(Routes.applicationCommands(clientID), { body: commands }) - .then(() => logger.info('Registered all application commands successfully.')) + rest.put(staff ? Routes.applicationGuildCommands(clientID, server) : Routes.applicationCommands(clientID), { body: commands }) + .then(() => logger.info('Registered application commands successfully.')) .catch(logger.error); } - -function deployStaffCommands() { - const commands: unknown[] = []; - - fs.readdirSync(commandsPath).forEach((dir) => { - if (staffCommands.includes(dir) && fs.statSync(`${commandsPath}/${dir}`).isDirectory()) { - const commandFiles = fs.readdirSync(`${commandsPath}/${dir}`).filter(file => file.endsWith('.js')); - - for (const commandFile of commandFiles) { - const command = require(`../Commands/${dir}/${commandFile}`); - commands.push(command.default.data.toJSON()); - } - } - }); - - rest.put(Routes.applicationGuildCommands(clientID, server), { body: commands }) - .then(() => { - rest.get(Routes.guild(server)) - .then((res: any) => logger.info(`Registered Staff application commands for \u001b[35m${res.name}\u001b[0m successfully.`)); - }).catch(logger.error); -} - // parse command line args to determine which type of deploy const args = process.argv[2]?.toLowerCase(); switch (args) { + case undefined: + deployCommands(); + break; + case '--staff': case '-s': - deployStaffCommands(); + deployCommands(true); break; case '-b': case '--both': deployCommands(); - deployStaffCommands(); - break; - - case undefined: - deployCommands(); + deployCommands(true); break; case '--help': diff --git a/src/index.ts b/src/index.ts index 6920328d..9c0ee6fe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,29 +1,17 @@ import fs from 'fs'; -import project from '../package.json'; import * as Sentry from '@sentry/node'; -import { Client, Collection, ActivityType } from 'discord.js'; +import { Client, Collection, ActivityType, ClientOptions } from 'discord.js'; import 'dotenv/config'; export class ExtendedClient extends Client { - constructor() { - super({ - intents: ['Guilds', 'GuildMessages', 'GuildMembers', 'MessageContent', 'GuildMessageReactions'], - allowedMentions: { parse: [], repliedUser: true }, - presence: { - status: 'online', - activities: [{ - state: '👀 Watching over 300+ networks... /hub browse', - type: ActivityType.Custom, - name: 'custom', - }], - }, - }); + constructor(options: ClientOptions) { + super(options); this.commands = new Collection(); this.commandCooldowns = new Collection(); this.reactionCooldowns = new Collection(); - this.description = project.description; - this.version = project.version; + this.description = 'A growing Discord bot which provides inter-server chat! https://discord-interchat.github.io/'; + this.version = '3.13.0'; } public async start(token?: string) { @@ -69,4 +57,17 @@ export class ExtendedClient extends Client { } } -new ExtendedClient().start(); +const client = new ExtendedClient({ + intents: ['Guilds', 'GuildMessages', 'GuildMembers', 'MessageContent', 'GuildMessageReactions'], + allowedMentions: { parse: [], repliedUser: true }, + presence: { + status: 'online', + activities: [{ + state: '👀 Watching over 300+ networks... /hub browse', + type: ActivityType.Custom, + name: 'custom', + }], + }, +}); + +client.start(); diff --git a/tsconfig.json b/tsconfig.json index 09b61f41..3ac348ae 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,101 +1,25 @@ { // "include": ["./typings/**/*.d.ts"], // "./typings/**/*.d.ts" "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - /* Projects */ - "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - /* Language and Environment */ - "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - // "rootDir": "./", /* Specify the root folder within your source files. */ - // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - "resolveJsonModule": true, /* Enable importing .json files. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - /* JavaScript Support */ - "allowJs": false, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - "outDir": "build", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "incremental": true, + "composite": true, + "target": "ESNext", + "module": "commonjs", + "moduleResolution": "Node", + "resolveJsonModule": true, + "allowJs": false, + "rootDir": "./src/", + "outDir": "./build/", + "esModuleInterop": true, + "strict": true, + "sourceMap": true, + // "inlineSources": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true }, "include": [ "src/**/*", "src/**/*.json", - "package.json", // "typings/**/*" ] }