Search in sources :

Example 6 with JDA

use of net.dv8tion.jda.api.JDA in project Saber-Bot by notem.

the class ShardManager method restartShard.

/**
 * Shuts down and recreates a JDA shard
 * @param shardId (Integer) shardID of the JDA shard
 */
public void restartShard(Integer shardId) throws LoginException, InterruptedException {
    if (this.isSharding()) {
        // do not handle shards not assigned to the current instance of the bot
        if (this.jdaShards.containsKey(shardId)) {
            // shutdown the shard
            Logging.info(this.getClass(), "Shutting down shard-" + shardId + ". . .");
            this.getShard(shardId).shutdownNow();
            this.jdaShards.remove(shardId);
            // configure the builder from the template
            Logging.info(this.getClass(), "Starting shard-" + shardId + ". . .");
            JDABuilder shardBuilder;
            if (shardId == 0) {
                shardBuilder = this.builder.useSharding(shardId, shardTotal);
            } else {
                shardBuilder = this.builder.useSharding(shardId, shardTotal);
            }
            // restart the shard (asynchronously)
            JDA shard = shardBuilder.build();
            this.jdaShards.put(shardId, shard);
        }
    } else {
        Logging.info(this.getClass(), "Restarting bot JDA. . .");
        this.jda.shutdownNow();
        this.jda = this.builder.build().awaitReady();
    }
}
Also used : JDABuilder(net.dv8tion.jda.api.JDABuilder) JDA(net.dv8tion.jda.api.JDA)

Example 7 with JDA

use of net.dv8tion.jda.api.JDA in project Saber-Bot by notem.

the class ScheduleManager method sortSchedule.

/**
 * Reorders the schedule so that entries are displayed by start datetime ascending order in
 * the discord schedule channel
 * @param cId schedule ID
 * @param reverseOrder (boolean) whether or not to reverse the sort order
 */
public void sortSchedule(String cId, boolean reverseOrder) {
    if (this.getScheduleSize(cId) > MAX_SIZE_TO_SYNC)
        return;
    if (this.isLocked(cId))
        return;
    // lock the channel
    this.lock(cId);
    // always unlock the schedule at finish regardless of success or failure
    try {
        // identify which shard is responsible for the schedule
        Document doc = Main.getDBDriver().getScheduleCollection().find(eq("_id", cId)).projection(fields(include("guildId"))).first();
        JDA jda = Main.getShardManager().getJDA(doc.getString("guildId"));
        // find the message channel and send the 'is typing' while processing
        MessageChannel chan = jda.getTextChannelById(cId);
        chan.sendTyping().queue();
        int sortOrder = 1;
        if (reverseOrder)
            sortOrder = -1;
        LinkedList<ScheduleEntry> unsortedEntries = new LinkedList<>();
        Main.getDBDriver().getEventCollection().find(eq("channelId", cId)).sort(new Document("start", sortOrder)).forEach((Consumer<? super Document>) document -> unsortedEntries.add(new ScheduleEntry(document)));
        // selection sort the entries by timestamp
        while (!unsortedEntries.isEmpty()) {
            // continue to send 'is typing'
            chan.sendTyping().queue();
            ScheduleEntry top = unsortedEntries.pop();
            ScheduleEntry min = top;
            for (ScheduleEntry cur : unsortedEntries) {
                Message minMsg = min.getMessageObject();
                Message topMsg = cur.getMessageObject();
                if (minMsg != null && topMsg != null) {
                    OffsetDateTime a = minMsg.getTimeCreated();
                    OffsetDateTime b = topMsg.getTimeCreated();
                    if (a.isAfter(b)) {
                        min = cur;
                    }
                }
            }
            // swap messages and update db
            if (!(min == top)) {
                Message tmp = top.getMessageObject();
                top.setMessageObject(min.getMessageObject());
                Main.getDBDriver().getEventCollection().updateOne(eq("_id", top.getId()), new Document("$set", new Document("messageId", min.getMessageObject().getId())));
                min.setMessageObject(tmp);
                Main.getDBDriver().getEventCollection().updateOne(eq("_id", min.getId()), new Document("$set", new Document("messageId", tmp.getId())));
            }
            // reload display
            top.reloadDisplay();
        }
    } catch (PermissionException e) {
        String m = e.getMessage() + ": Channel ID " + cId;
        Logging.warn(this.getClass(), m);
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    } finally {
        // always unlock
        this.unlock(cId);
    }
}
Also used : Message(net.dv8tion.jda.api.entities.Message) Document(org.bson.Document) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Projections.fields(com.mongodb.client.model.Projections.fields) Permission(net.dv8tion.jda.api.Permission) Logging(ws.nmathe.saber.utils.Logging) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Updates.set(com.mongodb.client.model.Updates.set) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Projections.include(com.mongodb.client.model.Projections.include) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) java.time(java.time) Guild(net.dv8tion.jda.api.entities.Guild) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Message(net.dv8tion.jda.api.entities.Message) JDA(net.dv8tion.jda.api.JDA) Document(org.bson.Document) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel)

