use of net.dv8tion.jda.api.interactions.commands.Command in project Bean by Xirado.
the class InteractionCommandHandler method handleSlashCommand.
public void handleSlashCommand(@NotNull SlashCommandInteractionEvent event, @Nullable Member member) {
Runnable r = () -> {
try {
if (!event.isFromGuild())
return;
Guild guild = event.getGuild();
SlashCommand command = null;
long guildId = event.getGuild().getIdLong();
if (registeredGuildCommands.containsKey(guildId)) {
List<SlashCommand> guildCommands = registeredGuildCommands.get(guildId).stream().filter(cmd -> cmd instanceof SlashCommand).map(cmd -> (SlashCommand) cmd).toList();
SlashCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (guildCommand != null)
command = guildCommand;
}
if (command == null) {
SlashCommand globalCommand = getRegisteredSlashCommands().stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (globalCommand != null)
command = globalCommand;
}
if (command != null) {
SlashCommandContext ctx = new SlashCommandContext(event);
List<Permission> neededPermissions = command.getRequiredUserPermissions();
List<Permission> neededBotPermissions = command.getRequiredBotPermissions();
if (neededPermissions != null && !member.hasPermission((GuildChannel) event.getChannel(), neededPermissions)) {
event.reply(LocaleLoader.ofGuild(guild).get("general.no_perms", String.class)).queue();
return;
}
if (neededBotPermissions != null && !event.getGuild().getSelfMember().hasPermission((GuildChannel) event.getChannel(), neededBotPermissions)) {
event.reply(LocaleLoader.ofGuild(guild).get("general.no_bot_perms1", String.class)).queue();
return;
}
if (command.getCommandFlags().contains(CommandFlag.DJ_ONLY)) {
if (!ctx.getGuildData().isDJ(member)) {
event.replyEmbeds(EmbedUtil.errorEmbed("You need to be a DJ to do this!")).queue();
return;
}
}
if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_VC)) {
GuildVoiceState guildVoiceState = member.getVoiceState();
if (guildVoiceState == null || !guildVoiceState.inAudioChannel()) {
event.replyEmbeds(EmbedUtil.errorEmbed("You are not connected to a voice-channel!")).queue();
return;
}
}
if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_SAME_VC)) {
GuildVoiceState voiceState = member.getVoiceState();
AudioManager manager = event.getGuild().getAudioManager();
if (manager.isConnected()) {
if (!manager.getConnectedChannel().equals(voiceState.getChannel())) {
event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in " + manager.getConnectedChannel().getAsMention() + "to do this!")).setEphemeral(true).queue();
return;
}
}
}
if (command.getCommandFlags().contains(CommandFlag.REQUIRES_LAVALINK_NODE)) {
if (!ctx.isLavalinkNodeAvailable()) {
event.replyEmbeds(EmbedUtil.errorEmbed("There are currently no voice nodes available!\nIf the issue persists, please leave a message on our support server!")).addActionRow(Util.getSupportButton()).queue();
return;
}
}
command.executeCommand(event, ctx);
Metrics.COMMANDS.labels("success").inc();
}
} catch (Exception e) {
Metrics.COMMANDS.labels("failed").inc();
LinkedDataObject translation = event.getGuild() == null ? LocaleLoader.getForLanguage("en_US") : LocaleLoader.ofGuild(event.getGuild());
if (event.isAcknowledged())
event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
}, ex -> {
});
else
event.replyEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
}, ex -> {
});
LOGGER.error("Could not execute slash-command", e);
StringBuilder path = new StringBuilder("/" + event.getCommandPath().replace("/", " "));
for (OptionMapping option : event.getOptions()) {
path.append(" *").append(option.getName()).append("* : ").append("`").append(option.getAsString()).append("`");
}
EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a slash-command!").addField("Guild", event.getGuild() == null ? "None (Direct message)" : event.getGuild().getIdLong() + " (" + event.getGuild().getName() + ")", true).addField("Channel", event.getGuild() == null ? "None (Direct message)" : event.getChannel().getName(), true).addField("User", event.getUser().getAsMention() + " (" + event.getUser().getAsTag() + ")", true).addField("Command", path.toString(), false).setColor(EmbedUtil.ERROR_COLOR);
event.getJDA().openPrivateChannelById(Bean.OWNER_ID).flatMap(c -> c.sendMessageEmbeds(builder.build()).content("```fix\n" + ExceptionUtils.getStackTrace(e) + "\n```")).queue();
}
};
Bean.getInstance().getCommandExecutor().execute(r);
}
use of net.dv8tion.jda.api.interactions.commands.Command 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();
}
});
}
}
use of net.dv8tion.jda.api.interactions.commands.Command in project JDA by DV8FromTheWorld.
the class CommandListUpdateActionImpl method addCommands.
@Nonnull
@Override
public CommandListUpdateAction addCommands(@Nonnull Collection<? extends CommandData> commands) {
Checks.noneNull(commands, "Command");
int newSlash = 0, newUser = 0, newMessage = 0;
for (CommandData command : commands) {
switch(command.getType()) {
case SLASH:
newSlash++;
break;
case MESSAGE:
newMessage++;
break;
case USER:
newUser++;
break;
}
}
Checks.check(slash + newSlash <= Commands.MAX_SLASH_COMMANDS, "Cannot have more than %d slash commands! Try using subcommands instead.", Commands.MAX_SLASH_COMMANDS);
Checks.check(user + newUser <= Commands.MAX_USER_COMMANDS, "Cannot have more than %d user context commands!", Commands.MAX_USER_COMMANDS);
Checks.check(message + newMessage <= Commands.MAX_MESSAGE_COMMANDS, "Cannot have more than %d message context commands!", Commands.MAX_MESSAGE_COMMANDS);
Checks.checkUnique(Stream.concat(commands.stream(), this.commands.stream()).map(c -> c.getType() + " " + c.getName()), "Cannot have multiple commands of the same type with identical names. " + "Name: \"%s\" with type %s appeared %d times!", (count, value) -> {
String[] tuple = value.split(" ", 2);
return new Object[] { tuple[1], tuple[0], count };
});
slash += newSlash;
user += newUser;
message += newMessage;
this.commands.addAll(commands);
return this;
}
use of net.dv8tion.jda.api.interactions.commands.Command in project BotCommands by freya022.
the class ApplicationCommandsUpdater method computeSlashCommands.
private void computeSlashCommands(List<ApplicationCommandInfo> guildApplicationCommands) {
guildApplicationCommands.stream().filter(a -> a instanceof SlashCommandInfo).map(a -> (SlashCommandInfo) a).distinct().forEachOrdered(info -> {
final CommandPath notLocalizedPath = info.getPath();
try {
final LocalizedCommandData localizedCommandData = LocalizedCommandData.of(context, guild, info);
// Put localized option names in order to resolve them when called
final List<OptionData> localizedMethodOptions = getLocalizedMethodOptions(info, localizedCommandData);
if (guild != null) {
info.putLocalizedOptions(guild.getIdLong(), localizedMethodOptions.stream().map(OptionData::getName).collect(Collectors.toList()));
}
localizedBaseNameToBaseName.put(localizedCommandData.getLocalizedPath().getName(), notLocalizedPath.getName());
final CommandPath localizedPath = localizedCommandData.getLocalizedPath();
final String description = localizedCommandData.getLocalizedDescription();
Checks.check(localizedPath.getNameCount() == notLocalizedPath.getNameCount(), "Localized path does not have the same name count as the not-localized path");
final boolean isDefaultEnabled = isDefaultEnabled(info);
if (localizedPath.getNameCount() == 1) {
// Standard command
final SlashCommandData rightCommand = Commands.slash(localizedPath.getName(), description);
map.put(Command.Type.SLASH, localizedPath, rightCommand);
rightCommand.addOptions(localizedMethodOptions);
rightCommand.setDefaultEnabled(isDefaultEnabled);
} else if (localizedPath.getNameCount() == 2) {
Checks.notNull(localizedPath.getSubname(), "Subcommand name");
final SlashCommandData commandData = (SlashCommandData) map.computeIfAbsent(Command.Type.SLASH, localizedPath, x -> {
final SlashCommandData tmpData = Commands.slash(localizedPath.getName(), "No description (base name)");
tmpData.setDefaultEnabled(isDefaultEnabled);
return tmpData;
});
// Subcommand of a command
final SubcommandData subcommandData = new SubcommandData(localizedPath.getSubname(), description);
subcommandData.addOptions(localizedMethodOptions);
commandData.addSubcommands(subcommandData);
} else if (localizedPath.getNameCount() == 3) {
Checks.notNull(localizedPath.getGroup(), "Command group name");
Checks.notNull(localizedPath.getSubname(), "Subcommand name");
final SubcommandGroupData groupData = getSubcommandGroup(Command.Type.SLASH, localizedPath, x -> {
final SlashCommandData commandData = Commands.slash(localizedPath.getName(), "No description (base name)");
commandData.setDefaultEnabled(isDefaultEnabled);
return commandData;
});
final SubcommandData subcommandData = new SubcommandData(localizedPath.getSubname(), description);
subcommandData.addOptions(localizedMethodOptions);
groupData.addSubcommands(subcommandData);
} else {
throw new IllegalStateException("A slash command with more than 4 path components got registered");
}
context.addApplicationCommandAlternative(localizedPath, Command.Type.SLASH, info);
if (!info.isOwnerRequired()) {
if (ownerOnlyCommands.contains(notLocalizedPath.getName())) {
LOGGER.warn("Non owner-only command '{}' is registered as a owner-only command because of another command with the same base name '{}'", notLocalizedPath, notLocalizedPath.getName());
}
}
if (info.isOwnerRequired()) {
if (info.isGuildOnly()) {
ownerOnlyCommands.add(notLocalizedPath.getName());
} else {
LOGGER.warn("Owner-only command '{}' cannot be owner-only as it is a global command", notLocalizedPath);
}
}
} catch (Exception e) {
throw new RuntimeException("An exception occurred while processing command '" + notLocalizedPath + "' at " + Utils.formatMethodShort(info.getMethod()), e);
}
});
}
use of net.dv8tion.jda.api.interactions.commands.Command in project BotCommands by freya022.
the class ApplicationCommandsUpdater method updateCommands.
@Blocking
public void updateCommands() {
final CommandListUpdateAction updateAction = guild != null ? guild.updateCommands() : context.getJDA().updateCommands();
final List<Command> commands = updateAction.addCommands(allCommandData).complete();
updatedCommands = true;
if (guild != null) {
thenAcceptGuild(commands, guild);
} else {
thenAcceptGlobal(commands);
}
}
Aggregations