Making a Ping-Pong Bot¶
Creating a Discord Bot¶
- Go to https://discord.com/developers/applications
- Create an Application
-
Give the application an awesome name (this will be used as the bots initial username)
-
Click Save Changes
-
Open the Bot tab
-
Make sure to make your bot public, this allows others to invite your bot to your server.
You only want require code grant enabled if you plan to use an oauth2 flow, the general user will not need this.
Add your Discord Bot to a Server¶
-
Retrieve your application/client ID from the General Information tab
-
Create an OAuth2 authorization URL (reference docs). Users who want to use Interaction Commands should also add the
applications.commands
scope. Some example URLs:https://discord.com/api/oauth2/authorize?client_id=492747769036013578&scope=bot
https://discord.com/api/oauth2/authorize?client_id=492747769036013578&scope=bot+applications.commands
Note
This can be done from the Bot tab at the very bottom. Here you can select the scope bot and some permissions required for your bots functionality (optional).
-
Open the authorization dialogue (click link from step 2)
- Select your Server (Requires permission to manage server)
-
Click Authorize
Connecting to Discord with a Bot Account¶
-
Retrieve your Bot Token from your application dashboard (https://discord.com/developers/applications)
Caution
Note that it is very important not to show this token to anyone, ever.
-
Set up your JDA project:
-
Create
JDABuilder
instance with token -
Build JDA using
JDABuilder.build()
public static void main(String[] arguments) throws Exception { JDA api = JDABuilder.createDefault(BOT_TOKEN).build(); }
Tip
It is often better to load your token in from an external file or environment variable, especially if you plan on publishing the source code.
Making a Ping-Pong Protocol¶
- Setup your JDA instance (see Connecting To Discord)
-
Implement an
EventListener
or extendListenerAdapter
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.getContentRaw(); // getContentRaw() is an atomic getter // getContentDisplay() 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(...) } } }
Info
More information about RestActions can be found here
-
Register your listener with either
JDABuilder.addEventListeners(new MyListener())
orJDA.addEventListeners(new MyListener())
(see Events)