15.03.2017 Views

Discord4J Documentation

discord4j

discord4j

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Discord4J</strong> <strong>Documentation</strong><br />

Release 1<br />

TheFjong & Austin<br />

June 01, 2016


<strong>Documentation</strong><br />

1 Important 3<br />

1.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3<br />

1.2 Logging In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6<br />

1.3 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7<br />

1.4 Bot Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9<br />

1.5 Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10<br />

1.6 User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11<br />

1.7 Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12<br />

1.8 Nifty Use Case Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13<br />

i


ii


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

<strong>Discord4J</strong> is an unofficial Java library that helps you access Discord’s API through REST and WebSockets.<br />

<strong>Discord4J</strong> makes it easy for you to write a bot. It nearly has full API support. (See Discord API Comparison)<br />

The sourcecode can be found on GitHub. Feel free to join us in the Discord API chat.<br />

<strong>Documentation</strong> 1


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

2 <strong>Documentation</strong>


CHAPTER 1<br />

Important<br />

It’s recommended that you always use the latest version available. You can find the latest version in the Discord Chat<br />

& on <strong>Discord4J</strong>’s Github page<br />

Please report any bugs you find to the Issue Tracker or to our Discord Chat<br />

This <strong>Documentation</strong> is still under development. If this site can’t help you, please use the Discord Chat<br />

1.1 Getting Started<br />

If you have any problems with this guide, please contact @Thefjong in Discord API Chat in the <strong>Discord4J</strong> channel.<br />

1.1.1 Requirements<br />

<strong>Discord4J</strong> requires you to have a registered Account or a bot account. You can register an account here.<br />

<strong>Discord4J</strong> requires Java and Java JDK aswell.<br />

Git & a Java IDE is optional but is recommended. Eclipse and Intellij IDEA are both excellent Java IDES.<br />

It is highly recommended that you make a bot account for your application.<br />

1.1.2 Making a bot account<br />

You can either get a bot account via CURL or via Discord API Website. If you’re going with Discord’s bot maker,<br />

then make an Application, then add the bot account afterwards. ;)<br />

Otherwise, you can follow this CURL tutorial:<br />

• Install Curl from Curl’s website<br />

There are 2 ways of getting a bot account:<br />

1. First you’ll need 2 account registred at Discord. Your main and your bot account.<br />

2. You’ll only need 1 account registered at Discord. Your main account only.<br />

If youre going with the second way: [A NAME FOR YOUR APPLICATION] will be the name of the bot.<br />

Let’s begin by making an application.<br />

Run this via CMD or Terminal or go here:‘Make an Application‘_:<br />

3


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

curl -H 'Authorization: [YOUR TOKEN]' \<br />

-H "Content-Type: application/json" \<br />

-X POST -d '{"name": "[A NAME FOR YOUR APPLICATION]"}' \<br />

https://discordapp.com/api/oauth2/applications<br />

You should get a response like this:<br />

