From cf6a5963b63be4d0af3f480db6ddd9476ce4ea26 Mon Sep 17 00:00:00 2001 From: yaansz Date: Sun, 5 Jun 2022 18:28:46 -0300 Subject: [PATCH 1/7] feat: rolegroup --- .../capivara/listeners/RoleGroup.java | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/main/java/com/softawii/capivara/listeners/RoleGroup.java diff --git a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java new file mode 100644 index 0000000..5ce1632 --- /dev/null +++ b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java @@ -0,0 +1,122 @@ +package com.softawii.capivara.listeners; + +import com.softawii.capivara.utils.Utils; +import com.softawii.curupira.annotations.IArgument; +import com.softawii.curupira.annotations.IButton; +import com.softawii.curupira.annotations.ICommand; +import com.softawii.curupira.annotations.IGroup; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.Commands; +import net.dv8tion.jda.api.interactions.components.buttons.Button; + +import java.awt.*; + +@IGroup(name = "role", description = "Role Group", hidden = false) +public class RoleGroup { + + // Specific Action + public static final String actionButton = "role-action-button"; + public static final String removeAction = "role-remove-action"; + // Confirm or Deny Action + public static final String confirmAction = "role-confirm-action"; + public static final String cancelAction = "role-cancel-action"; + + @ICommand(name="create", description = "Create a role", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name = "type", description = "Role type", type = OptionType.STRING, required = true, choices = { + @IArgument.IChoice(value="Channel", key="Channel"), + @IArgument.IChoice(value="Category", key="Category"), + @IArgument.IChoice(value="Free", key="Free") + }) + @IArgument(name = "name", description = "Role name", type = OptionType.STRING, required = false) + public static void create(SlashCommandInteractionEvent event) { + event.getChannel().sendMessage("Role created").queue(); + } + + // DELETE SECTION -> DELETE / CONFIRM / CANCEL + @ICommand(name="delete", description = "Delete a role", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="role", description = "Role", type = OptionType.ROLE, required = true) + public static void delete(SlashCommandInteractionEvent event) { + // Not null, because it's server side and required + Role role = event.getOption("role").getAsRole(); + String confirmId = String.format("%s:%s:%s", confirmAction, removeAction, role.getId()); + String cancelId = cancelAction; + + MessageEmbed messageEmbed = Utils.simpleEmbed("Are you sure?", + "You really want to delete the role " + role.getAsMention() + "??", + Color.RED); + + Button successButton = Button.success(confirmId, "Yes"); + Button cancelButton = Button.danger(cancelId, "No"); + + event.replyEmbeds(messageEmbed).addActionRow(successButton, cancelButton).setEphemeral(true).queue(); + } + + @ICommand(name="permissions", description = "update", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="role", description = "Role", type = OptionType.ROLE, required = true) + @IArgument(name="related", description = "Related", type = OptionType.CHANNEL, required = true) + @IArgument(name="type", description = "Apply to Channel or Category", type = OptionType.STRING, required = true, + choices = { + @IArgument.IChoice(value="Channel", key="Channel"), + @IArgument.IChoice(value="Category", key="Category") + }) + @IArgument(name="permissions", description = "Permissions", type = OptionType.STRING, required = true, + choices = { + @IArgument.IChoice(value="Read", key="Read"), + @IArgument.IChoice(value="Write", key="Write") + }) + public static void permissions(SlashCommandInteractionEvent event) { + event.getChannel().sendMessage("Role created").queue(); + } + + + @IButton(id=confirmAction) + public static void confirm(ButtonInteractionEvent event) { + System.out.println("Received confirm: " + event.getComponentId()); + + /* + Expected Args: + - buttonId + - actionId + - roleId + */ + String[] args = event.getComponentId().split(":"); + + if(args.length != 3) { + event.reply("Invalid arguments -> " + event.getComponentId()).setEphemeral(true).queue(); + return; + } + + String actionId = args[1]; + String roleId = args[2]; + + if(actionId.equals(removeAction)) { + // Guild never null because it's a button in a server + Role role = event.getGuild().getRoleById(roleId); + + if(role == null) { + event.reply("Role not found").setEphemeral(true).queue(); + return; + } + + MessageEmbed embed = Utils.simpleEmbed("Role deleted", + "Role '" + role.getName() + "' deleted", Color.RED); + event.editMessageEmbeds(embed).setActionRows().queue(); + role.delete().queue(); + } + } + + @IButton(id=cancelAction) + public static void cancel(ButtonInteractionEvent event) { + event.getMessage().delete().queue(); + event.reply("Cancelled").setEphemeral(true).queue(); + } + +} + From 5d614405148254f43479371ad717041e0eaba48a Mon Sep 17 00:00:00 2001 From: yaansz Date: Sun, 5 Jun 2022 20:03:34 -0300 Subject: [PATCH 2/7] feat: updating rolegroup --- build.gradle | 6 +- .../capivara/listeners/RoleGroup.java | 167 ++++++++++++++---- 2 files changed, 132 insertions(+), 41 deletions(-) diff --git a/build.gradle b/build.gradle index 9e6f3e8..d58c49c 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { } group 'com.softwaii.capivara' -version '1.0.1.1' +version '1.0.1.2' repositories { @@ -57,5 +57,5 @@ test { useJUnitPlatform() } -sourceCompatibility = JavaVersion.VERSION_16 -targetCompatibility = JavaVersion.VERSION_16 \ No newline at end of file +sourceCompatibility = JavaVersion.VERSION_17 +targetCompatibility = JavaVersion.VERSION_17 \ No newline at end of file diff --git a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java index 5ce1632..6952805 100644 --- a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java @@ -1,14 +1,10 @@ package com.softawii.capivara.listeners; import com.softawii.capivara.utils.Utils; -import com.softawii.curupira.annotations.IArgument; -import com.softawii.curupira.annotations.IButton; -import com.softawii.curupira.annotations.ICommand; -import com.softawii.curupira.annotations.IGroup; +import com.softawii.curupira.annotations.*; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.MessageEmbed; -import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.interactions.commands.Command; @@ -17,6 +13,9 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button; import java.awt.*; +import java.util.List; +import java.util.Objects; +import java.util.random.RandomGenerator; @IGroup(name = "role", description = "Role Group", hidden = false) public class RoleGroup { @@ -28,54 +27,145 @@ public class RoleGroup { public static final String confirmAction = "role-confirm-action"; public static final String cancelAction = "role-cancel-action"; - @ICommand(name="create", description = "Create a role", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name = "type", description = "Role type", type = OptionType.STRING, required = true, choices = { - @IArgument.IChoice(value="Channel", key="Channel"), - @IArgument.IChoice(value="Category", key="Category"), - @IArgument.IChoice(value="Free", key="Free") - }) - @IArgument(name = "name", description = "Role name", type = OptionType.STRING, required = false) + @ICommand(name="create", description = "Comando para criar um novo cargo", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name = "name", description = "O nome do cargo a ser criado", type = OptionType.STRING, required = false) + @IArgument(name="channel", description = "O canal que o cargo será vinculado", type = OptionType.CHANNEL, required = false) + @IArgument(name="color", description = "A cor do cargo em hexadecimal (#FFFFFF)", type = OptionType.STRING, required = false) + @IArgument(name="visible", description = "Se o cargo deve ser exibido na lista de cargos separadamente, ali do lado sabe??", type = OptionType.BOOLEAN, required = false) + @IArgument(name="mentionable", description = "Se o cargo pode ser mencionado, ou seja, @everyone!", type = OptionType.BOOLEAN, required = false) public static void create(SlashCommandInteractionEvent event) { - event.getChannel().sendMessage("Role created").queue(); + // Decoding + String name = event.getOption("name") != null ? event.getOption("name").getAsString() : null; + GuildChannel channel = event.getOption("channel") != null ? event.getOption("channel").getAsGuildChannel() : null; + + if((name == null) == (channel == null)) { + MessageEmbed embed = Utils.simpleEmbed("Erro", "Você deve informar apenas o nome do cargo ou apenas o canal de vinculação", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; + } else if(channel != null) { + name = channel.getName(); + } + + // Name Defined + String finalName = name; + if(event.getGuild().getRoles().stream().anyMatch(role -> role.getName().equals(finalName))) { + MessageEmbed embed = Utils.simpleEmbed("Erro", "Já existe um cargo com esse nome", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; + }; + + // Color + String strColor = event.getOption("color") != null ? event.getOption("color").getAsString() : null; + + Color color; + if(strColor != null) { + try { + color = Color.decode(strColor); + } catch (NumberFormatException e) { + MessageEmbed embed = Utils.simpleEmbed("Erro", "A cor informada não é uma cor válida", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; + } + } else { + RandomGenerator random = RandomGenerator.getDefault(); + color = new Color(random.nextInt(0, 255), random.nextInt(0, 255), random.nextInt(0, 255)); + } + + // Visible??? + boolean visible = event.getOption("visible") != null && event.getOption("visible").getAsBoolean(); + boolean mentionable = event.getOption("mentionable") == null || event.getOption("mentionable").getAsBoolean(); + + event.getGuild().createRole().setName(finalName).setColor(color).setHoisted(visible).setMentionable(mentionable).queue(role -> { + MessageEmbed embed = Utils.simpleEmbed("Cargo criado", "O cargo " + role.getAsMention()+ " foi criado com sucesso", Color.GREEN); + event.replyEmbeds(embed).setEphemeral(true).queue(); + }); } // DELETE SECTION -> DELETE / CONFIRM / CANCEL - @ICommand(name="delete", description = "Delete a role", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name="role", description = "Role", type = OptionType.ROLE, required = true) + @ICommand(name="delete", description = "Quer deletar um cargo do servidor, amigao?", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="role", description = "O cargo que tu quer deletar!", type = OptionType.ROLE, required = true) public static void delete(SlashCommandInteractionEvent event) { // Not null, because it's server side and required Role role = event.getOption("role").getAsRole(); String confirmId = String.format("%s:%s:%s", confirmAction, removeAction, role.getId()); String cancelId = cancelAction; - MessageEmbed messageEmbed = Utils.simpleEmbed("Are you sure?", - "You really want to delete the role " + role.getAsMention() + "??", + MessageEmbed messageEmbed = Utils.simpleEmbed("Você tem certeza disso?", + "Você realmente quer deletar o cargo " + role.getAsMention() + "?", Color.RED); - Button successButton = Button.success(confirmId, "Yes"); - Button cancelButton = Button.danger(cancelId, "No"); + Button successButton = Button.success(confirmId, "Sim! Pode continuar!"); + Button cancelButton = Button.danger(cancelId, "Não, Deus me livre!!"); event.replyEmbeds(messageEmbed).addActionRow(successButton, cancelButton).setEphemeral(true).queue(); } - @ICommand(name="permissions", description = "update", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name="role", description = "Role", type = OptionType.ROLE, required = true) - @IArgument(name="related", description = "Related", type = OptionType.CHANNEL, required = true) - @IArgument(name="type", description = "Apply to Channel or Category", type = OptionType.STRING, required = true, - choices = { - @IArgument.IChoice(value="Channel", key="Channel"), - @IArgument.IChoice(value="Category", key="Category") - }) - @IArgument(name="permissions", description = "Permissions", type = OptionType.STRING, required = true, - choices = { - @IArgument.IChoice(value="Read", key="Read"), - @IArgument.IChoice(value="Write", key="Write") - }) - public static void permissions(SlashCommandInteractionEvent event) { - event.getChannel().sendMessage("Role created").queue(); - } + @ISubGroup(name = "channel", description = "Channel SubGroup") + public static class Channel { + @ICommand(name = "permissions", description = "Quer atualizar rapidamente algumas permissões do seu cargo??", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name = "role", description = "Fala o cargo ai chefe", type = OptionType.ROLE, required = true) + @IArgument(name = "related", description = "Pra qual canal que tu quer atualizar???", type = OptionType.CHANNEL, required = true) + @IArgument(name = "permissions", description = "Permissions", type = OptionType.STRING, required = true, + choices = { + @IArgument.IChoice(value = "Read", key = "Read"), + @IArgument.IChoice(value = "Write", key = "Write"), + @IArgument.IChoice(value = "Connect", key = "Connect"), + @IArgument.IChoice(value = "Speak", key = "Speak") + }) + @IArgument(name = "allow", description = "Allow", type = OptionType.BOOLEAN, required = true) + public static void permissions(SlashCommandInteractionEvent event) { + + Role role = event.getOption("role").getAsRole(); + String permission = event.getOption("permissions").getAsString(); + boolean allow = event.getOption("allow").getAsBoolean(); + + + List voicePermissions = List.of("Connect", "Speak"); + List textPermissions = List.of("Read", "Write"); + ChannelType channelType = event.getOption("related").getChannelType(); + + // Everything is fine, let's update the permissions + if(channelType.isAudio()) { + VoiceChannel channel = event.getOption("related").getAsVoiceChannel(); + + if(!voicePermissions.contains(permission)) { + MessageEmbed messageEmbed = Utils.simpleEmbed("Permissão inválida", "Permissões de voz só podem ser: " + voicePermissions.toString(), Color.RED); + event.replyEmbeds(messageEmbed).setEphemeral(true).queue(); + return; + } + + if(allow) role.getManager().givePermissions(getPermission(permission)).queue(); + else role.getManager().revokePermissions(getPermission(permission)).queue(); + } + if(channelType.isMessage()) { + BaseGuildMessageChannel channel = (BaseGuildMessageChannel) event.getOption("related").getAsGuildChannel(); + + if(!textPermissions.contains(permission)) { + MessageEmbed messageEmbed = Utils.simpleEmbed("Permissão inválida", "Permissões de texto só podem ser: " + textPermissions.toString(), Color.RED); + event.replyEmbeds(messageEmbed).setEphemeral(true).queue(); + return; + } + + if(allow) channel.getManager().putRolePermissionOverride(role.getIdLong(), List.of(getPermission(permission)), null).queue(); + else channel.getManager().putRolePermissionOverride(role.getIdLong(), null, List.of(getPermission(permission))).queue(); + } + MessageEmbed messageEmbed = Utils.simpleEmbed("Permissões atualizadas", String.format("Permissão '%s' no canal atualizada com sucesso para o cargo %s", permission, role.getAsMention()), Color.GREEN); + event.replyEmbeds(messageEmbed).setEphemeral(true).queue(); + } + public static Permission getPermission(String permission){ + return switch (permission){ + case "Read" -> Permission.VIEW_CHANNEL; + case "Write" -> Permission.MESSAGE_SEND; + case "Connect" -> Permission.VOICE_CONNECT; + case "Speak" -> Permission.VOICE_SPEAK; + default -> throw new IllegalArgumentException("Invalid Permission"); + }; + } + } + + // SECTION BUTTON @IButton(id=confirmAction) public static void confirm(ButtonInteractionEvent event) { System.out.println("Received confirm: " + event.getComponentId()); @@ -114,8 +204,9 @@ public static void confirm(ButtonInteractionEvent event) { @IButton(id=cancelAction) public static void cancel(ButtonInteractionEvent event) { - event.getMessage().delete().queue(); - event.reply("Cancelled").setEphemeral(true).queue(); + MessageEmbed embed = Utils.simpleEmbed("Cancelado", "Cancelado com sucesso!! Não tente isso de novo heinn...", Color.RED); + + event.editMessageEmbeds(embed).setActionRows().queue(); } } From 26a967f93d596ec3cc58c81faf157f344c236bf3 Mon Sep 17 00:00:00 2001 From: yaansz Date: Mon, 6 Jun 2022 18:56:08 -0300 Subject: [PATCH 3/7] feat: clean command --- .../capivara/config/SpringConfig.java | 8 +++- .../capivara/listeners/RoleGroup.java | 47 +++++++++++++++++-- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/softawii/capivara/config/SpringConfig.java b/src/main/java/com/softawii/capivara/config/SpringConfig.java index c18b508..6beb584 100644 --- a/src/main/java/com/softawii/capivara/config/SpringConfig.java +++ b/src/main/java/com/softawii/capivara/config/SpringConfig.java @@ -4,6 +4,8 @@ import com.softawii.curupira.core.Curupira; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.requests.GatewayIntent; +import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -57,8 +59,10 @@ public LocalContainerEntityManagerFactoryBean entityManagerFactory() { public JDA jda() { JDA jda; try { - JDABuilder builder = JDABuilder.createDefault(discordToken); - builder.enableCache(CacheFlag.EMOTE, CacheFlag.ROLE_TAGS); + JDABuilder builder = JDABuilder.create(discordToken, GatewayIntent.GUILD_MEMBERS); + builder.enableIntents(GatewayIntent.GUILD_EMOJIS); + builder.setMemberCachePolicy(MemberCachePolicy.ALL); + builder.enableCache(CacheFlag.EMOTE, CacheFlag.ROLE_TAGS, CacheFlag.MEMBER_OVERRIDES); builder.addEventListeners(new PackageGroup.AutoCompleter()); jda = builder.build(); jda.awaitReady(); diff --git a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java index 6952805..54d44ba 100644 --- a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java @@ -23,6 +23,8 @@ public class RoleGroup { // Specific Action public static final String actionButton = "role-action-button"; public static final String removeAction = "role-remove-action"; + + public static final String cleanAction = "role-clean-action"; // Confirm or Deny Action public static final String confirmAction = "role-confirm-action"; public static final String cancelAction = "role-cancel-action"; @@ -92,7 +94,7 @@ public static void delete(SlashCommandInteractionEvent event) { MessageEmbed messageEmbed = Utils.simpleEmbed("Você tem certeza disso?", "Você realmente quer deletar o cargo " + role.getAsMention() + "?", - Color.RED); + Color.ORANGE); Button successButton = Button.success(confirmId, "Sim! Pode continuar!"); Button cancelButton = Button.danger(cancelId, "Não, Deus me livre!!"); @@ -100,6 +102,24 @@ public static void delete(SlashCommandInteractionEvent event) { event.replyEmbeds(messageEmbed).addActionRow(successButton, cancelButton).setEphemeral(true).queue(); } + @ICommand(name="clean", description = "Vamo fazer a limpa, hein?? Não vai sobrar ninguem!!", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="role", description = "Fala onde vamos limpar pro seu pai aqui!", type = OptionType.ROLE, required = true) + public static void clean(SlashCommandInteractionEvent event) { + // Not null, because it's server side and required + Role role = event.getOption("role").getAsRole(); + String confirmId = String.format("%s:%s:%s", confirmAction, cleanAction, role.getId()); + String cancelId = cancelAction; + + MessageEmbed messageEmbed = Utils.simpleEmbed("Você tem certeza disso?", + "Você realmente quer remover **TODOS** os usuários do cargo" + role.getAsMention() + "??? Isso é muito forte viu!", + Color.ORANGE); + + Button successButton = Button.success(confirmId, "Sim! Vamos limpar tudo!!"); + Button cancelButton = Button.danger(cancelId, "Não, terei piedade destes seres!!"); + + event.replyEmbeds(messageEmbed).addActionRow(successButton, cancelButton).setEphemeral(true).queue(); + } + @ISubGroup(name = "channel", description = "Channel SubGroup") public static class Channel { @ICommand(name = "permissions", description = "Quer atualizar rapidamente algumas permissões do seu cargo??", permissions = {Permission.ADMINISTRATOR}) @@ -191,14 +211,33 @@ public static void confirm(ButtonInteractionEvent event) { Role role = event.getGuild().getRoleById(roleId); if(role == null) { - event.reply("Role not found").setEphemeral(true).queue(); + MessageEmbed embed = Utils.simpleEmbed("Acharam o cargo antes de mim, temos um outro gerente na cidade", + "Verifica ai se deletaram o cargo '" + role.getName() + "' ok??", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); return; } - MessageEmbed embed = Utils.simpleEmbed("Role deleted", - "Role '" + role.getName() + "' deleted", Color.RED); + MessageEmbed embed = Utils.simpleEmbed("Deletei o cargo, de nada :ok_hand::skin-tone-3: ", + "Foi esse aqui que apaguei ó '" + role.getName() + "' ok??", Color.GREEN); event.editMessageEmbeds(embed).setActionRows().queue(); role.delete().queue(); + } else if(actionId.equals(cleanAction)) { + Role role = event.getGuild().getRoleById(roleId); + + if(role == null) { + MessageEmbed embed = Utils.simpleEmbed("Não achei esse cargo... :(", "Maior loucura! Talvez alguem já tenha excluido!", Color.RED); + event.editMessageEmbeds(embed).setActionRows().queue(); + return; + } + + event.getGuild().findMembersWithRoles(role).onSuccess(members -> { + for(Member member : members) { + event.getGuild().removeRoleFromMember(member, role).queue(); + } + }); + + MessageEmbed embed = Utils.simpleEmbed("Fiz a limpa!", "Todos os membros que tinham esse cargo foram removidos.", Color.GREEN); + event.editMessageEmbeds(embed).setActionRows().queue(); } } From 2a777ad9079359a27cae280d812382259e005949 Mon Sep 17 00:00:00 2001 From: Eduardo Cabral <47820549+FerroEduardo@users.noreply.github.com> Date: Mon, 6 Jun 2022 19:19:08 -0300 Subject: [PATCH 4/7] refactor: optimize clean command --- .../capivara/listeners/PackageGroup.java | 11 +++--- .../capivara/listeners/RoleGroup.java | 35 ++++++++++++------- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/softawii/capivara/listeners/PackageGroup.java b/src/main/java/com/softawii/capivara/listeners/PackageGroup.java index 1be15ee..f64c1d7 100644 --- a/src/main/java/com/softawii/capivara/listeners/PackageGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/PackageGroup.java @@ -1,19 +1,20 @@ package com.softawii.capivara.listeners; -import com.softawii.curupira.annotations.*; import com.softawii.capivara.core.PackageManager; import com.softawii.capivara.exceptions.*; import com.softawii.capivara.utils.Utils; +import com.softawii.curupira.annotations.*; import kotlin.Pair; import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.Emote; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; import net.dv8tion.jda.api.exceptions.HierarchyException; import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.selections.SelectMenu; @@ -21,8 +22,10 @@ import org.jetbrains.annotations.NotNull; import java.awt.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @IGroup(name= "Package", description = "Group to manage roles", hidden = false) diff --git a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java index 54d44ba..cba6c49 100644 --- a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java @@ -2,20 +2,19 @@ import com.softawii.capivara.utils.Utils; import com.softawii.curupira.annotations.*; -import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.Commands; import net.dv8tion.jda.api.interactions.components.buttons.Button; +import net.dv8tion.jda.api.requests.RestAction; import java.awt.*; +import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.random.RandomGenerator; +import java.util.stream.Collectors; @IGroup(name = "role", description = "Role Group", hidden = false) public class RoleGroup { @@ -198,7 +197,7 @@ public static void confirm(ButtonInteractionEvent event) { */ String[] args = event.getComponentId().split(":"); - if(args.length != 3) { + if (args.length != 3) { event.reply("Invalid arguments -> " + event.getComponentId()).setEphemeral(true).queue(); return; } @@ -206,7 +205,7 @@ public static void confirm(ButtonInteractionEvent event) { String actionId = args[1]; String roleId = args[2]; - if(actionId.equals(removeAction)) { + if (actionId.equals(removeAction)) { // Guild never null because it's a button in a server Role role = event.getGuild().getRoleById(roleId); @@ -221,7 +220,7 @@ public static void confirm(ButtonInteractionEvent event) { "Foi esse aqui que apaguei ó '" + role.getName() + "' ok??", Color.GREEN); event.editMessageEmbeds(embed).setActionRows().queue(); role.delete().queue(); - } else if(actionId.equals(cleanAction)) { + } else if (actionId.equals(cleanAction)) { Role role = event.getGuild().getRoleById(roleId); if(role == null) { @@ -230,14 +229,26 @@ public static void confirm(ButtonInteractionEvent event) { return; } + + Member selfMember = event.getGuild().getSelfMember(); + List> removeActions = new ArrayList<>(); event.getGuild().findMembersWithRoles(role).onSuccess(members -> { - for(Member member : members) { - event.getGuild().removeRoleFromMember(member, role).queue(); - } + members.forEach(member -> { + if (selfMember.canInteract(member)) { + removeActions.add(event.getGuild().removeRoleFromMember(member, role)); + } + }); }); - MessageEmbed embed = Utils.simpleEmbed("Fiz a limpa!", "Todos os membros que tinham esse cargo foram removidos.", Color.GREEN); - event.editMessageEmbeds(embed).setActionRows().queue(); + if (removeActions.isEmpty()) { + MessageEmbed embed = Utils.simpleEmbed("Tentei o que pude", "Tentei fazer a limpa, mas não encontrei alguém que eu possa remover o cargo", Color.ORANGE); + event.editMessageEmbeds(embed).setActionRows().queue(); + } else { + RestAction.accumulate(removeActions, Collectors.toList()).queue(voids -> { + MessageEmbed embed = Utils.simpleEmbed("Fiz a limpa!", String.format("Consegui remover o cargo de %d membros", removeActions.size()), Color.GREEN); + event.editMessageEmbeds(embed).setActionRows().queue(); + }); + } } } From ade1479cbc1c0793f2b54ff36561a127abaf5a3d Mon Sep 17 00:00:00 2001 From: yaansz Date: Mon, 6 Jun 2022 20:08:53 -0300 Subject: [PATCH 5/7] refactor: checking hierarchy --- .../capivara/listeners/RoleGroup.java | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java index cba6c49..00358cf 100644 --- a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java @@ -88,6 +88,13 @@ public static void create(SlashCommandInteractionEvent event) { public static void delete(SlashCommandInteractionEvent event) { // Not null, because it's server side and required Role role = event.getOption("role").getAsRole(); + + if(canInteract(event.getGuild().getSelfMember(), role)) { + MessageEmbed embed = Utils.simpleEmbed("Sem permissão irmão", "Esse cargo ta acima acima do meu! Missão Impossível", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; + } + String confirmId = String.format("%s:%s:%s", confirmAction, removeAction, role.getId()); String cancelId = cancelAction; @@ -106,6 +113,13 @@ public static void delete(SlashCommandInteractionEvent event) { public static void clean(SlashCommandInteractionEvent event) { // Not null, because it's server side and required Role role = event.getOption("role").getAsRole(); + + if(canInteract(event.getGuild().getSelfMember(), role)) { + MessageEmbed embed = Utils.simpleEmbed("Sem permissão irmão", "Esse cargo ta acima acima do meu! Missão Impossível", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; + } + String confirmId = String.format("%s:%s:%s", confirmAction, cleanAction, role.getId()); String cancelId = cancelAction; @@ -135,6 +149,13 @@ public static class Channel { public static void permissions(SlashCommandInteractionEvent event) { Role role = event.getOption("role").getAsRole(); + + if(canInteract(event.getGuild().getSelfMember(), role)) { + MessageEmbed embed = Utils.simpleEmbed("Sem permissão irmão", "Esse cargo ta acima acima do meu! Missão Impossível", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; + } + String permission = event.getOption("permissions").getAsString(); boolean allow = event.getOption("allow").getAsBoolean(); @@ -229,7 +250,6 @@ public static void confirm(ButtonInteractionEvent event) { return; } - Member selfMember = event.getGuild().getSelfMember(); List> removeActions = new ArrayList<>(); event.getGuild().findMembersWithRoles(role).onSuccess(members -> { @@ -259,5 +279,18 @@ public static void cancel(ButtonInteractionEvent event) { event.editMessageEmbeds(embed).setActionRows().queue(); } + + public static boolean canInteract(Member member, Role role) { + + int rolePosition = role.getPosition(); + int botPosition = member.getRoles().isEmpty() ? -1 : member.getRoles().get(0).getPosition(); + + if(botPosition == -1 || rolePosition >= botPosition) { + return false; + } + + return true; + } + } From caa961f998ed3ee6d879c8168d234ce075f65468 Mon Sep 17 00:00:00 2001 From: Eduardo Cabral <47820549+FerroEduardo@users.noreply.github.com> Date: Mon, 6 Jun 2022 20:17:23 -0300 Subject: [PATCH 6/7] refactor: translate replies and descriptions to pt_BR --- build.gradle | 2 +- .../capivara/listeners/PackageGroup.java | 140 +++++++++--------- .../capivara/listeners/RoleGroup.java | 2 +- 3 files changed, 72 insertions(+), 72 deletions(-) diff --git a/build.gradle b/build.gradle index d58c49c..0ca606b 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { } group 'com.softwaii.capivara' -version '1.0.1.2' +version '1.0.1.3' repositories { diff --git a/src/main/java/com/softawii/capivara/listeners/PackageGroup.java b/src/main/java/com/softawii/capivara/listeners/PackageGroup.java index f64c1d7..0860027 100644 --- a/src/main/java/com/softawii/capivara/listeners/PackageGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/PackageGroup.java @@ -37,18 +37,18 @@ public class PackageGroup { private static final String packageButton = "package-button"; private static final String roleMenu = "role-menu"; - @ICommand(name = "create", description = "Create a package to get roles", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name="name", description = "The package to be created", required = true, type= OptionType.STRING) - @IArgument(name="unique", description = "If the package is unique or not", required = false, type= OptionType.BOOLEAN) - @IArgument(name="description", description = "The package description", required = false, type= OptionType.STRING) - @IArgument(name="emoji", description = "The package emoji", required = false, type= OptionType.STRING) + @ICommand(name = "create", description = "Cria um package que terá cargos associados", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="name", description = "Nome do package que será criado", required = true, type= OptionType.STRING) + @IArgument(name="unique", description = "Se só poderá escolher um dos cargos do package", required = false, type= OptionType.BOOLEAN) + @IArgument(name="description", description = "Descrição do package", required = false, type= OptionType.STRING) + @IArgument(name="emoji", description = "Emoji associado ao package", required = false, type= OptionType.STRING) public static void create(SlashCommandInteractionEvent event) { System.out.println("create"); String name = event.getOption("name").getAsString(); if(name.contains(":")) { - event.reply("Package name can't contain ':'").queue(); + event.reply("O cargo não pode conter o caractere ':'").queue(); return; } @@ -63,22 +63,22 @@ public static void create(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("Provided emoji is not a single emoji").queue(); + event.reply("A mensagem não pode conter mais de um emoji").queue(); } try { packageManager.create(guildId, name, unique, description, emojiString, isUnicode); - event.reply("Package with name '" + name + "' created").queue(); + event.reply("Package com nome '" + name + "' foi craido").queue(); } catch (PackageAlreadyExistsException e) { - event.reply("Package already exists").queue(); + event.reply("O package já existe").queue(); } } - @ICommand(name = "edit", description = "Update a package", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name="name", description = "The package to update", required = true, type= OptionType.STRING, hasAutoComplete = true) - @IArgument(name="unique", description = "If the package is unique or not", required = false, type= OptionType.BOOLEAN) - @IArgument(name="description", description = "The package description", required = false, type= OptionType.STRING) - @IArgument(name="emoji", description = "The package emoji", required = false, type= OptionType.STRING) + @ICommand(name = "edit", description = "Atualizar o package", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="name", description = "Nome do package", required = true, type= OptionType.STRING, hasAutoComplete = true) + @IArgument(name="unique", description = "Se só poderá escolher um dos cargos do package", required = false, type= OptionType.BOOLEAN) + @IArgument(name="description", description = "Descrição do package", required = false, type= OptionType.STRING) + @IArgument(name="emoji", description = "Emoji do package", required = false, type= OptionType.STRING) public static void edit(SlashCommandInteractionEvent event) { System.out.println("update"); @@ -97,20 +97,20 @@ public static void edit(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("Provided emoji is not a single emoji").queue(); + event.reply("A mensagem não pode conter mais de um emoji").queue(); } } try { packageManager.update(guildId, name, unique, description, emojiString, isUnicode); - event.reply("Package with name '" + name + "' created").queue(); + event.reply("Package com nome '" + name + "' foi criado").queue(); } catch (PackageDoesNotExistException e) { - event.reply("Package '" + name +"' does not exist").setEphemeral(true).queue(); + event.reply("O package '" + name + "' não existe").setEphemeral(true).queue(); } } - @ICommand(name = "destroy", description = "Create a package to get roles", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name="name", description = "The package to remove the role to", required = true, type= OptionType.STRING, hasAutoComplete = true) + @ICommand(name = "destroy", description = "Destroi um package", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name="name", description = "O nome do package que será destruído", required = true, type= OptionType.STRING, hasAutoComplete = true) public static void destroy(SlashCommandInteractionEvent event) { System.out.println("destroy"); @@ -119,9 +119,9 @@ public static void destroy(SlashCommandInteractionEvent event) { try { packageManager.destroy(guildId, name); - event.reply("Package with name '" + name + "' destroyed").queue(); + event.reply("O package com nome '" + name + "' foi destruído").queue(); } catch (PackageDoesNotExistException e) { - event.reply("Package does not exist").queue(); + event.reply("O package não existe").queue(); } } @@ -129,18 +129,18 @@ public static void destroy(SlashCommandInteractionEvent event) { @ISubGroup(name = "role", description = "role subgroup") public static class RoleGroup { - @ICommand(name = "add", description = "Add a role to a package", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name = "package", description = "The package to add the role to", required = true, type = OptionType.STRING, hasAutoComplete = true) - @IArgument(name = "role", description = "role to be added", required = true, type = OptionType.ROLE) - @IArgument(name = "name", description = "The name to link to the role", required = false, type = OptionType.STRING) - @IArgument(name = "description", description = "The description to link to the role", required = false, type = OptionType.STRING) - @IArgument(name = "emoji", description = "The emoji to link to the role", required = false, type = OptionType.STRING) + @ICommand(name = "add", description = "Adicionar um cargo em um package", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name = "package", description = "O package que o cargo será adicionado", required = true, type = OptionType.STRING, hasAutoComplete = true) + @IArgument(name = "role", description = "Cargo que será adicionado", required = true, type = OptionType.ROLE) + @IArgument(name = "name", description = "Nome para associar ao cargo", required = false, type = OptionType.STRING) + @IArgument(name = "description", description = "A descrição que será associada ao cargo", required = false, type = OptionType.STRING) + @IArgument(name = "emoji", description = "O emoji que será associado ao cargo", required = false, type = OptionType.STRING) public static void add(SlashCommandInteractionEvent event) { Long guildId = event.getGuild().getIdLong(); String packageName = event.getOption("package").getAsString(); if(packageName.contains(":")) { - event.reply("Package name can't contain ':'").queue(); + event.reply("O nome do package não pode conter o caractere ':'").queue(); return; } @@ -148,7 +148,7 @@ public static void add(SlashCommandInteractionEvent event) { String name = event.getOption("name") != null ? event.getOption("name").getAsString() : role.getName(); if(name.contains(":")) { - event.reply("Role name can't contain ':'").queue(); + event.reply("O nome do cargo não pode conter o caractere ':'").queue(); return; } @@ -161,27 +161,27 @@ public static void add(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("Provided emoji is not a single emoji").queue(); + event.reply("A mensagem não pode conter mais de um emoji").queue(); } try { packageManager.addRole(guildId, packageName, role, name, description, emojiString, isUnicode); - event.reply("Role '" + role.getName() + "' added to package '" + packageName + "'").queue(); + event.reply("Cargo '" + role.getName() + "' adicionado ao package '" + packageName + "'").queue(); } catch (PackageDoesNotExistException e) { - event.reply("Package does not exist").queue(); + event.reply("O package não existe").queue(); } catch (RoleAlreadyAddedException e) { - event.reply("Role already added to package").queue(); + event.reply("O cargo já está presente no package").queue(); } catch (KeyAlreadyInPackageException e) { - event.reply("Key '" + name + "' already linked to package").queue(); + event.reply("A chave/nome '" + name + "' já está associada ao package").queue(); } } - @ICommand(name = "edit", description = "Edit a role in a package", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name = "package", description = "The package to edit", required = true, type = OptionType.STRING, hasAutoComplete = true) - @IArgument(name = "name", description = "The name to link to the role", required = true, type = OptionType.STRING, hasAutoComplete = true) - @IArgument(name = "role", description = "The role to be edited", required = false, type = OptionType.ROLE) - @IArgument(name = "description", description = "The description to link to the role", required = false, type = OptionType.STRING) - @IArgument(name = "emoji", description = "The emoji to link to the role", required = false, type = OptionType.STRING) + @ICommand(name = "edit", description = "Edita um cargo de um package", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name = "package", description = "Nome do package que será editado", required = true, type = OptionType.STRING, hasAutoComplete = true) + @IArgument(name = "name", description = "Nome associado ao cargo", required = true, type = OptionType.STRING, hasAutoComplete = true) + @IArgument(name = "role", description = "Cargo que será editado", required = false, type = OptionType.ROLE) + @IArgument(name = "description", description = "Descrição associado ao cargo", required = false, type = OptionType.STRING) + @IArgument(name = "emoji", description = "Emoji associado ao cargo", required = false, type = OptionType.STRING) public static void edit(SlashCommandInteractionEvent event) { // Primary Key Long guildId = event.getGuild().getIdLong(); @@ -200,25 +200,25 @@ public static void edit(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("Provided emoji is not a single emoji").queue(); + event.reply("A mensagem não pode conter mais de um emoji").queue(); } } try { packageManager.editRole(guildId, packageName, name, role, description, emojiString, isUnicode); - event.reply("Role '" + role.getName() + "' added to package '" + packageName + "'").queue(); + event.reply("Cargo '" + role.getName() + "' adicionado ao package '" + packageName + "'").queue(); } catch (PackageDoesNotExistException e) { - event.reply("Package does not exist").queue(); + event.reply("O package não existe").queue(); } catch (RoleAlreadyAddedException e) { - event.reply("Role already added to package").queue(); + event.reply("O cargo já está presente no package").queue(); } catch (RoleDoesNotExistException e) { - event.reply("Role does not exist").queue(); + event.reply("O cargo não existe").queue(); } } - @ICommand(name = "remove", description = "Remove a role from a package", permissions = {Permission.ADMINISTRATOR}) - @IArgument(name = "package", description = "The package to add the role to", required = true, type = OptionType.STRING, hasAutoComplete = true) - @IArgument(name = "name", description = "role link to remove", required = true, type = OptionType.STRING, hasAutoComplete = true) + @ICommand(name = "remove", description = "Remove um cargo de um package", permissions = {Permission.ADMINISTRATOR}) + @IArgument(name = "package", description = "Package que terá o cargo removido", required = true, type = OptionType.STRING, hasAutoComplete = true) + @IArgument(name = "name", description = "Nome do cargo associado ao package", required = true, type = OptionType.STRING, hasAutoComplete = true) public static void remove(SlashCommandInteractionEvent event) { Long guildId = event.getGuild().getIdLong(); String packageName = event.getOption("package").getAsString(); @@ -226,16 +226,16 @@ public static void remove(SlashCommandInteractionEvent event) { try { packageManager.removeRole(guildId, packageName, roleName); - event.reply(String.format("Role '%s' removed from '%s'", roleName, packageName)).queue(); + event.reply(String.format("Cargo '%s' removido de '%s'", roleName, packageName)).queue(); } catch (RoleDoesNotExistException | RoleNotFoundException e) { - event.reply(String.format("Role '%s' does not exists in '%s'", roleName, packageName)).queue(); + event.reply(String.format("Cargo '%s' não está presente em '%s'", roleName, packageName)).queue(); } catch (PackageDoesNotExistException e) { - event.reply("Package does not exist").queue(); + event.reply("O package não existe").queue(); } } } - @ICommand(name = "list", description = "List all packages") + @ICommand(name = "list", description = "Lista todos os packages") public static void list(SlashCommandInteractionEvent event) { boolean showError = event.getMember().hasPermission(Permission.ADMINISTRATOR); @@ -245,13 +245,13 @@ public static void list(SlashCommandInteractionEvent event) { event.replyEmbeds(guildPackages).queue(); } - @ICommand(name = "message", description = "Generate a message with a button to packages") - @IArgument(name="title", description = "Title of the message", required = true, type= OptionType.STRING) - @IArgument(name="description", description = "Description of the message", required = true, type= OptionType.STRING) - @IArgument(name="button-text", description = "Text of the button", required = true, type= OptionType.STRING) - @IArgument(name="type", description = "Get Multiple or an Package", required = true, type= OptionType.STRING, + @ICommand(name = "message", description = "Gera uma mensagem com botões associados aos packages") + @IArgument(name="title", description = "Título da mensagem", required = true, type= OptionType.STRING) + @IArgument(name="description", description = "Descrição da mensagem", required = true, type= OptionType.STRING) + @IArgument(name="button-text", description = "Texto do botão", required = true, type= OptionType.STRING) + @IArgument(name="type", description = "Um ou mais packages", required = true, type= OptionType.STRING, choices={@IArgument.IChoice(key="Packages", value="packages"), @IArgument.IChoice(key="Unique", value="Unique")}) - @IRange(value=@IArgument(name="package", description = "The package", required = false, type= OptionType.STRING, hasAutoComplete = true), min = 0, max = 20) + @IRange(value=@IArgument(name="package", description = "O package", required = false, type= OptionType.STRING, hasAutoComplete = true), min = 0, max = 20) public static void message(SlashCommandInteractionEvent event) { System.out.println("message"); Long guildId = event.getGuild().getIdLong(); @@ -270,7 +270,7 @@ public static void message(SlashCommandInteractionEvent event) { // Get Multiple or All Packages if(type.equals("packages")) { if(!packages.isEmpty() && !packageManager.checkIfAllPackagesExist(guildId, packages)) { - event.reply("One or more packages does not exist").queue(); + event.reply("Um ou mais packages não existem").queue(); return; } MessageEmbed messageEmbed = Utils.simpleEmbed(title, description, Color.GREEN); @@ -285,12 +285,12 @@ public static void message(SlashCommandInteractionEvent event) { event.replyEmbeds(messageEmbed).addActionRow(button).queue(); } else { if(packages.size() != 1) { - event.reply("You need to specify exactly one package").queue(); + event.reply("Você precisa especificar exatamente **UM** package").queue(); return; } if(!packageManager.checkIfPackageExists(guildId, packages.get(0))) { - event.reply("The package does not exist").queue(); + event.reply("O package não existe").queue(); return; } MessageEmbed messageEmbed = Utils.simpleEmbed(title, description, Color.GREEN); @@ -316,7 +316,7 @@ public static void packageGetter(ButtonInteractionEvent event) { SelectMenu menu = packageManager.getGuildPackagesMenu(guildId, Arrays.stream(packages).toList(), packageMenu, emotes); - event.reply("Please select a package").addActionRow(menu).setEphemeral(true).queue(); + event.reply("Selecione um package").addActionRow(menu).setEphemeral(true).queue(); } @IMenu(id=packageMenu) @@ -337,13 +337,13 @@ public static void package_selector(SelectMenuInteractionEvent event) { List emotes = event.getGuild().getEmotes(); menu = packageManager.getGuildPackageRoleMenu(guildId, _package, customId, event.getMember(), roleIds, emotes); } catch (PackageDoesNotExistException e) { - event.editMessage("Package does not exist").setActionRow().queue(); + event.editMessage("O package não existe").setActionRow().queue(); return; } - event.reply("Please select a role").addActionRow(menu).setEphemeral(true).queue(); + event.reply("Selecione um cargo").addActionRow(menu).setEphemeral(true).queue(); - }, () -> event.editMessage("No package selected").queue() + }, () -> event.editMessage("Nenhum package foi selecionado").queue() ); } @@ -361,11 +361,11 @@ public static void packageUniqueMenu(ButtonInteractionEvent event) { List emotes = event.getGuild().getEmotes(); menu = packageManager.getGuildPackageRoleMenu(guildId, _package, customId, event.getMember(), roleIds, emotes); } catch (PackageDoesNotExistException e) { - event.editMessage("Package does not exist").setActionRow().queue(); + event.editMessage("O package não existe").setActionRow().queue(); return; } - event.reply("Please select a role").addActionRow(menu).setEphemeral(true).queue(); + event.reply("Selecione um cargo").addActionRow(menu).setEphemeral(true).queue(); } @IMenu(id=roleMenu) @@ -381,7 +381,7 @@ public static void getting_role(SelectMenuInteractionEvent event) { Role role = event.getGuild().getRoleById(roleId); if(role == null) { - event.editMessage(event.getMessage().getContentDisplay() + "\nRole " + opt.getLabel() + " : " + opt.getValue() + " does not exist").queue(); + event.editMessage(event.getMessage().getContentDisplay() + "\nCargo " + opt.getLabel() + " : " + opt.getValue() + " não existe").queue(); return; } @@ -392,11 +392,11 @@ public static void getting_role(SelectMenuInteractionEvent event) { event.getGuild().removeRoleFromMember(event.getMember(), role).queue(); } } catch(HierarchyException e) { - event.getChannel().sendMessage("Bot cannot assignee the role " + opt.getValue() + " to you").queue(); + event.getChannel().sendMessage("Não posso atribuir o cargo " + opt.getValue() + " para você").queue(); } }); - event.reply("Your roles have been updated").setEphemeral(true).queue(); + event.reply("Seus cargos foram atualizados").setEphemeral(true).queue(); } public static class AutoCompleter extends ListenerAdapter { diff --git a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java index 00358cf..0d60a02 100644 --- a/src/main/java/com/softawii/capivara/listeners/RoleGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/RoleGroup.java @@ -219,7 +219,7 @@ public static void confirm(ButtonInteractionEvent event) { String[] args = event.getComponentId().split(":"); if (args.length != 3) { - event.reply("Invalid arguments -> " + event.getComponentId()).setEphemeral(true).queue(); + event.reply("Argumentos inválidos -> " + event.getComponentId()).setEphemeral(true).queue(); return; } From 7d9b7d9d466bbb57468910e1e4dcaa80d30ab3c3 Mon Sep 17 00:00:00 2001 From: yaansz Date: Mon, 6 Jun 2022 21:49:14 -0300 Subject: [PATCH 7/7] feat: new messages --- build.gradle | 2 +- .../capivara/core/PackageManager.java | 2 +- .../capivara/listeners/PackageGroup.java | 128 +++++++++++++----- .../com/softawii/capivara/utils/Utils.java | 19 ++- 4 files changed, 114 insertions(+), 37 deletions(-) diff --git a/build.gradle b/build.gradle index 0ca606b..07d3587 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { } group 'com.softwaii.capivara' -version '1.0.1.3' +version '1.0.1.4' repositories { diff --git a/src/main/java/com/softawii/capivara/core/PackageManager.java b/src/main/java/com/softawii/capivara/core/PackageManager.java index 9d7a32b..05baab9 100644 --- a/src/main/java/com/softawii/capivara/core/PackageManager.java +++ b/src/main/java/com/softawii/capivara/core/PackageManager.java @@ -121,7 +121,7 @@ public MessageEmbed getGuildPackages(Long guildId, List roles, boolean sho String name = key.getName(); String description = pkg.getDescription(); - if(description != null) sb.append("*").append(description).append("*\n\n"); + if(!description.isBlank()) sb.append("*").append(description).append("*\n\n"); pkg.getRoles().forEach(role -> { Long roleId = role.getRoleId(); diff --git a/src/main/java/com/softawii/capivara/listeners/PackageGroup.java b/src/main/java/com/softawii/capivara/listeners/PackageGroup.java index 0860027..8b58827 100644 --- a/src/main/java/com/softawii/capivara/listeners/PackageGroup.java +++ b/src/main/java/com/softawii/capivara/listeners/PackageGroup.java @@ -7,6 +7,7 @@ import kotlin.Pair; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Emote; +import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; @@ -19,6 +20,8 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.selections.SelectMenu; import net.dv8tion.jda.api.interactions.components.selections.SelectOption; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.awt.*; @@ -37,18 +40,20 @@ public class PackageGroup { private static final String packageButton = "package-button"; private static final String roleMenu = "role-menu"; + private static final Logger LOGGER = LogManager.getLogger(PackageGroup.class); + @ICommand(name = "create", description = "Cria um package que terá cargos associados", permissions = {Permission.ADMINISTRATOR}) @IArgument(name="name", description = "Nome do package que será criado", required = true, type= OptionType.STRING) @IArgument(name="unique", description = "Se só poderá escolher um dos cargos do package", required = false, type= OptionType.BOOLEAN) @IArgument(name="description", description = "Descrição do package", required = false, type= OptionType.STRING) @IArgument(name="emoji", description = "Emoji associado ao package", required = false, type= OptionType.STRING) public static void create(SlashCommandInteractionEvent event) { - System.out.println("create"); - - String name = event.getOption("name").getAsString(); + String name = event.getOption("name").getAsString(); if(name.contains(":")) { - event.reply("O cargo não pode conter o caractere ':'").queue(); + LOGGER.debug(String.format("create: Package Name contains :, just ignore it (%s)", name)); + MessageEmbed embed = Utils.simpleEmbed("Nome muito feio!", "O nome do package não pode conter o caracter ':', foi mal, problemas internos aqui!", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); return; } @@ -63,14 +68,26 @@ public static void create(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("A mensagem não pode conter mais de um emoji").queue(); + LOGGER.debug("create: Package contains Multiple Emojis"); + MessageEmbed embed = Utils.simpleEmbed("Quantos Emojis você quer amigão??", + "Você só pode usar um por vez, vamo maneirar ai...", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; } try { packageManager.create(guildId, name, unique, description, emojiString, isUnicode); - event.reply("Package com nome '" + name + "' foi craido").queue(); + LOGGER.info(String.format("create: Package %s created", name)); + MessageEmbed embed = Utils.simpleEmbed("Pacote criado e pronto pra usar!", + String.format("Tudo pronto pra você adicionar vários cargos no pacote '%s', só usar os comandos de /package role ...", name), + Color.GREEN, + new MessageEmbed.Field("Características", "O pacote é único? " + (unique ? "Sim" : "Não") + "\n" + "Descrição: " + description + "\n" + "Emoji: " + emojiString, false)); + + event.replyEmbeds(embed).queue(); } catch (PackageAlreadyExistsException e) { - event.reply("O package já existe").queue(); + LOGGER.info(String.format("create: Package %s already exists", name)); + MessageEmbed embed = Utils.simpleEmbed("Pacote já existe!", "Ta querendo criar de novo por que??? Ta doido?", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } @@ -80,12 +97,9 @@ public static void create(SlashCommandInteractionEvent event) { @IArgument(name="description", description = "Descrição do package", required = false, type= OptionType.STRING) @IArgument(name="emoji", description = "Emoji do package", required = false, type= OptionType.STRING) public static void edit(SlashCommandInteractionEvent event) { - System.out.println("update"); - String name = event.getOption("name").getAsString(); Long guildId = event.getGuild().getIdLong(); - Boolean unique = event.getOption("unique") != null ? event.getOption("unique").getAsBoolean() : null; String description = event.getOption("description") != null ? event.getOption("description").getAsString() : null; String emojiString = event.getOption("emoji") != null ? event.getOption("emoji").getAsString() : null; @@ -97,35 +111,53 @@ public static void edit(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("A mensagem não pode conter mais de um emoji").queue(); + LOGGER.debug("edit: Package contains Multiple Emojis"); + MessageEmbed embed = Utils.simpleEmbed("Quantos Emojis você quer amigão??", "Você só pode usar um por vez, vamo maneirar ai...", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; } } try { packageManager.update(guildId, name, unique, description, emojiString, isUnicode); + LOGGER.info(String.format("edit: Package %s updated", name)); event.reply("Package com nome '" + name + "' foi criado").queue(); + + StringBuilder sb = new StringBuilder(); + if (unique != null) sb.append("O pacote é único? ").append(unique ? "Sim" : "Não").append("\n"); + if (description != null) sb.append("Descrição: ").append(description).append("\n"); + if (emojiString != null) sb.append("Emoji: ").append(emojiString).append("\n"); + + MessageEmbed embed = Utils.simpleEmbed("Pacote atualizado, ta como se tivesse criado de novo", + "Só usar os comandos de /package role ...", + Color.GREEN, + new MessageEmbed.Field("O que mudou???", sb.toString(), false)); + event.replyEmbeds(embed).queue(); } catch (PackageDoesNotExistException e) { - event.reply("O package '" + name + "' não existe").setEphemeral(true).queue(); + LOGGER.info(String.format("edit: Package %s does not exist", name)); + MessageEmbed embed = Utils.simpleEmbed("Pacote não existe", "Você pode criar um novo pacote com /package create", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } @ICommand(name = "destroy", description = "Destroi um package", permissions = {Permission.ADMINISTRATOR}) @IArgument(name="name", description = "O nome do package que será destruído", required = true, type= OptionType.STRING, hasAutoComplete = true) public static void destroy(SlashCommandInteractionEvent event) { - System.out.println("destroy"); - Long guildId = event.getGuild().getIdLong(); String name = event.getOption("name").getAsString(); try { packageManager.destroy(guildId, name); - event.reply("O package com nome '" + name + "' foi destruído").queue(); + LOGGER.info(String.format("destroy: Package %s destroyed", name)); + MessageEmbed embed = Utils.simpleEmbed(String.format("Pacote %s destruído", name), "Acabamos com esse ai, mas sempre que quiser criar um novo você já sabe!", Color.GREEN); + event.replyEmbeds(embed).queue(); } catch (PackageDoesNotExistException e) { - event.reply("O package não existe").queue(); + LOGGER.debug(String.format("destroy: Package %s does not exist", name)); + MessageEmbed embed = Utils.simpleEmbed("Pacote não existe", "Ta doido?? Apagando pacote que não existe", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } - @ISubGroup(name = "role", description = "role subgroup") public static class RoleGroup { @@ -140,7 +172,9 @@ public static void add(SlashCommandInteractionEvent event) { String packageName = event.getOption("package").getAsString(); if(packageName.contains(":")) { - event.reply("O nome do package não pode conter o caractere ':'").queue(); + LOGGER.debug(String.format("add: Package Name contains :, just ignore it (%s)", packageName)); + MessageEmbed embed = Utils.simpleEmbed("Nome muito feio!", "O nome do package não pode conter o caracter ':', foi mal, problemas internos aqui!", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); return; } @@ -148,7 +182,9 @@ public static void add(SlashCommandInteractionEvent event) { String name = event.getOption("name") != null ? event.getOption("name").getAsString() : role.getName(); if(name.contains(":")) { - event.reply("O nome do cargo não pode conter o caractere ':'").queue(); + LOGGER.debug(String.format("add: Role Name contains :, just ignore it (%s)", name)); + MessageEmbed embed = Utils.simpleEmbed("Nome muito feio!", "O nome do cargo não pode conter o caracter ':', foi mal, problemas internos aqui!", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); return; } @@ -161,18 +197,30 @@ public static void add(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("A mensagem não pode conter mais de um emoji").queue(); + LOGGER.debug("add: MultipleEmojiMessageException"); + MessageEmbed embed = Utils.simpleEmbed("Emoji muito feio!", "O emoji não pode conter mais de um emoji, tu ta doidinho!", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); + return; } try { packageManager.addRole(guildId, packageName, role, name, description, emojiString, isUnicode); - event.reply("Cargo '" + role.getName() + "' adicionado ao package '" + packageName + "'").queue(); + LOGGER.info(String.format("add: Role %s added to package %s", role.getName(), packageName)); + MessageEmbed embed = Utils.simpleEmbed("Cargo adicionado!", String.format("O cargo %s foi adicionado ao pacote '%s', qualquer lista com o pacote já está atualizada", + role.getAsMention(), packageName), Color.GREEN); + event.replyEmbeds(embed).queue(); } catch (PackageDoesNotExistException e) { - event.reply("O package não existe").queue(); + LOGGER.debug("add: PackageDoesNotExistException"); + MessageEmbed embed = Utils.simpleEmbed("Pacote não existe!", String.format("O pacote '%s' não existe, crie-o primeiro!", packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (RoleAlreadyAddedException e) { - event.reply("O cargo já está presente no package").queue(); + LOGGER.debug("add: RoleAlreadyAddedException"); + MessageEmbed embed = Utils.simpleEmbed("Cargo já existe!", String.format("O cargo '%s' já existe no pacote '%s'!", role.getAsMention(), packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (KeyAlreadyInPackageException e) { - event.reply("A chave/nome '" + name + "' já está associada ao package").queue(); + LOGGER.debug("add: KeyAlreadyInPackageException"); + MessageEmbed embed = Utils.simpleEmbed("Nome já existe!", String.format("O nome '%s' já existe no pacote '%s'!", name, packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } @@ -200,19 +248,29 @@ public static void edit(SlashCommandInteractionEvent event) { emojiString = emoji.getFirst(); isUnicode = emoji.getSecond(); } catch (MultipleEmojiMessageException e) { - event.reply("A mensagem não pode conter mais de um emoji").queue(); + LOGGER.debug("edit: MultipleEmojiMessageException"); + MessageEmbed embed = Utils.simpleEmbed("Muitos emojis!", "Não é possível usar mais de um emoji ao mesmo tempo!", Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } try { packageManager.editRole(guildId, packageName, name, role, description, emojiString, isUnicode); - event.reply("Cargo '" + role.getName() + "' adicionado ao package '" + packageName + "'").queue(); + LOGGER.info("edit: Role edited successfully"); + MessageEmbed embed = Utils.simpleEmbed("Cargo editado!", String.format("O cargo '%s' foi editado com sucesso no pacote '%s'!", role.getAsMention(), packageName), Color.GREEN); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (PackageDoesNotExistException e) { - event.reply("O package não existe").queue(); + LOGGER.debug("edit: PackageDoesNotExistException"); + MessageEmbed embed = Utils.simpleEmbed("Pacote não existe!", String.format("O pacote '%s' não existe!", packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (RoleAlreadyAddedException e) { - event.reply("O cargo já está presente no package").queue(); + LOGGER.debug("edit: RoleAlreadyAddedException"); + MessageEmbed embed = Utils.simpleEmbed("Cargo já existe!", String.format("O cargo '%s' já existe no pacote '%s'!", name, packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (RoleDoesNotExistException e) { - event.reply("O cargo não existe").queue(); + LOGGER.debug("edit: RoleDoesNotExistException"); + MessageEmbed embed = Utils.simpleEmbed("Cargo não existe!", String.format("O cargo '%s' não existe no pacote '%s'!", name, packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } @@ -226,11 +284,17 @@ public static void remove(SlashCommandInteractionEvent event) { try { packageManager.removeRole(guildId, packageName, roleName); - event.reply(String.format("Cargo '%s' removido de '%s'", roleName, packageName)).queue(); + LOGGER.info("remove: Role removed successfully"); + MessageEmbed embed = Utils.simpleEmbed("Cargo removido!", String.format("O cargo '%s' foi removido com sucesso do pacote '%s'!", roleName, packageName), Color.GREEN); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (RoleDoesNotExistException | RoleNotFoundException e) { - event.reply(String.format("Cargo '%s' não está presente em '%s'", roleName, packageName)).queue(); + LOGGER.debug("remove: RoleDoesNotExistException | RoleNotFoundException"); + MessageEmbed embed = Utils.simpleEmbed("Cargo não existe!", String.format("O cargo '%s' não existe no pacote '%s'!", roleName, packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } catch (PackageDoesNotExistException e) { - event.reply("O package não existe").queue(); + LOGGER.debug("remove: PackageDoesNotExistException"); + MessageEmbed embed = Utils.simpleEmbed("Pacote não existe!", String.format("O pacote '%s' não existe!", packageName), Color.RED); + event.replyEmbeds(embed).setEphemeral(true).queue(); } } diff --git a/src/main/java/com/softawii/capivara/utils/Utils.java b/src/main/java/com/softawii/capivara/utils/Utils.java index f8c3c7a..a10c0fa 100644 --- a/src/main/java/com/softawii/capivara/utils/Utils.java +++ b/src/main/java/com/softawii/capivara/utils/Utils.java @@ -15,13 +15,26 @@ public class Utils { public static MessageEmbed simpleEmbed(String title, String description, Color color) { - return new EmbedBuilder() + return simpleEmbed(title, description, color, null); + } + + public static MessageEmbed simpleEmbed(String title, String description, Color color, MessageEmbed.Field... fields) { + EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(title) .setDescription(description) - .setColor(color) - .build(); + .setColor(color); + + if(fields != null) { + for (MessageEmbed.Field field : fields) { + embedBuilder.addField(field); + } + } + + return embedBuilder.build(); } + + public static List extractEmojis(String text) { List emojis = EmojiParser.extractEmojis(text);