Search in sources :

Example 21 with JDA

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);
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) LoginException(javax.security.auth.login.LoginException) Arrays(java.util.Arrays) Getter(lombok.Getter) Async(br.com.brjdevs.java.utils.async.Async) Utils(net.kodehawa.mantarobot.utils.Utils) LoggerFactory(org.slf4j.LoggerFactory) VoiceChannelListener(net.kodehawa.mantarobot.commands.music.listener.VoiceChannelListener) ICommandProcessor(net.kodehawa.mantarobot.core.processor.core.ICommandProcessor) MantaroBot(net.kodehawa.mantarobot.MantaroBot) RateLimitedException(net.dv8tion.jda.core.exceptions.RateLimitedException) JSONObject(org.json.JSONObject) Calendar(java.util.Calendar) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JDA(net.dv8tion.jda.core.JDA) Delegate(lombok.experimental.Delegate) Config(net.kodehawa.mantarobot.data.Config) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) MantaroData.config(net.kodehawa.mantarobot.data.MantaroData.config) Logger(org.slf4j.Logger) Utils.pretty(net.kodehawa.mantarobot.utils.Utils.pretty) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) BirthdayTask(net.kodehawa.mantarobot.commands.utils.birthday.BirthdayTask) java.util.concurrent(java.util.concurrent) Game(net.dv8tion.jda.core.entities.Game) JDABuilder(net.dv8tion.jda.core.JDABuilder) SessionController(net.dv8tion.jda.core.utils.SessionController) MantaroListener(net.kodehawa.mantarobot.core.listeners.MantaroListener) AccountType(net.dv8tion.jda.core.AccountType) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) DateUtils(org.apache.commons.lang3.time.DateUtils) MantaroEventManager(net.kodehawa.mantarobot.core.MantaroEventManager) Objects(java.util.Objects) SessionControllerAdapter(net.dv8tion.jda.core.utils.SessionControllerAdapter) MantaroData(net.kodehawa.mantarobot.data.MantaroData) NativeAudioSendFactory(com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory) JSONObject(org.json.JSONObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 22 with JDA

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();
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) JDA(net.dv8tion.jda.core.JDA)

Example 23 with JDA

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();
}
Also used : WebSocketListener(stream.flarebot.flarebot.ws.WebSocketListener) Metrics(stream.flarebot.flarebot.metrics.Metrics) VoiceChannelCleanup(stream.flarebot.flarebot.tasks.VoiceChannelCleanup) ConcurrentHashSet(org.eclipse.jetty.util.ConcurrentHashSet) ShardUtils(stream.flarebot.flarebot.util.ShardUtils) GsonBuilder(com.google.gson.GsonBuilder) Map(java.util.Map) DataInterceptor(stream.flarebot.flarebot.web.DataInterceptor) Request(okhttp3.Request) PlayerCache(stream.flarebot.flarebot.objects.PlayerCache) WebUtils(stream.flarebot.flarebot.util.WebUtils) Set(java.util.Set) PlayerManager(com.arsenarsen.lavaplayerbridge.PlayerManager) ErrorResponseException(net.dv8tion.jda.core.exceptions.ErrorResponseException) PlayerListener(stream.flarebot.flarebot.audio.PlayerListener) DefaultShardManagerBuilder(net.dv8tion.jda.bot.sharding.DefaultShardManagerBuilder) WebhookClient(net.dv8tion.jda.webhook.WebhookClient) ZipOutputStream(java.util.zip.ZipOutputStream) Row(com.datastax.driver.core.Row) TextChannel(net.dv8tion.jda.core.entities.TextChannel) GuildCountAnalytics(stream.flarebot.flarebot.analytics.GuildCountAnalytics) LocalDateTime(java.time.LocalDateTime) SimpleDateFormat(java.text.SimpleDateFormat) MigrationHandler(stream.flarebot.flarebot.util.MigrationHandler) ShardManager(net.dv8tion.jda.bot.sharding.ShardManager) GeneralUtils(stream.flarebot.flarebot.util.general.GeneralUtils) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) Scheduler(stream.flarebot.flarebot.scheduler.Scheduler) ApiRoute(stream.flarebot.flarebot.api.ApiRoute) ApiRequester(stream.flarebot.flarebot.api.ApiRequester) Properties(java.util.Properties) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) RestAction(net.dv8tion.jda.core.requests.RestAction) InputStreamReader(java.io.InputStreamReader) ApiFactory(stream.flarebot.flarebot.web.ApiFactory) File(java.io.File) Guild(net.dv8tion.jda.core.entities.Guild) WebhookClientBuilder(net.dv8tion.jda.webhook.WebhookClientBuilder) OkHttpClient(okhttp3.OkHttpClient) CassandraController(stream.flarebot.flarebot.database.CassandraController) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) ConnectionPool(okhttp3.ConnectionPool) BufferedReader(java.io.BufferedReader) NativeAudioSendFactory(com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory) JsonObject(com.google.gson.JsonObject) ScheduledFuture(java.util.concurrent.ScheduledFuture) FlareBotTask(stream.flarebot.flarebot.scheduler.FlareBotTask) URLDecoder(java.net.URLDecoder) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) SelfUser(net.dv8tion.jda.core.entities.SelfUser) RedisController(stream.flarebot.flarebot.database.RedisController) JSONObject(org.json.JSONObject) Permission(net.dv8tion.jda.core.Permission) Gson(com.google.gson.Gson) WebSocketFactory(stream.flarebot.flarebot.ws.WebSocketFactory) JDA(net.dv8tion.jda.core.JDA) ZipEntry(java.util.zip.ZipEntry) ActivityAnalytics(stream.flarebot.flarebot.analytics.ActivityAnalytics) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) QueueListener(stream.flarebot.flarebot.music.QueueListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) List(java.util.List) LocalDate(java.time.LocalDate) stream.flarebot.flarebot.commands(stream.flarebot.flarebot.commands) UnknownBindingException(com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LibraryFactory(com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory) RequestBody(okhttp3.RequestBody) JsonElement(com.google.gson.JsonElement) ResultSet(com.datastax.driver.core.ResultSet) FutureAction(stream.flarebot.flarebot.scheduler.FutureAction) Constants(stream.flarebot.flarebot.util.Constants) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) Sentry(io.sentry.Sentry) Nonnull(javax.annotation.Nonnull) JSONConfig(io.github.binaryoverload.JSONConfig) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) Logger(org.slf4j.Logger) SentryClient(io.sentry.SentryClient) Game(net.dv8tion.jda.core.entities.Game) DateTime(org.joda.time.DateTime) FileInputStream(java.io.FileInputStream) AnalyticsHandler(stream.flarebot.flarebot.analytics.AnalyticsHandler) NINOListener(stream.flarebot.flarebot.mod.nino.NINOListener) TimeUnit(java.util.concurrent.TimeUnit) Level(ch.qos.logback.classic.Level) GuildAnalytics(stream.flarebot.flarebot.analytics.GuildAnalytics) JDAMultiShard(com.arsenarsen.lavaplayerbridge.utils.JDAMultiShard) Spark(spark.Spark) JSONArray(org.json.JSONArray) JDA(net.dv8tion.jda.core.JDA)