{"secret": "XXX", "redirect_uris": [], "description": "", "name": "THE NAME OF THE APPLICATION", "id"<br />

Keep the ‘secret’ and the ‘ID’ safe. You have now succesfully created an application!<br />

Now you want to make the bot itself. Run this via CMD or Terminal:<br />

curl -H 'Authorization: [YOUR TOKEN]' \<br />

-H "Content-Type: application/json" \<br />

-X POST -d '{"token": "[YOUR BOTS USERS TOKEN]


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

...<br />

<br />

...<br />

<br />

jitpack.io<br />

https://jitpack.io<br />

<br />

<br />

...<br />

<br />

...<br />

<br />

com.github.austinv11<br />

Discord4j<br />

@VERSION@<br />


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

1.7.9<br />

<br />

<br />

...<br />

Gradle:<br />

...<br />

dependencies {<br />

...<br />

compile "org.slf4j:slf4j-simple:1.7.9"<br />

}<br />

...<br />

1.2 Logging In<br />

If you have any problems with this guide, please contact @Thefjong in Discord API Chat on the <strong>Discord4J</strong> channel.<br />

1.2.1 Tutorial<br />

Alright let’s start with a clean Java app.<br />

public class TestBot<br />

{<br />

public static void main(String[] args)<br />

{<br />

}<br />

}<br />

Now you’ll want to make a method that will return an IDiscordClient object. Extend your class with the getClient<br />

method & add a throws Exception to your main method’s signature.<br />

public class TestBot<br />

{<br />

public static void main(String[] args) throws Exception<br />

{<br />

}<br />

}<br />

public static IDiscordClient getClient(String token) throws DiscordException<br />

{<br />

return new ClientBuilder().withToken(token).login();<br />

}<br />

This method will take a bot token as a parameter, and return an IDiscordClient. (The ‘Getting Started’ section outlines<br />

getting a token)<br />

Now you want to make a public static variable in your class, that you’ll set to getClient(YOUR TOKEN). Your class<br />

should look similar to this:<br />

public class TestBot<br />

{<br />

public static IDiscordClient discordClient;<br />

6 Chapter 1. Important


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

public static void main(String[] args) throws Exception<br />

{<br />

if(args.length < 1)<br />

System.out.print("You need to specify a token before continuing");<br />

}<br />

discordClient = getClient(args[0]);<br />

}<br />

public static IDiscordClient getClient(String token) throws DiscordException<br />

{<br />

return new ClientBuilder().withToken(token).login();<br />

}<br />

This will take an argument and pass it to the getClient method. When you run your jar, remember to put a token as an<br />

argument!<br />

An alternative to the current approach is to just hardcode the your bot’s token. Which you may find convenient for<br />

testing.<br />

Now you have successfully logged in to your discordClient!<br />

1.2.2 Completed Example<br />

public class TestBot<br />

{<br />

public static IDiscordClient discordClient;<br />

public static void main(String[] args) throws Exception<br />

{<br />

if(args.length < 1)<br />

System.out.print("You need to specify a token before continuing");<br />

}<br />

discordClient = getClient(args[0]);<br />

}<br />

public static IDiscordClient getClient(String token) throws DiscordException<br />

{<br />

return new ClientBuilder().withToken(token).login();<br />

}<br />

1.3 Events<br />

If you have any problems with this guide, please contact @Thefjong in Discord API Chat in the <strong>Discord4J</strong> channel.<br />

See all Events here: JavaDocs<br />

1.3.1 Ready Event<br />

First you want to register a listener via your IDiscordClient variable. You can do so by the getDispatcher() method in<br />

IDiscordClient, and then registerListener(IListener). You can either make an EventHandler that listens so all events<br />

that your class have an @EventSubscriber annotation over it, and make a file for each Event that you listens to.<br />

1.3. Events 7


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

See following code:<br />

public static void main(String[] args) throws Exception<br />

{<br />

if(args.length < 1)<br />

System.out.print("You need to specify a token before continuing");<br />

discordClient = getClient(args[0]);<br />

}<br />

discordClient.getDispatcher().registerListener(new EventHandler());<br />

discordClient.getDispatcher().registerListener(new ReadyEventListener());<br />

The line that has (new EventHandler()) registers a listener that works by making methods that has an @EventSubscriber<br />

annotation.<br />

The line that has (new ReadyEventListener()) registers a listeners that implements IListener. This file will only react<br />

when one specific event is dispatched.<br />

The EventHandler class:<br />

public class EventHandler<br />

{<br />

@EventSubscriber<br />

public void onReadyEvent(ReadyEvent event)<br />

{<br />

System.out.println("The bot is now ready");<br />

doSomething();<br />

}<br />

}<br />

@EventSubscriber<br />

public void onMessageEvent(MessageReceivedEvent event)<br />

{<br />

System.out.println(event.getMessage().getAuthor().getName() + ": " + event.getMessage<br />

}<br />

The ReadyEventListener class:<br />

public class ReadyEventListener implements IListener<br />

{<br />

public void handle(ReadyEvent event)<br />

{<br />

System.out.println("The bot is now ready");<br />

doSomething();<br />

}<br />

}<br />

The EventHandler class listens on 2 events. Both ReadyEvent and MessageReceivedEvent. The class will print “The<br />

Bot is now ready” in the console when the ReadyEvent is dispatched. The class will also print the a message with a<br />

name when the bot has received a message.<br />

The ReadyEventListener only listens on ReadyEvent and will not be called when MessageReceivedEvent has been<br />

dispatched.<br />

ReadyEvent is probably the most useful Events that <strong>Discord4J</strong> has, because you cant really do anything Discord wise<br />

without the bot being ready.<br />

8 Chapter 1. Important


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

1.3.2 Full Example<br />

public static void main(String[] args) throws Exception<br />

{<br />

if(args.length < 1)<br />

System.out.print("You need to specify a token before continuing");<br />

discordClient = getClient(args[0]);<br />

}<br />

discordClient.getDispatcher().registerListener(new EventHandler());<br />

discordClient.getDispatcher().registerListener(new ReadyEventListener());<br />

public class EventHandler<br />

{<br />

@EventSubscriber<br />

public void onReadyEvent(ReadyEvent event)<br />

{<br />

System.out.println("The bot is now ready");<br />

doSomething();<br />

}<br />

}<br />

@EventSubscriber<br />

public void onMessageEvent(MessageReceivedEvent event)<br />

{<br />

System.out.println(event.getMessage().getAuthor().getName() + ": " + event.getMessage<br />

}<br />

public class ReadyEventListener implements IListener<br />

{<br />

public void handle(ReadyEvent event)<br />

{<br />

System.out.println("The bot is now ready");<br />

doSomething();<br />

}<br />

}<br />

1.4 Bot Settings<br />

If you have any problems with this guide, please contact @Thefjong in Discord API Chat in the <strong>Discord4J</strong> channel.<br />

1.4.1 Updating Presence / Game information<br />

public void updateBotPresence(IDiscordClient client)<br />

{<br />

client.updatePresence(false, Optional.of("Bot things :3"));<br />

}<br />

1.4.2 Getting Presence / Game Playing<br />

1.4. Bot Settings 9


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

public Presences getPresence(IDiscordClient client, String userID)<br />

{<br />

client.getUserByID(userID).getPresence();<br />

}<br />

1.4.3 Changing Your Username<br />

public void changeBotUsername(IDiscordClient client) throws DiscordException, HTTP429Exception<br />

{<br />

client.changeUsername("Butt bot");<br />

}<br />

1.4.4 Changing Avatar<br />

public void changeBotAvatar(IDiscordClient client)<br />

{<br />

client.changeAvatar(Image.forFile(new File("BotAvatar.png")));<br />

client.changeAvatar(Image.forUrl("jpg", "Random.org/avatar.jpg"));<br />

client.changeAvatar(Image.forData("jpg", **Byte Array**));<br />

client.changeAvatar(Image.forUser(client.getUserByID("UserID of the person you want to get the im<br />

client.changeAvatar(Image.forStream("png", **InputStreamObject**));<br />

}<br />

Don’t believe that this is all you’re limited to! Our Java Docs feature a bunch of nifty stuff.<br />

1.5 Channel<br />

If you have any problems with this guide, please contact @Thefjong in Discord API Chat in the <strong>Discord4J</strong> channel.<br />

1.5.1 Getting a Channel by ID<br />

First of all you might be wondering how to get the id from a channel. Do following:<br />

Afterwards, put the link in notepad or something. Then copy the id out of it, like I do here:<br />

Or you can type out the channel with the hashtag syntax (i.e. #general) an add a backslash in front (like this: \#general).<br />

Sending the message should get you the channel id in the form “”.<br />

Now we want to use it in our ultra amazing bot.<br />

public IChannel getChannelForID(IDiscordClient client, String id)<br />

{<br />

return client.getChannelByID(id);<br />

}<br />

10 Chapter 1. Important


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

That was quite easy.<br />

1.5.2 Getting Messages in a Channel<br />

{<br />

}<br />

public MessageList getMessages(IDiscordClient client, String ChannelID)<br />

return client.getChannelByID(ChannelID).getMessages();<br />

1.5.3 Toggling Typing Status<br />

{<br />

}<br />

public void toggleTypingStatus(IDiscordClient client, String ChannelID)<br />

client.getChannelByID(ChannelID).toggleTypingStatus();<br />

1.5.4 Changing Channel Name, Position & Topic<br />

public void changeChannel(IDiscordClient client, String ChannelID)<br />

{<br />

client.getChannelByID(ChannelID).changeName("Bot chat");<br />

client.getChannelByID(ChannelID).changePosition(0);<br />

client.getChannelByID(ChannelID).changeTopic("Bot chat, only for Awesome bots...");<br />

}<br />

1.5.5 Sending Files and Messages<br />

public void SendFileAndMessage(IDiscordClient client, String ChannelID)<br />

{<br />

client.getChannelByID(ChannelID).sendFile(new File("filetosend"));<br />

client.getChannelByID(ChannelID).sendMessage("Heyo Everyone.. wut");<br />

}<br />

There’s lots of methods more... These are just some examples. see Javadocs for more.<br />

1.6 User<br />

If you have any problems with this guide, please contact @Thefjong in Discord API Chat in the <strong>Discord4J</strong> channel.<br />

1.6.1 Getting a user by ID<br />

You can type out the user with the @mention syntax (i.e. @Austin) an add a backslash in front (like this: \@Austin).<br />

Sending the message should get you the user id in the form “”. NOTE: This will still mention the user!<br />

Now we want to use it in our ultra amazing bot.<br />

1.6. User 11


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

public IUser getUserForID(IDiscordClient client, String id)<br />

{<br />

return client.getUserByID(id);<br />

}<br />

That was quite easy.<br />

1.6.2 Get the voice channel our bot is connected to (if present)<br />

public Optional getVoiceChannel(IDiscordClient client, String userID)<br />

{<br />

return client.getUserByID(userID).getVoiceChannel();<br />

}<br />

1.6.3 Sending a Private Message<br />

public void sendPrivateMessage(IDiscordClient client, String userID) throws DiscordException, HTTP429<br />

{<br />

IPrivateChannel channel = client.getOrCreatePMChannel(client.getUserByID(userID));<br />

channel.sendMessage("Hello User");<br />

}<br />

There’s an overload of information at our Java Docs. This is just a little slice of the awesomeness.<br />

1.7 Audio<br />

If you have any problems with this guide, please contact @Thefjong in ‘Discord API Chat‘_ in the <strong>Discord4J</strong> channel.<br />

1.7.1 Grabbing a Channel<br />

public AudioChannel getAudioChannel(IDiscordClient client, String id) throws DiscordException<br />

{<br />

return client.getVoiceChannelByID(id).getAudioChannel();<br />

}<br />

1.7.2 Playing Audio Example<br />

public void playFile(AudioChannel channel, String path) throws Exception<br />

{<br />

if (channel == null)<br />

throw new NullPointerException("Argument: 'channel'");<br />

// Let's make sure our bot is<br />

// actually there..<br />

channel.join();<br />

File _rawFile = new java.io.File(path);<br />

// :< | Handle how ever you see fit<br />

if (_rawFile == null)<br />

12 Chapter 1. Important


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

return;<br />

}<br />

channel.queueFile(_rawFile);<br />

// You should hear the content<br />

// of that file now! :><br />

1.7.3 General Media Control<br />

public void example(AudioChannel channel)<br />

{<br />

// Interupts our bot's audio stream. It will<br />

// continue where it left off.<br />

channel.pause();<br />

// ^ This guy's partner<br />

channel.isPaused();<br />

// Resumes the bot's audio stream. Operates<br />

// well with the #pause() function<br />

channel.resume();<br />

// Updates the volume at which this bot<br />

// plays audio. This can go pretty darn<br />

// high, so avoid killing anyone's ears.<br />

channel.setVolume(4);<br />

channel.setVolume(1000); //


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

@EventSubscriber<br />

public void watchForCommands(MessageReceivedEvent event)<br />

{<br />

try<br />

{<br />

IMessage _message = event.getMessage();<br />

String _content = _message.getContent();<br />

if (!_content.startsWith(KEY))<br />

return;<br />

String _command = _content.toLowerCase();<br />

String[] _args = null;<br />

if (_content.contains(" "))<br />

{<br />

_command = _command.split(" ")[0];<br />

_args = _content.substring(_content.indexOf(' ') + 1).split(" ");<br />

}<br />

}<br />

}<br />

catch (Exception ex)<br />

{<br />

// Handle how ever you please<br />

}<br />

}<br />

Alright we have that done. Let’s walk through what we just did.. * Someone sends your everyday casual message<br />

on a channel the bot was invited to * We listen for the event fired by <strong>Discord4J</strong>. How nice of them! * We grab<br />

that message from the event (_message) * We also store the content of our message as we’ll be using it quite a bit<br />

(_content) * We verify that we’re actually handling a command, and not those memes your friends keep sending.<br />

(_content.startsWith()) * Now that we’re positive we’re dealing with a command lets create some variables...<br />

• _command: This will hold our actual command the user used. (!help messages | ‘help’ is the command in this<br />

case)<br />

• _args: This will hold the arguments the user provided while executing the command. Keep in mind that they<br />

may not have done so!<br />

• Wait a second! We have that ‘args’ variable, but by default we assign it to a null value... That doesn’t make any sense! :/<br />

– That’s a fair point! So that means we’ll have to grab those..<br />

• Remove that first pesky space, and then split the rest up into an array to make dealing with these arguments<br />

worlds easier.<br />

• Listen for an event that is fired whenever we do this. Oh wait... let’s go make that!<br />

private final IMessage message;<br />

private final String command;<br />

private final IUser by;<br />

private final String[] args;<br />

public CommandExecutionEvent(IMessage message, String command, IUser by, String[] args)<br />

{<br />

14 Chapter 1. Important


<strong>Discord4J</strong> <strong>Documentation</strong>, Release 1<br />

}<br />

this.message = message;<br />

this.command = command;<br />

this.by = by;<br />

this.args = args;<br />

public String[] getArgs()<br />

{<br />

return args;<br />

}<br />

public IMessage getMessage()<br />

{<br />

return message;<br />

}<br />

public boolean isCommand(String command)<br />

{<br />

return command.equalsIgnoreCase(command);<br />

}<br />

public IUser getBy()<br />

{<br />

return by;<br />

}<br />

• Alrighty. Now that we have that lets jump back to that other class...<br />

.....<br />

if (_content.contains(" "))<br />

{<br />

_command = _command.split(" ")[0];<br />

_args = _content.substring(_content.indexOf(' ') + 1).split(" ");<br />

}<br />

CommandExecutionEvent _event = new CommandExecutionEvent(_message, _command, _message.getAuthor()<br />

getClient().getDispatcher().dispatch(_event);<br />

.....<br />

• The first addition was the creation of our event object containing all of the data for this event<br />

• Next we tell <strong>Discord4J</strong> to fire that event off to all of our listeners which will handle our event accordingly<br />

• We’re done! Just for fun I’ll also show you a quick use-case scenario for this<br />

.....<br />

@EventSubscriber<br />

public void handle(CommandExecutionEvent event)<br />

{<br />

if (event.isCommand("ping"))<br />

event.getMessage().reply("Pong!");<br />

}<br />

.....<br />

Good luck! :><br />

1.8. Nifty Use Case Examples 15

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!