-
-
Notifications
You must be signed in to change notification settings - Fork 98
JDA Tips and Tricks
This guide gives lists some tips and tricks to ease the life of developers working with JDA, the Discord framework used by this project.
Use ISnowflake#getIdLong instead of ISnowflake#getId
Internally JDA uses long
s instead of String
s, so they are faster and still work.
Example:
long userId = event.getUser().getIdLong();
However, in some cases using long is sub-optimal, for example when comparing it to a component ID. Component IDs are custom strings allowing storing data within the ID. Example:
String userThatClickedId = event.getUser().getId();
String userId = idArgs.get(0);
if (userThatClickedId.equals(userId)) {
...
}
If you already have a long
instead though, JDA can still do it, but it requires some extra efforts.
Almost all Discord requests do not run automatically and require an explicit .queue();
.
Affected requests are called RestActions. The rule of thumb is, if your message returns a result it likely has to be queued. Most IDEs can detect such a situation, as seen in the following example:
Some of the many RestAction
types give you more flexibility and additional functionality.
For example, when editing a message, you can not just add 500 options to the TextChannel#editMessageById() method. Instead, it returns a MessageAction object, which allows you to set all the components and more.
Whenever you need an instance of JDA
, the framework got you covered and offers a general getJDA()
method available on pretty much any JDA related object.
Cast JDA to JDAImpl
for more methods
This is a dangerous tip and we advise you to not consider it unless there is really no other option. If you are unsure, please ask the other developers for help.
Internally JDA uses JDAImpl
instead of JDA
, which has way more (internal) methods. While almost, if not all, of them are probably not relevant, some might prove useful in very specific use-cases.
Since this is an internal API, breaking changes can happen with any new version of JDA and it also has no documentation.
Due to the complexity of JDA, you might easily run into a situation where you solve a problem in a certain but not optimal way that is either overly complex or just very lengthy. This chapter shows some tricks to help you use JDA correct and better.
JDA offers some shortcuts to methods and patterns frequently used:
- JDA#openPrivateChannelById, instead of manually retrieving the user and calling User#openPrivateChannel
- JDA#getGuildChannelById also applies to textchannels, storechannels and more. So a Guild instance is not required to get channels.