net.dv8tion.jda.core.JDA Java Examples

The following examples show how to use net.dv8tion.jda.core.JDA. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JDA3Handler.java    From sdcf4j with GNU Lesser General Public License v3.0 9 votes vote down vote up
/**
 * Creates a new instance of this class.
 *
 * @param jda A JDA instance.
 */
public JDA3Handler(JDA jda) {
    jda.addEventListener(new ListenerAdapter() {
        @Override
        public void onMessageReceived(MessageReceivedEvent event) {
            handleMessageCreate(event);
        }
    });
}
 
Example #2
Source File: UIController.java    From DiscordBlueBot with MIT License 7 votes vote down vote up
public void stopBot(ActionEvent actionEvent) {
    try {
        for(JDA shard : MainBot.getJdaList()) {
            shard.shutdown();
        }
        logger.info("Bot stopped.");
        running = false;
    } catch (NullPointerException nullPtr) {
        logger.error("No running instance of the bot.");
    }
}
 
Example #3
Source File: ShutDownCommand.java    From DiscordBlueBot with MIT License 7 votes vote down vote up
@Override
public void action(String[] args, MessageReceivedEvent event) {
    logger.info("Forced shutdown ...");
    new JSONSaver();
    event.getTextChannel().sendMessage("I've been shut down.").queue();
    for(JDA shard : MainBot.getJdaList()) {
        shard.shutdown();
    }
}
 
Example #4
Source File: Vote3.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
public static void loadPolls(JDA jda) {

        jda.getGuilds().forEach(g -> {

            File f = new File("SERVER_SETTINGS/" + g.getId() + "/betavote.dat");
            if (f.exists())
                try {
                    Poll poll = getPoll(g);
                    polls.put(g, poll);
                    tempList.put(g, poll.getMessage(g));
                } catch (IOException | ClassNotFoundException | NullPointerException e) {
                    e.printStackTrace();
                }

        });

    }
 
Example #5
Source File: ShardInfoCommand.java    From FlareBot with MIT License 6 votes vote down vote up
@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);
}
 
