Search in sources :

Example 1 with CommandPrivilege

use of net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege in project triumph-cmds by TriumphTeam.

the class SlashCommandManager method updateAllCommands.

/**
 * Updates all the commands in one go.
 * This should be used if the default trigger for the updating of the commands isn't working.
 * Or if commands are added after the initial setup.
 */
public void updateAllCommands() {
    jda.updateCommands().addCommands(globalCommands.values().stream().map(SlashCommand::asCommandData).collect(Collectors.toList())).queue();
    guildCommands.entrySet().stream().map(entry -> {
        final Guild guild = jda.getGuildById(entry.getKey());
        return guild != null ? Maps.immutableEntry(guild, entry.getValue()) : null;
    }).filter(Objects::nonNull).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)).forEach((guild, commands) -> guild.updateCommands().addCommands(commands.values().stream().map(SlashCommand::asCommandData).collect(Collectors.toList())).queue(cmds -> guild.updateCommandPrivileges(cmds.stream().map(cmd -> {
        final SlashCommand<S> command = commands.get(cmd.getName());
        if (command == null)
            return null;
        final List<CommandPrivilege> privileges = Stream.concat(command.getEnabledRoles().stream().map(id -> new CommandPrivilege(CommandPrivilege.Type.ROLE, true, id)), command.getDisabledRoles().stream().map(id -> new CommandPrivilege(CommandPrivilege.Type.ROLE, false, id))).collect(Collectors.toList());
        if (privileges.isEmpty())
            return null;
        return Maps.immutableEntry(cmd.getId(), privileges);
    }).filter(Objects::nonNull).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))).queue()));
}
Also used : JDA(net.dv8tion.jda.api.JDA) VoiceChannel(net.dv8tion.jda.api.entities.VoiceChannel) ExecutionProvider(dev.triumphteam.cmd.core.execution.ExecutionProvider) ChoiceKey(dev.triumphteam.cmd.slash.choices.ChoiceKey) HashMap(java.util.HashMap) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) SenderMapper(dev.triumphteam.cmd.core.sender.SenderMapper) Supplier(java.util.function.Supplier) BaseCommand(dev.triumphteam.cmd.core.BaseCommand) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) CommandManager(dev.triumphteam.cmd.core.CommandManager) Guild(net.dv8tion.jda.api.entities.Guild) ChoiceRegistry(dev.triumphteam.cmd.slash.choices.ChoiceRegistry) Role(net.dv8tion.jda.api.entities.Role) Map(java.util.Map) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) SlashSender(dev.triumphteam.cmd.slash.sender.SlashSender) MessageKey(dev.triumphteam.cmd.core.message.MessageKey) AsyncExecutionProvider(dev.triumphteam.cmd.core.execution.AsyncExecutionProvider) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) SyncExecutionProvider(dev.triumphteam.cmd.core.execution.SyncExecutionProvider) Nullable(org.jetbrains.annotations.Nullable) Contract(org.jetbrains.annotations.Contract) List(java.util.List) Stream(java.util.stream.Stream) NotNull(org.jetbrains.annotations.NotNull) SenderValidator(dev.triumphteam.cmd.core.sender.SenderValidator) Collections(java.util.Collections) Objects(java.util.Objects) Guild(net.dv8tion.jda.api.entities.Guild) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with CommandPrivilege

use of net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege in project reputation-bot by RainbowDashLabs.

the class Permissions method buildGuildPriviledges.

