Search in sources :

Example 1 with CommandContext

use of ml.duncte123.skybot.objects.command.CommandContext in project SkyBot by duncte123.

the class ShardInfoCommand method embedTable.

private void embedTable(CommandContext ctx) {
    final EmbedBuilder embedBuilder = new EmbedBuilder();
    final int currentShard = ctx.getJDA().getShardInfo().getShardId();
    final ShardManager shardManager = ctx.getJDA().getShardManager();
    final ShardCacheView shardCache = shardManager.getShardCache();
    final List<JDA> shards = new ArrayList<>(shardCache.asList());
    Collections.reverse(shards);
    for (final JDA shard : shards) {
        final StringBuilder valueBuilder = new StringBuilder();
        final LongLongPair channelStats = getConnectedVoiceChannels(shard);
        valueBuilder.append("**Status:** ").append(getShardStatus(shard)).append("\n**Ping:** ").append(shard.getGatewayPing()).append("\n**Guilds:** ").append(shard.getGuildCache().size()).append("\n**VCs:** ").append(channelStats.getFirst()).append(" / ").append(channelStats.getSecond());
        final int shardId = shard.getShardInfo().getShardId();
        embedBuilder.addField(String.format("Shard #%s%s", shardId, shardId == currentShard ? " (current)" : ""), valueBuilder.toString(), true);
    }
    final long connectedShards = shardCache.applyStream((s) -> s.filter((shard) -> shard.getStatus() == JDA.Status.CONNECTED).count());
    final String avgPing = new DecimalFormat("###").format(shardManager.getAverageGatewayPing());
    final long guilds = shardManager.getGuildCache().size();
    final LongLongPair channelStats = getConnectedVoiceChannels(shardManager);
    embedBuilder.addField("Total/Average", String.format("**Connected:** %s\n**Ping:** %s\n**Guilds:** %s\n**VCs:** %s / %s", connectedShards, avgPing, guilds, channelStats.getFirst(), channelStats.getSecond()), false);
    sendEmbed(ctx, embedBuilder);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) LongLongPair(ml.duncte123.skybot.objects.pairs.LongLongPair) JDA(net.dv8tion.jda.api.JDA) ShardCacheView(net.dv8tion.jda.api.utils.cache.ShardCacheView) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager)

Example 2 with CommandContext

use of ml.duncte123.skybot.objects.command.CommandContext in project SkyBot by duncte123.

the class ShardInfoCommand method asciiInfo.

private void asciiInfo(CommandContext ctx) {
    final List<String> headers = new ArrayList<>();
    headers.add("ID");
    headers.add("Status");
    headers.add("Ping");
    headers.add("Guilds");
    headers.add("VCs");
    List<List<String>> table = new ArrayList<>();
    final int currentShard = ctx.getJDA().getShardInfo().getShardId();
    final ShardManager shardManager = ctx.getJDA().getShardManager();
    final List<JDA> shards = new ArrayList<>(shardManager.getShards());
    Collections.reverse(shards);
    for (final JDA shard : shards) {
        final List<String> row = new ArrayList<>();
        final int shardId = shard.getShardInfo().getShardId();
        row.add(shardId + (currentShard == shardId ? " (current)" : ""));
        row.add(getShardStatus(shard));
        row.add(String.valueOf(shard.getGatewayPing()));
        row.add(String.valueOf(shard.getGuildCache().size()));
        final LongLongPair channelStats = getConnectedVoiceChannels(shard);
        row.add(channelStats.getFirst() + " / " + channelStats.getSecond());
        table.add(row);
        if (table.size() == 20) {
            MessageUtils.sendMsg(ctx, makeAsciiTable(headers, table, shardManager));
            table = new ArrayList<>();
        }
    }
    if (!table.isEmpty()) {
        MessageUtils.sendMsg(ctx, makeAsciiTable(headers, table, shardManager));
    }
}
Also used : LongLongPair(ml.duncte123.skybot.objects.pairs.LongLongPair) JDA(net.dv8tion.jda.api.JDA) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ShardManager(net.dv8tion.jda.api.sharding.ShardManager)

Example 3 with CommandContext

use of ml.duncte123.skybot.objects.command.CommandContext in project SkyBot by duncte123.

