Search in sources :

Example 6 with CommandListUpdateAction

use of net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction 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)

Example 7 with CommandListUpdateAction

use of net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction in project JDA by DV8FromTheWorld.

the class SlashBotExample method main.

public static void main(String[] args) throws LoginException {
    JDA jda = // slash commands don't need any intents
    JDABuilder.createLight("BOT_TOKEN_HERE", EnumSet.noneOf(GatewayIntent.class)).addEventListeners(new SlashBotExample()).build();
    // These commands take up to an hour to be activated after creation/update/delete
    CommandListUpdateAction commands = jda.updateCommands();
    // Moderation commands with required options
    commands.addCommands(Commands.slash("ban", "Ban a user from this server. Requires permission to ban users.").addOptions(// USER type allows to include members of the server or other users by id
    new OptionData(USER, "user", "The user to ban").setRequired(// This command requires a parameter
    true)).addOptions(// This is optional
    new OptionData(INTEGER, "del_days", "Delete messages from the past days.").setRequiredRange(0, // Only allow values between 0 and 7 (inclusive)
    7)).addOptions(// optional reason
    new OptionData(STRING, "reason", "The ban reason to use (default: Banned by <user>)")));
    // Simple reply commands
    commands.addCommands(Commands.slash("say", "Makes the bot say what you tell it to").addOption(STRING, "content", "What the bot should say", // you can add required options like this too
    true));
    // Commands without any inputs
    commands.addCommands(Commands.slash("leave", "Make the bot leave the server"));
    commands.addCommands(Commands.slash("prune", "Prune messages from this channel").addOption(INTEGER, "amount", // simple optional argument
    "How many messages to prune (Default 100)"));
    // Send the new set of commands to discord, this will override any existing global commands with the new set provided here
    commands.queue();
}
Also used : JDA(net.dv8tion.jda.api.JDA) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent)

Example 8 with CommandListUpdateAction

use of net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction in project discord-bot-reddit-java by Glaxier0.

the class GivePermissionCommand method addCommandsToGuild.

private void addCommandsToGuild(Guild guild) {
    CommandListUpdateAction guildCommands = guild.updateCommands();
    guildCommands.addCommands(Commands.slash("play", "Play a song on your voice channel.").addOptions(new OptionData(OptionType.STRING, "query", "Song url or name.").setRequired(true)), Commands.slash("skip", "Skip the current song."), Commands.slash("pause", "Pause the current song."), Commands.slash("resume", "Resume paused song."), Commands.slash("leave", "Make bot leave voice channel."), Commands.slash("queue", "List song queue."), Commands.slash("swap", "Swap order of two songs in queue").addOptions(new OptionData(OptionType.INTEGER, "songnum1", "Song number in the queue to be changed.").setRequired(true), new OptionData(OptionType.INTEGER, "songnum2", "Song number in queue to be changed.").setRequired(true)), Commands.slash("shuffle", "Shuffle the queue."), Commands.slash("mhelp", "Help page for music commands.")).queue();
}
Also used : OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction)

Example 9 with CommandListUpdateAction

use of net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction in project discord-bot-reddit-java by Glaxier0.

the class Bot method addCommands.

