Fixed command manager and removed permission manager stuff

Fixed commands that were added, not done with polls
This commit is contained in:
Teriuihi 2022-09-10 05:20:24 +02:00
parent 45e7d9994b
commit e465c38994
25 changed files with 215 additions and 491 deletions

View File

@ -7,6 +7,7 @@ import com.alttd.console.ConsoleCommandManager;
import com.alttd.database.Database;
import com.alttd.database.DatabaseTables;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;

View File

@ -7,6 +7,7 @@ import com.alttd.database.Database;
import com.alttd.util.Logger;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
@ -17,10 +18,8 @@ import java.awt.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class CommandManager extends ListenerAdapter {
@ -29,21 +28,25 @@ public class CommandManager extends ListenerAdapter {
private final HashMap<String, List<ScopeInfo>> commandList = new HashMap<>();
public CommandManager(JDA jda) {
commandList.put("manage", new ArrayList<>(List.of(new ScopeInfo(CommandScope.GLOBAL, 0))));
loadCommands();
commands = List.of(new CommandHelp(jda, this),
new CommandPoll(jda, this),
new CommandManage(jda, this));
Logger.info("Loading commands...");
commands = List.of(
new CommandManage(jda, this),
new CommandHelp(jda, this),
new CommandPoll(jda, this));
}
@Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
String commandName = event.getName();
Optional<DiscordCommand> first = commands.stream()
.filter(discordCommand -> discordCommand.getName().equalsIgnoreCase(event.getCommandString()))
.filter(discordCommand -> discordCommand.getName().equalsIgnoreCase(commandName))
.findFirst();
if (first.isEmpty()) {
event.replyEmbeds(new EmbedBuilder()
.setTitle("Invalid command")
.setDescription("We couldn't find this command, please report this issue to a Teri")
.setDescription("We couldn't find a command called [" + commandName + "], please report this issue to a Teri")
.setColor(Color.RED)
.build())
.setEphemeral(true)
@ -56,7 +59,7 @@ public class CommandManager extends ListenerAdapter {
@Override
public void onCommandAutoCompleteInteraction(@NotNull CommandAutoCompleteInteractionEvent event) {
Optional<DiscordCommand> first = commands.stream()
.filter(discordCommand -> discordCommand.getName().equalsIgnoreCase(event.getCommandString()))
.filter(discordCommand -> discordCommand.getName().equalsIgnoreCase(event.getName()))
.findFirst();
if (first.isEmpty())
return;
@ -75,7 +78,7 @@ public class CommandManager extends ListenerAdapter {
return commands;
}
public List<DiscordCommand> getCommands(TextChannel textChannel) {
public List<DiscordCommand> getCommands(Guild guild) {
return commands.stream().filter(command -> {
List<ScopeInfo> scopeInfoList = commandList.get(command.getName());
for (ScopeInfo scopeInfo : scopeInfoList) {
@ -84,7 +87,7 @@ public class CommandManager extends ListenerAdapter {
return true;
}
case GUILD -> {
if (textChannel.getGuild().getIdLong() == scopeInfo.getId())
if (guild.getIdLong() == scopeInfo.getId())
return true;
}
}
@ -112,7 +115,7 @@ public class CommandManager extends ListenerAdapter {
return true;
}
private void loadCommands() {
synchronized private void loadCommands() {
String sql = "SELECT * FROM commands";
PreparedStatement statement = null;
@ -140,7 +143,7 @@ public class CommandManager extends ListenerAdapter {
}
}
public List<ScopeInfo> getActiveLocations(String command) {
synchronized public List<ScopeInfo> getActiveLocations(String command) {
return commandList.getOrDefault(command, new ArrayList<>());
}
}

View File

@ -1,5 +1,5 @@
package com.alttd.commandManager;
public enum CommandScope {
GLOBAL, GUILD, USER
GLOBAL, GUILD
}

View File

@ -2,6 +2,7 @@ package com.alttd.commandManager;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
public abstract class DiscordCommand {
@ -21,4 +22,5 @@ public abstract class DiscordCommand {
return getHelpMessage();
}
public abstract CommandData getCommandData();
}

View File

@ -2,59 +2,39 @@ package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.CommandManager;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubOption;
import com.alttd.permissions.PermissionManager;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData;
import java.util.ArrayList;
import java.util.HashMap;
public class CommandManage extends DiscordCommand {
private final HashMap<String, SubOption> subOptionsMap = new HashMap<>();
private final CommandData commandData;
public CommandManage(JDA jda, CommandManager commandManager) {
SlashCommandData slashCommandData = Commands.slash(getName(), "Enable commands and assign permissions")
.addSubcommandGroups(
new SubcommandGroupData("set", "Set a permission for a user")
.addSubcommands(
new SubcommandData("user", "Set a permission for a user")
.addOption(OptionType.MENTIONABLE, "user", "The user to set the permission for", true)
.addOption(OptionType.STRING, "permission", "The permission to set for a user", true, true)
.addOption(OptionType.STRING, "state", "To allow or deny the permission (true/false)", true, true),
new SubcommandData("group", "Set a permission for a group")
.addOption(OptionType.MENTIONABLE, "group", "The group to set the permission for", true)
.addOption(OptionType.STRING, "permission", "The permission to set for a group", true, true)
.addOption(OptionType.STRING, "state", "To allow or deny the permission (true/false)", true, true)
),
new SubcommandGroupData("unset", "unset a permission for a user")
.addSubcommands(
new SubcommandData("user", "Unset a permission for a user")
.addOption(OptionType.MENTIONABLE, "user", "The user to unset the permission for", true)
.addOption(OptionType.STRING, "permission", "The permission to unset for a user", true, true),
new SubcommandData("group", "Unset a permission for a group")
.addOption(OptionType.MENTIONABLE, "group", "The group to unset the permission for", true)
.addOption(OptionType.STRING, "permission", "The permission to unset for a group", true, true)
)
)
commandData = Commands.slash(getName(), "Enable commands and assign permissions")
.addSubcommands(
new SubcommandData("enable", "Enable a command in a channel")
.addOption(OptionType.STRING, "command", "Name of the command to enable", true, true),
new SubcommandData("disable", "Disable a command")
.addOption(OptionType.STRING, "command", "Name of the command to disable", true, true)
);
slashCommandData.setDefaultEnabled(true);
commandData.setDefaultEnabled(true);
Util.registerSubOptions(subOptionsMap,
new SubCommandDisable(commandManager, null, this),
new SubCommandEnable(commandManager, null, this));
Util.registerCommand(commandManager, jda, slashCommandData, getName());
new SubCommandEnable(commandManager, null, this),
new SubCommandEnable(commandManager, null, this)
);
Util.registerCommand(commandManager, jda, commandData, getName());
}
@Override
@ -68,10 +48,6 @@ public class CommandManage extends DiscordCommand {
event.replyEmbeds(Util.guildOnlyCommand(getName())).setEphemeral(true).queue();
return;
}
if (PermissionManager.getInstance().hasPermission(event.getTextChannel(), event.getIdLong(), Util.getGroupIds(event.getMember()), getPermission())) {
event.replyEmbeds(Util.noPermission(getName())).setEphemeral(true).queue();
return;
}
String subcommandName = event.getInteraction().getSubcommandGroup();
subcommandName = subcommandName == null ? event.getInteraction().getSubcommandName() : subcommandName;
@ -93,11 +69,20 @@ public class CommandManage extends DiscordCommand {
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
SubOption subOption = subOptionsMap.get(event.getSubcommandName());
if (subOption instanceof SubCommand subCommand)
subCommand.suggest(event);
else
event.replyChoices(new ArrayList<>()).queue();
}
@Override
public String getHelpMessage() {
return null;
}
@Override
public CommandData getCommandData() {
return commandData;
}
}

View File

@ -34,36 +34,37 @@ public class SubCommandDisable extends SubCommand {
public void execute(SlashCommandInteractionEvent event) {
Guild guild = event.getGuild();
if (guild == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "This command can only be used within guilds")).queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "This command can only be used within guilds")).setEphemeral(true).queue();
return;
}
OptionMapping option = event.getOption("command");
if (option == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find command parameter.")).queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find command parameter.")).setEphemeral(true).queue();
return;
}
String commandName = option.getAsString();
DiscordCommand command = commandManager.getCommand(commandName);
if (command == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find a command with that name.")).queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find a command with that name.")).setEphemeral(true).queue();
return;
}
if (disableCommand(command, guild.getIdLong())) {
// Util.deleteCommand(guild, guild.retri, command.getName()); //TODO add a way to disable commands?
event.replyEmbeds(Util.genericSuccessEmbed("Disabled command",
Parser.parse("Successfully disabled <command> in <guild>!",
Template.of("command", commandName.toLowerCase()),
Template.of("guild", guild.getName())
))).queue();
))).setEphemeral(true).queue();
} else {
event.replyEmbeds(Util.genericErrorEmbed("Failed to disable command",
Parser.parse("Unable to disable <command> in <guild>, is it already disabled?",
Template.of("command", commandName.toLowerCase()),
Template.of("guild", guild.getName())
))).queue();
))).setEphemeral(true).queue();
}
}

