Skip to content

3) Getting Started

Florian Spieß edited this page Mar 3, 2017 · 23 revisions

Making a Ping-Pong Bot

Creating a Discord Bot

  1. Go to https://discordapp.com/developers/applications/me
  2. Create an Application
  3. Give the application an awesome name (this will be used as the bots initial username)

name

  1. Click Create App
  2. Once you are in your application review page, click Create Bot User (Confirm pop-up)

create bot

  1. [OPTIONAL] If you want your bot to be invited to servers by other discord users check Public Bot (DO NOT CHECK Require OAuth2 Code Grant unless you know what you're doing!)

Add your Discord Bot to a Server

  1. Retrieve your application/client ID

client id

  1. Create an OAuth2 authorization URL (reference docs) Example: https://discordapp.com/api/oauth2/authorize?client_id=287329057639497740&scope=bot
  2. Open the authorization dialogue (click link from step 2)
  3. Select your Server (Requires permission to manage server)
  4. Click Authorize

authorize

Connecting to Discord with a Bot Account

  1. Retrieve your Bot Token from your application dashboard (https://discordapp.com/developers/applications/me)

get token

  1. Setup JDA Project
  1. Create JDABuilder instance with token type AccountType.BOT

  2. Set your token

  3. Build JDA using either JDABuilder.buildBlocking() or JDABuilder.buildAsync() depending on your needs

    public static void main(String[] arguments)
    {
        JDA api = new JDABuilder(AccountType.BOT).setToken("[REDACTED]").buildAsync();
    }

Making a Ping-Pong Protocol

  1. Setup your JDA instance (see Connecting To Discord)

  2. Implement an EventListener or extend ListenerAdapter

    public class MyListener extends ListenerAdapter 
    {
        @Override
        public void onMessageReceived(MessageReceivedEvent event)
        {
            if (event.getAuthor().isBot()) return;
            // We don't want to respond to other bot accounts, including ourself
            Message message = event.getMessage();
            String content = message.getRawContent(); 
            // getRawContent() is an atomic getter
            // getContent() is a lazy getter which modifies the content for e.g. console view (strip discord formatting)
            if (content.equals("!ping"))
            {
                MessageChannel channel = event.getChannel();
                channel.sendMessage("Pong!").queue(); // Important to call .queue() on the RestAction returned by sendMessage(...)
            }
        }
    }
  3. Register your listener with either JDABuilder.addListener(new MyListener()) or JDA.addEventListener(new MyListener())