public static void buildGuildPriviledges(GuildData guildData, Guild guild) {
    var settings = guildData.getGuildSettings(guild);
    var optRole = settings.generalSettings().managerRole().map(guild::getRoleById);
    List<Role> roles;
    log.debug("Refreshing command priviledges for guild {}", Guilds.prettyName(guild));
    if (optRole.isEmpty()) {
        log.debug("No manager role defined on guild {}. Using admin roles.", guild.getIdLong());
        roles = guild.getRoles().stream().filter(r -> r.hasPermission(Permission.ADMINISTRATOR)).limit(5).collect(Collectors.toList());
    } else {
        log.debug("Using manager role on {}", Guilds.prettyName(guild));
        roles = Collections.singletonList(optRole.get());
    }
    List<CommandPrivilege> privileges = new ArrayList<>();
    for (Role role : roles) {
        privileges.add(CommandPrivilege.enable(role));
    }
    privileges.add(CommandPrivilege.enable(guild.retrieveOwner().complete().getUser()));
    var adminCommands = guild.retrieveCommands().complete().stream().filter(c -> !c.isDefaultEnabled()).collect(Collectors.toList());
    Map<String, Collection<CommandPrivilege>> commandPrivileges = new HashMap<>();
    for (var adminCommand : adminCommands) {
        commandPrivileges.put(adminCommand.getId(), privileges);
    }
    log.debug("Update done. Set restricted commands to {} priviledges", privileges.size());
    guild.updateCommandPrivileges(commandPrivileges).complete();
}
Also used : Role(net.dv8tion.jda.api.entities.Role) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) GuildData(de.chojo.repbot.data.GuildData) JDA(net.dv8tion.jda.api.JDA) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Logger(org.slf4j.Logger) Permission(net.dv8tion.jda.api.Permission) Collection(java.util.Collection) HashMap(java.util.HashMap) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) Role(net.dv8tion.jda.api.entities.Role) Map(java.util.Map) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Collection(java.util.Collection) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege)

Example 3 with CommandPrivilege

use of net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege in project DIH4JDA by DynxstyGIT.

the class InteractionHandler method registerCommandPrivileges.

/**
 * Registers all Command Privileges.
 *
 * @param jda The {@link JDA} instance.
 */
private void registerCommandPrivileges(JDA jda) {
    for (Guild guild : jda.getGuilds()) {
        Map<String, Set<CommandPrivilege>> privileges = new HashMap<>();
        guild.retrieveCommands().queue(commands -> {
            for (Command command : commands) {
                if (privileges.containsKey(command.getId()))
                    continue;
                Optional<SlashCommandInteraction> interactionOptional = this.slashCommandIndex.keySet().stream().filter(p -> p.equals(command.getName()) || p.split("/")[0].equals(command.getName())).map(slashCommandIndex::get).filter(p -> p.getPrivileges() != null && p.getPrivileges().length > 0).findFirst();
                if (interactionOptional.isPresent()) {
                    SlashCommandInteraction interaction = interactionOptional.get();
                    if (interaction.getBaseClass().getSuperclass().equals(GlobalSlashCommand.class)) {
                        DIH4JDALogger.error(String.format("Can not register command privileges for global command %s (%s).", command.getName(), interaction.getBaseClass().getSimpleName()));
                        continue;
                    }
                    privileges.put(command.getId(), new HashSet<>(Arrays.asList(interaction.getPrivileges())));
                    DIH4JDALogger.info(String.format("[%s] Registered privileges for command %s: %s", guild.getName(), command.getName(), Arrays.stream(interaction.getPrivileges()).map(CommandPrivilege::toData).collect(Collectors.toList())), DIH4JDALogger.Type.COMMAND_PRIVILEGE_REGISTERED);
                }
                if (privileges.isEmpty())
                    continue;
                guild.updateCommandPrivileges(privileges).queue();
            }
        });
    }
}
Also used : java.util(java.util) JDA(net.dv8tion.jda.api.JDA) IMessageContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.IMessageContextCommand) MessageContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent) MessageContextInteraction(com.dynxsty.dih4jda.commands.interactions.context_command.MessageContextInteraction) GuildContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.dao.GuildContextCommand) CompletableFuture(java.util.concurrent.CompletableFuture) Reflections(org.reflections.Reflections) Command(net.dv8tion.jda.api.interactions.commands.Command) UserContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent) Guild(net.dv8tion.jda.api.entities.Guild) DIH4JDA(com.dynxsty.dih4jda.DIH4JDA) SlashCommandInteraction(com.dynxsty.dih4jda.commands.interactions.slash_command.SlashCommandInteraction) DIH4JDALogger(com.dynxsty.dih4jda.DIH4JDALogger) ISlashCommand(com.dynxsty.dih4jda.commands.interactions.slash_command.ISlashCommand) SubcommandGroupData(net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData) UserContextInteraction(com.dynxsty.dih4jda.commands.interactions.context_command.UserContextInteraction) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) IUserContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.IUserContextCommand) SubcommandData(net.dv8tion.jda.api.interactions.commands.build.SubcommandData) GlobalContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.dao.GlobalContextCommand) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData) Collectors(java.util.stream.Collectors) SlashCommandData(net.dv8tion.jda.api.interactions.commands.build.SlashCommandData) Nullable(org.jetbrains.annotations.Nullable) com.dynxsty.dih4jda.commands.interactions.slash_command.dao(com.dynxsty.dih4jda.commands.interactions.slash_command.dao) Contract(org.jetbrains.annotations.Contract) BaseContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.dao.BaseContextCommand) CommandNotRegisteredException(com.dynxsty.dih4jda.exceptions.CommandNotRegisteredException) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) NotNull(org.jetbrains.annotations.NotNull) IMessageContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.IMessageContextCommand) GuildContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.dao.GuildContextCommand) Command(net.dv8tion.jda.api.interactions.commands.Command) ISlashCommand(com.dynxsty.dih4jda.commands.interactions.slash_command.ISlashCommand) IUserContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.IUserContextCommand) GlobalContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.dao.GlobalContextCommand) BaseContextCommand(com.dynxsty.dih4jda.commands.interactions.context_command.dao.BaseContextCommand) Guild(net.dv8tion.jda.api.entities.Guild) SlashCommandInteraction(com.dynxsty.dih4jda.commands.interactions.slash_command.SlashCommandInteraction)

