melhore esse código

melhore esse código


const Event = require('../../structures/Event')
const { ButtonBuilder, ActionRowBuilder, StringSelectMenuBuilder, EmbedBuilder, InteractionType, PermissionsBitField, ChannelType, StringSelectMenuOptionBuilder, ButtonStyle } = require('discord.js')

const ticketConfig = require('../../utils/ticketConfig')
const { defaultPermissions, embedLogsTicket } = require('../../utils/exports')

module.exports = class extends Event {
    constructor(client) {
        super(client, {
            name: 'interactionCreate'
        })
    }

    run = async (interaction) => {
        if (!interaction.guild) return
        if (!interaction) return

        if (interaction.type === InteractionType.ApplicationCommand) {
            const cmd = this.client.slashCommands.find(c => c.name == interaction.commandName)

            if (cmd) {
                cmd.run(interaction)
            }
        } else if (interaction.type === InteractionType.MessageComponent) {
            if (interaction.customId.startsWith('openTicket')) {
                const channel = await interaction.guild.channels.create({
                    name: `ticket-${interaction.user.username}`,
                    type: ChannelType.GuildText,
                    parent: ticketConfig.openTicketCategory,
                    topic: `ticket-waiting-${interaction.user.id}`,
                    permissionOverwrites: [
                        {
                            id: interaction.guild.id,
                            deny: [PermissionsBitField.Flags.ViewChannel]
                        },
                        {
                            id: interaction.user.id,
                            allow: [
                                defaultPermissions
                            ]
                        },
                    ]
                })

                interaction.reply({ content: `Seu ticket foi aberto com sucesso no canal ${channel.toString()}!`, ephemeral: true })

                const buttons = ticketConfig.ticketCategories.map(c => c.button).map(x => new StringSelectMenuOptionBuilder(x))
                const row = new ActionRowBuilder()
                    .addComponents([
                        new StringSelectMenuBuilder()
                            .setCustomId(`ticketSelectMenu`)
                            .setPlaceholder('Selecione uma categoria')
                            .addOptions(buttons)
                    ])

                const msg = await channel.send({ content: interaction.user.toString(), embeds: [ticketConfig.openTicketEmbed], components: [row] })
                msg.pin()

                setTimeout(async () => {
                    const topic = channel.topic.split('-')[1]
                    if (topic == 'waiting') {
                        const closingButton = new ActionRowBuilder()
                            .addComponents(
                                new ButtonBuilder()
                                    .setCustomId('nil')
                                    .setLabel('Deletando ticket...')
                                    .setEmoji('🗑️')
                                    .setStyle(ButtonStyle.Secondary)
                                    .setDisabled(true),
                            );

                        await msg.edit({ components: [closingButton] })
                        await channel.send({ content: 'Você demorou muito para selecionar. Deletando ticket...' })

                        setTimeout(() => {
                            channel.delete().catch()
                        }, 2000)
                    }
                }, 20000)
            } else if (interaction.customId === 'closeTicket') {
                let topic = interaction.channel.topic.split('-')[2]

                if (!interaction.guild.members.cache.has(topic)) {
                    return interaction.reply({ content: `${interaction.user}, o dono do ticket saiu do servidor. Aguarde um administrador deletar o ticket manualmente.` })
                }

                if (!interaction.channel.permissionsFor(topic).has([PermissionsBitField.Flags.ViewChannel])) { return interaction.reply({ content: 'Esse ticket já está fechado!', ephemeral: true }) }

                await interaction.channel.permissionOverwrites.edit(
                    interaction.channel.topic.split('-')[2],
                    { ViewChannel: false }
                ).catch(e => {
                    console.log(e)
                    return interaction.reply(`${interaction.user.username}, alguma coisa aconteceu de errado ao fechar esse ticket`)
                })

                const deleteButton = new ButtonBuilder()
                    .setLabel('Deletar ticket')
                    .setEmoji('🗑')
                    .setCustomId('deleteTicket')
                    .setStyle(ButtonStyle.Danger)

                const row = new ActionRowBuilder().addComponents(deleteButton)

                const embed = new EmbedBuilder()
                    .setDescription(`O ticket foi fechado por ${interaction.user}`)
                    .setColor('#FF0000')

                interaction.message.edit({
                    components: [
                        new ActionRowBuilder().addComponents(
                            new ButtonBuilder(interaction.message.components[0].components[0].data)
                                .setDisabled(true)
                        )]
                })
                interaction.reply({ embeds: [embed], components: [row] }).catch((e) => { console.log(e) })

                interaction.guild.channels.cache.get(ticketConfig.logsChannel).send({ embeds: [embedLogsTicket(interaction, interaction.channel.name, 'Fechado', '#ffff00')] }).catch()
            } else if (interaction.customId === 'deleteTicket') {
                if (!interaction.member.permissions.has(PermissionsBitField.Flags.Administrator) && !(interaction.member.member.roles.cache.some(r => ticketConfig.staffRoles.includes(r.id)))) return interaction.reply({ content: 'Você precisa de permissão para executar esse comando.', ephemeral: true })

                interaction.message.edit({
                    components: [
                        new ActionRowBuilder().addComponents(
                            new ButtonBuilder(interaction.message.components[0].components[0].data)
                                .setDisabled(true),
                        )
                    ]
                })

                await interaction.reply({ content: 'O ticket será deletado em 5 segundos.' })
                interaction.guild.channels.cache.get(ticketConfig.logsChannel).send({ embeds: [embedLogsTicket(interaction, interaction.channel.name, 'Deletado', '#ff0000')] }).catch()

                setTimeout(() => {
                    if (interaction && interaction.channel) {
                        interaction.channel.delete().catch()
                    }
                }, 5000)
            } else if (interaction.customId.startsWith('ticketSelectMenu')) {
                const ticketObject = ticketConfig.ticketCategories.find(n => n.name.toLowerCase() === interaction.values[0].toLowerCase());
                if (!ticketObject) return

                const category = ticketObject.category

                let count = 0

                const allChannels = interaction.guild.channels.cache
                    .filter(c => c.type === ChannelType.GuildText && c.permissionsFor(interaction.user.id).has([PermissionsBitField.Flags.ViewChannel]) && (c.parentId === category))

                allChannels.forEach(i => {
                    if (count == 1 || !i.topic) return

                    const topicSplit = i.topic.split('-')[1]

                    if ((i.topic).includes(`${interaction.user.id}`) && (topicSplit == ticketObject.name)) {
                        count++;
                        return interaction.reply({ content: 'Você já tem um ticket dessa categoria aberto!', ephemeral: true })
                    }

                })

                if (count) { return }


                interaction.channel.edit({
                    name: `${ticketObject.name}-${interaction.user.username}`,
                    topic: `ticket-${ticketObject.name}-${interaction.user.id}`,
                    parent: category,
                    permissionOverwrites: [
                        {
                            id: interaction.guild.id,
                            deny: [PermissionsBitField.Flags.ViewChannel]
                        },
                        {
                            id: interaction.user.id,
                            allow: [defaultPermissions]
                        },
                        ...ticketObject.staffRoles

                    ]
                })

                const embed = new EmbedBuilder()
                    .setColor('#2B2D31')
                    .setDescription(`👋 Olá ${interaction.user}, tudo bem?\n\nEm breve um membro da nossa **equipe** responsável pela categoria selecionada irá te responder.\n\nDescreva com **detalhes** o motivo do seu ticket para **agilizar** o atendimento, se\nnecessário o envio de algum tipo de arquivo, envie-o antecipadamente para que\no atendimento seja realizado mais rápido.\n\n*Por favor, não marque nenhum membro da equipe nessa sala.*`)

                const row = new ActionRowBuilder()
                    .addComponents(
                        new ButtonBuilder()
                            .setCustomId('closeTicket')
                            .setLabel('Fechar ticket')
                            .setEmoji('🔒')
                            .setStyle(ButtonStyle.Secondary),
                    );


                interaction.message.edit({
                    embeds: [embed],
                    components: [row]
                })

                interaction.guild.channels.cache.get(ticketConfig.logsChannel).send({ embeds: [embedLogsTicket(interaction, `${ticketObject.name}-${interaction.user.username}`, 'Aberto', '#00ff00')] }).catch()

                interaction.deferUpdate()
            }
        }
    }
}