use of net.dv8tion.jda.core.JDA in project MantaroBot by Mantaro.
the class MantaroShard method updateStatus.
/**
* Updates Mantaro's "splash".
* Splashes are random gags like "now seen in theaters!" that show on Mantaro's status.
* This has been on Mantaro since 2016, so it's part of its "personality" as a bot.
*/
public void updateStatus() {
Runnable changeStatus = () -> {
// insert $CURRENT_YEAR meme here
if (DateUtils.isSameDay(christmas, Calendar.getInstance())) {
getJDA().getPresence().setGame(Game.playing(String.format("%shelp | %s | [%d]", config().get().prefix[0], "Merry Christmas!", getId())));
return;
} else if (DateUtils.isSameDay(newYear, Calendar.getInstance())) {
getJDA().getPresence().setGame(Game.playing(String.format("%shelp | %s | [%d]", config().get().prefix[0], "Happy New Year!", getId())));
return;
}
AtomicInteger users = new AtomicInteger(0), guilds = new AtomicInteger(0);
if (MantaroBot.getInstance() != null) {
Arrays.stream(MantaroBot.getInstance().getShardedMantaro().getShards()).filter(Objects::nonNull).map(MantaroShard::getJDA).forEach(jda -> {
users.addAndGet((int) jda.getUserCache().size());
guilds.addAndGet((int) jda.getGuildCache().size());
});
}
String newStatus = new JSONObject(Utils.wgetResty(config.apiTwoUrl + "/mantaroapi/splashes/random", null)).getString("splash").replace("%ramgb%", String.valueOf(((long) (Runtime.getRuntime().maxMemory() * 1.2D)) >> 30L)).replace("%usercount%", users.toString()).replace("%guildcount%", guilds.toString()).replace("%shardcount%", String.valueOf(getTotalShards())).replace("%prettyusercount%", pretty(users.get())).replace("%prettyguildcount%", pretty(guilds.get()));
getJDA().getPresence().setGame(Game.playing(String.format("%shelp | %s | [%d]", config().get().prefix[0], newStatus, getId())));
log.debug("Changed status to: " + newStatus);
};
changeStatus.run();
Async.task("Splash Thread", changeStatus, 10, TimeUnit.MINUTES);
}
use of net.dv8tion.jda.core.JDA in project c0debaseBot by Biospheere.
the class StatsCommand method execute.
@Override
public void execute(String[] args, Message msg) {
JDA jda = msg.getJDA();
EmbedBuilder eb = getEmbed(msg.getGuild(), msg.getAuthor());
eb.addField("JDA Version", JDAInfo.VERSION, true);
eb.addField("Ping", jda.getPing() + "ms", true);
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
eb.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);
eb.addField("Commands", String.valueOf(CodebaseBot.getInstance().getCommandManager().getAvailableCommands().size()), true);
eb.addField("Mitglieder", String.valueOf(jda.getUserCache().size()), true);
eb.addField("Java Version", System.getProperty("java.runtime.version").replace("+", "_"), true);
eb.addField("Betriebssystem", ManagementFactory.getOperatingSystemMXBean().getName(), true);
eb.addField("CPU Threads", String.valueOf(ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors()), true);
eb.addField("RAM Usage", (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() + ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed()) / 1000000 + " / " + (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() + ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getMax()) / 1000000 + " MB", true);
eb.addField("Threads", String.valueOf(Thread.activeCount()), true);
msg.getChannel().sendMessage(eb.build()).queue();
}
use of net.dv8tion.jda.core.JDA in project FlareBot by FlareBot.
the class FlareBot method stop.
private void stop() {
if (EXITING.get())
return;
LOGGER.info("Saving data.");
EXITING.set(true);
Constants.getImportantLogChannel().sendMessage("Average load time of this session: " + manager.getGuildWrapperLoader().getLoadTimes().stream().mapToLong(v -> v).average().orElse(0) + "\nTotal loads: " + manager.getGuildWrapperLoader().getLoadTimes().size()).complete();
for (ScheduledFuture<?> scheduledFuture : Scheduler.getTasks().values()) // No tasks in theory should block this or cause issues. We'll see
scheduledFuture.cancel(false);
for (JDA client : shardManager.getShards()) // todo: Make a replacement for the array
client.removeEventListener(events);
sendData();
manager.getGuilds().invalidateAll();
shardManager.shutdown();
LOGGER.info("Finished saving!");
for (JDA client : shardManager.getShards()) client.shutdown();
}
use of net.dv8tion.jda.core.JDA in project FredBoat by Frederikam.
the class JDAUtil method countUniqueUsers.
/**
* A count of unique users over the provided shards. This is an expensive operation given FredBoats scale.
* <p>
* Optionally pass in a value of value of previous counts / expected size to that we can initialize the set used
* to count the unique values with an approriate size reducing expensive resizing operations.
*/
@CheckReturnValue
public static int countUniqueUsers(@Nonnull Collection<JDA> shards, @Nullable AtomicInteger expectedUserCount) {
if (shards.size() == 1) {
// a single shard provides a cheap call for getting user cardinality
return Math.toIntExact(shards.iterator().next().getUserCache().size());
}
int expected = expectedUserCount != null && expectedUserCount.get() > 0 ? expectedUserCount.get() : LongOpenHashSet.DEFAULT_INITIAL_SIZE;
// add 10k for good measure
LongOpenHashSet uniqueUsers = new LongOpenHashSet(expected + 10000);
TObjectProcedure<User> adder = user -> {
uniqueUsers.add(user.getIdLong());
return true;
};
Collections.unmodifiableCollection(shards).forEach(// this means however, that for the (small) duration, the map cannot be used by other threads (if there are any)
shard -> ((JDAImpl) shard).getUserMap().forEachValue(adder));
return uniqueUsers.size();
}
use of net.dv8tion.jda.core.JDA in project FredBoat by Frederikam.
the class ClearCommand method onInvoke.
// TODO: Redo this
// TODO: i18n this class
@Override
public void onInvoke(@Nonnull CommandContext context) {
JDA jda = context.guild.getJDA();
TextChannel channel = context.channel;
Member invoker = context.invoker;
if (!invoker.hasPermission(channel, Permission.MESSAGE_MANAGE) && !PermsUtil.checkPerms(PermissionLevel.BOT_ADMIN, invoker)) {
context.replyWithName("You must have Manage Messages to do that!");
return;
}
if (!context.guild.getSelfMember().hasPermission(channel, Permission.MESSAGE_HISTORY)) {
context.reply(context.i18n("permissionMissingBot") + " **" + Permission.MESSAGE_HISTORY.getName() + "**");
return;
}
MessageHistory history = new MessageHistory(channel);
history.retrievePast(50).queue(msgs -> {
Metrics.successfulRestActions.labels("retrieveMessageHistory").inc();
ArrayList<Message> toDelete = new ArrayList<>();
for (Message msg : msgs) {
if (msg.getAuthor().equals(jda.getSelfUser()) && youngerThanTwoWeeks(msg)) {
toDelete.add(msg);
}
}
if (toDelete.isEmpty()) {
context.reply("No messages found.");
} else if (toDelete.size() == 1) {
context.reply("Found one message, deleting.");
CentralMessaging.deleteMessage(toDelete.get(0));
} else {
if (!context.hasPermissions(Permission.MESSAGE_MANAGE)) {
context.reply("I must have the `Manage Messages` permission to delete my own messages in bulk.");
return;
}
context.reply("Deleting **" + toDelete.size() + "** messages.");
CentralMessaging.deleteMessages(channel, toDelete);
}
}, CentralMessaging.getJdaRestActionFailureHandler(String.format("Failed to retrieve message history in channel %s in guild %s", channel.getId(), context.guild.getId())));
}
Aggregations