1

Example Discord bot with JDA

Class Java 1 revisions 322 8 months ago 8 months ago
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;

import javax.security.auth.login.LoginException;

public class Example {
    private static final String API_TOKEN = ""; // No I am NOT leaking MY token!

    public static void main(String[] args) {
        try {
            JDA jda = new JDABuilder(AccountType.BOT).setToken(API_TOKEN) // There's CLIENT instead of BOT fyi
                    .addEventListener(new Handler())                      // Handles stuff
                    .buildBlocking();                                     // There's also an async one
        } catch (LoginException e) {
            // Bad token probably
            e.printStackTrace();
        } catch (InterruptedException e) {
            // buildBlocking() blocks, and blocking can be interrupted
            // Though this will never happen.. ?
            e.printStackTrace();
        }
    }

    // This is where we handle stuff.
    // This should probably be in a separate file.
    static class Handler extends ListenerAdapter {
        @Override
        public void onMessageReceived(MessageReceivedEvent event) {
            User author = event.getAuthor();               // The guy (or bot?)
            Message message = event.getMessage();          // Message object, which *contains* the actual message
            MessageChannel channel = event.getChannel();   // TextChannel, PrivateChannel, or Group
            String content = message.getContentDisplay();  // Actual message string
            boolean bot = author.isBot();                  // THEY ARE BOTS!!

            // Basic logging
            System.out.printf("[%s#%s]@[#%s]: %s\n", author.getName(), author.getDiscriminator(), channel.getName(), content);

            if (content.startsWith("!ping")) {
                channel.sendMessage("pong aaaaaaa").queue();    // Notice the .queue() !!
            }
        }
    }
}

This is an example Discord bot built with JDA Java library.

You can drop the code in an Example.java file, put a correct API_TOKEN (which you'd get from here), and then compile with JDA added to the classpath.

When you run it you should see something like this:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J: Failed to load class "org.slf4j.impl.StaticMDCBinder".
SLF4J: Defaulting to no-operation MDCAdapter implementation.
SLF4J: See http://www.slf4j.org/codes.html#no_static_mdc_binder for further details.
[main] INFO JDA - Login Successful!
[JDA MainWS-WriteThread] INFO WebSocketClient - Connected to WebSocket
[JDA MainWS-ReadThread] INFO JDA - Finished Loading!

You can ignore the warning I guess. After that, the bot will be online and it should respond to a !ping.

The code itself is explained in comments and should be very easy to understand. The code is rather basic but it should get you started.