Example 24 with JDA

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();
}
Also used : CheckReturnValue(javax.annotation.CheckReturnValue) LongOpenHashSet(it.unimi.dsi.fastutil.longs.LongOpenHashSet) JDAImpl(net.dv8tion.jda.core.entities.impl.JDAImpl) User(net.dv8tion.jda.core.entities.User) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TObjectProcedure(gnu.trove.procedure.TObjectProcedure) Collection(java.util.Collection) JDA(net.dv8tion.jda.core.JDA) Nonnull(javax.annotation.Nonnull) Collections(java.util.Collections) Nullable(javax.annotation.Nullable) User(net.dv8tion.jda.core.entities.User) JDAImpl(net.dv8tion.jda.core.entities.impl.JDAImpl) LongOpenHashSet(it.unimi.dsi.fastutil.longs.LongOpenHashSet) CheckReturnValue(javax.annotation.CheckReturnValue)

Example 25 with JDA

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())));
}
Also used : MessageHistory(net.dv8tion.jda.core.entities.MessageHistory) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Message(net.dv8tion.jda.core.entities.Message) JDA(net.dv8tion.jda.core.JDA) ArrayList(java.util.ArrayList) Member(net.dv8tion.jda.core.entities.Member)

Aggregations

JDA (net.dv8tion.jda.core.JDA)42 Guild (net.dv8tion.jda.core.entities.Guild)10 TextChannel (net.dv8tion.jda.core.entities.TextChannel)9 Document (org.bson.Document)9 Permission (net.dv8tion.jda.core.Permission)7 Main (ws.nmathe.saber.Main)7 Consumer (java.util.function.Consumer)6 Message (net.dv8tion.jda.core.entities.Message)6 JSONObject (org.json.JSONObject)5 Logging (ws.nmathe.saber.utils.Logging)5 ArrayList (java.util.ArrayList)4 Collections (java.util.Collections)4 Date (java.util.Date)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 Member (net.dv8tion.jda.core.entities.Member)4 Bson (org.bson.conversions.Bson)4 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)3 User (net.dv8tion.jda.core.entities.User)3 PermissionException (net.dv8tion.jda.core.exceptions.PermissionException)3