Example 8 with JDA

use of net.dv8tion.jda.api.JDA in project MantaroBot by Mantaro.

the class DebugCmds method info.

@Subscribe
public void info(CommandRegistry cr) {
    cr.register("info", new SimpleCommand(CommandCategory.INFO) {

        @Override
        protected void call(Context ctx, String content, String[] args) {
            var config = ctx.getConfig();
            var bot = ctx.getBot();
            var guilds = 0L;
            var users = 0L;
            var clusterTotal = 0L;
            var players = 0L;
            var totalMemory = 0L;
            var queueSize = 0L;
            var totalThreadCount = 0L;
            var totalCommandCount = 0L;
            String nodeData;
            try (Jedis jedis = ctx.getJedisPool().getResource()) {
                nodeData = jedis.hget("node-stats-" + config.getClientId(), "node-" + bot.getNodeNumber());
            }
            try (Jedis jedis = ctx.getJedisPool().getResource()) {
                var stats = jedis.hgetAll("shardstats-" + config.getClientId());
                for (var shards : stats.entrySet()) {
                    var json = new JSONObject(shards.getValue());
                    guilds += json.getLong("guild_count");
                    users += json.getLong("cached_users");
                }
                var clusters = jedis.hgetAll("node-stats-" + config.getClientId());
                for (var cluster : clusters.entrySet()) {
                    var json = new JSONObject(cluster.getValue());
                    totalMemory += json.getLong("used_memory");
                    queueSize += json.getLong("queue_size");
                    totalThreadCount += json.getLong("thread_count");
                    totalCommandCount += json.getLong("commands_ran");
                }
                clusterTotal = clusters.size();
            }
            // We don't need to account for node stats delay here
            if (config.isPremiumBot()) {
                queueSize = ctx.getBot().getAudioManager().getTotalQueueSize();
            }
            List<LavalinkSocket> lavaLinkSockets = ctx.getBot().getLavaLink().getNodes();
            for (var lavaLink : lavaLinkSockets) {
                if (lavaLink.isAvailable() && lavaLink.getStats() != null) {
                    players += lavaLink.getStats().getPlayingPlayers();
                }
            }
            var responseTotal = bot.getShardManager().getShardCache().stream().mapToLong(JDA::getResponseTotal).sum();
            var mApiRequests = 0;
            try {
                mApiRequests = new JSONObject(APIUtils.getFrom("/mantaroapi/ping")).getInt("requests_served");
            } catch (IOException | JSONException ignored) {
            }
            // Get the master node.
            var node = new JSONObject(nodeData);
            var shardManager = ctx.getShardManager();
            var jda = ctx.getJDA();
            ctx.send("```prolog\n" + " --------- Technical Information --------- \n\n" + "Uptime: " + Utils.formatDuration(ctx.getLanguageContext(), node.getLong("uptime")) + "\n" + "Version: " + MantaroInfo.VERSION + " (Git: " + MantaroInfo.GIT_REVISION + ")\n" + "Libraries: " + "[ JDA: %s, LP: %s ]".formatted(JDAInfo.VERSION, PlayerLibrary.VERSION) + "\n" + "Commands: " + CommandProcessor.REGISTRY.commands().values().stream().filter(command -> command.category() != null).count() + "\n\n --------- Debug Information --------- \n\n" + "Replies: " + "[ Discord: %,d, MAPI: %,d ]".formatted(responseTotal, mApiRequests) + "\n" + "Nodes: " + "%,d (Current: %,d)".formatted(clusterTotal, ctx.getBot().getNodeNumber()) + "\n" + "CPU: " + "%.2f%% (Cores: %,d)".formatted(getInstanceCPUUsage() * 100, getAvailableProcessors()) + "\n" + "Memory: " + Utils.formatMemoryAmount(totalMemory) + " [Node: " + Utils.formatMemoryAmount(getTotalMemory() - getFreeMemory()) + "]" + "\n\n --------- Mantaro Information --------- \n\n" + "Guilds: " + "%,d (Node: %,d)".formatted(guilds, shardManager.getGuildCache().size()) + "\n" + "User Cache: " + "%,d (Node: %,d)".formatted(users, shardManager.getUserCache().size()) + "\n" + "Shards: " + bot.getShardManager().getShardsTotal() + " (This: " + jda.getShardInfo().getShardString() + ")" + "\n" + "Threads: " + "%,d (Node: %,d)".formatted(totalThreadCount, Thread.activeCount()) + "\n" + "Commands Used: " + "%,d (Node: %,d)".formatted(totalCommandCount, CommandListener.getCommandTotal()) + "\n" + "Overall: " + "[ Players: %,d, Queue: %,d ]".formatted(players, queueSize) + "\n" + "```");
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Gets the bot technical information. Nothing all that interesting, but shows cute stats.").build();
        }
    });
    cr.registerAlias("info", "status");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Jedis(redis.clients.jedis.Jedis) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JSONObject(org.json.JSONObject) JDA(net.dv8tion.jda.api.JDA) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) LinkedList(java.util.LinkedList) List(java.util.List) Subscribe(com.google.common.eventbus.Subscribe)