the class MessageListener method handleMessageEventChecked.

private void handleMessageEventChecked(String raw, Guild guild, GuildMessageReceivedEvent event) {
    final GuildSetting settings = GuildSettingsUtils.getGuild(guild.getIdLong(), this.variables);
    final String customPrefix = settings.getCustomPrefix();
    final Message message = event.getMessage();
    if (settings.isMessageLogging()) {
        final MessageData data = MessageData.from(message);
        this.redis.storeMessage(data, isGuildPatron(guild));
    }
    if (!commandManager.isCommand(customPrefix, raw) && doAutoModChecks(event, settings, raw)) {
        return;
    }
    final User selfUser = event.getJDA().getSelfUser();
    final long selfId = selfUser.getIdLong();
    final String selfRegex = "<@!?" + selfId + '>';
    if (raw.matches(selfRegex)) {
        sendMsg(new MessageConfig.Builder().setChannel(event.getChannel()).setMessageFormat("Hey %s, try `%shelp` for a list of commands. If it doesn't work scream at _duncte123#1245_", event.getAuthor(), customPrefix).build());
        return;
    }
    final String[] split = raw.replaceFirst(Pattern.quote(Settings.PREFIX), "").split("\\s+");
    final List<CustomCommand> autoResponses = commandManager.getAutoResponses(guild.getIdLong());
    if (!autoResponses.isEmpty() && invokeAutoResponse(autoResponses, split, event)) {
        return;
    }
    if (doesNotStartWithPrefix(selfId, raw, customPrefix) || !canRunCommands(raw, customPrefix, event)) {
        return;
    }
    if (raw.matches(selfRegex + "(.*)")) {
        // Handle the chat command
        Objects.requireNonNull(commandManager.getCommand("chat")).executeCommand(new CommandContext("chat", Arrays.asList(split).subList(1, split.length), event, variables));
    } else {
        // Handle the command
        commandManager.runCommand(event, customPrefix);
    }
}
Also used : UnknownUser(ml.duncte123.skybot.objects.user.UnknownUser) CustomCommand(ml.duncte123.skybot.objects.command.custom.CustomCommand) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) MessageData(ml.duncte123.skybot.objects.discord.MessageData) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) GuildSetting(com.dunctebot.models.settings.GuildSetting)

Example 4 with CommandContext

use of ml.duncte123.skybot.objects.command.CommandContext in project SkyBot by duncte123.

the class PurgeUserCommand method execute.

@Override
public void execute(@Nonnull CommandContext ctx) {
    final List<Member> mentionedMembers = ctx.getMentionedArg(0);
    if (mentionedMembers.isEmpty()) {
        sendMsg(ctx, "I could not find any members with that name");
        return;
    }
    final Member targetMember = mentionedMembers.get(0);
    final User targetUser = targetMember.getUser();
    final TextChannel channel = ctx.getChannel();
    final Message message = ctx.getMessage();
    channel.getIterableHistory().takeAsync(DEL_COUNT).thenApplyAsync((msgs) -> msgs.stream().filter((msg) -> msg.getAuthor().equals(targetUser)).collect(Collectors.toList())).thenApplyAsync((msgs) -> {
        final List<CompletableFuture<Void>> futures = channel.purgeMessages(msgs);
        sendSuccess(message);
        try {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
        } catch (InterruptedException | ExecutionException e) {
            Sentry.captureException(e);
            return 0;
        }
        return msgs.size();
    }).exceptionally((thr) -> {
        String cause = "";
        if (thr.getCause() != null) {
            cause = " caused by: " + thr.getCause().getMessage();
        }
        sendMsg(ctx, "ERROR: " + thr.getMessage() + cause);
        sendError(message);
        return 0;
    }).whenCompleteAsync((count, thr) -> {
        sendMsg(DELETE_MESSAGE_AFTER_SECONDS.apply(5L).setChannel(ctx.getChannel()).setMessageFormat("Removed %d messages! (this message will auto delete in 5 seconds)", count).build());
        channel.deleteMessageById(message.getIdLong()).queue(null, ignore(UNKNOWN_MESSAGE));
        modLog(String.format("%d messages by %#s removed in %s by %#s", count, targetUser, channel, ctx.getAuthor()), ctx.getGuild());
    });
}
Also used : Message(net.dv8tion.jda.api.entities.Message) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) Permission(net.dv8tion.jda.api.Permission) ModerationUtils.modLog(ml.duncte123.skybot.utils.ModerationUtils.modLog) UNKNOWN_MESSAGE(net.dv8tion.jda.api.requests.ErrorResponse.UNKNOWN_MESSAGE) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Collectors(java.util.stream.Collectors) User(net.dv8tion.jda.api.entities.User) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) ErrorResponseException.ignore(net.dv8tion.jda.api.exceptions.ErrorResponseException.ignore) MessageUtils(me.duncte123.botcommons.messaging.MessageUtils) Sentry(io.sentry.Sentry) Nonnull(javax.annotation.Nonnull) DELETE_MESSAGE_AFTER_SECONDS(me.duncte123.botcommons.messaging.MessageConfigDefaults.DELETE_MESSAGE_AFTER_SECONDS) TextChannel(net.dv8tion.jda.api.entities.TextChannel) CompletableFuture(java.util.concurrent.CompletableFuture) User(net.dv8tion.jda.api.entities.User) Message(net.dv8tion.jda.api.entities.Message) ExecutionException(java.util.concurrent.ExecutionException) Member(net.dv8tion.jda.api.entities.Member)

