Search in sources :

Example 21 with CommandContext

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

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 22 with CommandContext

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

the class TokenCommand method execute.

@Override
public void execute(@Nonnull CommandContext ctx) {
    final List<String> args = ctx.getArgs();
    final Matcher matcher = TOKEN_REGEX.matcher(args.get(0));
    if (!matcher.matches()) {
        sendMsg(ctx, "Your input `" + args.get(0) + "` has the wrong token format.");
        return;
    }
    final DuncteApis apis = ctx.getVariables().getApis();
    final JsonNode json = apis.decodeToken(args.get(0));
    if (json.get("success").asBoolean()) {
        handleSuccess(args.get(0), json.get("data"), ctx);
        return;
    }
    final JsonNode error = json.get("error");
    final String errorType = error.get("type").asText();
    final String errorMessage = error.get("message").asText();
    sendMsg(ctx, String.format("Invalid token: (%s) %s", errorType, errorMessage));
}
Also used : DuncteApis(ml.duncte123.skybot.objects.api.DuncteApis) Matcher(java.util.regex.Matcher) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 23 with CommandContext

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

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 24 with CommandContext

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

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 25 with CommandContext

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

the class PronounsCheckCommand method execute.

@Override
public void execute(@Nonnull CommandContext ctx) {
    final User target = getMentionedUser(ctx);
    final long userId = target.getIdLong();
    final JsonNode json = ctx.getApis().getPronouns(userId);
    final boolean isSelf = userId == ctx.getAuthor().getIdLong();
    if (json == null) {
        sendMsg(ctx, (isSelf ? "You do" : target.getName() + " does") + " not have any pronouns set");
        return;
    }
    final String pronouns = json.get("pronouns").asText();
    final String singular = json.get("singular").asBoolean() ? "Singular" : "Plural";
    final String userName = isSelf ? "Your" : target.getName() + "'s";
    final String format = "%s current pronouns are:%n**%s** (%s)";
    sendMsg(ctx, String.format(format, userName, pronouns, singular));
}
Also used : AirUtils.getMentionedUser(ml.duncte123.skybot.utils.AirUtils.getMentionedUser) User(net.dv8tion.jda.api.entities.User) JsonNode(com.fasterxml.jackson.databind.JsonNode)

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