Search in sources :

Example 11 with SlashCommandInteractionEvent

use of net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent in project Ninbot by Nincodedo.

the class SlashCommandEventMessageExecutorTest method executeOneMessageAction.

@Test
void executeOneMessageAction() {
    SlashCommandInteractionEvent slashCommandEvent = Mockito.mock(SlashCommandInteractionEvent.class);
    ReplyCallbackAction replyAction = Mockito.mock(ReplyCallbackAction.class);
    when(slashCommandEvent.reply(any(Message.class))).thenReturn(replyAction);
    messageExecutor = new SlashCommandEventMessageExecutor(slashCommandEvent);
    messageExecutor.addMessageResponse("wow");
    messageExecutor.executeActions();
    verify(slashCommandEvent, times(1)).reply(any(Message.class));
}
Also used : Message(net.dv8tion.jda.api.entities.Message) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) ReplyCallbackAction(net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction) Test(org.junit.jupiter.api.Test)

Example 12 with SlashCommandInteractionEvent

use of net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent in project JDA by DV8FromTheWorld.

the class SlashBotExample method ban.

public void ban(SlashCommandInteractionEvent event, User user, Member member) {
    // Let the user know we received the command before doing anything else
    event.deferReply(true).queue();
    // This is a special webhook that allows you to send messages without having permissions in the channel and also allows ephemeral messages
    InteractionHook hook = event.getHook();
    // All messages here will now be ephemeral implicitly
    hook.setEphemeral(true);
    if (!event.getMember().hasPermission(Permission.BAN_MEMBERS)) {
        hook.sendMessage("You do not have the required permissions to ban users from this server.").queue();
        return;
    }
    Member selfMember = event.getGuild().getSelfMember();
    if (!selfMember.hasPermission(Permission.BAN_MEMBERS)) {
        hook.sendMessage("I don't have the required permissions to ban users from this server.").queue();
        return;
    }
    if (member != null && !selfMember.canInteract(member)) {
        hook.sendMessage("This user is too powerful for me to ban.").queue();
        return;
    }
    // optional command argument, fall back to 0 if not provided
    // this last part is a method reference used to "resolve" the option value
    int delDays = event.getOption("del_days", 0, OptionMapping::getAsInt);
    // optional ban reason with a lazy evaluated fallback (supplier)
    String reason = event.getOption("reason", // used if getOption("reason") is null (not provided)
    () -> "Banned by " + event.getUser().getAsTag(), // used if getOption("reason") is not null (provided)
    OptionMapping::getAsString);
    // Ban the user and send a success response
    event.getGuild().ban(user, delDays, reason).reason(// audit-log reason
    reason).flatMap(v -> hook.sendMessage("Banned user " + user.getAsTag())).queue();
}
Also used : OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) LoginException(javax.security.auth.login.LoginException) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) JDA(net.dv8tion.jda.api.JDA) ButtonInteractionEvent(net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent) Permission(net.dv8tion.jda.api.Permission) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) Member(net.dv8tion.jda.api.entities.Member) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) User(net.dv8tion.jda.api.entities.User) Commands(net.dv8tion.jda.api.interactions.commands.build.Commands) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) JDABuilder(net.dv8tion.jda.api.JDABuilder) OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) EnumSet(java.util.EnumSet) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) Member(net.dv8tion.jda.api.entities.Member)

Example 13 with SlashCommandInteractionEvent

use of net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent in project JavaBot by Java-Discord.

the class MigrationsListSubcommand method handleSlashCommandInteraction.

@Override
public ReplyCallbackAction handleSlashCommandInteraction(SlashCommandInteractionEvent event) {
    try (var s = Files.list(MigrationUtils.getMigrationsDirectory())) {
        EmbedBuilder embedBuilder = new EmbedBuilder().setTitle("List of Runnable Migrations");
        var paths = s.filter(path -> path.getFileName().toString().endsWith(".sql")).toList();
        if (paths.isEmpty()) {
            embedBuilder.setDescription("There are no migrations to run. Please add them to the `/migrations/` resource directory.");
            return event.replyEmbeds(embedBuilder.build());
        }
        paths.forEach(path -> {
            StringBuilder sb = new StringBuilder(150);
            sb.append("```sql\n");
            try {
                String sql = Files.readString(path);
                sb.append(sql, 0, Math.min(sql.length(), 100));
                if (sql.length() > 100)
                    sb.append("...");
            } catch (IOException e) {
                e.printStackTrace();
                sb.append("Error: Could not read SQL: ").append(e.getMessage());
            }
            sb.append("\n```");
            embedBuilder.addField(path.getFileName().toString(), sb.toString(), false);
        });
        return event.replyEmbeds(embedBuilder.build());
    } catch (IOException | URISyntaxException e) {
        return Responses.error(event, e.getMessage());
    }
}
Also used : ISlashCommand(net.javadiscord.javabot.command.interfaces.ISlashCommand) Files(java.nio.file.Files) Responses(net.javadiscord.javabot.command.Responses) URISyntaxException(java.net.URISyntaxException) MigrationUtils(net.javadiscord.javabot.data.h2db.MigrationUtils) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ReplyCallbackAction(net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException)