Example 5 with CommandContext

use of ml.duncte123.skybot.objects.command.CommandContext in project SkyBot by duncte123.

the class LockEmoteCommand method execute.

@Override
public void execute(@Nonnull CommandContext ctx) {
    if (ctx.getArgs().isEmpty()) {
        this.sendUsageInstructions(ctx);
        return;
    }
    final Message message = ctx.getMessage();
    final List<Emote> mentionedEmotes = message.getEmotes();
    final List<Role> mentionedRoles = new ArrayList<>(message.getMentionedRoles());
    if (mentionedRoles.isEmpty()) {
        // Loop over the args and check if there are roles found in text
        ctx.getArgs().forEach((arg) -> mentionedRoles.addAll(FinderUtil.findRoles(arg, ctx.getGuild())));
    }
    if (mentionedEmotes.isEmpty() || mentionedRoles.isEmpty()) {
        this.sendUsageInstructions(ctx);
        return;
    }
    final Emote emote = mentionedEmotes.get(0);
    if (cannotInteractWithEmote(ctx, emote)) {
        return;
    }
    emote.getManager().setRoles(new HashSet<>(mentionedRoles)).queue();
    sendSuccess(message);
    final List<String> roleNames = mentionedRoles.stream().map(Role::getName).collect(Collectors.toList());
    sendMsg(ctx, "The emote " + emote.getAsMention() + " has been locked to users that have the " + "following roles: `" + String.join("`, `", roleNames) + "`");
}
Also used : Role(net.dv8tion.jda.api.entities.Role) Message(net.dv8tion.jda.api.entities.Message) UnlockEmoteCommand.cannotInteractWithEmote(ml.duncte123.skybot.commands.guild.owner.UnlockEmoteCommand.cannotInteractWithEmote) Emote(net.dv8tion.jda.api.entities.Emote) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Aggregations

CommandContext (ml.duncte123.skybot.objects.command.CommandContext)9 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)7 ArrayList (java.util.ArrayList)6 User (net.dv8tion.jda.api.entities.User)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 List (java.util.List)4 CustomCommand (ml.duncte123.skybot.objects.command.custom.CustomCommand)4 LongLongPair (ml.duncte123.skybot.objects.pairs.LongLongPair)4 JDA (net.dv8tion.jda.api.JDA)4 Member (net.dv8tion.jda.api.entities.Member)4 Message (net.dv8tion.jda.api.entities.Message)4 ShardManager (net.dv8tion.jda.api.sharding.ShardManager)4 Nonnull (javax.annotation.Nonnull)3 DataObject (net.dv8tion.jda.api.utils.data.DataObject)3 JDAImpl (net.dv8tion.jda.internal.JDAImpl)3 GuildSetting (com.dunctebot.models.settings.GuildSetting)2 Parser (com.jagrosh.jagtag.Parser)2 Sentry (io.sentry.Sentry)2 DecimalFormat (java.text.DecimalFormat)2 HashSet (java.util.HashSet)2