blob: 0e6fafd3041a381ca16c2b4493c5df520dcc16e3 [file] [log] [blame]
pineafanad54d752022-04-18 19:01:43 +01001import Discord, { CommandInteraction, GuildMember, Message, MessageActionRow, MessageButton } from "discord.js";
2import { SelectMenuOption, SlashCommandSubcommandBuilder } from "@discordjs/builders";
3import { WrappedCheck } from "jshaiku";
4import generateEmojiEmbed from "../../utils/generateEmojiEmbed.js";
5import getEmojiByName from "../../utils/getEmojiByName.js";
pineafane625d782022-05-09 18:04:32 +01006import addPlural from "../../utils/plurals.js";
pineafan6702cef2022-06-13 17:52:37 +01007import client from "../../utils/client.js";
pineafanad54d752022-04-18 19:01:43 +01008
9const command = (builder: SlashCommandSubcommandBuilder) =>
10 builder
11 .setName("track")
12 .setDescription("Moves a user along a role track")
13 .addUserOption(option => option.setName("user").setDescription("The user to manage").setRequired(true))
14
15const generateFromTrack = (position: number, active: any, size: number, disabled: any) => {
16 active = active ? "ACTIVE" : "INACTIVE"
17 disabled = disabled ? "GREY." : ""
18 if (position == 0 && size == 1) return "TRACKS.SINGLE." + disabled + active
19 if (position == size - 1) return "TRACKS.VERTICAL.BOTTOM." + disabled + active
20 if (position == 0) return "TRACKS.VERTICAL.TOP." + disabled + active
21 return "TRACKS.VERTICAL.MIDDLE." + disabled + active
22}
23
24const callback = async (interaction: CommandInteraction) => {
PineappleFanb3dd83c2022-06-17 10:53:48 +010025 const { renderUser } = client.logger;
pineafanad54d752022-04-18 19:01:43 +010026 const member = interaction.options.getMember("user") as GuildMember;
27 const guild = interaction.guild;
pineafan6702cef2022-06-13 17:52:37 +010028 let config = await client.database.read(guild.id);
pineafanad54d752022-04-18 19:01:43 +010029 await interaction.reply({embeds: [new generateEmojiEmbed()
30 .setEmoji("NUCLEUS.LOADING")
31 .setTitle("Loading")
32 .setStatus("Danger")
33 ], ephemeral: true})
34 let track = 0
35 let generated;
36 const roles = await guild.roles.fetch()
37 let memberRoles = await member.roles
38 while (true) {
39 let data = config.tracks[track]
40 let managed = data.manageableBy.some(element => {return memberRoles.cache.has(element)})
41 let dropdown = new Discord.MessageSelectMenu().addOptions(config.tracks.map((option, index) => {
42 let hasRoleInTrack = option.track.some(element => {return memberRoles.cache.has(element)})
43 return new SelectMenuOption({
44 default: index == track,
45 label: option.name,
46 value: index.toString(),
pineafane625d782022-05-09 18:04:32 +010047 description: option.track.length == 0 ? "No" : addPlural(option.track.length, "role"),
PineappleFanb3dd83c2022-06-17 10:53:48 +010048 emoji: client.emojis.resolve(getEmojiByName("TRACKS.SINGLE." + (hasRoleInTrack ? "ACTIVE" : "INACTIVE"), "id"))
pineafanad54d752022-04-18 19:01:43 +010049 })
50 })).setCustomId("select").setMaxValues(1)
51 let allowed = []
52 generated = "**Track:** " + data.name + "\n" + "**Member:** " + renderUser(member.user) + "\n"
53 generated += (data.nullable ? "Members do not need a role in this track" : "A role in this track is required") + "\n"
54 generated += (data.retainPrevious ? "When promoted, the user keeps previous roles" : "Members will lose their current role when promoted") + "\n"
55 generated += "\n" + data.track.map((role, index) => {
56 let allow = (roles.get(role).position >= (interaction.member as GuildMember).roles.highest.position) && !managed
57 allowed.push(!allow)
58 return getEmojiByName(generateFromTrack(
59 index,
60 memberRoles.cache.has(role),
61 data.track.length,
62 allow
63 )) + " " +
64 roles.get(role).name + " [<@&" + roles.get(role).id + ">]"
65 }).join("\n")
66 let selected = [];
67 for (let i = 0; i < data.track.length; i++) {
68 if (memberRoles.cache.has(data.track[i])) selected.push(data.track[i])
69 }
70 let conflict = data.retainPrevious ? false : selected.length > 1;
71 let conflictDropdown
72 let currentRoleIndex
73 if (conflict) {
74 generated += `\n\n${getEmojiByName(`PUNISH.WARN.${managed ? "YELLOW" : "RED"}`)} This user has ${selected.length} roles from this track. `
75 conflictDropdown = []
76 if (
77 (roles.get(selected[0]).position < memberRoles.highest.position) || managed
78 ) {
79 generated += `In order to promote or demote this user, you must select which role the member should keep.`
80 selected.forEach(role => {
81 conflictDropdown.push(new SelectMenuOption({
82 label: roles.get(role).name,
83 value: roles.get(role).id,
84 }))
85 })
86 conflictDropdown = [new Discord.MessageSelectMenu()
87 .addOptions(conflictDropdown)
88 .setCustomId("conflict")
89 .setMaxValues(1)
90 .setPlaceholder("Select a role to keep")]
91 } else {
92 generated += "You don't have permission to manage one or more of the users roles, and therefore can't select one to keep."
93 }
94 } else {
95 currentRoleIndex = selected.length == 0 ? -1 : data.track.indexOf(selected[0].toString())
96 }
97 let m = await interaction.editReply({embeds: [new generateEmojiEmbed()
98 .setEmoji("TRACKS.ICON")
99 .setTitle("Tracks")
100 .setDescription(`${generated}`)
101 .setStatus("Success")
102 ], components: [
103 new MessageActionRow().addComponents(dropdown)
104 ]
105 .concat(conflict && conflictDropdown.length ? [new MessageActionRow().addComponents(conflictDropdown)] : [])
106 .concat([
107 new MessageActionRow().addComponents([
108 new MessageButton()
109 .setEmoji(getEmojiByName("CONTROL.UP", "id"))
110 .setLabel("Move up")
111 .setCustomId("promote")
112 .setStyle("SUCCESS")
113 .setDisabled(conflict || currentRoleIndex == 0 || (currentRoleIndex == -1 ? false : !allowed[currentRoleIndex - 1])),
114 new MessageButton()
115 .setEmoji(getEmojiByName("CONTROL.DOWN", "id"))
116 .setLabel("Move down")
117 .setCustomId("demote")
118 .setStyle("DANGER")
119 .setDisabled(conflict || (
120 data.nullable ? currentRoleIndex <= -1 :
121 currentRoleIndex == data.track.length - 1 || currentRoleIndex <= -1
122 ) || !allowed[currentRoleIndex]),
123 ])
124 ])})
125 let component;
126 try {
pineafanc6158ab2022-06-17 16:34:07 +0100127 component = await (m as Message).awaitMessageComponent({time: 300000});
pineafanad54d752022-04-18 19:01:43 +0100128 } catch (e) {
129 return
130 }
131 component.deferUpdate()
132 if (component.customId == "conflict") {
133 let rolesToRemove = selected.filter(role => role != component.values[0])
134 await member.roles.remove(rolesToRemove)
135 } else if (component.customId == "promote") {
136 if (
137 currentRoleIndex == -1 ? allowed[data.track.length - 1] :
138 allowed[currentRoleIndex - 1] && allowed[currentRoleIndex]
139 ) {
140 if (currentRoleIndex == -1) {
141 await member.roles.add(data.track[data.track.length - 1])
142 } else if (currentRoleIndex < data.track.length) {
143 if (!data.retainPrevious) await member.roles.remove(data.track[currentRoleIndex])
144 await member.roles.add(data.track[currentRoleIndex - 1])
145 }
146 }
147 } else if (component.customId == "demote") {
148 if(allowed[currentRoleIndex]) {
149 if (currentRoleIndex == data.track.length - 1) {
150 if (data.nullable) await member.roles.remove(data.track[currentRoleIndex])
151 } else if (currentRoleIndex > -1) {
152 await member.roles.remove(data.track[currentRoleIndex])
153 await member.roles.add(data.track[currentRoleIndex + 1])
154 }
155 }
156 } else if (component.customId == "select") {
157 track = component.values[0]
158 }
159 }
160}
161
pineafan6702cef2022-06-13 17:52:37 +0100162const check = async (interaction: CommandInteraction, defaultCheck: WrappedCheck) => {
PineappleFan19b002b2022-05-19 11:54:01 +0100163 let member = (interaction.member as GuildMember)
pineafanad54d752022-04-18 19:01:43 +0100164 // Allow the owner to promote anyone
PineappleFan19b002b2022-05-19 11:54:01 +0100165 if (member.id == interaction.guild.ownerId) return true
pineafan6702cef2022-06-13 17:52:37 +0100166 // Check if the user can manage any of the tracks
167 // @ts-ignore
PineappleFanb3dd83c2022-06-17 10:53:48 +0100168 let tracks = (await client.database.get(interaction.guild.id)).tracks
pineafan6702cef2022-06-13 17:52:37 +0100169 let managed = false
170 tracks.forEach(element => { if (element.track.manageableBy.some(role => member.roles.cache.has(role))) managed = true });
pineafanad54d752022-04-18 19:01:43 +0100171 // Check if the user has manage_roles permission
pineafan6702cef2022-06-13 17:52:37 +0100172 if (!managed && ! member.permissions.has("MANAGE_ROLES")) throw "You do not have the `manage_roles` permission";
pineafanad54d752022-04-18 19:01:43 +0100173 // Allow track
pineafan6702cef2022-06-13 17:52:37 +0100174 return true;
pineafanad54d752022-04-18 19:01:43 +0100175}
176
177export { command };
178export { callback };
pineafanc6158ab2022-06-17 16:34:07 +0100179export { check };
180