Example 4 with CommandPrivilege

use of net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege in project JDA by DV8FromTheWorld.

the class GuildImpl method updateCommandPrivileges.

@Nonnull
@Override
public RestAction<Map<String, List<CommandPrivilege>>> updateCommandPrivileges(@Nonnull Map<String, ? extends Collection<CommandPrivilege>> privileges) {
    Checks.notNull(privileges, "Privileges");
    privileges.forEach((key, value) -> {
        Checks.isSnowflake(key, "Map Key");
        Checks.noneNull(value, "Privilege List for Command");
        Checks.check(value.size() <= 10, "Cannot have more than 10 privileges for a command!");
    });
    DataArray array = DataArray.empty();
    privileges.forEach((commandId, list) -> {
        DataObject entry = DataObject.empty();
        entry.put("id", commandId);
        entry.put("permissions", DataArray.fromCollection(list));
        array.add(entry);
    });
    Route.CompiledRoute route = Route.Interactions.EDIT_ALL_COMMAND_PERMISSIONS.compile(getJDA().getSelfUser().getApplicationId(), getId());
    return new RestActionImpl<>(getJDA(), route, RequestBody.create(Requester.MEDIA_TYPE_JSON, array.toJson()), (response, request) -> {
        Map<String, List<CommandPrivilege>> map = new HashMap<>();
        response.getArray().stream(DataArray::getObject).forEach(obj -> {
            String id = obj.getString("id");
            List<CommandPrivilege> list = parsePrivilegesList(obj);
            map.put(id, list);
        });
        return map;
    });
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Nonnull(javax.annotation.Nonnull)

Example 5 with CommandPrivilege

use of net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege in project TechDiscordBot by TechsCode-Team.

the class ModulesManager method load.

public void load() {
    TechDiscordBot.getJDA().updateCommands().queue();
    CommandListUpdateAction commands = TechDiscordBot.getGuild().updateCommands();
    for (Class<?> each : ProjectUtil.getClasses("me.TechsCode.TechDiscordBot.module")) {
        if (CommandModule.class.isAssignableFrom(each) && !Modifier.isAbstract(each.getModifiers())) {
            try {
                CommandModule module = (CommandModule) each.getConstructor(TechDiscordBot.class).newInstance(TechDiscordBot.getBot());
                if (module.getName() == null)
                    continue;
                cmdModules.add(module);
                CommandData cmdData = new CommandData(module.getName(), module.getDescription() == null ? "No description set." : module.getDescription()).addOptions(module.getOptions()).setDefaultEnabled(module.getCommandPrivileges().length == 0);
                commands.addCommands(cmdData);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        } else if (Module.class.isAssignableFrom(each) && !Modifier.isAbstract(each.getModifiers())) {
            try {
                Module module = (Module) each.getConstructor(TechDiscordBot.class).newInstance(TechDiscordBot.getBot());
                module.enable();
                modules.add(module);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }
    commands.addCommands(new CommandData("ticket", "Manage tickets.").addSubcommands(new SubcommandData("add", "Add a member to a ticket.").addOptions(new OptionData(OptionType.USER, "member", "Member to add.", true)), new SubcommandData("remove", "Remove a member from a ticket.").addOptions(new OptionData(OptionType.USER, "member", "Member to remove.", true)), new SubcommandData("transcript", "Force make a ticket transcript."), new SubcommandData("close", "Close a ticket.").addOptions(new OptionData(OptionType.STRING, "reason", "Reason to close the ticket. (Optional)")))).queue(cmds -> {
        cmds.forEach(command -> {
            CommandPrivilege[] privilege = cmdModules.stream().filter(c -> c.getName().equals(command.getName())).map(CommandModule::getCommandPrivileges).findFirst().orElse(new CommandPrivilege[] {});
            if (privilege.length > 0)
                TechDiscordBot.getGuild().updateCommandPrivilegesById(command.getId(), Arrays.asList(privilege)).queue();
        });
    });
    TechDiscordBot.getJDA().addEventListener(modules.toArray());
    TechDiscordBot.getJDA().addEventListener(cmdModules.toArray());
    Runtime.getRuntime().addShutdownHook(new Thread(() -> modules.forEach(Module::onDisable)));
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) SubcommandData(net.dv8tion.jda.api.interactions.commands.build.SubcommandData) TechDiscordBot(me.TechsCode.TechDiscordBot.TechDiscordBot) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData) InvocationTargetException(java.lang.reflect.InvocationTargetException) ArrayList(java.util.ArrayList) SlashCommandEvent(net.dv8tion.jda.api.events.interaction.SlashCommandEvent) SubscribeEvent(net.dv8tion.jda.api.hooks.SubscribeEvent) List(java.util.List) Modifier(java.lang.reflect.Modifier) ProjectUtil(me.TechsCode.TechDiscordBot.util.ProjectUtil) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) Cooldown(me.TechsCode.TechDiscordBot.objects.Cooldown) TechDiscordBot(me.TechsCode.TechDiscordBot.TechDiscordBot) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) InvocationTargetException(java.lang.reflect.InvocationTargetException) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) SubcommandData(net.dv8tion.jda.api.interactions.commands.build.SubcommandData)

Aggregations

CommandPrivilege (net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege)5 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Collectors (java.util.stream.Collectors)3 JDA (net.dv8tion.jda.api.JDA)3 Guild (net.dv8tion.jda.api.entities.Guild)3 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Role (net.dv8tion.jda.api.entities.Role)2 Contract (org.jetbrains.annotations.Contract)2 NotNull (org.jetbrains.annotations.NotNull)2 Nullable (org.jetbrains.annotations.Nullable)2 DIH4JDA (com.dynxsty.dih4jda.DIH4JDA)1 DIH4JDALogger (com.dynxsty.dih4jda.DIH4JDALogger)1 IMessageContextCommand (com.dynxsty.dih4jda.commands.interactions.context_command.IMessageContextCommand)1 IUserContextCommand (com.dynxsty.dih4jda.commands.interactions.context_command.IUserContextCommand)1 MessageContextInteraction (com.dynxsty.dih4jda.commands.interactions.context_command.MessageContextInteraction)1 UserContextInteraction (com.dynxsty.dih4jda.commands.interactions.context_command.UserContextInteraction)1 BaseContextCommand (com.dynxsty.dih4jda.commands.interactions.context_command.dao.BaseContextCommand)1