Example 9 with JDA

use of net.dv8tion.jda.api.JDA in project c0debaseBot by Biospheere.

the class StatsCommand method execute.

@Override
public void execute(final String[] args, final Message message) {
    final JDA jda = message.getJDA();
    final long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
    final EmbedBuilder embedBuilder = getEmbed(message.getGuild(), message.getAuthor());
    embedBuilder.addField("JDA Version", JDAInfo.VERSION, true);
    embedBuilder.addField("Ping", jda.getGatewayPing() + "ms", true);
    embedBuilder.addField("Uptime", String.valueOf(TimeUnit.MILLISECONDS.toDays(uptime) + "d " + TimeUnit.MILLISECONDS.toHours(uptime) % 24 + "h " + TimeUnit.MILLISECONDS.toMinutes(uptime) % 60 + "m " + TimeUnit.MILLISECONDS.toSeconds(uptime) % 60 + "s"), true);
    embedBuilder.addField("Commands", String.valueOf(bot.getCommandManager().getAvailableCommands().size()), true);
    embedBuilder.addField("Mitglieder", String.valueOf(jda.getGuilds().stream().mapToInt(Guild::getMemberCount).sum()), true);
    embedBuilder.addField("Java Version", System.getProperty("java.runtime.version").replace("+", "_"), true);
    embedBuilder.addField("Betriebssystem", ManagementFactory.getOperatingSystemMXBean().getName(), true);
    message.getChannel().sendMessage(embedBuilder.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) JDA(net.dv8tion.jda.api.JDA)

Example 10 with JDA

use of net.dv8tion.jda.api.JDA in project Saber-Bot by notem.

the class ParsingUtilities method compileUserList.

/**
 * generates a list of user IDs for a given RSVP category of an event
 * @param entry ScheduleEntry object
 * @param category name of RSVP category
 * @return List of Stings or null if category is invalid
 */
private static List<String> compileUserList(ScheduleEntry entry, String category) {
    Set<String> users = null;
    if (category.toLowerCase().equals("no-input")) {
        List<String> rsvped = new ArrayList<>();
        Set<String> keys = entry.getRsvpMembers().keySet();
        for (String key : keys) {
            rsvped.addAll(entry.getRsvpMembersOfType(key));
        }
        JDA shard = Main.getShardManager().getJDA(entry.getGuildId());
        Guild guild = shard.getGuildById(entry.getGuildId());
        GuildChannel channel = shard.getTextChannelById(entry.getChannelId());
        users = guild.getMembers().stream().filter(member -> member.getPermissions(channel).contains(Permission.MESSAGE_READ)).map(member -> member.getUser().getId()).filter(memberId -> !rsvped.contains(memberId)).collect(Collectors.toSet());
    } else {
        List<String> members = entry.getRsvpMembers().get(category);
        if (members != null)
            users = entry.getRsvpMembersOfType(category);
    }
    return (users == null) ? null : new ArrayList<>(users);
}
Also used : net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) BiFunction(java.util.function.BiFunction) StringUtils(org.apache.commons.lang3.StringUtils) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) ChronoUnit(java.time.temporal.ChronoUnit) Matcher(java.util.regex.Matcher) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) LocalTime(java.time.LocalTime) Main(ws.nmathe.saber.Main) Pattern(java.util.regex.Pattern) JDA(net.dv8tion.jda.api.JDA)

Aggregations

JDA (net.dv8tion.jda.api.JDA)24 Document (org.bson.Document)7 Main (ws.nmathe.saber.Main)7 Consumer (java.util.function.Consumer)6 Permission (net.dv8tion.jda.api.Permission)6 PermissionException (net.dv8tion.jda.api.exceptions.PermissionException)6 Logging (ws.nmathe.saber.utils.Logging)5 TextChannel (net.dv8tion.jda.api.entities.TextChannel)4 Bson (org.bson.conversions.Bson)4 Filters (com.mongodb.client.model.Filters)3 Projections.fields (com.mongodb.client.model.Projections.fields)3 Projections.include (com.mongodb.client.model.Projections.include)3 ZonedDateTime (java.time.ZonedDateTime)3 ChronoUnit (java.time.temporal.ChronoUnit)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 Guild (net.dv8tion.jda.api.entities.Guild)3 Message (net.dv8tion.jda.api.entities.Message)3 MessageUtilities (ws.nmathe.saber.utils.MessageUtilities)3 Calendar (com.google.api.services.calendar.Calendar)2