Example #6
Source File: Counter.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static void loadAll(JDA jda) {

        jda.getGuilds().forEach(g -> {

            File path = new File("SERVER_SETTINGS/" + g.getId() + "/counters");

            if (!path.exists())
                path.mkdirs();

            File[] files = path.listFiles();
            if (files.length < 1)
                return;

            List<CCounter> counts = new ArrayList<>();
            Arrays.stream(files).forEach(f -> {
                try {
                    FileInputStream fis = new FileInputStream(f);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    CCounter out = (CCounter) ois.readObject();
                    counts.add(out);
                    ois.close();
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            });
            counters.put(g, counts);
        });
    }
 
Example #7
Source File: JDA3Handler.java    From sdcf4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Tries to get objects (like channel, user, long) from the given strings.
 *
 * @param jda The jda object.
 * @param args The string array.
 * @return An object array.
 */
private Object[] getObjectsFromString(JDA jda, String[] args) {
    Object[] objects = new Object[args.length];
    for (int i = 0; i < args.length; i++) {
        objects[i] = getObjectFromString(jda, args[i]);
    }
    return objects;
}
 
Example #8
Source File: QuoteCmd.java    From Selfbot with Apache License 2.0 5 votes vote down vote up
private static MessageChannel resolveChannel(String id, JDA jda)
{
    MessageChannel mc = jda.getTextChannelById(id);
    if(mc!=null)
        return mc;
    mc = jda.getPrivateChannelById(id);
    if(mc!=null)
        return mc;
    User u = jda.getUserById(id);
    if(u!=null)
        return u.openPrivateChannel().complete();
    return null;
}
 
Example #9
Source File: GuildsListener.java    From DiscordBlueBot with MIT License 5 votes vote down vote up
private TextChannel retrieveLogChannel() {
    for(JDA shard : MainBot.getJdaList()) {
        if(shard.getTextChannelById(MainBot.getConfig().getGuildsLogChannelId()) != null) {
            return shard.getTextChannelById(MainBot.getConfig().getGuildsLogChannelId());
        }
    }
    return null;
}
 
Example #10
Source File: FlareBot.java    From FlareBot with MIT License 5 votes vote down vote up
/**
 * 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!");
}
 
Example #11
Source File: MessageUtils.java    From FlareBot with MIT License 5 votes vote down vote up
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);
}
 
Example #12
Source File: Botmessage.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static void setSupplyingMessage(JDA jda) {

        if (!custom) {
            jda.getGuilds().forEach(g -> g.getMembers().forEach(m -> count()));
            jda.getPresence().setGame(Game.of("Supplying " + members + " users" + " | -help | v." + STATICS.VERSION));
            members = 0;
        }
    }
 
Example #13
Source File: Vote2.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static void loadPolls(JDA jda) {

        jda.getGuilds().forEach(g -> {

            File f = new File("SERVER_SETTINGS/" + g.getId() + "/vote.dat");
            if (f.exists())
                try {
                    polls.put(g, getPoll(g));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }

        });

    }
 
Example #14
Source File: Autochannel.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static void load(JDA jda) {

        try {
            PreparedStatement ps = Main.getMySql().getConn().prepareStatement("SELECT * FROM autochans");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Guild g = getGuild(rs.getString("guild"), jda);
                autochans.put(getVchan(rs.getString("chan"), g), g);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
Example #15
Source File: UpdateClient.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static void checkIfUpdate(JDA jda) {

        if (new File("SERVER_SETTINGS/no_update_info").exists())
            return;

        if (STATICS.BOT_OWNER_ID != 0 && isUdate()) {
            jda.getUserById(STATICS.BOT_OWNER_ID).openPrivateChannel().queue(c -> sendUpdateMsg(c));
        }
    }
 
Example #16
Source File: BotMetrics.java    From FlareBot with MIT License 5 votes vote down vote up
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;
}
 
Example #17
Source File: StatusCommand.java    From FlareBot with MIT License 4 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    int quaterShards = Getters.getShards().size() / 4;
    double ping = Getters.getShards().stream().mapToLong(JDA::getPing).average().orElse(-1);

    int deadShard = 0;
    int reconnecting = 0;
    int connecting = 0;
    int noVoiceConnections = 0;
    int highResponseTime = 0;

    for (int shardId = 0; shardId < Getters.getShards().size(); shardId++) {
        JDA jda = ShardUtils.getShardById(shardId);
        if (jda == null) {
            connecting++;
            continue;
        }

        boolean reconnect = ShardUtils.isReconnecting(shardId);
        if (ShardUtils.isDead(shardId))
            deadShard++;
        if (reconnect)
            reconnecting++;
        if (jda.getVoiceChannelCache().stream().noneMatch(vc -> vc.getMembers().contains(vc.getGuild().getSelfMember())))
            noVoiceConnections++;
        if (ShardUtils.getLastEventTime(shardId) >= 1500 && !reconnect)
            highResponseTime++;
    }
    StringBuilder sb = new StringBuilder();
    if (reconnecting > Math.min(quaterShards, 10))
        sb.append("⚠ WARNING: A lot of shards are currently reconnecting! This could mean the bot is unable to be " +
                "used on several thousand servers for a few minutes! (").append(reconnecting).append(" shards reconnecting)").append("\n");
    if (highResponseTime > Math.min(quaterShards, 20))
        sb.append("⚠ WARNING: We seem to be experiencing a high event time on quite a few shards, this is usually " +
                "down to discord not wanting to co-op with us :( please be patient while these ")
                .append(highResponseTime).append(" shards go back to normal!").append("\n");
    if (deadShard > 5)
        sb.append(" SEVERE: We have quite a few dead shards! Please report this on the [Support Server](")
                .append(Constants.INVITE_URL).append(")").append("\n");

    String status = deadShard == 0 && highResponseTime == 0 && reconnecting < (Math.max(quaterShards, 5))
            ? "Good! :)" : "Issues :/";
    if (deadShard > 5)
        status = "Severe issues! Discord could be dying! @EVERYONE RUN!";
    sb.append("Bot Status: ").append(status).append("\n\n");

    sb.append(String.format("FlareBot Version: %s\n" +
                    "JDA Version: %s\n" +
                    "Current Shard: %s\n" +
                    "* Average Ping: %s\n" +
                    "* Ping By Shard: %s\n" +
                    "* Dead Shards: %s shards\n" +
                    "* No Voice Connections: %s shards\n" +
                    "* Shards Reconnecting: %s shards\n" +
                    "* Shards Connecting: %s shards\n" +
                    "* High Last Event Time: %s shards\n" +
                    "Guilds: %d | Users: %d | Connected VCs: %d | Active VCs: %d",
            FlareBot.getVersion(),
            JDAInfo.VERSION,
            channel.getJDA().getShardInfo() == null ? 0 : channel.getJDA().getShardInfo().getShardId(),
            ping,
            Arrays.toString(ShardUtils.getPingsForShards()),
            deadShard,
            noVoiceConnections,
            reconnecting,
            connecting,
            highResponseTime,
            Getters.getGuildCache().size(),
            Getters.getUserCache().size(),
            Getters.getConnectedVoiceChannels(),
            Getters.getActiveVoiceChannels()
    ));

    channel.sendMessage("**FlareBot's Status**\n```prolog\n" + sb.toString() + "\n```").queue();
}
 
Example #18
Source File: JDA3Handler.java    From sdcf4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the parameters which are used to invoke the executor's method.
 *
 * @param splitMessage The spit message (index 0: command, index > 0: arguments)
 * @param command The command.
 * @param event The event.
 * @return The parameters which are used to invoke the executor's method.
 */
private Object[] getParameters(String[] splitMessage, SimpleCommand command, MessageReceivedEvent event) {
    String[] args = Arrays.copyOfRange(splitMessage, 1, splitMessage.length);
    Class<?>[] parameterTypes = command.getMethod().getParameterTypes();
    final Object[] parameters = new Object[parameterTypes.length];
    int stringCounter = 0;
    for (int i = 0; i < parameterTypes.length; i++) { // check all parameters
        Class<?> type = parameterTypes[i];
        if (type == String.class) {
            if (stringCounter++ == 0) {
                parameters[i] = splitMessage[0]; // the first split is the command
            } else {
                if (args.length + 2 > stringCounter) {
                    // the first string parameter is the command, the other ones are the arguments
                    parameters[i] = args[stringCounter - 2];
                }
            }
        } else if (type == String[].class) {
            parameters[i] = args;
        } else if (type == MessageReceivedEvent.class) {
            parameters[i] = event;
        } else if (type == JDA.class) {
            parameters[i] = event.getJDA();
        } else if (type == MessageChannel.class) {
            parameters[i] = event.getChannel();
        } else if (type == Message.class) {
            parameters[i] = event.getMessage();
        } else if (type == User.class) {
            parameters[i] = event.getAuthor();
        } else if (type == Member.class) {
            parameters[i] = event.getMember();
        } else if (type == TextChannel.class) {
            parameters[i] = event.getTextChannel();
        } else if (type == PrivateChannel.class) {
            parameters[i] = event.getPrivateChannel();
        } else if (type == Channel.class) {
            parameters[i] = event.getTextChannel();
        } else if (type == Group.class) {
            parameters[i] = event.getGroup();
        } else if (type == Guild.class) {
            parameters[i] = event.getGuild();
        } else if (type == Integer.class || type == int.class) {
            parameters[i] = event.getResponseNumber();
        } else if (type == Object[].class) {
            parameters[i] = getObjectsFromString(event.getJDA(), args);
        } else {
            // unknown type
            parameters[i] = null;
        }
    }
    return parameters;
}
 
Example #19
Source File: JDA3Handler.java    From sdcf4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Handles a received message.
 *
 * @param event The MessageReceivedEvent.
 */
private void handleMessageCreate(final MessageReceivedEvent event) {
    JDA jda = event.getJDA();
    if (event.getAuthor() == jda.getSelfUser()) {
        return;
    }
    String[] splitMessage = event.getMessage().getContentRaw().split("[\\s&&[^\\n]]++");
    String commandString = splitMessage[0];
    SimpleCommand command = commands.get(commandString.toLowerCase());
    if (command == null) {
        // maybe it requires a mention
        if (splitMessage.length > 1) {
            command = commands.get(splitMessage[1].toLowerCase());
            if (command == null || !command.getCommandAnnotation().requiresMention()) {
                return;
            }
            // remove the first which is the mention
            splitMessage = Arrays.copyOfRange(splitMessage, 1, splitMessage.length);
        } else {
            return;
        }
    }
    Command commandAnnotation = command.getCommandAnnotation();
    if (commandAnnotation.requiresMention()) {
        Matcher matcher = USER_MENTION.matcher(commandString);
        if (!matcher.find() || !matcher.group("id").equals(jda.getSelfUser().getId())) {
            return;
        }
    }
    if (event.isFromType(ChannelType.PRIVATE) && !commandAnnotation.privateMessages()) {
        return;
    }
    if (!event.isFromType(ChannelType.PRIVATE) && !commandAnnotation.channelMessages()) {
        return;
    }
    if (!hasPermission(event.getAuthor(), commandAnnotation.requiredPermissions())) {
        if (Sdcf4jMessage.MISSING_PERMISSIONS.getMessage() != null) {
            event.getChannel().sendMessage(Sdcf4jMessage.MISSING_PERMISSIONS.getMessage()).queue();
        }
        return;
    }
    final Object[] parameters = getParameters(splitMessage, command, event);
    if (commandAnnotation.async()) {
        final SimpleCommand commandFinal = command;
        Thread t = new Thread(() -> invokeMethod(commandFinal, event, parameters));
        t.setDaemon(true);
        t.start();
    } else {
        invokeMethod(command, event, parameters);
    }
}
 
Example #20
Source File: DiscordBotCore.java    From DiscordBot with Apache License 2.0 4 votes vote down vote up
public JDA getJDA() {
	return this.jda;
}
 
Example #21
Source File: Discord.java    From DiscordBot with Apache License 2.0 4 votes vote down vote up
public JDA getJDA() {
	return jda;
}
 
Example #22
Source File: Autochannel.java    From DiscordBot with Apache License 2.0 4 votes vote down vote up
private static Guild getGuild(String id, JDA jda) {
    return jda.getGuildById(id);
}
 
Example #23
Source File: Events.java    From FlareBot with MIT License 4 votes vote down vote up
@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();
    }
}
 
