/** * This returns the {@link net.dv8tion.jda.core.JDA.Status JDA.Status} of the shard which has the same id as the one provided. * <br>If there is no shard with an id that matches the provided one, then this returns {@code null}. * * @param shardId * The id of the shard. * * @return The {@link net.dv8tion.jda.core.JDA.Status JDA.Status} of the shard with the given shardId or * {@code null} if no shard has the given id */ default JDA.Status getStatus(final int shardId) { final JDA jda = this.getShardCache().getElementById(shardId); return jda == null ? null : jda.getStatus(); }
/** * This possibly-null will return the first connected JDA shard. * This means that a lot of methods like sending embeds works even with shard 0 offline. * * @return The first possible JDA shard which is connected. */ @Nonnull public JDA getClient() { for (JDA jda : shardManager.getShardCache()) { if (jda.getStatus() == JDA.Status.LOADING_SUBSYSTEMS || jda.getStatus() == JDA.Status.CONNECTED) return jda; } throw new IllegalStateException("getClient was called when no shards were connected!"); }
/** * Checks if a shard is connecting using the provided shard ID. * <p> * Returns {@code false} if the shard ID is invalid. * * @param shardId The shard ID to check for reconnecting. * @return If the shard is reconnecting or not */ public static boolean isReconnecting(int shardId) { return shardId >= 0 && shardId <= getShardCount() && (getShardById(shardId).getStatus() == JDA.Status.RECONNECT_QUEUED || getShardById(shardId).getStatus() == JDA.Status.ATTEMPTING_TO_RECONNECT); }
private static boolean isValidChannel(String channel) { if (MagiBridge.jda == null) return false; if (MagiBridge.jda.getStatus() != JDA.Status.CONNECTED) return false; if (MagiBridge.jda.getTextChannelById(channel) == null) { MagiBridge.getLogger().error("The channel " + channel + " defined in the config isn't a valid Discord Channel ID!"); MagiBridge.getLogger().error("Replace it with a valid one then reload the plugin!"); return false; } return true; }
private JSONArray buildShards() { JSONArray shards = new JSONArray(); for (JDA shard : metrics.getAvaire().getShardManager().getShards()) { JSONObject stats = new JSONObject(); stats.put("id", shard.getShardInfo().getShardId()) .put("guilds", shard.getGuilds().size()) .put("users", shard.getUsers().size()) .put("status", shard.getStatus()) .put("channels", (shard.getTextChannels().size() + shard.getVoiceChannels().size())) .put("latency", shard.getPing()); shards.put(stats); } return shards; }
@Nullable public SelfUser getSelfUser() { for (JDA shard : getShardManager().getShards()) { if (shard.getStatus().equals(JDA.Status.CONNECTED)) { return shard.getSelfUser(); } } return null; }
@Override public void run(Context context) { MessageReceivedEvent event = context.getEvent(); JDA jda = event.getJDA(); ShardManager manager = jda.asBot().getShardManager(); String message = manager.getShards().stream() .sorted(Comparator.comparingInt(a -> a.getShardInfo().getShardId())) .map(shard -> shard.getShardInfo().getShardId() + ": " + shard.getStatus()) .collect(Collectors.joining("\n")); context.reply("```\n%s```", message); } }
@Override public void run() { while (true) { if (MagiBridge.getConfig().CORE.ENABLE_UPDATER && MagiBridge.jda.getStatus() == JDA.Status.CONNECTED) { String topic = FormatType.TOPIC_FORMAT.get() .replace("%players%", Integer.valueOf(Sponge.getServer().getOnlinePlayers().size()).toString()) .replace("%maxplayers%", Integer.valueOf(Sponge.getServer().getMaxPlayers()).toString()) .replace("%tps%", Long.valueOf(Math.round(Sponge.getServer().getTicksPerSecond())).toString()) .replace("%daysonline%", Long.valueOf(ManagementFactory.getRuntimeMXBean().getUptime() / (24 * 60 * 60 * 1000)).toString()) .replace("%hoursonline%", Long.valueOf((ManagementFactory.getRuntimeMXBean().getUptime() / (60 * 60 * 1000)) % 24).toString()) .replace("%minutesonline%", Long.valueOf((ManagementFactory.getRuntimeMXBean().getUptime() / (60 * 1000)) % 60).toString()); try { if (MagiBridge.jda.getTextChannelById(MagiBridge.getConfig().CHANNELS.MAIN_CHANNEL) == null) { MagiBridge.getLogger().error("The main-discord-channel is INVALID, replace it with a valid one and restart the server!"); continue; } MagiBridge.jda.getTextChannelById(MagiBridge.getConfig().CHANNELS.MAIN_CHANNEL).getManager().setTopic(topic).queue(); } catch (NullPointerException e) { e.printStackTrace(); } } int interval = MagiBridge.getConfig().CORE.UPDATER_INTERVAL * 1000; try { Thread.sleep(interval < 10000 ? 10000 : interval); } catch (InterruptedException e) { MagiBridge.getLogger().error("The topic updater was interrupted!"); e.printStackTrace(); } } }
/** * Checks if we're ready yet by checking if all the shards are connected and ready to serve events. * * @return <code>True</code> if all shards has connected and are ready, <code>False</code> otherwise. */ public boolean areWeReadyYet() { if (getShardManager() == null) { return false; } for (JDA shard : getShardManager().getShards()) { if (shard.getStatus() != JDA.Status.CONNECTED) { return false; } } return true; }
@Override public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) { PagedTableBuilder tb = new PagedTableBuilder(); tb.addColumn("Shard ID"); tb.addColumn("Status"); tb.addColumn("Ping"); tb.addColumn("Guild Count"); tb.addColumn("Connected VCs"); List<JDA> shards = new ArrayList<>(Getters.getShards()); Collections.reverse(shards); for (JDA jda : shards) { List<String> row = new ArrayList<>(); row.add(ShardUtils.getDisplayShardId(jda) + (ShardUtils.getShardId(channel.getJDA()) == ShardUtils.getShardId(jda) ? " (You)" : "")); row.add(WordUtils.capitalizeFully(jda.getStatus().toString().replace("_", " "))); row.add(String.valueOf(jda.getPing())); row.add(String.valueOf(jda.getGuilds().size())); row.add(String.valueOf(jda.getVoiceChannels().stream().filter(vc -> vc.getMembers().contains(vc.getGuild() .getSelfMember())).count())); tb.addRow(row); } PaginationUtil.sendPagedMessage(channel, tb.build(), 0, sender, ButtonGroupConstants.SHARDINFO); }
public void stopStuff(Boolean fake) { if (!fake) { if (jda != null) { DiscordHandler.sendMessageToChannel(Config.CHANNELS.MAIN_CHANNEL, Config.MESSAGES.SERVER_STOPPING); DiscordHandler.close(); if (updater != null) updater.interrupt(); jda.getTextChannelById(Config.CHANNELS.MAIN_CHANNEL).getManager().setTopic(FormatType.OFFLINE_TOPIC_FORMAT.get()).queue(); jda.shutdown(); long time = System.currentTimeMillis(); while ((System.currentTimeMillis() - time < 10000) && (jda != null && jda.getStatus() != JDA.Status.SHUTDOWN)) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return; } } logger.info("Disconnecting from Discord..."); if (jda != null && jda.getStatus() != JDA.Status.SHUTDOWN && jda.getStatus() != JDA.Status.SHUTTING_DOWN) { jda.shutdownNow(); } // Unregistering listeners Sponge.getEventManager().unregisterPluginListeners(this); Sponge.getEventManager().registerListeners(this, this); Config = null; }
public void reportStatus(int shardId, JDA.Status oldStatus, JDA.Status status) { DiscordBot shard = getShardFor(BotConfig.BOT_GUILD_ID); if (shard == null || shard.getJda() == null) { return; } Guild guild = shard.getJda().getGuildById(BotConfig.BOT_GUILD_ID); if (guild == null) { LOGGER.warn("Can't find BOT_GUILD_ID " + BotConfig.BOT_GUILD_ID); return; } TextChannel channel = guild.getTextChannelById(BotConfig.BOT_STATUS_CHANNEL_ID); if (channel == null) { LOGGER.warn("Can't find BOT_STATUS_CHANNEL_ID " + BotConfig.BOT_STATUS_CHANNEL_ID); return; } if (channel.getJDA().getStatus() == JDA.Status.CONNECTED) { int length = 1 + (int) Math.floor(Math.log10(shards.length)); shard.queue.add(channel.sendMessage( String.format(Emojibet.SHARD_ICON + " `%0" + length + "d/%0" + length + "d` | ~~%s~~ -> %s", shardId, shards.length, oldStatus.toString(), status.toString()))); } }
public void shutdown() { if(shuttingDown) return; shuttingDown = true; threadpool.shutdownNow(); if(jda.getStatus()!=JDA.Status.SHUTTING_DOWN) { jda.getGuilds().stream().forEach(g -> { g.getAudioManager().closeAudioConnection(); AudioHandler ah = (AudioHandler)g.getAudioManager().getSendingHandler(); if(ah!=null) { ah.stopAndClear(); ah.getPlayer().destroy(); nowplaying.updateTopic(g.getIdLong(), ah, true); } }); jda.shutdown(); } if(gui!=null) gui.dispose(); System.exit(0); }
public static EmbedBuilder getEmbed() { if (cachedJDA == null || cachedJDA.getStatus() != JDA.Status.CONNECTED) cachedJDA = flareBot.getClient(); EmbedBuilder defaultEmbed = new EmbedBuilder().setColor(ColorUtils.FLAREBOT_BLUE); // We really need to PR getAuthor and things into EmbedBuilder. if (cachedJDA != null) { defaultEmbed.setAuthor("FlareBot", "https://flarebot.stream", cachedJDA.getSelfUser().getEffectiveAvatarUrl()); } return defaultEmbed.setColor(ColorUtils.FLAREBOT_BLUE); }
@Override public void handle(Event event) { threadExecutor.submit(() -> { bot.getContainer().setLastAction(event.getJDA().getShardInfo() == null ? 0 : event.getJDA().getShardInfo().getShardId(), System.currentTimeMillis()); bot.updateJda(event.getJDA()); if (!(event.getJDA().getStatus() == JDA.Status.CONNECTED)) { return; } List<Object> listenerCopy = new LinkedList<>(listeners); for (Object listener : listenerCopy) { try { ((EventListener) listener).onEvent(event); } catch (PermissionException throwable) { Logger.fatal("unchecked permission error!"); Logger.fatal(throwable); } catch (Throwable throwable) { Logger.fatal(throwable); bot.getContainer().reportError(throwable); } } }); }
@Override public void on(Context context) { MessageReceivedEvent e = context.getEvent(); JDA jda = e.getJDA(); if (context.getArgs().length == 2) { long serverId; int shardCount; try { serverId = Long.parseLong(context.getArgs()[0]); shardCount = Integer.parseInt(context.getArgs()[1]); } catch (NumberFormatException ignored) { context.reply("Usage: {{prefix}}shard <guild id> <shard count>"); return; } long shardId = (serverId >> 22) % shardCount; context.reply("Guild with ID `%d` is on shard `%d`.", serverId, shardId); } else { context.reply("This guild is on shard number `%d` of `%d`.\nThe JDA status for this shard is `%s`.", jda.getShardInfo().getShardId(), jda.getShardInfo().getShardTotal(), jda.getStatus().name()); } } }
public boolean count() { if (FlareBot.instance().getShardManager() == null) return false; for (JDA jda : Getters.getShards()) { if (jda.getStatus() != JDA.Status.CONNECTED) return false; } this.guildCount = Getters.getGuildCache().size(); this.userCount = Getters.getUserCache().size(); this.textChannelCount = Getters.getTextChannelCache().size(); this.voiceChannelCount = Getters.getVoiceChannelCache().size(); return true; }
if (!shard.getStatus().equals(JDA.Status.CONNECTED)) { shards.add(new MessageEmbed.Field(String.format("Shard #%s %s", i, getShardConnectionIcon(shard.getStatus()) ), formatShardStatus(shard.getStatus()), true)); continue; getShardConnectionIcon(shard.getStatus()), currentShardId == shard.getShardInfo().getShardId() ? "\uD83D\uDCCC" : "" ), String.format("%s users\n%s guilds\n%s ms ping",
@Override public void onGuildJoin(GuildJoinEvent event) { if (event.getJDA().getStatus() == JDA.Status.CONNECTED && event.getGuild().getSelfMember().getJoinDate().plusMinutes(2).isAfter(OffsetDateTime.now())) { Constants.getGuildLogChannel().sendMessage(new EmbedBuilder() .setColor(new Color(96, 230, 144)) .setThumbnail(event.getGuild().getIconUrl()) .setFooter(event.getGuild().getId(), event.getGuild().getIconUrl()) .setAuthor(event.getGuild().getName(), null, event.getGuild().getIconUrl()) .setTimestamp(event.getGuild().getSelfMember().getJoinDate()) .setDescription("Guild Created: `" + event.getGuild().getName() + "` :smile: :heart:\n" + "Guild Owner: " + event.getGuild().getOwner().getUser().getName() + "\nGuild Members: " + event.getGuild().getMembers().size()).build()).queue(); } }