use of net.dv8tion.jda.api.interactions.commands.Command in project Bean by Xirado.
the class InteractionCommandHandler method handleUserContextCommand.
public void handleUserContextCommand(@NotNull UserContextInteractionEvent event) {
if (!event.isFromGuild())
return;
Guild guild = event.getGuild();
Member member = event.getMember();
UserContextCommand command = null;
if (registeredGuildCommands.containsKey(guild.getIdLong())) {
List<UserContextCommand> guildCommands = registeredGuildCommands.get(guild.getIdLong()).stream().filter(cmd -> cmd instanceof UserContextCommand).map(cmd -> (UserContextCommand) cmd).toList();
UserContextCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (guildCommand != null)
command = guildCommand;
}
if (command == null) {
UserContextCommand globalCommand = getRegisteredUserContextCommands().stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (globalCommand != null)
command = globalCommand;
}
if (command == null)
return;
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.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;
}
}
}
UserContextCommand finalCommand = command;
Runnable r = () -> {
try {
finalCommand.executeCommand(event);
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 user-context-menu-command", e);
EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a user-context-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", event.getName(), 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().submit(r);
}
use of net.dv8tion.jda.api.interactions.commands.Command in project Bean by Xirado.
the class InteractionCommandHandler method handleMessageContextCommand.
public void handleMessageContextCommand(@NotNull MessageContextInteractionEvent event) {
if (!event.isFromGuild())
return;
Guild guild = event.getGuild();
Member member = event.getMember();
MessageContextCommand command = null;
if (registeredGuildCommands.containsKey(guild.getIdLong())) {
List<MessageContextCommand> guildCommands = registeredGuildCommands.get(guild.getIdLong()).stream().filter(cmd -> cmd instanceof MessageContextCommand).map(cmd -> (MessageContextCommand) cmd).toList();
MessageContextCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (guildCommand != null)
command = guildCommand;
}
if (command == null) {
MessageContextCommand globalCommand = getRegisteredMessageContextCommands().stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (globalCommand != null)
command = globalCommand;
}
if (command == null)
return;
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.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;
}
}
}
MessageContextCommand finalCommand = command;
Runnable r = () -> {
try {
finalCommand.executeCommand(event);
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 message-context-menu-command", e);
EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a message-context-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", event.getName(), 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().submit(r);
}
use of net.dv8tion.jda.api.interactions.commands.Command in project dDiscordBot by DenizenScript.
the class DiscordCommandCommand method execute.
@Override
public void execute(ScriptEntry scriptEntry) {
DiscordBotTag bot = scriptEntry.requiredArgForPrefix("id", DiscordBotTag.class);
ElementTag commandInstruction = scriptEntry.getElement("instruction");
DiscordGroupTag group = scriptEntry.getObjectTag("group");
ElementTag name = scriptEntry.getElement("name");
ElementTag description = scriptEntry.getElement("description");
MapTag options = scriptEntry.getObjectTag("options");
ElementTag enabled = scriptEntry.getElement("enabled");
ListTag enableFor = scriptEntry.getObjectTag("enable_for");
ListTag disableFor = scriptEntry.getObjectTag("disable_for");
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(), bot, commandInstruction, group, name, description, options, enabled, enableFor, disableFor);
}
if (group != null && group.bot == null) {
group.bot = bot.bot;
}
JDA client = bot.getConnection().client;
Bukkit.getScheduler().runTaskAsynchronously(DenizenDiscordBot.instance, () -> {
try {
if (commandInstruction == null) {
Debug.echoError(scriptEntry, "Must have a command instruction!");
scriptEntry.setFinished(true);
return;
} else if (name == null) {
Debug.echoError(scriptEntry, "Must specify a name!");
scriptEntry.setFinished(true);
return;
}
DiscordCommandInstruction commandInstructionEnum = DiscordCommandInstruction.valueOf(commandInstruction.asString().toUpperCase());
boolean isEnabled = enabled == null || enabled.asBoolean();
switch(commandInstructionEnum) {
case CREATE:
{
if (description == null) {
Debug.echoError(scriptEntry, "Must specify a description!");
scriptEntry.setFinished(true);
return;
}
SlashCommandData data = Commands.slash(name.asString(), description.asString());
if (options != null) {
for (ObjectTag optionObj : options.map.values()) {
MapTag option = optionObj.asType(MapTag.class, scriptEntry.getContext());
ElementTag typeStr = (ElementTag) option.getObject("type");
if (typeStr == null) {
Debug.echoError(scriptEntry, "Command options must specify a type!");
scriptEntry.setFinished(true);
return;
}
OptionType optionType = OptionType.valueOf(typeStr.toString().toUpperCase());
ElementTag optionName = (ElementTag) option.getObject("name");
ElementTag optionDescription = (ElementTag) option.getObject("description");
ElementTag optionIsRequired = (ElementTag) option.getObject("required");
MapTag optionChoices = (MapTag) option.getObject("choices");
if (optionName == null) {
Debug.echoError(scriptEntry, "Command options must specify a name!");
scriptEntry.setFinished(true);
return;
} else if (optionDescription == null) {
Debug.echoError(scriptEntry, "Command options must specify a description!");
scriptEntry.setFinished(true);
return;
}
if (optionType == OptionType.SUB_COMMAND) {
data.addSubcommands(new SubcommandData(optionName.asString(), optionDescription.asString()));
} else /*
support these later
needs recursive logic
else if (optionType == OptionType.SUB_COMMAND_GROUP) {
data.addSubcommandGroups(new SubcommandGroupData(optionName.asString(), optionDescription.asString()));
}
*/
{
OptionData optionData = new OptionData(optionType, optionName.asString(), optionDescription.asString(), optionIsRequired == null ? true : optionIsRequired.asBoolean());
if (optionChoices != null) {
if (optionType != OptionType.STRING && optionType != OptionType.INTEGER) {
Debug.echoError(scriptEntry, "Command options with choices must be either STRING or INTEGER!");
scriptEntry.setFinished(true);
return;
}
for (Map.Entry<StringHolder, ObjectTag> subChoiceValue : optionChoices.map.entrySet()) {
MapTag choice = subChoiceValue.getValue().asType(MapTag.class, scriptEntry.getContext());
ElementTag choiceName = (ElementTag) choice.getObject("name");
ElementTag choiceValue = (ElementTag) choice.getObject("value");
if (choiceName == null) {
Debug.echoError(scriptEntry, "Command option choices must specify a name!");
scriptEntry.setFinished(true);
return;
} else if (choiceValue == null) {
Debug.echoError(scriptEntry, "Command option choices must specify a value!");
scriptEntry.setFinished(true);
return;
}
if (optionType == OptionType.STRING) {
optionData.addChoice(choiceName.asString(), choiceValue.asString());
} else {
optionData.addChoice(choiceName.asString(), choiceValue.asInt());
}
}
}
data.addOptions(optionData);
}
}
}
CommandCreateAction action;
if (group == null) {
Debug.log("Registering a slash command globally may take up to an hour.");
action = (CommandCreateAction) client.upsertCommand(data);
} else {
action = (CommandCreateAction) group.getGuild().upsertCommand(data);
}
action.setDefaultEnabled(isEnabled);
Command slashCommand = action.complete();
scriptEntry.addObject("command", new DiscordCommandTag(bot.bot, group == null ? null : group.getGuild(), slashCommand));
break;
}
case PERMS:
{
if (enableFor == null && disableFor == null) {
Debug.echoError(scriptEntry, "Must specify privileges!");
scriptEntry.setFinished(true);
return;
} else if (group == null) {
Debug.echoError(scriptEntry, "Must specify a group!");
scriptEntry.setFinished(true);
return;
}
Command bestMatch = matchCommandByName(scriptEntry, name, client, group);
if (bestMatch == null) {
return;
}
List<CommandPrivilege> privileges = new ArrayList<>();
if (enableFor != null) {
addPrivileges(scriptEntry, true, enableFor, privileges);
}
if (disableFor != null) {
addPrivileges(scriptEntry, false, disableFor, privileges);
}
bestMatch.editCommand().setDefaultEnabled(isEnabled).complete();
group.guild.updateCommandPrivilegesById(bestMatch.getIdLong(), privileges).complete();
break;
}
case DELETE:
{
Command bestMatch = matchCommandByName(scriptEntry, name, client, group);
if (bestMatch == null) {
return;
}
if (group == null) {
client.deleteCommandById(bestMatch.getIdLong()).complete();
} else {
group.getGuild().deleteCommandById(bestMatch.getIdLong()).complete();
}
break;
}
}
} catch (Exception e) {
Debug.echoError(e);
}
scriptEntry.setFinished(true);
});
}
use of net.dv8tion.jda.api.interactions.commands.Command in project dDiscordBot by DenizenScript.
the class DiscordBotTag method registerTags.
public static void registerTags() {
AbstractFlagTracker.registerFlagHandlers(tagProcessor);
// <--[tag]
// @attribute <DiscordBotTag.name>
// @returns ElementTag
// @plugin dDiscordBot
// @description
// Returns the name of the bot.
// -->
tagProcessor.registerTag(ElementTag.class, "name", (attribute, object) -> {
return new ElementTag(object.bot);
});
// <--[tag]
// @attribute <DiscordBotTag.self_user>
// @returns DiscordUserTag
// @plugin dDiscordBot
// @description
// Returns the bot's own Discord user object.
// -->
tagProcessor.registerTag(DiscordUserTag.class, "self_user", (attribute, object) -> {
DiscordConnection connection = object.getConnection();
if (connection == null) {
return null;
}
return new DiscordUserTag(object.bot, connection.client.getSelfUser());
});
// <--[tag]
// @attribute <DiscordBotTag.groups>
// @returns ListTag(DiscordGroupTag)
// @plugin dDiscordBot
// @description
// Returns a list of all groups (aka 'guilds' or 'servers') that this Discord bot has access to.
// -->
tagProcessor.registerTag(ListTag.class, "groups", (attribute, object) -> {
DiscordConnection connection = object.getConnection();
if (connection == null) {
return null;
}
ListTag list = new ListTag();
for (Guild guild : connection.client.getGuilds()) {
list.addObject(new DiscordGroupTag(object.bot, guild));
}
return list;
});
// <--[tag]
// @attribute <DiscordBotTag.commands>
// @returns ListTag(DiscordCommandTag)
// @plugin dDiscordBot
// @description
// Returns a list of all application commands.
// -->
tagProcessor.registerTag(ListTag.class, "commands", (attribute, object) -> {
DiscordConnection connection = object.getConnection();
if (connection == null) {
return null;
}
ListTag list = new ListTag();
for (Command command : connection.client.retrieveCommands().complete()) {
list.addObject(new DiscordCommandTag(object.bot, null, command));
}
return list;
});
// <--[tag]
// @attribute <DiscordBotTag.group[<name>]>
// @returns DiscordGroupTag
// @plugin dDiscordBot
// @description
// Returns the Discord group (aka 'guild' or 'server') that best matches the input name, or null if there's no match.
// -->
tagProcessor.registerTag(DiscordGroupTag.class, "group", (attribute, object) -> {
if (!attribute.hasParam()) {
return null;
}
DiscordConnection connection = object.getConnection();
if (connection == null) {
return null;
}
String matchString = CoreUtilities.toLowerCase(attribute.getParam());
Guild bestMatch = null;
for (Guild guild : connection.client.getGuilds()) {
String guildName = CoreUtilities.toLowerCase(guild.getName());
if (matchString.equals(guildName)) {
bestMatch = guild;
break;
}
if (guildName.contains(matchString)) {
bestMatch = guild;
}
}
if (bestMatch == null) {
return null;
}
return new DiscordGroupTag(object.bot, bestMatch);
});
// <--[tag]
// @attribute <DiscordBotTag.command[<name>]>
// @returns DiscordCommandTag
// @plugin dDiscordBot
// @description
// Returns the application command that best matches the input name, or null if there's no match.
// -->
tagProcessor.registerTag(DiscordCommandTag.class, "command", (attribute, object) -> {
if (!attribute.hasParam()) {
return null;
}
DiscordConnection connection = object.getConnection();
if (connection == null) {
return null;
}
String matchString = CoreUtilities.toLowerCase(attribute.getParam());
Command bestMatch = null;
for (Command command : connection.client.retrieveCommands().complete()) {
String commandName = CoreUtilities.toLowerCase(command.getName());
if (matchString.equals(commandName)) {
bestMatch = command;
break;
}
if (commandName.contains(matchString)) {
bestMatch = command;
}
}
if (bestMatch == null) {
return null;
}
return new DiscordCommandTag(object.bot, null, bestMatch);
});
}
use of net.dv8tion.jda.api.interactions.commands.Command in project dDiscordBot by DenizenScript.
the class DiscordCommandTag method registerTags.
public static void registerTags() {
AbstractFlagTracker.registerFlagHandlers(tagProcessor);
// <--[tag]
// @attribute <DiscordCommandTag.id>
// @returns ElementTag(Number)
// @plugin dDiscordBot
// @description
// Returns the ID of the command.
// -->
tagProcessor.registerTag(ElementTag.class, "id", (attribute, object) -> {
return new ElementTag(object.command_id);
});
// <--[tag]
// @attribute <DiscordCommandTag.name>
// @returns ElementTag
// @plugin dDiscordBot
// @description
// Returns the name of the command.
// -->
tagProcessor.registerTag(ElementTag.class, "name", (attribute, object) -> {
return new ElementTag(object.getCommand().getName());
});
// <--[tag]
// @attribute <DiscordCommandTag.description>
// @returns ElementTag
// @plugin dDiscordBot
// @description
// Returns the description of the command.
// -->
tagProcessor.registerTag(ElementTag.class, "description", (attribute, object) -> {
return new ElementTag(object.getCommand().getDescription());
});
// <--[tag]
// @attribute <DiscordCommandTag.options>
// @returns ListTag(MapTag)
// @plugin dDiscordBot
// @description
// Returns the option MapTags of the command. This is the same value as the one provided when creating a command, as documented in <@link command DiscordCommand>.
// -->
tagProcessor.registerTag(ListTag.class, "options", (attribute, object) -> {
ListTag options = new ListTag();
for (Command.Option option : object.getCommand().getOptions()) {
MapTag map = new MapTag();
map.putObject("type", new ElementTag(option.getType().toString().toLowerCase().replaceAll("_", "")));
map.putObject("name", new ElementTag(option.getName()));
map.putObject("description", new ElementTag(option.getDescription()));
map.putObject("required", new ElementTag(option.isRequired()));
if (option.getType() == OptionType.STRING || option.getType() == OptionType.INTEGER) {
ListTag choices = new ListTag();
for (Command.Choice choice : option.getChoices()) {
MapTag choiceData = new MapTag();
choiceData.putObject("name", new ElementTag(choice.getName()));
if (option.getType() == OptionType.STRING) {
choiceData.putObject("value", new ElementTag(choice.getAsString()));
} else {
choiceData.putObject("value", new ElementTag(choice.getAsLong()));
}
choices.addObject(choiceData);
}
map.putObject("choices", choices);
}
options.addObject(map);
}
return options;
});
}
Aggregations