Search in sources :

Example 1 with Command

use of com.jagrosh.jdautilities.command.Command in project MMDBot by MinecraftModDevelopment.

the class CmdHelp method execute.

/**
 * Prepare the potential scrolling buttons for a help command,
 * and send the message with the proper embeds.
 * <p>
 * See {@link #getEmbed(int)} for the implementation.
 */
public void execute(SlashCommandEvent e) {
    OptionMapping commandName = e.getOption("command");
    commands = CommandModule.getCommandClient().getCommands();
    commands.addAll(CommandModule.getCommandClient().getSlashCommands());
    updateMaximum(commands.size());
    // If no command specified, show all.
    if (commandName == null) {
        sendPaginatedMessage(e);
    } else {
        Command command = CommandModule.getCommandClient().getCommands().stream().filter(// Find the command with the matching name
        com -> com.getName().equals(commandName.getAsString())).findFirst().orElseGet(// And return it as Command.
        CmdHelp::new);
        // Build the embed that summarises the command.
        EmbedBuilder embed = new EmbedBuilder();
        embed.setAuthor(References.NAME, References.ISSUE_TRACKER, MMDBot.getJDA().getSelfUser().getAvatarUrl());
        embed.setDescription("Command help:");
        embed.addField(command.getName(), command.getHelp(), false);
        // If we have arguments defined and there's content, add it to the embed
        if (command.getArguments() != null && command.getArguments().length() > 0) {
            embed.addField("Arguments", command.getArguments(), false);
        }
        embed.setFooter(References.NAME).setTimestamp(Instant.now());
        e.replyEmbeds(embed.build()).queue();
    }
}
Also used : OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Command(com.jagrosh.jdautilities.command.Command) PaginatedCommand(com.mcmoddev.mmdbot.modules.commands.community.PaginatedCommand)

Example 2 with Command

use of com.jagrosh.jdautilities.command.Command in project MMDBot by MinecraftModDevelopment.

the class CmdHelp method getEmbed.

/**
 * Given a starting index, build an embed that we can display for users
 * to summarise all available commands.
 * Intended to be used with pagination in the case of servers with LOTS of commands.
 */
