Search in sources :

Example 11 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Baymax by napstr.

the class HelpDeskListener method onReady.

// revisit for when there is more than one shard
@Override
public void onReady(ReadyEvent event) {
    // 1. Clean up the channel
    // 2. Post the root message
    ShardManager shardManager = Objects.requireNonNull(event.getJDA().getShardManager(), "Shard manager required");
    for (BaymaxConfig.HelpDesk helpDesk : this.baymaxConfig.getHelpDesks()) {
        TextChannel channel = shardManager.getTextChannelById(helpDesk.getChannelId());
        if (channel == null) {
            log.warn("Failed to find and setup configured help desk channel {}", helpDesk.getChannelId());
            return;
        }
        init(channel, helpDesk.getModelName(), helpDesk.getModelUri());
    }
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) BaymaxConfig(space.npstr.baymax.config.properties.BaymaxConfig)

Example 12 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Sx4 by sx4-discord-bot.

the class YouTubeHandler method onYouTubeUpload.

public void onYouTubeUpload(YouTubeUploadEvent event) {
    ShardManager shardManager = this.bot.getShardManager();
    String uploaderId = event.getChannel().getId();
    List<Bson> guildPipeline = List.of(Aggregates.match(Operators.expr(Operators.eq("$_id", "$$guildId"))), Aggregates.project(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L)))));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("uploaderId", uploaderId)), Aggregates.lookup("guilds", List.of(new Variable<>("guildId", "$guildId")), guildPipeline, "premium"), Aggregates.addFields(new Field<>("premium", Operators.cond(Operators.isEmpty("$premium"), false, Operators.get(Operators.arrayElemAt("$premium", 0), "premium")))));
    this.bot.getMongo().aggregateYouTubeNotifications(pipeline).whenComplete((notifications, aggregateException) -> {
        if (ExceptionUtility.sendErrorMessage(aggregateException)) {
            return;
        }
        this.executor.submit(() -> {
            List<WriteModel<Document>> bulkUpdate = new ArrayList<>();
            notifications.forEach(notification -> {
                if (!notification.getBoolean("enabled", true)) {
                    return;
                }
                long channelId = notification.getLong("channelId");
                TextChannel textChannel = shardManager.getTextChannelById(channelId);
                if (textChannel == null) {
                    return;
                }
                Document webhookData = notification.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
                boolean premium = notification.getBoolean("premium");
                WebhookMessage message;
                try {
                    message = this.format(event, notification.get("message", YouTubeManager.DEFAULT_MESSAGE)).setAvatarUrl(premium ? webhookData.get("avatar", this.bot.getConfig().getYouTubeAvatar()) : this.bot.getConfig().getYouTubeAvatar()).setUsername(premium ? webhookData.get("name", "Sx4 - YouTube") : "Sx4 - YouTube").build();
                } catch (IllegalArgumentException e) {
                    // possibly create an error field when this happens so the user can debug what went wrong
                    bulkUpdate.add(new UpdateOneModel<>(Filters.eq("_id", notification.getObjectId("_id")), Updates.unset("message"), new UpdateOptions()));
                    return;
                }
                this.bot.getYouTubeManager().sendYouTubeNotification(textChannel, webhookData, message).whenComplete(MongoDatabase.exceptionally());
            });
            if (!bulkUpdate.isEmpty()) {
                this.bot.getMongo().bulkWriteYouTubeNotifications(bulkUpdate).whenComplete(MongoDatabase.exceptionally());
            }
            Document data = new Document("type", YouTubeType.UPLOAD.getRaw()).append("videoId", event.getVideo().getId()).append("title", event.getVideo().getTitle()).append("uploaderId", event.getChannel().getId());
            this.bot.getMongo().insertYouTubeNotificationLog(data).whenComplete(MongoDatabase.exceptionally());
        });
    });
}
Also used : ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Document(org.bson.Document) Bson(org.bson.conversions.Bson) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) TextChannel(net.dv8tion.jda.api.entities.TextChannel)

Example 13 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project PurrBot by purrbot-site.

the class ReadyListener method onReady.

@Override
public void onReady(@NotNull ReadyEvent event) {
    ShardManager shardManager = bot.getShardManager();
    JDA jda = event.getJDA();
    shards++;
    logger.info("Shard {} ({} Guilds) ready!", jda.getShardInfo().getShardId(), jda.getGuildCache().size());
    WebhookEmbed embed = new WebhookEmbedBuilder().setColor(0x00FF00).setTitle(new WebhookEmbed.EmbedTitle(Emotes.STATUS_READY.getEmote(), null)).addField(new WebhookEmbed.EmbedField(true, "Guilds:", String.valueOf(jda.getGuilds().size()))).addField(new WebhookEmbed.EmbedField(true, "Shard:", String.valueOf(jda.getShardInfo().getShardId()))).setFooter(new WebhookEmbed.EmbedFooter("Ready at", null)).setTimestamp(ZonedDateTime.now()).build();
    webhookUtil.sendMsg(jda.getSelfUser().getEffectiveAvatarUrl(), "Shard ready!", embed);
    if (shards == jda.getShardInfo().getShardTotal()) {
        shardManager.setPresence(OnlineStatus.ONLINE, Activity.of(Activity.ActivityType.WATCHING, bot.getMessageUtil().getBotGame(shardManager.getGuildCache().size())));
        bot.startUpdater();
        WebhookEmbed finished = new WebhookEmbedBuilder().setColor(0x00FF00).setTitle(new WebhookEmbed.EmbedTitle(String.format("\\%s ready!", jda.getSelfUser().getName()), null)).setDescription(String.format("\\%s is online and ready to bring you fun and nekos. <:catUwU:703924268022497340>", jda.getSelfUser().getName())).build();
        webhookUtil.sendMsg(jda.getSelfUser().getEffectiveAvatarUrl(), "Ready!", finished);
        logger.info("Loaded Bot {} vBOT_VERSION with {} shard(s) and {} guilds!", jda.getSelfUser().getAsTag(), shardManager.getShardCache().size(), bot.getMessageUtil().formatNumber(shardManager.getGuildCache().size()));
    }
}
Also used : WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) JDA(net.dv8tion.jda.api.JDA) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) ShardManager(net.dv8tion.jda.api.sharding.ShardManager)