Example #24
Source File: Getters.java    From FlareBot with MIT License 4 votes vote down vote up
public static List<JDA> getShards() {
    return flareBot().getShardManager().getShards();
}
 
Example #25
Source File: ShardUtils.java    From FlareBot with MIT License 2 votes vote down vote up
/**
 * Checks if a shard is dead by comparing the last event time to the provided timeout.
 *
 * @param jda     The shard to check for being dead.
 * @param timeout The timeout the compare the last event time
 * @return Whether the shard is dead or not.
 */
public static boolean isDead(JDA jda, long timeout) {
    return isDead(jda.getShardInfo().getShardId(), timeout);
}
 
Example #26
Source File: ShardUtils.java    From FlareBot with MIT License 2 votes vote down vote up
/**
 * Checks if a shard is dead by comparing the last event time to the {@link ShardUtils#POSSIBLE_DEAD_SHARD_TIMEOUT}.
 *
 * @param jda The shard to check for being dead.
 * @return Whether the shard is dead or not.
 */
public static boolean isDead(JDA jda) {
    return isDead(jda.getShardInfo().getShardId(), POSSIBLE_DEAD_SHARD_TIMEOUT);
}
 
Example #27
Source File: ShardUtils.java    From FlareBot with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example #28
Source File: ShardUtils.java    From FlareBot with MIT License 2 votes vote down vote up
/**
 * Checks if a shard is reconnecting using the provided JDA instance.
 *
 * @param jda The shard to check for reconnecting.
 * @return If the shard is reconnecting or not.
 * @see ShardUtils#isReconnecting(int)
 */
public static boolean isReconnecting(JDA jda) {
    return isReconnecting(jda.getShardInfo().getShardId());
}
 
Example #29
Source File: ShardUtils.java    From FlareBot with MIT License 2 votes vote down vote up
/**
 * Retrieves a {@code JDA} instance of a particular shard (Specified by the ID).
 *
 * @param shardId The shard ID to get.
 */
public static JDA getShardById(int shardId) {
    return flareBot.getShardManager().getShardById(shardId);
}
 
Example #30
Source File: ShardUtils.java    From FlareBot with MIT License 2 votes vote down vote up
/**
 * Get the "display" shard ID, this is basically the normal shard ID + 1 so that it is no longer 0 indexed.
 *
 * @param jda The JDA instance of a certain shard.
 * @return The JDA shard ID as an integer + 1.
 */
public static int getDisplayShardId(JDA jda) {
    return getShardId(jda) + 1;
}