private void addCommands(JDA jda) {
    while (jda.getGuildById(TEST_SERVER) == null) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    Guild testServer = jda.getGuildById(TEST_SERVER);
    CommandListUpdateAction testServerCommands = testServer.updateCommands();
    CommandListUpdateAction globalCommands = jda.updateCommands();
    testServerCommands.addCommands(// admin commands
    Commands.slash("givepermission", "Give permission to guild").addOptions(new OptionData(OptionType.STRING, "guildid", "Guild id.").setRequired(true), new OptionData(OptionType.STRING, "guildname", "Guild name.").setRequired(false)), Commands.slash("retrievepermission", "Retrieve permission from guild").addOptions(new OptionData(OptionType.STRING, "guildid", "Guild id.").setRequired(true)), Commands.slash("guilds", "Get guild list that bot is in."), Commands.slash("status", "Get reddit post statuses."), Commands.slash("stats", "Get user stats.").addOptions(new OptionData(OptionType.MENTIONABLE, "user", "User with mention.").setRequired(true)), Commands.slash("users", "Get bot users."), Commands.slash("logs", "Get logs."), Commands.slash("getguild", "Get guild id."), Commands.slash("addguild", "Add guild to the premium list.").addOptions(new OptionData(OptionType.STRING, "guildname", "Guild name.").setRequired(true)).addOptions(new OptionData(OptionType.STRING, "guildid", "Guild ID.").setRequired(true)), Commands.slash("removeguild", "Remove guild from premium list.").addOptions(new OptionData(OptionType.STRING, "guildid", "Guild ID.").setRequired(true)), Commands.slash("getguilds", "Get premium guilds."), // Music Commands
    Commands.slash("play", "Play a song on your voice channel.").addOptions(new OptionData(OptionType.STRING, "query", "Song url or name.").setRequired(true)), Commands.slash("skip", "Skip the current song."), Commands.slash("pause", "Pause the current song."), Commands.slash("resume", "Resume paused song."), Commands.slash("leave", "Make bot leave voice channel."), Commands.slash("queue", "List song queue."), Commands.slash("swap", "Swap order of two songs in queue").addOptions(new OptionData(OptionType.INTEGER, "songnum1", "Song number in the queue to be changed.").setRequired(true), new OptionData(OptionType.INTEGER, "songnum2", "Song number in queue to be changed.").setRequired(true)), Commands.slash("shuffle", "Shuffle the queue."), Commands.slash("mhelp", "Help page for music commands.")).queue();
    globalCommands.addCommands(// nsfw commands
    Commands.slash("hentai", "Get random hentai image/gif/video."), Commands.slash("porn", "Get random porn image/gif/video."), // reddit commands
    Commands.slash("unexpected", "Get top r/unexpected posts."), Commands.slash("dankmemes", "Get top r/dankmemes posts."), Commands.slash("memes", "Get top r/memes posts."), Commands.slash("greentext", "Get top r/greentext posts."), Commands.slash("blursedimages", "Get top r/blursedimages posts."), Commands.slash("perfectlycutscreams", "Get top r/perfectlycutscreams posts."), Commands.slash("interestingasfuck", "Get top r/interestingasfuck posts."), Commands.slash("facepalm", "Get top r/facepalm posts."), // test commands
    Commands.slash("help", "Info page about bot commands"), Commands.slash("monke", "Get my favorite random monke video."), Commands.slash("github", "My github page and source code of bot."), Commands.slash("howgay", "Calculate how gay is someone.").addOptions(new OptionData(OptionType.USER, "user", "User to calculate how gay.").setRequired(true)), Commands.slash("errrkek", "Calculate how man is someone.").addOptions(new OptionData(OptionType.USER, "user", "User to calculate how man.").setRequired(true)), Commands.slash("topgg", "Top.gg page of Glaxier bot."), // to-do commands
    Commands.slash("todoadd", "Add a task to your to-do list.").addOptions(new OptionData(OptionType.STRING, "task", "A to-do task.").setRequired(true)), Commands.slash("todolist", "Shows your to-do list."), Commands.slash("todoremove", "Remove a task from your to-do list.").addOptions(new OptionData(OptionType.INTEGER, "taskid", "To-do task id to remove.").setRequired(true)), Commands.slash("todoupdate", "Update a task in your to-do list.").addOptions(new OptionData(OptionType.INTEGER, "taskid", "To-do task id to remove.").setRequired(true), new OptionData(OptionType.STRING, "task", "Updated to-do task.").setRequired(true)), Commands.slash("todocomplete", "Complete a task in your to-do list.").addOptions(new OptionData(OptionType.INTEGER, "taskid", "To-do task id to remove.").setRequired(true)), Commands.slash("todoclear", "Clears your to-do list.")).queue();
}
Also used : OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) Guild(net.dv8tion.jda.api.entities.Guild)

Example 10 with CommandListUpdateAction

use of net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction in project TAS-Battle by MCPfannkuchenYT.

the class TASDiscordBot method run.

@Override
public void run() {
    for (Guild g : jda.getGuilds()) {
        CommandListUpdateAction updater = g.updateCommands();
        updater.addCommands(new CommandData("play", "Show other players that you are ready to play!"));
        updater.addCommands(new CommandData("online", "Show all players that are online on the server"));
        updater.addCommands(new CommandData("link", "Link your Discord account to your Minecraft Account"));
        updater.queue();
    }
    recreateMessage();
}
Also used : CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) Guild(net.dv8tion.jda.api.entities.Guild) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData)

Aggregations

CommandListUpdateAction (net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction)11 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Guild (net.dv8tion.jda.api.entities.Guild)4 CommandData (net.dv8tion.jda.api.interactions.commands.build.CommandData)4 OptionData (net.dv8tion.jda.api.interactions.commands.build.OptionData)4 JDA (net.dv8tion.jda.api.JDA)3 Arrays (java.util.Arrays)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 Command (net.dv8tion.jda.api.interactions.commands.Command)2 Commands (net.dv8tion.jda.api.interactions.commands.build.Commands)2 GenericCommand (at.xirado.bean.command.GenericCommand)1 AbstractIdleService (com.google.common.util.concurrent.AbstractIdleService)1 Color (java.awt.Color)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1