Skip to content

Commit

Permalink
🎫 Ticket: Add/Rem role, more logs and fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed May 1, 2024
1 parent 3515eb9 commit 0e98d27
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 20 deletions.
2 changes: 1 addition & 1 deletion release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class Build {
}

async release (): Promise<void> {
const args = ['.', '--compress', 'Brotli', '--no-bytecode', '--public-packages', '"*"', '--public']
const args = ['.', '--no-bytecode', '--public-packages', '"*"', '--public']
const builds: string[] = []
const manifests: BuildManifest[] = []

Expand Down
79 changes: 79 additions & 0 deletions src/discord/commands/configs/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { sendEmbed } from '@/discord/components/payments'
import { ticketButtonsConfig } from '@/discord/components/tickets'
import { Database, validarURL } from '@/functions'
import { CustomButtonBuilder, Discord } from '@/functions/Discord'
import { type RoleForConfig } from '@/interfaces/Ticket'
import {
ActionRowBuilder,
type ApplicationCommandOptionChoiceData,
ApplicationCommandOptionType,
ApplicationCommandType,
ButtonStyle,
Expand Down Expand Up @@ -257,10 +259,44 @@ new Command({
description: '[ 🎫 Ticket ] Chat onde seram enviadas as logs dos tickets.',
type: ApplicationCommandOptionType.Channel,
channelTypes: [ChannelType.GuildText]
},
{
name: 'add-role-team',
required: false,
description: '[ 🎫 Ticket ] Adicionar cargos do suporte.',
type: ApplicationCommandOptionType.Role
},
{
name: 'rem-role-team',
description: '[ 🎫 Ticket ] Remover cargos',
type: ApplicationCommandOptionType.String,
required: false,
autocomplete: true
}
]
}
],
async autoComplete (interaction) {
const { options, guildId } = interaction

switch (options.getSubcommand()) {
case 'ticket': {
switch (options.data[0].options?.[0].name) {
case 'rem-role-team': {
const roles = await db.guilds.get(`${guildId}.config.ticket.roles`) as RoleForConfig[]
const respond: Array<ApplicationCommandOptionChoiceData<string | number>> = []
if (roles !== undefined) {
for (const role of roles) {
respond.push({ name: `${role.name} | ${role.id}`, value: role.id })
}
}
await interaction.respond(respond)
break
}
}
}
}
},
async run (interaction) {
if (
await Discord.Permission(
Expand Down Expand Up @@ -474,6 +510,49 @@ new Command({
const limit = options.getNumber('limit')
const claimChannel = options.getChannel('claim-channel')
const logs = options.getChannel('logs-channel')
const addRole = options.getRole('add-role-team')
const remRole = options.getString('rem-role-team')

if (addRole !== null) {
const roles = await db.guilds.get(`${guildId}.config.ticket.roles`) as RoleForConfig[]

if ((roles ?? []).some((role) => role.id === addRole.id)) {
await interaction.editReply({
embeds: [new EmbedBuilder({
title: '❌ Esse cargo já está na lista!'
}).setColor('Red')]
})
return
}

const newRoles = [
...(roles ?? []),
{ name: addRole.name, id: addRole.id }
] satisfies RoleForConfig[]

console.log(roles, newRoles)

await new Database({
interaction,
pathDB: 'config.ticket.roles',
typeDB: 'guilds'
}).set({
data: newRoles
})
}

if (remRole !== null) {
const roles = await db.guilds.get(`${guildId}.config.ticket.roles`) as RoleForConfig[]
const removedRole = roles.filter((role) => role.id !== remRole)

await new Database({
interaction,
pathDB: 'config.ticket.roles',
typeDB: 'guilds'
}).set({
data: removedRole
})
}

if (channel !== null) {
const sendChannel = guild?.channels.cache.get(String(channel?.id)) as TextChannel
Expand Down
5 changes: 2 additions & 3 deletions src/discord/components/tickets/collectorButtons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export async function ticketCollectorButtons (options: {
Switch: async () => { await Constructor.switch({ channelId: key.split('-')[1] ?? channelId }) },
Question: async () => { await ButtonConstructor.Question() },

Delete: async () => { await Constructor.delete({ ask: true }) },
Delete: async () => { await Constructor.delete({ ask: true, channelId: key.split('-')[1] ?? channelId }) },
DeleteTemplate: async () => { await Constructor.DeleteTemplate() },

SetSelect: async () => { await ButtonConstructor.setSystem({ type: 'select' }) },
Expand Down Expand Up @@ -129,8 +129,7 @@ export async function ticketCollectorButtons (options: {
Transcript: async () => { await Constructor.Transcript({ channelId: key.split('-')[1] }) },

/* Sistema de Claim */
Claim: async () => { await ClaimConstructor.Claim({ key }) },
SaveLogs: async () => { await ClaimConstructor.SaveLogs() }
Claim: async () => { await ClaimConstructor.Claim({ key }) }
}

const customIdHandler = customIdHandlers[key.split('-')[0]]
Expand Down
5 changes: 1 addition & 4 deletions src/discord/components/tickets/functions/claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export class TicketClaim {
const buttons = await this.buttons({ channelId })

const message = await channelClaim.send({
content: (ticketConfig?.roles ?? []).length > 0 ? ticketConfig.roles?.map((role) => `<@&${role.id}>`).join(' ') : undefined,
embeds: [embed],
components: [buttons]
})
Expand Down Expand Up @@ -198,8 +199,4 @@ export class TicketClaim {
})
})
}

async SaveLogs (): Promise<void> {

}
}
41 changes: 37 additions & 4 deletions src/discord/components/tickets/functions/ticket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { db } from '@/app'
import { createRow, CustomButtonBuilder, delay, Discord } from '@/functions'
import { type Claim, type TicketConfig, type Ticket as TicketDBType, type User } from '@/interfaces/Ticket'
import { ActionRowBuilder, AttachmentBuilder, ButtonBuilder, type ButtonInteraction, ButtonStyle, type CacheType, ChannelType, type ChatInputCommandInteraction, codeBlock, ComponentType, EmbedBuilder, type GuildBasedChannel, type ModalSubmitInteraction, type OverwriteResolvable, PermissionsBitField, type StringSelectMenuInteraction, TextChannel } from 'discord.js'
import { type History, type Claim, type TicketConfig, type Ticket as TicketDBType, type User } from '@/interfaces/Ticket'
import { ActionRowBuilder, AttachmentBuilder, ButtonBuilder, type ButtonInteraction, ButtonStyle, type CacheType, ChannelType, type ChatInputCommandInteraction, codeBlock, ComponentType, EmbedBuilder, type GuildBasedChannel, type Message, type ModalSubmitInteraction, type OverwriteResolvable, PermissionsBitField, type StringSelectMenuInteraction, TextChannel } from 'discord.js'
import { TicketClaim } from './claim'
import { ticketButtonsConfig } from './ticketUpdateConfig'

Expand Down Expand Up @@ -331,6 +331,17 @@ export class Ticket {
footer: { text: `Por: ${user.displayName} | Id: ${user.id}`, iconURL: user?.avatarURL() ?? undefined }
}).setColor(isOpen ? 'Green' : 'Red')
]
}).then(async (message) => {
await db.tickets.push(`${guildId}.tickets.${channelId}.history`, {
role: 'bot',
message: {
id: message.id,
content: `Usuário ${user.username}, ${isOpen ? 'abriu o ticket' : 'fechou o ticket'}!`
},
date: message.createdAt,
deleted: false,
user: { id: this.interaction.client.user.id, name: this.interaction.client.user.username }
} satisfies History)
})

if (claim?.channelId === undefined || claim?.messageId === undefined) {
Expand Down Expand Up @@ -647,11 +658,16 @@ export class Ticket {
}).setColor('Red')]
})
} else {
let content: string = ''
let messageSend: Message<true> | undefined
if (memberTeam) {
await channel.send({
embeds: [new EmbedBuilder({
title: `Usuário ${user.displayName}, reivindicou o ticket!`
}).setColor('Green')]
}).then((message) => {
content += `Usuário ${user.displayName}, reivindicou o ticket!`
messageSend = message
})
} else {
await channel.send({
Expand All @@ -660,8 +676,21 @@ export class Ticket {
timestamp: new Date(),
footer: { text: `Por: ${interaction.user.displayName} | ${interaction.user.id}`, iconURL: interaction.user?.avatarURL() ?? undefined }
}).setColor('Green')]
}).then(async (message) => {
content += `Usuário ${changeUsers.map((user) => user.displayName).join(', ')} adicionado ao Ticket!`
messageSend = message
})
}
await db.tickets.push(`${guildId}.tickets.${channelId}.history`, {
role: 'bot',
message: {
id: messageSend?.id ?? '0',
content
},
date: messageSend?.createdAt ?? new Date(),
deleted: false,
user: { id: interaction.client.user.id, name: interaction.client.user.username }
} satisfies History)
}
return false
})
Expand Down Expand Up @@ -737,7 +766,7 @@ export class Ticket {
{ name: '\u200E', value: '\u200E', inline },

{ name: '🔎 Ticket ID:', value: codeBlock(ticket.channelId), inline },
{ name: '🤝 Convidados:', value: codeBlock(ticket.users.length === 0 ? 'Não houve convidados!' : ticket.users?.map((user) => user.displayName)?.join(', ')), inline },
{ name: '🤝 Convidados:', value: codeBlock(ticket.users.length === 0 ? 'Não houve convidados!' : ticket.users?.map((user) => `\n\nUser: ${user.displayName} \nId: ${user.id}`)?.join(', ')), inline },
{ name: '\u200E', value: '\u200E', inline },

{ name: '📅 Data:', value: codeBlock(new Date(ticket.createAt).toLocaleString()), inline },
Expand Down Expand Up @@ -767,7 +796,11 @@ export class Ticket {
const dia = data.getDate().toString().padStart(2, '0')

text += dia !== dayCache ? `\n\n[${ano}:${mes}:${dia}]\n\n` : ''
text += `[${data.getHours()}:${data.getMinutes()}] [${message.role}]${message.deleted ? ' [DELETED] ' : ''} ${message.user.name}: ${message.message.content}\n`
if (message.role === 'bot') {
text += `\n\n[${data.getHours()}:${data.getMinutes()}] ${message.message.content}\n\n`
} else {
text += `[${data.getHours()}:${data.getMinutes()}] [${message.role}]${message.deleted ? ' [DELETED] ' : ''} ${message.user.name}: ${message.message.content}\n`
}

dayCache = dia
}
Expand Down
11 changes: 9 additions & 2 deletions src/discord/components/tickets/functions/ticketUpdateConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,15 @@ export async function ticketButtonsConfig ({
confirm?: boolean
}): Promise<void> {
const { guildId, channelId } = interaction
if (interaction.isChatInputCommand()) return
if (message === undefined) message = interaction.message as Message<boolean>
if (message === undefined && !interaction.isChatInputCommand()) message = interaction.message as Message<boolean>
if (message === undefined) {
await interaction.editReply({
embeds: [new EmbedBuilder({
title: '❌ | Não foi possivel estimar a mensagem onde os botões serão implementados!'
}).setColor('Red')]
})
return
}

const options: Array<{ label: string, description: string, value: string, emoji: string }> = []
const data = await db.messages.get(`${guildId}.ticket.${channelId}.messages.${message.id}`)
Expand Down
12 changes: 6 additions & 6 deletions src/functions/setDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,22 @@ export class Database implements DatabaseType {
* Seta inforamções no database
*/
public async set (options: {
data: TextChannel | CategoryChannel | string | number
data: TextChannel | CategoryChannel | string | number | any[]
text?: string
}): Promise<void> {
const { data, text } = options
const { interaction, pathDB, typeDB } = this
const { user, guildId, channel } = interaction
try {
if (typeof data === 'string' || typeof data === 'number') {
if (typeof data === 'string' || typeof data === 'number' || Array.isArray(data)) {
const { user, guildId, channel } = interaction
await db[typeDB ?? 'guilds'].set(`${guildId}.${pathDB}`, data)

try {
const embedCategoriaSet = new EmbedBuilder()
.setDescription('**✅ - Informação ' + '``' + data + '`` ' + `${text ?? 'foi atribuído a propriedade'} ${pathDB}!**`)
.setColor('Green')
.setAuthor({ name: `${user.username}`, iconURL: `${user.displayAvatarURL()}` })
const embedCategoriaSet = new EmbedBuilder({
description: `**✅ - Informação ${Array.isArray(data) ? '*Array*' : data} ${text ?? 'foi atribuído a propriedade'} ${pathDB}!**`,
author: { name: user.username, iconURL: user.displayAvatarURL() }
}).setColor('Green')

await interaction.editReply({ embeds: [embedCategoriaSet] })
} catch (error) {
Expand Down
6 changes: 6 additions & 0 deletions src/interfaces/Ticket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,14 @@ export interface TicketUser {
}
}

export interface RoleForConfig {
id: string
name: string
}

export interface TicketConfig {
limit?: number
claimId?: string
logsId?: string
roles?: RoleForConfig[]
}

0 comments on commit 0e98d27

Please sign in to comment.