Skip to content

Commit

Permalink
code clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
Kathund committed Jul 30, 2024
1 parent a5e51aa commit bcea998
Show file tree
Hide file tree
Showing 11 changed files with 144 additions and 169 deletions.
1 change: 0 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export default [
'no-constant-condition': ['error', { checkLoops: false }],
'prefer-const': ['warn', { destructuring: 'all' }],
curly: ['warn', 'multi-line', 'consistent'],
'@typescript-eslint/no-explicit-any': 'off',
'logical-assignment-operators': 'warn',
'no-template-curly-in-string': 'error',
'quote-props': ['error', 'as-needed'],
Expand Down
4 changes: 2 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { deployCommands } from './src/functions/deployCommands';
import { Client, Events, GatewayIntentBits } from 'discord.js';
import deployCommands from './src/functions/deployCommands';
import { execute } from './src/events/ready';
import { token } from './config.json';

const client = new Client({
const client: Client = new Client({
intents: [
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessages,
Expand Down
14 changes: 8 additions & 6 deletions src/commands/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const data = new SlashCommandBuilder()
.setDescription('Shows info about the bot')
.addStringOption((option) => option.setName('query').setDescription('The query to search for').setRequired(false));

export const execute = async (interaction: ChatInputCommandInteraction) => {
export async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
try {
const query = interaction.options.getString('query') || null;
if (!query) {
Expand All @@ -15,25 +15,27 @@ export const execute = async (interaction: ChatInputCommandInteraction) => {
.setDescription(
'The documentation for Hypixel API • Reborn can be found [here](https://hypixel-api-reborn.github.io).'
);
return await interaction.reply({ embeds: [embed] });
await interaction.reply({ embeds: [embed] });
return;
}
const docs = await Doc.fetch(
'https://raw.githubusercontent.com/hypixel-api-reborn/hypixel-api-reborn/docs/master.json',
{ force: true }
);
return await interaction.reply({ embeds: [docs.resolveEmbed(query)] });
await interaction.reply({ embeds: [docs.resolveEmbed(query)] });
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
if (interaction.replied || interaction.deferred) {
return await interaction.followUp({
await interaction.followUp({
content: 'Something went wrong. Please try again later.',
ephemeral: true
});
return;
}
return await interaction.reply({
await interaction.reply({
content: 'Something went wrong. Please try again later.',
ephemeral: true
});
}
};
}
106 changes: 66 additions & 40 deletions src/commands/tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ import {
ModalActionRowComponentBuilder,
ChatInputCommandInteraction,
AutocompleteInteraction,
GuildMemberRoleManager,
SlashCommandBuilder,
TextInputBuilder,
ActionRowBuilder,
TextInputStyle,
ModalBuilder,
EmbedBuilder,
TextChannel
ChannelType
} from 'discord.js';
import { contributorsRole, teamRole, devRole, supportCategory } from '../../config.json';
import { deleteTag, getTag, getTagNames } from '../functions/mongo';
import { Tag as TagType } from '../types/main';
import { GuildMember } from 'discord.js';

export const data = new SlashCommandBuilder()
.setName('tag')
Expand Down Expand Up @@ -50,11 +49,12 @@ export const data = new SlashCommandBuilder()
)
);

export const autoComplete = async (interaction: AutocompleteInteraction) => {
export async function autoComplete(interaction: AutocompleteInteraction): Promise<void> {
const focusedOption = interaction.options.getFocused(true);
const input = focusedOption.value;
const names = (await getTagNames()).names as string[];
let choices: string | any[] = [];
const names = (await getTagNames()).names;
if (!names) return;
let choices: string | string[] = [];
if (
('send' === interaction.options.getSubcommand() ||
'edit' === interaction.options.getSubcommand() ||
Expand All @@ -65,12 +65,13 @@ export const autoComplete = async (interaction: AutocompleteInteraction) => {
}
const displayedChoices = choices.slice(0, 25);
await interaction.respond(displayedChoices.map((choice) => ({ name: choice, value: choice })));
};
}

export const execute = async (interaction: ChatInputCommandInteraction) => {
export async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
try {
if (!interaction.member) return;
const subCommand = interaction.options.getSubcommand();
const memberRoles = (interaction.member as GuildMember).roles.cache.map((role) => role.id);
const memberRoles = (interaction.member.roles as GuildMemberRoleManager).cache.map((role) => role.id);
switch (subCommand) {
case 'add': {
if (memberRoles.some((role) => [contributorsRole, teamRole, devRole].includes(role))) {
Expand All @@ -95,15 +96,17 @@ export const execute = async (interaction: ChatInputCommandInteraction) => {
modal.addComponents(tagFormNameReason, tagFormContentReason);
await interaction.showModal(modal);
} else {
return await interaction.reply({
await interaction.reply({
content: 'You do not have permission to use this command',
ephemeral: true
});
}
break;
}
case 'edit': {
const name = (interaction.options.getString('name') as string).toLowerCase();
let name = interaction.options.getString('name');
if (!name) return;
name = name.toLowerCase();
if (memberRoles.some((role) => [teamRole, devRole].includes(role))) {
const modal = new ModalBuilder()
.setCustomId(`t.e.${name}`)
Expand All @@ -121,7 +124,7 @@ export const execute = async (interaction: ChatInputCommandInteraction) => {
modal.addComponents(tagFormContentReason);
await interaction.showModal(modal);
} else {
return await interaction.reply({
await interaction.reply({
content: 'You do not have permission to use this command',
ephemeral: true
});
Expand All @@ -130,42 +133,51 @@ export const execute = async (interaction: ChatInputCommandInteraction) => {
}
case 'delete': {
if (memberRoles.some((role) => [teamRole, devRole].includes(role))) {
const inputTag = await deleteTag((interaction.options.getString('name') as string).toLowerCase());
const name = interaction.options.getString('name');
if (!name) return;
const inputTag = await deleteTag(name.toLowerCase());
if (inputTag.success) {
return await interaction.reply({
await interaction.reply({
content: 'Tag deleted successfully',
ephemeral: true
});
return;
}
return await interaction.reply({
await interaction.reply({
content: 'Tag not found',
ephemeral: true
});
return;
}
return await interaction.reply({
await interaction.reply({
content: 'You do not have permission to use this command',
ephemeral: true
});
return;
}
case 'send': {
const name = (interaction.options.getString('name') as string).toLowerCase();
const name = interaction.options.getString('name');
if (!name) return;
let messageLink = interaction.options.getString('message-link') || null;
const user = interaction.options.getUser('user');
const inputTag = await getTag(name);
const inputTag = await getTag(name.toLowerCase());
if (inputTag.success) {
if (!inputTag.tag?.status) return;
await interaction.deferReply({ ephemeral: true });
if (messageLink) {
if (!messageLink.includes('discord.com/channels/')) {
return await interaction.followUp({
await interaction.followUp({
content: 'Invalid message link',
ephemeral: true
});
return;
}
if (!messageLink.includes('https://')) {
return await interaction.followUp({
await interaction.followUp({
content: 'Invalid message link',
ephemeral: true
});
return;
}
if (messageLink.startsWith('https://canary.discord.com')) {
messageLink = messageLink.replace('canary.', '');
Expand All @@ -176,70 +188,84 @@ export const execute = async (interaction: ChatInputCommandInteraction) => {
const split = messageLink.split('https://discord.com/channels/')[1].split('/');
const channel = await interaction.client.channels.fetch(split[1]);
if (!channel) {
return await interaction.followUp({
await interaction.followUp({
content: 'Channel not found',
ephemeral: true
});
return;
}
if ((channel as TextChannel).parentId !== supportCategory) {
return await interaction.followUp({
if (channel.type !== ChannelType.GuildText) {
await interaction.followUp({
content: 'Invalid channel type',
ephemeral: true
});
return;
}
if (channel.parentId !== supportCategory) {
await interaction.followUp({
content: 'Tags can only be sent in support channels',
ephemeral: true
});
return;
}
const message = await (channel as TextChannel).messages.fetch(split[2]);
const message = await channel.messages.fetch(split[2]);
if (!message) {
return await interaction.followUp({
await interaction.followUp({
content: 'Message not found',
ephemeral: true
});
return;
}
message.reply({
content: user
? `${user.toString()}\n\n${(inputTag.tag as TagType).content}`
: (inputTag.tag as TagType).content
content: user ? `${user.toString()}\n\n${inputTag.tag.content}` : inputTag.tag.content
});
} else {
if ((interaction.channel as TextChannel).parentId !== supportCategory) {
return await interaction.followUp({
if (!interaction.channel) return;
if (interaction.channel.type !== ChannelType.GuildText) {
return;
}
if (interaction.channel.parentId !== supportCategory) {
await interaction.followUp({
content: 'Tags can only be sent in support channels',
ephemeral: true
});
return;
}
(interaction.channel as TextChannel).send({
content: user
? `${user.toString()}\n\n${(inputTag.tag as TagType).content}`
: (inputTag.tag as TagType).content
interaction.channel.send({
content: user ? `${user.toString()}\n\n${inputTag.tag.content}` : inputTag.tag.content
});
}

const embed = new EmbedBuilder().setTitle('Tag sent').setDescription(`Tag \`${name}\` sent`);
return await interaction.followUp({ embeds: [embed] });
await interaction.followUp({ embeds: [embed] });
return;
}
return await interaction.reply({
await interaction.reply({
content: 'Tag not found',
ephemeral: true
});
return;
}
default: {
const embed = new EmbedBuilder()
.setTitle('Invalid subcommand')
.setDescription('Please provide a valid subcommand');
return await interaction.reply({ embeds: [embed] });
await interaction.reply({ embeds: [embed] });
}
}
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
if (interaction.replied || interaction.deferred) {
return await interaction.followUp({
await interaction.followUp({
content: 'Something went wrong. Please try again later.',
ephemeral: true
});
return;
}
return await interaction.reply({
await interaction.reply({
content: 'Something went wrong. Please try again later.',
ephemeral: true
});
}
};
}
29 changes: 12 additions & 17 deletions src/events/interactionCreate.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
/* eslint-disable no-console */
import { Interaction, Events, InteractionType, EmbedBuilder, GuildMember } from 'discord.js';
import { Interaction, Events, InteractionType, EmbedBuilder, GuildMemberRoleManager } from 'discord.js';
import { teamRole, devRole } from '../../config.json';
import { Tag, modifyTag } from '../functions/mongo';
import { eventMessage } from '../functions/logger';

export const name = Events.InteractionCreate;
export const execute = async (interaction: Interaction) => {
export async function execute(interaction: Interaction): Promise<void> {
try {
const memberRoles = (interaction.member as GuildMember).roles.cache.map((role) => role.id);
if (!interaction.member || !interaction.channel || !interaction.guild) return;
const memberRoles = (interaction.member.roles as GuildMemberRoleManager).cache.map((role) => role.id);
if (interaction.isChatInputCommand()) {
const command = interaction.client.commands.get(interaction.commandName);
if (!command) return;
if (!interaction.channel) return;
if (!interaction.guild) return;
try {
try {
eventMessage(
`Interaction Event trigged by ${interaction.user.username} (${interaction.user.id}
) ran command ${interaction.commandName} in ${interaction.guild.id} in ${interaction.channel.id}`
);
} catch (error: any) {
console.log(error);
}
eventMessage(
`Interaction Event trigged by ${interaction.user.username} (${
interaction.user.id
}) ran command ${interaction.commandName} in ${interaction.guild.id} in ${interaction.channel.id}`
);
await command.execute(interaction);
} catch (error: any) {
} catch (error) {
console.log(error);
}
} else if (interaction.isAutocomplete()) {
Expand Down Expand Up @@ -68,7 +63,7 @@ export const execute = async (interaction: Interaction) => {
}
}
}
} catch (error: any) {
} catch (error) {
console.log(error);
}
};
}
15 changes: 8 additions & 7 deletions src/events/ready.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { errorMessage, eventMessage } from '../functions/logger';
import { deployEvents } from '../functions/deployEvents';
import { Client } from 'discord.js';
import deployEvents from '../functions/deployEvents';
import { eventMessage } from '../functions/logger';
import { connectDB } from '../functions/mongo';
import { Client } from 'discord.js';

export const execute = (client: Client) => {
export function execute(client: Client): void {
try {
eventMessage(`Logged in as ${client.user?.username} (${client.user?.id})!`);
deployEvents(client);
connectDB();
} catch (error: any) {
errorMessage(error);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
}
};
}
Loading

0 comments on commit bcea998

Please sign in to comment.