@Override
protected EmbedBuilder getEmbed(int index) {
    EmbedBuilder embed = new EmbedBuilder();
    embed.setAuthor(References.NAME, References.ISSUE_TRACKER, MMDBot.getJDA().getSelfUser().getAvatarUrl());
    embed.setDescription("All registered commands:");
    // Embeds have a 25 field limit. We need to make sure we don't exceed that.
    if (commands.size() < items_per_page) {
        for (Command c : commands) embed.addField(c.getName(), c.getHelp(), true);
    } else {
        // Make sure we only go up to the limit.
        for (int i = index; i < index + items_per_page; i++) if (i < commands.size())
            embed.addField(commands.get(i).getName(), commands.get(i).getHelp(), true);
    }
    embed.setFooter(References.NAME).setTimestamp(Instant.now());
    return embed;
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Command(com.jagrosh.jdautilities.command.Command) PaginatedCommand(com.mcmoddev.mmdbot.modules.commands.community.PaginatedCommand)

Example 3 with Command

use of com.jagrosh.jdautilities.command.Command in project GeyserDiscordBot by GeyserMC.

the class GeyserBot method main.

public static void main(String[] args) throws IOException, LoginException {
    // Load properties into the PropertiesManager
    Properties prop = new Properties();
    prop.load(new FileInputStream("bot.properties"));
    PropertiesManager.loadProperties(prop);
    // Setup sentry.io
    if (PropertiesManager.getSentryDsn() != null) {
        LOGGER.info("Loading sentry.io...");
        Sentry.init(options -> {
            options.setDsn(PropertiesManager.getSentryDsn());
            options.setEnvironment(PropertiesManager.getSentryEnv());
            LOGGER.info("Sentry.io loaded");
        });
    }
    // Connect to github
    github = new GitHubBuilder().withOAuthToken(PropertiesManager.getGithubToken()).build();
    // Initialize the waiter
    EventWaiter waiter = new EventWaiter();
    // Load filters
    SwearHandler.loadFilters();
    // Load the db
    StorageType storageType = StorageType.getByName(PropertiesManager.getDatabaseType());
    if (storageType == StorageType.UNKNOWN) {
        LOGGER.error("Invalid database type! '" + PropertiesManager.getDatabaseType() + "'");
        System.exit(1);
    }
    try {
        storageManager = storageType.getStorageManager().getDeclaredConstructor().newInstance();
        storageManager.setupStorage();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        LOGGER.error("Unable to create database link!");
        System.exit(1);
    }
    // Setup the main client
    CommandClientBuilder client = new CommandClientBuilder();
    client.setActivity(null);
    // No owner
    client.setOwnerId("0");
    client.setPrefix(PropertiesManager.getPrefix());
    client.useHelpBuilder(false);
    client.addCommands(COMMANDS.toArray(new Command[0]));
    client.addSlashCommands(SLASH_COMMANDS.toArray(new SlashCommand[0]));
    client.setListener(new CommandErrorHandler());
    client.setCommandPreProcessBiFunction((event, command) -> !SwearHandler.filteredMessages.contains(event.getMessage().getIdLong()));
    // Setup the tag client
    CommandClientBuilder tagClient = new CommandClientBuilder();
    tagClient.setActivity(null);
    // No owner
    tagClient.setOwnerId("0");
    String tagPrefix = PropertiesManager.getPrefix() + PropertiesManager.getPrefix();
    tagClient.setPrefix(tagPrefix);
    tagClient.setPrefixes(new String[] { "!tag " });
    tagClient.useHelpBuilder(false);
    tagClient.addCommands(TagsManager.getTags().toArray(new Command[0]));
    tagClient.setListener(new TagsListener());
    tagClient.setCommandPreProcessBiFunction((event, command) -> !SwearHandler.filteredMessages.contains(event.getMessage().getIdLong()));
    tagClient.setManualUpsert(true);
    // Disable pings on replies
    MessageAction.setDefaultMentionRepliedUser(false);
    // Setup the thread pool
    generalThreadPool = Executors.newScheduledThreadPool(5);
    // Register JDA
    try {
        jda = JDABuilder.createDefault(PropertiesManager.getToken()).setChunkingFilter(ChunkingFilter.ALL).setMemberCachePolicy(MemberCachePolicy.ALL).enableIntents(GatewayIntent.GUILD_MEMBERS).enableIntents(GatewayIntent.GUILD_PRESENCES).enableCache(CacheFlag.ACTIVITY).enableCache(CacheFlag.ROLE_TAGS).setStatus(OnlineStatus.ONLINE).setActivity(Activity.playing("Booting...")).setEnableShutdownHook(true).setEventManager(new SentryEventManager()).addEventListeners(waiter, new LogHandler(), new SwearHandler(), new PersistentRoleHandler(), new FileHandler(), new LevelHandler(), new DumpHandler(), new ErrorAnalyzer(), new ShutdownHandler(), new VoiceGroupHandler(), new BadLinksHandler(), client.build(), tagClient.build()).build();
    } catch (IllegalArgumentException exception) {
        LOGGER.error("Failed to initialize JDA!", exception);
        System.exit(1);
    }
    // Register listeners
    jda.addEventListener();
    // Setup the http server
    if (PropertiesManager.enableWeb()) {
        try {
            httpServer = new Server();
            httpServer.start();
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
        }
    }
    // Setup the update check scheduler
    UpdateManager.setup();
    // Setup the health check scheduler
    HealthCheckerManager.setup();
    // Setup the rss feed check scheduler
    RssFeedManager.setup();
    // Setup all slow mode handlers
    generalThreadPool.schedule(() -> {
        for (Guild guild : jda.getGuilds()) {
            for (SlowModeInfo info : storageManager.getSlowModeChannels(guild)) {
                jda.addEventListener(new SlowmodeHandler(info.getChannel(), info.getDelay()));
            }
        }
    }, 5, TimeUnit.SECONDS);
    // Start the bStats tracking thread
    generalThreadPool.scheduleAtFixedRate(() -> {
        JSONArray servers = new JSONArray(RestClient.get("https://bstats.org/api/v1/plugins/5273/charts/servers/data"));
        JSONArray players = new JSONArray(RestClient.get("https://bstats.org/api/v1/plugins/5273/charts/players/data"));
        int serverCount = servers.getJSONArray(servers.length() - 1).getInt(1);
        int playerCount = players.getJSONArray(players.length() - 1).getInt(1);
        jda.getPresence().setActivity(Activity.playing(BotHelpers.coolFormat(serverCount) + " servers, " + BotHelpers.coolFormat(playerCount) + " players"));
    }, 5, 60 * 5, TimeUnit.SECONDS);
}
Also used : SlowmodeHandler(org.geysermc.discordbot.listeners.SlowmodeHandler) SentryEventManager(org.geysermc.discordbot.util.SentryEventManager) SwearHandler(org.geysermc.discordbot.listeners.SwearHandler) Server(org.geysermc.discordbot.http.Server) GitHubBuilder(org.kohsuke.github.GitHubBuilder) Properties(java.util.Properties) Guild(net.dv8tion.jda.api.entities.Guild) ErrorAnalyzer(org.geysermc.discordbot.listeners.ErrorAnalyzer) SlashCommand(com.jagrosh.jdautilities.command.SlashCommand) LogHandler(org.geysermc.discordbot.listeners.LogHandler) LevelHandler(org.geysermc.discordbot.listeners.LevelHandler) SlowModeInfo(org.geysermc.discordbot.storage.SlowModeInfo) ShutdownHandler(org.geysermc.discordbot.listeners.ShutdownHandler) TagsListener(org.geysermc.discordbot.tags.TagsListener) StorageType(org.geysermc.discordbot.storage.StorageType) CommandErrorHandler(org.geysermc.discordbot.listeners.CommandErrorHandler) JSONArray(org.json.JSONArray) EventWaiter(com.jagrosh.jdautilities.commons.waiter.EventWaiter) DumpHandler(org.geysermc.discordbot.listeners.DumpHandler) FileInputStream(java.io.FileInputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) CommandClientBuilder(com.jagrosh.jdautilities.command.CommandClientBuilder) LoginException(javax.security.auth.login.LoginException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) FileHandler(org.geysermc.discordbot.listeners.FileHandler) PersistentRoleHandler(org.geysermc.discordbot.listeners.PersistentRoleHandler) BadLinksHandler(org.geysermc.discordbot.listeners.BadLinksHandler) SlashCommand(com.jagrosh.jdautilities.command.SlashCommand) Command(com.jagrosh.jdautilities.command.Command) VoiceGroupHandler(org.geysermc.discordbot.listeners.VoiceGroupHandler)

Example 4 with Command

use of com.jagrosh.jdautilities.command.Command in project MusicBot by jagrosh.

the class PlayCmd method doCommand.

@Override
public void doCommand(CommandEvent event) {
    if (event.getArgs().isEmpty() && event.getMessage().getAttachments().isEmpty()) {
        AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
        if (handler.getPlayer().getPlayingTrack() != null && handler.getPlayer().isPaused()) {
            if (DJCommand.checkDJPermission(event)) {
                handler.getPlayer().setPaused(false);
                event.replySuccess("Resumed **" + handler.getPlayer().getPlayingTrack().getInfo().title + "**.");
            } else
                event.replyError("Only DJs can unpause the player!");
            return;
        }
        StringBuilder builder = new StringBuilder(event.getClient().getWarning() + " Play Commands:\n");
        builder.append("\n`").append(event.getClient().getPrefix()).append(name).append(" <song title>` - plays the first result from Youtube");
        builder.append("\n`").append(event.getClient().getPrefix()).append(name).append(" <URL>` - plays the provided song, playlist, or stream");
        for (Command cmd : children) builder.append("\n`").append(event.getClient().getPrefix()).append(name).append(" ").append(cmd.getName()).append(" ").append(cmd.getArguments()).append("` - ").append(cmd.getHelp());
        event.reply(builder.toString());
        return;
    }
    String args = event.getArgs().startsWith("<") && event.getArgs().endsWith(">") ? event.getArgs().substring(1, event.getArgs().length() - 1) : event.getArgs().isEmpty() ? event.getMessage().getAttachments().get(0).getUrl() : event.getArgs();
    event.reply(loadingEmoji + " Loading... `[" + args + "]`", m -> bot.getPlayerManager().loadItemOrdered(event.getGuild(), args, new ResultHandler(m, event, false)));
}
Also used : Command(com.jagrosh.jdautilities.command.Command) DJCommand(com.jagrosh.jmusicbot.commands.DJCommand) MusicCommand(com.jagrosh.jmusicbot.commands.MusicCommand) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) AudioHandler(com.jagrosh.jmusicbot.audio.AudioHandler)