View File

@ -38,36 +38,36 @@ public class SubCommandEnable extends SubCommand {
public void execute(SlashCommandInteractionEvent event) {
Guild guild = event.getGuild();
if (guild == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "This command can only be used within guilds")).queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "This command can only be used within guilds")).setEphemeral(true).queue();
return;
}
OptionMapping option = event.getOption("command");
if (option == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find command parameter.")).queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find command parameter.")).setEphemeral(true).queue();
return;
}
String commandName = option.getAsString();
DiscordCommand command = commandManager.getCommand(commandName);
if (command == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find a command with that name.")).queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to find a command called [" + commandName + "].")).setEphemeral(true).queue();
return;
}
if (enableCommand(command, guild.getIdLong())) {
Util.registerCommand(guild, command.getCommandData(), command.getName());
event.replyEmbeds(Util.genericSuccessEmbed("Enabled command",
Parser.parse("Successfully enabled <command> in <guild>!",
Template.of("command", commandName.toLowerCase()),
Template.of("guild", guild.getName())
))).queue();
))).setEphemeral(true).queue();
} else {
event.replyEmbeds(Util.genericErrorEmbed("Failed to enable command",
Parser.parse("Unable to enabled <command> in <guild>, is it already enabled?",
Parser.parse("Unable to enable <command> in <guild>, is it already enabled?",
Template.of("command", commandName.toLowerCase()),
Template.of("guild", guild.getName())
))).queue();
))).setEphemeral(true).queue();
}
}
@ -82,7 +82,7 @@ public class SubCommandEnable extends SubCommand {
statement.setString(1, command.getName());
statement.setString(2, "GUILD");
statement.setLong(3, guildId);
if (!statement.execute()) {
if (statement.executeUpdate() == 0) {
Logger.warning("Unable to enable command: % for guild: %", command.getName(), String.valueOf(guildId));
return false;
}

View File

@ -1,58 +0,0 @@
package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommandGroup;
import com.alttd.commandManager.SubOption;
import com.alttd.permissions.PermissionManager;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import java.util.HashMap;
public class SubCommandGroupSet extends SubCommandGroup {
private final HashMap<String, SubOption> subOptionsMap = new HashMap<>();
protected SubCommandGroupSet(DiscordCommand parent) {
super(parent);
Util.registerSubOptions(subOptionsMap,
new SubCommandUnsetGroup(this, getParent()),
new SubCommandUnsetUser(this, getParent()));
}
@Override
public String getName() {
return "set";
}
@Override
public void execute(SlashCommandInteractionEvent event) {
if (PermissionManager.getInstance().hasPermission(event.getTextChannel(), event.getIdLong(), Util.getGroupIds(event.getMember()), getPermission())) {
event.replyEmbeds(Util.noPermission(getName())).setEphemeral(true).queue();
return;
}
String subcommandName = event.getInteraction().getSubcommandName();
if (subcommandName == null) {
Logger.severe("No subcommand found for %", getName());
return;
}
SubOption subOption = subOptionsMap.get(subcommandName);
if (subOption == null) {
event.replyEmbeds(Util.invalidSubcommand(subcommandName))
.setEphemeral(true)
.queue();
return;
}
subOption.execute(event);
}
@Override
public String getHelpMessage() {
return null;
}
}

View File

@ -1,57 +0,0 @@
package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommandGroup;
import com.alttd.commandManager.SubOption;
import com.alttd.permissions.PermissionManager;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import java.util.HashMap;
public class SubCommandGroupUnset extends SubCommandGroup {
private final HashMap<String, SubOption> subOptionsMap = new HashMap<>();
protected SubCommandGroupUnset(DiscordCommand parent) {
super(parent);
Util.registerSubOptions(subOptionsMap,
new SubCommandUnsetGroup(this, getParent()),
new SubCommandUnsetUser(this, getParent()));
}
@Override
public String getName() {
return "unset";
}
@Override
public void execute(SlashCommandInteractionEvent event) {
if (PermissionManager.getInstance().hasPermission(event.getTextChannel(), event.getIdLong(), Util.getGroupIds(event.getMember()), getPermission())) {
event.replyEmbeds(Util.noPermission(getName())).setEphemeral(true).queue();
return;
}
String subcommandName = event.getInteraction().getSubcommandName();
if (subcommandName == null) {
Logger.severe("No subcommand found for %", getName());
return;
}
SubOption subOption = subOptionsMap.get(subcommandName);
if (subOption == null) {
event.replyEmbeds(Util.invalidSubcommand(subcommandName))
.setEphemeral(true)
.queue();
return;
}
subOption.execute(event);
}
@Override
public String getHelpMessage() {
return null;
}
}

View File

@ -1,34 +0,0 @@
package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
public class SubCommandSetGroup extends SubCommand {
protected SubCommandSetGroup(SubCommandGroup parentGroup, DiscordCommand parent) {
super(parentGroup, parent);
}
@Override
public String getName() {
return "group";
}
@Override
public void execute(SlashCommandInteractionEvent event) {
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
}
@Override
public String getHelpMessage() {
return null;
}
}

View File

@ -1,34 +0,0 @@
package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
public class SubCommandSetUser extends SubCommand {
protected SubCommandSetUser(SubCommandGroup parentGroup, DiscordCommand parent) {
super(parentGroup, parent);
}
@Override
public String getName() {
return "user";
}
@Override
public void execute(SlashCommandInteractionEvent event) {
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
}
@Override
public String getHelpMessage() {
return null;
}
}

View File

@ -1,34 +0,0 @@
package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
public class SubCommandUnsetGroup extends SubCommand {
protected SubCommandUnsetGroup(SubCommandGroup parentGroup, DiscordCommand parent) {
super(parentGroup, parent);
}
@Override
public String getName() {
return "group";
}
@Override
public void execute(SlashCommandInteractionEvent event) {
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
}
@Override
public String getHelpMessage() {
return null;
}
}

View File

@ -1,34 +0,0 @@
package com.alttd.commandManager.commands.AddCommand;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
public class SubCommandUnsetUser extends SubCommand {
protected SubCommandUnsetUser(SubCommandGroup parentGroup, DiscordCommand parent) {
super(parentGroup, parent);
}
@Override
public String getName() {
return "user";
}
@Override
public void execute(SlashCommandInteractionEvent event) {
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
}
@Override
public String getHelpMessage() {
return null;
}
}

View File

@ -3,20 +3,18 @@ package com.alttd.commandManager.commands;
import com.alttd.commandManager.CommandManager;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.config.MessagesConfig;
import com.alttd.permissions.PermissionManager;
import com.alttd.templates.Parser;
import com.alttd.templates.Template;
import com.alttd.util.Util;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.AutoCompleteQuery;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
import java.awt.*;
import java.util.List;
@ -26,14 +24,15 @@ import java.util.stream.Collectors;
public class CommandHelp extends DiscordCommand {
private final CommandManager commandManager;
private final CommandData commandData;
public CommandHelp(JDA jda, CommandManager commandManager) {
this.commandManager = commandManager;
SlashCommandData slashCommandData = Commands.slash(getName(), "Show info about all commands or a specific command.")
commandData = Commands.slash(getName(), "Show info about all commands or a specific command.")
.addOption(OptionType.STRING, "command", "Command to get more info about", true , true);
Util.registerCommand(commandManager, jda, slashCommandData, getName());
Util.registerCommand(commandManager, jda, commandData, getName());
}
@Override
@ -43,24 +42,11 @@ public class CommandHelp extends DiscordCommand {
@Override
public void execute(SlashCommandInteractionEvent event) {
PermissionManager permissionManager = PermissionManager.getInstance();
if (permissionManager.hasPermission(event.getTextChannel(), event.getIdLong(), Util.getGroupIds(event.getMember()), getPermission())) {
event.replyEmbeds(Util.noPermission(getName())).setEphemeral(true).queue();
return;
}
StringBuilder helpMessage = new StringBuilder();
List<OptionMapping> options = event.getOptions();
TextChannel textChannel = event.getTextChannel();
if (options.size() == 0) {
commandManager.getCommands(textChannel).stream()
.filter(command -> permissionManager.hasPermission(
textChannel,
event.getUser().getIdLong(),
Util.getGroupIds(event.getMember()),
command.getPermission()))
.forEach(command -> helpMessage.append(command.getHelpMessage()));
commandManager.getCommands(event.getGuild()).forEach(command -> helpMessage.append(command.getHelpMessage()));
} else {
OptionMapping optionMapping = event.getOption("command");
if (optionMapping == null) {
@ -118,4 +104,9 @@ public class CommandHelp extends DiscordCommand {
public String getHelpMessage() {
return MessagesConfig.HELP_HELP;
}
@Override
public CommandData getCommandData() {
return commandData;
}
}

View File

@ -1,5 +0,0 @@
package com.alttd.commandManager.commands;
public class CommandRoles {
//TODO allow users to do /roles and get a dropdown that has all the roles they can add to themselves (mayb /roles notifications and /roles display or something idk)
}

View File

@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ButtonData {
public class ButtonData { //TODO add a feature that updates a total votes count on polls while they're active
private final UUID buttonId;
private final long pollId;
List<Long> votes;

View File

@ -2,17 +2,16 @@ package com.alttd.commandManager.commands.PollCommand;
import com.alttd.commandManager.CommandManager;
import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubOption;
import com.alttd.permissions.PermissionManager;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import java.util.HashMap;
@ -20,40 +19,41 @@ import java.util.HashMap;
public class CommandPoll extends DiscordCommand {
private final HashMap<String, SubOption> subOptionsMap = new HashMap<>();
private final CommandData commandData;
public CommandPoll(JDA jda, CommandManager commandManager) {
SlashCommandData slashCommandData = Commands.slash(getName(), "Create, edit, and manage polls")
commandData = Commands.slash(getName(), "Create, edit, and manage polls")
.addSubcommands(
new SubcommandData("add", "Add a new poll to a channel")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll should go into", true)
.addOption(OptionType.STRING, "title", "Title of the embed (max 256 characters)", true),
new SubcommandData("edit_title", "Edit the title of a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you're editing", true)
.addOption(OptionType.STRING, "message_id", "Id of the poll you're editing", true)
.addOption(OptionType.STRING, "title", "The new title for the poll (max 256 characters)", true),
new SubcommandData("edit_description", "Edit the description of a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you're editing", true)
.addOption(OptionType.STRING, "message_id", "Id of the poll you're editing", true)
.addOption(OptionType.STRING, "description", "The new description for the poll (max 2048 characters)", true),
new SubcommandData("add_button", "Add a button to a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you're adding a button to", true)
.addOption(OptionType.STRING, "message_id", "Id of the poll you're adding a button to", true)
.addOption(OptionType.INTEGER, "button_row", "Row the button should go in (1-5)", true)
.addOption(OptionType.STRING, "button_name", "Name of the button you're adding"),
new SubcommandData("remove_button", "Remove a button from a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you're removing a button from", true)
.addOption(OptionType.STRING, "message_id", "Id of the poll you're removing a button from", true)
.addOption(OptionType.STRING, "button_name", "Name of the button you're removing"),
new SubcommandData("open", "Open a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you're opening", true),
.addOption(OptionType.STRING, "message_id", "Id of the poll you're opening", true),
new SubcommandData("close", "Close a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you're closing", true),
.addOption(OptionType.STRING, "message_id", "Id of the poll you're closing", true),
new SubcommandData("results", "Get the results for a poll")
.addOption(OptionType.CHANNEL, "channel", "Channel this poll is in", true)
.addOption(OptionType.INTEGER, "message_id", "Id of the poll you want the results for", true));
slashCommandData.setDefaultEnabled(true);
.addOption(OptionType.STRING, "message_id", "Id of the poll you want the results for", true));
commandData.setDefaultEnabled(true);
Util.registerSubOptions(subOptionsMap,
new SubCommandAdd(null,this),
new SubCommandAddButton(null, this),
@ -63,7 +63,7 @@ public class CommandPoll extends DiscordCommand {
new SubCommandOpen(null, this),
new SubCommandRemoveButton(null, this),
new SubCommandResults(null,this));
Util.registerCommand(commandManager, jda, slashCommandData, getName());
Util.registerCommand(commandManager, jda, commandData, getName());
}
@Override
@ -77,10 +77,6 @@ public class CommandPoll extends DiscordCommand {
event.replyEmbeds(Util.guildOnlyCommand(getName())).setEphemeral(true).queue();
return;
}
if (PermissionManager.getInstance().hasPermission(event.getTextChannel(), event.getIdLong(), Util.getGroupIds(event.getMember()), getPermission())) {
event.replyEmbeds(Util.noPermission(getName())).setEphemeral(true).queue();
return;
}
String subcommandName = event.getInteraction().getSubcommandGroup();
subcommandName = subcommandName == null ? event.getInteraction().getSubcommandName() : subcommandName;
@ -109,4 +105,9 @@ public class CommandPoll extends DiscordCommand {
public String getHelpMessage() {
return null;
}
@Override
public CommandData getCommandData() {
return commandData;
}
}

View File

@ -40,16 +40,14 @@ public class SubCommandAddButton extends SubCommand {
if (!Util.validateGuildMessageChannel(event.getInteraction(), channel, ChannelType.TEXT, member))
return;
Long messageId = OptionMappingParsing.getLong("message_id", event, getName());
Long messageId = Util.parseLong(OptionMappingParsing.getString("message_id", event, getName()));
if (messageId == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to retrieve message id."))
.setEphemeral(true)
.queue();
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid message id")).setEphemeral(true).queue();
return;
}
//TODO verify that message id is in database
Long rowLong = OptionMappingParsing.getLong("button_row", event, getName());
Long rowLong = Util.parseLong(OptionMappingParsing.getString("button_row", event, getName()));
if (rowLong == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to retrieve button row."))
.setEphemeral(true)

View File

@ -4,6 +4,7 @@ import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import com.alttd.util.OptionMappingParsing;
import com.alttd.util.Util;
import net.dv8tion.jda.api.entities.GuildMessageChannel;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
@ -21,12 +22,17 @@ public class SubCommandClose extends SubCommand {
@Override
public void execute(SlashCommandInteractionEvent event) {
GuildMessageChannel channel = OptionMappingParsing.getGuildChannel("channel", event, getName());
if (channel == null)
if (channel == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid channel")).setEphemeral(true).queue();
return;
Long messageId = OptionMappingParsing.getLong("message_id", event, getName());
if (messageId == null)
}
Long messageId = Util.parseLong(OptionMappingParsing.getString("message_id", event, getName()));
if (messageId == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid message id")).setEphemeral(true).queue();
return;
}
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {

View File

@ -12,6 +12,8 @@ import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInterac
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import java.util.ArrayList;
public class SubCommandEditDescription extends SubCommand {
protected SubCommandEditDescription(SubCommandGroup parentGroup, DiscordCommand parent) {
super(parentGroup, parent);
@ -25,30 +27,47 @@ public class SubCommandEditDescription extends SubCommand {
@Override
public void execute(SlashCommandInteractionEvent event) {
GuildMessageChannel channel = OptionMappingParsing.getGuildChannel("channel", event, getName());
if (channel == null)
if (channel == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid channel")).setEphemeral(true).queue();
return;
Long messageId = OptionMappingParsing.getLong("message_id", event, getName());
if (messageId == null)
}
Long messageId = Util.parseLong(OptionMappingParsing.getString("message_id", event, getName()));
if (messageId == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid message id")).setEphemeral(true).queue();
return;
}
String description = OptionMappingParsing.getString("description", event, getName());
if (description == null || description.length() > 2048) {
if (description == null)
event.replyEmbeds(Util.genericErrorEmbed("Error", "No description found")).setEphemeral(true).queue();
else
event.replyEmbeds(Util.genericErrorEmbed("Error", "Description too long")).setEphemeral(true).queue();
return;
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
event.replyEmbeds(Util.genericWaitingEmbed("Waiting...", "Editing poll...")).setEphemeral(true).queue(hook -> {
channel.retrieveMessageById(messageId).queue(message -> updatePoll(message, description, hook),
error -> hook.editOriginalEmbeds(Util.genericErrorEmbed("Error", "Unable to find message with id [" + messageId + "].")).queue());
});
}
//Copied over while working on add button
private void updatePoll(GuildMessageChannel channel, int rowId, String buttonName, Message message,
InteractionHook hook) {
private void updatePoll(Message message, String description, InteractionHook hook) {
EmbedBuilder firstEmbedBuilder = Util.getFirstEmbedBuilder(message);
if (firstEmbedBuilder == null) {
hook.editOriginalEmbeds(Util.genericErrorEmbed("Error", "Unable to get embed from poll message."))
.queue();
return;
}
message.editMessageEmbeds(firstEmbedBuilder.build());//TODO finish this
message.editMessageEmbeds(firstEmbedBuilder.setDescription(description).build()).queue(
resultMessage -> hook.editOriginalEmbeds(Util.genericSuccessEmbed("Success", "Updated the poll description.")).queue(),
error -> hook.editOriginalEmbeds(Util.genericErrorEmbed("Error", "Unable to edit poll message.")).queue());
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
event.replyChoices(new ArrayList<>()).queue();
}
@Override

View File

@ -4,9 +4,15 @@ import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import com.alttd.util.OptionMappingParsing;
import com.alttd.util.Util;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.GuildMessageChannel;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import java.util.ArrayList;
public class SubCommandEditTitle extends SubCommand {
protected SubCommandEditTitle(SubCommandGroup parentGroup, DiscordCommand parent) {
@ -21,19 +27,47 @@ public class SubCommandEditTitle extends SubCommand {
@Override
public void execute(SlashCommandInteractionEvent event) {
GuildMessageChannel channel = OptionMappingParsing.getGuildChannel("channel", event, getName());
if (channel == null)
if (channel == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid channel")).setEphemeral(true).queue();
return;
Long messageId = OptionMappingParsing.getLong("message_id", event, getName());
if (messageId == null)
}
Long messageId = Util.parseLong(OptionMappingParsing.getString("message_id", event, getName()));
if (messageId == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid message id")).setEphemeral(true).queue();
return;
}
String title = OptionMappingParsing.getString("title", event, getName());
if (title == null || title.length() > 256) {
if (title == null)
event.replyEmbeds(Util.genericErrorEmbed("Error", "No title found")).setEphemeral(true).queue();
else
event.replyEmbeds(Util.genericErrorEmbed("Error", "Title too long")).setEphemeral(true).queue();
return;
}
event.replyEmbeds(Util.genericWaitingEmbed("Waiting...", "Editing poll...")).setEphemeral(true).queue(hook -> {
channel.retrieveMessageById(messageId).queue(message -> updatePoll(message, title, hook),
error -> hook.editOriginalEmbeds(Util.genericErrorEmbed("Error", "Unable to find message with id [" + messageId + "].")).queue());
});
}
private void updatePoll(Message message, String title, InteractionHook hook) {
EmbedBuilder firstEmbedBuilder = Util.getFirstEmbedBuilder(message);
if (firstEmbedBuilder == null) {
hook.editOriginalEmbeds(Util.genericErrorEmbed("Error", "Unable to get embed from poll message."))
.queue();
return;
}
message.editMessageEmbeds(firstEmbedBuilder.setTitle(title).build()).queue(
resultMessage -> hook.editOriginalEmbeds(Util.genericSuccessEmbed("Success", "Updated the poll title.")).queue(),
error -> hook.editOriginalEmbeds(Util.genericErrorEmbed("Error", "Unable to edit poll message.")).queue());
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {
event.replyChoices(new ArrayList<>()).queue();
}
@Override

View File

@ -4,6 +4,7 @@ import com.alttd.commandManager.DiscordCommand;
import com.alttd.commandManager.SubCommand;
import com.alttd.commandManager.SubCommandGroup;
import com.alttd.util.OptionMappingParsing;
import com.alttd.util.Util;
import net.dv8tion.jda.api.entities.GuildMessageChannel;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
@ -21,12 +22,17 @@ public class SubCommandOpen extends SubCommand {
@Override
public void execute(SlashCommandInteractionEvent event) {
GuildMessageChannel channel = OptionMappingParsing.getGuildChannel("channel", event, getName());
if (channel == null)
if (channel == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid channel")).setEphemeral(true).queue();
return;
Long messageId = OptionMappingParsing.getLong("message_id", event, getName());
if (messageId == null)
}
Long messageId = Util.parseLong(OptionMappingParsing.getString("message_id", event, getName()));
if (messageId == null) {
event.replyEmbeds(Util.genericErrorEmbed("Error", "Invalid message id")).setEphemeral(true).queue();
return;
}
}
@Override
public void suggest(CommandAutoCompleteInteractionEvent event) {

View File

@ -16,12 +16,16 @@ public class SettingsConfig extends AbstractConfig {
settingsConfig.readConfig(SettingsConfig.class, settingsConfig);
}
// SETTINGS
public static String TOKEN = "token";
public static boolean DEBUG = false;
private void loadSettings() {
TOKEN = settingsConfig.getString("settings.token", TOKEN);
DEBUG = settingsConfig.getBoolean("settings.debug", DEBUG);
}
// DATABASE
public static String DATABASE_DRIVER = "mysql";
public static String DATABASE_IP = "localhost";
public static String DATABASE_PORT = "3306";
@ -38,9 +42,10 @@ public class SettingsConfig extends AbstractConfig {
DATABASE_PASSWORD = settingsConfig.getString("settings.database_password", DATABASE_PASSWORD);
}
// ACTIVITY
public static String STATUS = "ONLINE";
public static String ACTIVITY = "Testing";
private void loadActivity() {
STATUS = settingsConfig.getString("settings.status", STATUS);
ACTIVITY = settingsConfig.getString("settings.activity", ACTIVITY);

View File

@ -1,103 +0,0 @@
package com.alttd.permissions;
import com.alttd.util.Logger;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class PermissionManager {
private static PermissionManager instance = null;
HashMap<Long, List<String>> userPermissions;
HashMap<Long, List<String>> groupPermissions;
HashMap<Long, List<String>> channelEnabledCommands;
List<String> privateEnabledCommands;
public PermissionManager(HashMap<Long, List<String>> userPermissions,
HashMap<Long, List<String>> groupPermissions,
HashMap<Long, List<String>> channelEnabledCommands,
List<String> privateEnabledCommands) {
this.userPermissions = userPermissions;
this.groupPermissions = groupPermissions;
this.channelEnabledCommands = channelEnabledCommands;
this.privateEnabledCommands = privateEnabledCommands;
instance = this;
}
/**
* Check if a user has a certain permission and if that permission is enabled in the specified channel
*
* @param textChannel Text channel command was executed in
* @param member Member to check permission for
* @param permission Permission to check for
*
* @return True if the member has permission or is owner, false if not
*/
public boolean hasPermission(TextChannel textChannel, Member member, String permission) {
return hasPermission(textChannel,
member.getIdLong(),
member.getRoles().stream().map(ISnowflake::getIdLong).collect(Collectors.toList()),
permission);
}
/**
* Check if a user has a certain permission and if that permission is enabled in the specified channel
*
* @param textChannel Text channel command was executed in
* @param userId ID of the user to check for
* @param groupIds List of group id's a user has (can be null or empty)
* @param permission Permission to check for
*
* @return True if the user has permission or is owner, false if not
*/
public boolean hasPermission(TextChannel textChannel, long userId, List<Long> groupIds, String permission) {
permission = permission.toLowerCase();
if (textChannel instanceof PrivateChannel) {
if (isDisabled(privateEnabledCommands, permission))
return false;
} else {
if (textChannel.getGuild().getOwnerIdLong() == userId)
return true;
if (isDisabled(channelEnabledCommands.get(textChannel.getIdLong()), permission.toLowerCase()))
return false;
}
return hasPermission(userId, groupIds, permission);
}
private boolean isDisabled(List<String> enabledCommandList, String permission) {
if (enabledCommandList == null || enabledCommandList.isEmpty())
return false;
return !enabledCommandList.contains(permission);
}
private boolean hasPermission(long userId, List<Long> groupIds, String permission) {
if (hasPermission(userPermissions.get(userId), permission))
return true;
if (groupIds == null || groupIds.isEmpty())
return false;
for (long groupId : groupIds) {
if (hasPermission(groupPermissions.get(groupId), permission))
return true;
}
return false;
}
private boolean hasPermission(List<String> permissions, String permission) {
if (permission == null || permission.isEmpty())
return false;
return permissions.contains(permission);
}
/**
* Get the permission manager instance
*
* @return Permission manager instance
*/
public static PermissionManager getInstance() {
return instance;
}
}

View File

@ -4,11 +4,13 @@ import com.alttd.commandManager.CommandManager;
import com.alttd.commandManager.ScopeInfo;
import com.alttd.commandManager.SubOption;
import com.alttd.config.MessagesConfig;
import com.alttd.config.SettingsConfig;
import com.alttd.templates.Parser;
import com.alttd.templates.Template;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.SlashCommandInteraction;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
@ -20,6 +22,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Util {
public static List<Long> getGroupIds(Member member) {
@ -99,20 +102,38 @@ public class Util {
public static void registerCommand(CommandManager commandManager, JDA jda, CommandData commandData, String commandName) {
for (ScopeInfo info : commandManager.getActiveLocations(commandName)) {
switch (info.getScope()) {
case GLOBAL -> jda.updateCommands().addCommands(commandData).queue();
case GUILD, USER -> {
case GLOBAL -> {
if (SettingsConfig.DEBUG)
Logger.info("Loading command [" + commandName + "] on global.");
jda.upsertCommand(commandData).queue();
// jda.updateCommands().addCommands(commandData).queue();
}
case GUILD -> {
Guild guildById = jda.getGuildById(info.getId());
if (guildById == null)
{
Logger.warning("Tried to add command % to invalid guild %.", commandName, String.valueOf(info.getId()));
continue;
}
guildById.updateCommands().addCommands(commandData).queue(RestAction.getDefaultSuccess(), Util::handleFailure);
registerCommand(guildById, commandData, commandName);
}
}
}
}
public static void registerCommand(Guild guild, CommandData commandData, String commandName) {
if (SettingsConfig.DEBUG)
Logger.info("Loading command [" + commandName + "] on guild [" + guild.getName() + "].");
// guild.upsertCommand(commandData).queue();
guild.upsertCommand(commandData).queue(RestAction.getDefaultSuccess(), Util::handleFailure);
}
public static void deleteCommand(Guild guild, long id, String commandName) {
if (SettingsConfig.DEBUG)
Logger.info("Deleting command [" + commandName + "] on guild [" + guild.getName() + "].");
guild.deleteCommandById(id).queue();
}
public static void registerSubOptions(HashMap<String, SubOption> subCommandMap, SubOption... subOptions) {
for (SubOption subOption : subOptions)
subCommandMap.put(subOption.getName(), subOption);
@ -151,4 +172,14 @@ public class Util {
MessageEmbed messageEmbed = message.getEmbeds().get(0);
return new EmbedBuilder(messageEmbed);
}
public static Long parseLong(String message_id) {
long l;
try {
l = Long.parseLong(message_id);
} catch (NumberFormatException ignored) {
return null;
}
return l;
}
}