Example 14 with SlashCommandInteractionEvent

use of net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent in project JavaBot by Java-Discord.

the class HelpChannelManager method sendThanksButtonsMessage.

private void sendThanksButtonsMessage(List<Member> potentialHelpers, ChannelReservation reservation, Interaction interaction, TextChannel channel) {
    List<ItemComponent> thanksButtons = new ArrayList<>(25);
    for (var helper : potentialHelpers.subList(0, Math.min(potentialHelpers.size(), 20))) {
        thanksButtons.add(new ButtonImpl("help-thank:" + reservation.getId() + ":" + helper.getId(), helper.getEffectiveName(), ButtonStyle.SUCCESS, false, Emoji.fromUnicode("❤")));
    }
    ActionRow controlsRow = ActionRow.of(new ButtonImpl("help-thank:" + reservation.getId() + ":done", "Unreserve", ButtonStyle.PRIMARY, false, Emoji.fromUnicode("✅")), new ButtonImpl("help-thank:" + reservation.getId() + ":cancel", "Cancel", ButtonStyle.SECONDARY, false, Emoji.fromUnicode("❌")));
    InteractionHook hook;
    if (interaction.getType() == InteractionType.COMPONENT) {
        hook = ((ButtonInteractionEvent) interaction).getHook();
    } else if (interaction.getType() == InteractionType.COMMAND) {
        hook = ((SlashCommandInteractionEvent) interaction).getHook();
    } else {
        throw new IllegalStateException("Unable to obtain Interaction Hook!");
    }
    hook.sendMessage(THANK_MESSAGE_TEXT).setEphemeral(true).queue();
    List<ActionRow> rows = new ArrayList<>(5);
    rows.add(controlsRow);
    rows.addAll(MessageActionUtils.toActionRows(thanksButtons));
    channel.sendMessage(THANK_MESSAGE_TEXT).setActionRows(rows).queue();
}
Also used : InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) ItemComponent(net.dv8tion.jda.api.interactions.components.ItemComponent) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) ButtonImpl(net.dv8tion.jda.internal.interactions.component.ButtonImpl)

Example 15 with SlashCommandInteractionEvent

use of net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent in project Discord-Core-Bot-Apple by demodude4u.

the class DiscordBot method startUp.

