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();
}
}
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);
}
}
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");
}
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();
}
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);
}
Aggregations