Example 5 with Command

use of com.jagrosh.jdautilities.command.Command in project GeyserDiscordBot by GeyserMC.

the class TagsCommand method handle.

protected MessageEmbed handle(String search) {
    EmbedBuilder embed = new EmbedBuilder();
    // Get tag names based on search
    List<String> tagNames = new ArrayList<>();
    for (Command tag : TagsManager.getTags()) {
        if (!tag.getName().equals("alias") && tag.getName().contains(search)) {
            tagNames.add(tag.getName());
        }
    }
    // Sort the tag names
    Collections.sort(tagNames);
    if (tagNames.isEmpty()) {
        embed.setColor(BotColors.FAILURE.getColor());
        embed.setTitle("No tags found");
        embed.setDescription("No tags were found for your search.");
        embed.setFooter("Use `" + PropertiesManager.getPrefix() + "tag aliases <name>` to see all the aliases for a certain tag");
    } else {
        embed.setColor(BotColors.SUCCESS.getColor());
        embed.setTitle("Tags (" + tagNames.size() + ")");
        embed.setDescription("`" + String.join("`, `", tagNames) + "`");
        embed.setFooter("Use `" + PropertiesManager.getPrefix() + "tag <name>` to show a tag");
    }
    return embed.build();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Command(com.jagrosh.jdautilities.command.Command) SlashCommand(com.jagrosh.jdautilities.command.SlashCommand) ArrayList(java.util.ArrayList)

Aggregations

Command (com.jagrosh.jdautilities.command.Command)12 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)5 SlashCommand (com.jagrosh.jdautilities.command.SlashCommand)3 CommandEvent (com.jagrosh.jdautilities.command.CommandEvent)2 AudioHandler (com.jagrosh.jmusicbot.audio.AudioHandler)2 DJCommand (com.jagrosh.jmusicbot.commands.DJCommand)2 MusicCommand (com.jagrosh.jmusicbot.commands.MusicCommand)2 OwnerCommand (com.jagrosh.jmusicbot.commands.OwnerCommand)2 PaginatedCommand (com.mcmoddev.mmdbot.modules.commands.community.PaginatedCommand)2 AudioLoadResultHandler (com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler)2 IOException (java.io.IOException)2 SwearHandler (org.geysermc.discordbot.listeners.SwearHandler)2 CommandClientBuilder (com.jagrosh.jdautilities.command.CommandClientBuilder)1 SlashCommandEvent (com.jagrosh.jdautilities.command.SlashCommandEvent)1 EventWaiter (com.jagrosh.jdautilities.commons.waiter.EventWaiter)1 MMDBot (com.mcmoddev.mmdbot.MMDBot)1 GistUtils (com.mcmoddev.mmdbot.gist.GistUtils)1 Utils (com.mcmoddev.mmdbot.utilities.Utils)1 ScriptTrick (com.mcmoddev.mmdbot.utilities.tricks.ScriptTrick)1 Trick (com.mcmoddev.mmdbot.utilities.tricks.Trick)1