@Override
protected void startUp() throws Exception {
    info.addTechnology("[DCBA](https://github.com/demodude4u/Discord-Core-Bot-Apple)", Optional.empty(), "Discord Core Bot Apple");
    info.addTechnology("[JDA](https://github.com/DV8FromTheWorld/JDA)", Optional.of("5.0 alpha"), "Java Discord API");
    if (configJson.has("command_prefix")) {
        setCommandPrefix(Optional.of(configJson.getString("command_prefix")));
    }
    JDABuilder builder = // 
    JDABuilder.createDefault(configJson.getString("bot_token")).setEnableShutdownHook(// 
    false).addEventListeners(new ListenerAdapter() {

        @Override
        public void onCommandAutoCompleteInteraction(CommandAutoCompleteInteractionEvent event) {
            SlashCommandDefinition commandDefinition = commandSlash.get(event.getCommandPath());
            Optional<AutoCompleteHandler> autoCompleteHandler = commandDefinition.getAutoCompleteHandler();
            if (autoCompleteHandler.isPresent()) {
                AutoCompleteEvent autoCompleteEvent = new AutoCompleteEvent(event);
                autoCompleteHandler.get().handleAutoComplete(autoCompleteEvent);
            }
        }

        @Override
        public void onMessageContextInteraction(MessageContextInteractionEvent event) {
            MessageCommandDefinition commandDefinition = commandMessage.get(event.getName());
            boolean ephemeral = commandDefinition.hasRestriction(CommandRestriction.EPHEMERAL);
            CommandReporting reporting = createReporting(event);
            InteractionHook hook = event.deferReply(ephemeral).complete();
            MessageCommandEvent commandEvent = new MessageCommandEvent(event, reporting, hook, ephemeral);
            commandService.submit(() -> {
                try {
                    commandDefinition.getHandler().handleCommand(commandEvent);
                } catch (Exception e) {
                    reporting.addException(e);
                } finally {
                    if (!commandDefinition.hasRestriction(CommandRestriction.NO_REPORTING)) {
                        submitReport(reporting);
                    }
                    if (!reporting.getExceptions().isEmpty()) {
                        commandEvent.replyEmbed(new EmbedBuilder().setColor(Color.red).appendDescription("Sorry, there was a problem completing your request.\n" + reporting.getExceptions().stream().map(e -> "`" + e.getMessage() + "`").distinct().collect(Collectors.joining("\n"))).build());
                    }
                    if (!commandEvent.hasReplied()) {
                        hook.deleteOriginal().complete();
                    }
                }
            });
        }

        @Override
        public void onMessageDelete(MessageDeleteEvent event) {
            if (textWatcher.isPresent()) {
                textWatcher.get().deletedMessage(event);
            }
        }

        @Override
        public void onMessageReactionAdd(MessageReactionAddEvent event) {
            if (reactionWatcher.isPresent()) {
                reactionWatcher.get().seenReaction(event);
            }
        }

        @Override
        public void onMessageReactionRemove(MessageReactionRemoveEvent event) {
            if (reactionWatcher.isPresent()) {
                reactionWatcher.get().seenReactionRemoved(event);
            }
        }

        @Override
        public void onMessageReactionRemoveAll(MessageReactionRemoveAllEvent event) {
            if (reactionWatcher.isPresent()) {
                reactionWatcher.get().seenAllReactionRemoved(event);
            }
        }

        @Override
        public void onMessageReceived(MessageReceivedEvent event) {
            if (textWatcher.isPresent()) {
                textWatcher.get().seenMessage(event);
            }
            Message message = event.getMessage();
            MessageChannel channel = message.getChannel();
            String rawContent = message.getContentRaw().trim();
            String mentionMe = "<@!" + event.getJDA().getSelfUser().getId() + ">";
            // String mentionMe = event.getJDA().getSelfUser().getAsMention();
            boolean isPrivateChannel = channel instanceof PrivateChannel;
            if (isPrivateChannel && ignorePrivateChannels) {
                return;
            }
            boolean startsWithMentionMe = message.getMentionedUsers().stream().anyMatch(u -> u.getIdLong() == event.getJDA().getSelfUser().getIdLong()) && rawContent.startsWith(mentionMe);
            if (startsWithMentionMe) {
                rawContent = rawContent.substring(mentionMe.length()).trim();
            }
            Optional<String> effectivePrefix = getOldCommandPrefix(event);
            boolean startsWithCommandPrefix = effectivePrefix.isPresent() && rawContent.startsWith(effectivePrefix.get());
            if (startsWithCommandPrefix) {
                rawContent = rawContent.substring(effectivePrefix.get().length()).trim();
            }
            if (!event.getAuthor().isBot() && (isPrivateChannel || startsWithMentionMe || startsWithCommandPrefix)) {
                String[] split = rawContent.split("\\s+");
                if (split.length > 0) {
                    String command = split[0];
                    SlashCommandDefinition commandDefinition = commandLegacy.get(command.toLowerCase());
                    if (commandDefinition != null) {
                        boolean isPermitted = checkPermitted(channel, event.getMember(), commandDefinition);
                        if (isPermitted) {
                            event.getChannel().sendMessageEmbeds(new EmbedBuilder().appendDescription("Please use /" + commandDefinition.getPath().replace("/", " ")).build()).complete();
                        }
                    }
                }
            }
        }

        @Override
        public void onMessageUpdate(MessageUpdateEvent event) {
            if (textWatcher.isPresent()) {
                textWatcher.get().editedMessage(event);
            }
        }

        @Override
        public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
            SlashCommandDefinition commandDefinition = commandSlash.get(event.getCommandPath());
            boolean ephemeral = commandDefinition.hasRestriction(CommandRestriction.EPHEMERAL);
            CommandReporting reporting = createReporting(event);
            InteractionHook hook = event.deferReply(ephemeral).complete();
            SlashCommandEvent commandEvent = new SlashCommandEvent(event, reporting, hook, ephemeral);
            commandService.submit(() -> {
                try {
                    commandDefinition.getHandler().handleCommand(commandEvent);
                } catch (Exception e) {
                    System.err.println("Uncaught Exception!");
                    e.printStackTrace();
                    reporting.addException(e);
                } finally {
                    if (!commandDefinition.hasRestriction(CommandRestriction.NO_REPORTING)) {
                        submitReport(reporting);
                    }
                    if (!reporting.getExceptions().isEmpty()) {
                        commandEvent.replyEmbed(new EmbedBuilder().setColor(Color.red).appendDescription("Sorry, there was a problem completing your request.\n" + reporting.getExceptions().stream().map(e -> "`" + e.getMessage() + "`").distinct().collect(Collectors.joining("\n"))).build());
                    }
                    if (!commandEvent.hasReplied()) {
                        hook.deleteOriginal().complete();
                    }
                }
            });
        }
    });
    if (customSetup != null) {
        builder = customSetup.apply(builder);
    }
    jda = builder.build().awaitReady();
    jda.setRequiredScopes("bot", "applications.commands");
    reportingUserID = Optional.ofNullable(configJson.optString("reporting_user_id", null));
    reportingChannelID = Optional.ofNullable(configJson.optString("reporting_channel_id", null));
    if (configJson.has("debug_guild_commands")) {
        String guildId = configJson.getString("debug_guild_commands");
        Guild guild = jda.getGuildById(guildId);
        CommandListUpdateAction updateCommands = guild.updateCommands();
        buildUpdateCommands(updateCommands);
        updateCommands.queue();
    }
    CommandListUpdateAction updateCommands = jda.updateCommands();
    buildUpdateCommands(updateCommands);
    updateCommands.queue();
}
Also used : Color(java.awt.Color) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) Permission(net.dv8tion.jda.api.Permission) MessageUpdateEvent(net.dv8tion.jda.api.events.message.MessageUpdateEvent) Scanner(java.util.Scanner) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ChannelType(net.dv8tion.jda.api.entities.ChannelType) CommandInteractionPayload(net.dv8tion.jda.api.interactions.commands.CommandInteractionPayload) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Guild(net.dv8tion.jda.api.entities.Guild) Map(java.util.Map) OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) PrintWriter(java.io.PrintWriter) Message(net.dv8tion.jda.api.entities.Message) SubcommandData(net.dv8tion.jda.api.interactions.commands.build.SubcommandData) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) Instant(java.time.Instant) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) SlashCommandData(net.dv8tion.jda.api.interactions.commands.build.SlashCommandData) List(java.util.List) MessageReactionRemoveAllEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveAllEvent) MessageDeleteEvent(net.dv8tion.jda.api.events.message.MessageDeleteEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) MessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent) JDA(net.dv8tion.jda.api.JDA) MessageContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent) LocalDateTime(java.time.LocalDateTime) Function(java.util.function.Function) PrivateChannel(net.dv8tion.jda.api.entities.PrivateChannel) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) JDABuilder(net.dv8tion.jda.api.JDABuilder) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SubcommandGroupData(net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData) ExecutorService(java.util.concurrent.ExecutorService) StringWriter(java.io.StringWriter) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData) Commands(net.dv8tion.jda.api.interactions.commands.build.Commands) ChronoUnit(java.time.temporal.ChronoUnit) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) PrivateChannel(net.dv8tion.jda.api.entities.PrivateChannel) MessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent) Message(net.dv8tion.jda.api.entities.Message) JDABuilder(net.dv8tion.jda.api.JDABuilder) MessageUpdateEvent(net.dv8tion.jda.api.events.message.MessageUpdateEvent) Guild(net.dv8tion.jda.api.entities.Guild) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) MessageReactionRemoveAllEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveAllEvent) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) Optional(java.util.Optional) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) JSONException(org.json.JSONException) IOException(java.io.IOException) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) MessageContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent) MessageDeleteEvent(net.dv8tion.jda.api.events.message.MessageDeleteEvent)

Aggregations

SlashCommandInteractionEvent (net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent)24 Commands (net.dv8tion.jda.api.interactions.commands.build.Commands)11 NotNull (org.jetbrains.annotations.NotNull)11 SlashCommand (at.xirado.bean.command.SlashCommand)10 SlashCommandContext (at.xirado.bean.command.SlashCommandContext)10 OptionType (net.dv8tion.jda.api.interactions.commands.OptionType)10 Permission (net.dv8tion.jda.api.Permission)9 EmbedUtil (at.xirado.bean.misc.EmbedUtil)7 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)7 Bean (at.xirado.bean.Bean)6 Guild (net.dv8tion.jda.api.entities.Guild)6 Member (net.dv8tion.jda.api.entities.Member)6 OptionMapping (net.dv8tion.jda.api.interactions.commands.OptionMapping)5 OptionData (net.dv8tion.jda.api.interactions.commands.build.OptionData)5 ReplyCallbackAction (net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction)5 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 Util (at.xirado.bean.misc.Util)3 FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)3 SQLException (java.sql.SQLException)3