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