Java源码示例:net.dv8tion.jda.core.JDA
示例1
/**
* 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);
}
});
}
示例2
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();
}
});
}
示例3
@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);
}
示例4
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;
}
}
示例5
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);
});
}
示例6
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();
}
});
}
示例7
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();
}
}
示例8
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));
}
}
示例9
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;
}
示例10
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);
}
示例11
/**
* 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!");
}
示例12
@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();
}
}
示例13
@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();
}
}
示例14
private TextChannel retrieveLogChannel() {
for(JDA shard : MainBot.getJdaList()) {
if(shard.getTextChannelById(MainBot.getConfig().getGuildsLogChannelId()) != null) {
return shard.getTextChannelById(MainBot.getConfig().getGuildsLogChannelId());
}
}
return null;
}
示例15
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.");
}
}
示例16
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;
}
示例17
/**
* 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;
}
示例18
private static Guild getGuild(String id, JDA jda) {
return jda.getGuildById(id);
}
示例19
@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();
}
示例20
public static List<JDA> getShards() {
return flareBot().getShardManager().getShards();
}
示例21
public JDA getJDA() {
return jda;
}
示例22
public JDA getJDA() {
return this.jda;
}
示例23
/**
* 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);
}
}
示例24
/**
* 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;
}
示例25
/**
* Get the shard ID of a JDA instance, if the JDA instance doesn't have ShardInfo (aka not sharded) then it will
* return 0.
*
* @param jda The JDA instance of a certain shard.
* @return The JDA shard ID as an integer.
*/
public static int getShardId(JDA jda) {
if (jda.getShardInfo() == null) return 0;
return jda.getShardInfo().getShardId();
}
示例26
/**
* 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;
}
示例27
/**
* 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);
}
示例28
/**
* 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());
}
示例29
/**
* 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);
}
示例30
/**
* 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);
}