Example 14 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project PurrBot by purrbot-site.

the class CmdStats method run.

@Override
public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) {
    JDA jda = msg.getJDA();
    ShardManager shardManager = bot.getShardManager();
    long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
    EmbedBuilder stats = bot.getEmbedUtil().getEmbed(member).setAuthor(bot.getMsg(guild.getId(), "purr.info.stats.embed.title")).addField(bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_total_title"), bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_total_value").replace("{shards}", formatNumber(shardManager.getShardCache().size())).replace("{guilds}", formatNumber(shardManager.getGuildCache().size())), false).addField(bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_this_title"), bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_this_value").replace("{id}", String.valueOf(jda.getShardInfo().getShardId())).replace("{guilds}", formatNumber(jda.getGuildCache().size())), false).addField(bot.getMsg(guild.getId(), "purr.info.stats.embed.other_title"), bot.getMsg(guild.getId(), "purr.info.stats.embed.other_value").replace("{ram}", getRAM()).replace("{days}", getDaysString(uptime, guild.getId())).replace("{hours}", getHoursString(uptime, guild.getId())).replace("{minutes}", getMinutesString(uptime, guild.getId())).replace("{seconds}", getSecondsString(uptime, guild.getId())), false);
    tc.sendMessageEmbeds(stats.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) JDA(net.dv8tion.jda.api.JDA) ShardManager(net.dv8tion.jda.api.sharding.ShardManager)

Example 15 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project SkyBot by duncte123.

the class MessageListener method onGuildMessageReceived.

protected void onGuildMessageReceived(GuildMessageReceivedEvent event) {
    final Guild guild = event.getGuild();
    if (isBotfarm(guild)) {
        return;
    }
    // This happens?
    final User author = event.getAuthor();
    if (event.getMember() == null && !event.isWebhookMessage()) {
        final Exception weirdEx = new Exception(String.format("Got null member for no webhook message (what the fuck):\n Event:GuildMessageReceivedEvent\nMember:%s\nMessage:%s\nAuthor:%s (bot %s)", event.getMember(), event.getMessage(), author, author.isBot()));
        LOGGER.error("Error with message listener", weirdEx);
        Sentry.captureException(weirdEx);
    }
    if (author.isBot() || author.isSystem() || event.isWebhookMessage() || // Just in case Discord fucks up *again*
    event.getMember() == null) {
        return;
    }
    final String raw = event.getMessage().getContentRaw().trim();
    if (raw.equals(Settings.PREFIX + "shutdown") && isDev(author.getIdLong())) {
        LOGGER.info("Initialising shutdown!!!");
        final ShardManager manager = Objects.requireNonNull(event.getJDA().getShardManager());
        event.getMessage().addReaction(MessageUtils.getSuccessReaction()).queue(success -> shutdownBot(manager), failure -> shutdownBot(manager));
        return;
    }
    this.handlerThread.submit(() -> {
        try {
            setJDAContext(event.getJDA());
            handleMessageEventChecked(raw, guild, event);
        } catch (Exception e) {
            Sentry.captureException(e);
            e.printStackTrace();
        }
    });
}
Also used : UnknownUser(ml.duncte123.skybot.objects.user.UnknownUser) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) DunctebotGuild(ml.duncte123.skybot.entities.jda.DunctebotGuild)

Aggregations

ShardManager (net.dv8tion.jda.api.sharding.ShardManager)41 JDA (net.dv8tion.jda.api.JDA)19 Member (net.dv8tion.jda.api.entities.Member)15 Guild (net.dv8tion.jda.api.entities.Guild)14 User (net.dv8tion.jda.api.entities.User)14 ArrayList (java.util.ArrayList)12 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 Permission (net.dv8tion.jda.api.Permission)8 TextChannel (net.dv8tion.jda.api.entities.TextChannel)8 Arrays (java.util.Arrays)5 Executors (java.util.concurrent.Executors)5 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)5 Nonnull (javax.annotation.Nonnull)5 DefaultShardManagerBuilder (net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder)5 Document (org.bson.Document)5 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)4 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)4 DecimalFormat (java.text.DecimalFormat)4 IOException (java.io.IOException)3