Javacord logo supplied by Javacord community

Discord Bots with Javacord: How to Make Your First Bot

Caleb Garcia
Java Playground
Published in
8 min readAug 13, 2020

--

In my last article, Creating a Discord Developer Application, I talked about the Discord Developer Portal, how to create a Developer Application, and I gave you a few ideas on what you can do with your bot. In this article, I’ll finally be answering some questions you might have about this whole series. Before I answer any of those questions, though, allow me to provide a quick disclaimer.

Disclaimer Time!

This article assumes you understand the basics of the Java programming language to a functional level. This includes but is not limited to an understanding of methods, object creation, and lambdas. If you are not familiar with these concepts, save this article on the side and come back to it when you are. For total beginners, I would recommend w3schools as an excellent place to learn the basics of Java and other languages.

On another important note: This is not an official Javacord article or series, and I am not a Javacord team member. I am simply spreading the word and proper usage of the library I like to use for my Discord bots. This article does, however, include information provided directly from the Javacord team to ensure I am giving you the most correct and clean code as possible.

Now, it’s time to answer that first big question.

What is Javacord?

Javacord is an amazing library that allows you to communicate with the Discord API from your Java code in a greatly simplified manner. You can create objects and call methods that your bot will use to send messages, manipulate roles on a user, and so much more. The Javacord website has everything clearly laid out in terms of proper documentation and example code so that even the total beginner can create a basic Discord bot. I’ll be referencing some of their examples, wiki pages, and JavaDocs in this article and any future articles about bots for you to read up more on how the library works.

I would highly recommend you join the official Javacord Discord server before you start working with this library. There is an absolutely wonderful community surrounding it (and I’m happy to say I’m a part of it) that is always willing to help you with an issue if you’re willing to learn. Here you can speak with me, the creators, the contributors, and plenty of other bot developers just like you. Come join in on the discussion!

So I need Javacord for my bot, how do I get it?

The Javacord wiki’s welcome page tells you exactly what to do to put Javacord in your bot project whether you’re using Gradle or Maven. In our case of using Gradle, it’s a very simple couple of steps:

  1. Open the build.gradle file in your IntelliJ bot project
  2. Delete the testCompile line in the dependencies block (this line is for doing tests on your code, which I may cover in a later article)
  3. Where you deleted the previous line, add the following: implementation ‘org.javacord:javacord:3.0.6’

Make sure to click the Load Gradle Changes button at the top right after you add this line. This allows Gradle to import Javacord into your project for you to create your bot.

Congratulations! After a few moments of importing, you will officially have access to countless tools to use to write your bot with. Now, we’re going to use them for a very simple bot that we’ll expand on later in this article.

How do I make my bot do something?

Back on Javacord’s home page, there is an excellent example labeled “Logging in” we are going to use to verify that your bot is up and running. This is always a good test to run right after you do all of this setup, so we’re going to do it here as well. When you are done following the example, your main file should look something like the picture below (remember to replace yourtokenhere with the bot’s token we got in the last article).

import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
public class Bot { public static void main(String[] args) {
DiscordApi api = new DiscordApiBuilder().setToken("yourtokenhere").login().join);
// Add a listener which answers with "Pong!" if someone writes "!ping"
api.addMessageCreateListener(event -> {
if (event.getMessageContent().equalsIgnoreCase("!ping")) {
event.getChannel().sendMessage("Pong!");
}
});
// Print the invite url of your bot
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
}
}

From here, you can run your bot by pressing Shift+F10; if you’ve followed all of these steps correctly, you should see the print statement with the bot’s invite link appear in the console at the bottom of the screen. Use this to invite your bot to your server so you can test out how it works!

What did I just write?

At the beginning of getting into this library, some things may be a little confusing, so I’ll break down what’s going on inside of the main method here:

  • First: we’re creating a DiscordApi instance. Simply put, this is what allows us to interact with the Discord API. We create an instance of the DiscordApiBuilder class, pass it the token to login with, and then tell it to log in to the bot’s account. join() is a method of the CompletableFuture that login() returns; it blocks the current thread and returns the completed DiscordApi instance to the api variable.
  • Second: we add what’s called a “listener”. A listener does exactly what it sounds like; it waits and listens for a certain thing to happen, and in the following code block, it reacts accordingly. In our case, we’re listening for any message that the bot can read. Every time that happens, it’s called an event and the bot can access information about it using the event parameter. You can use whatever name for the event you’d like, but you want it to still be representative of the event you’re passing in to the lambda (in this case, a MessageCreateEvent).
  • Third: every time the bot gets a message, it checks to see if the message content of the event matches “!ping”. The equalsIgnoreCase() method does this comparison and, as the name entails, ignores upper or lower case letters, and returns a true or false value based on the match.
  • Fourth: if the message content matches, we get the text channel that the event happened in, and to it, we send the message “Pong!”.
  • Lastly: The final line in the main method is simply a print statement that calls the createBotInvite() method of the API instance. This prints out the URL that you can use to invite the bot to your server.

Once your bot is in your server, testing the code you just wrote is very simple. In any channel the bot has access to, send a !ping message and you should get the programmed response back almost immediately.

Testing the ping command (supplied by author)

Congratulations x2! You technically have a functional Discord bot. It doesn’t do anything too helpful at the moment, though, so let’s fix that!

I want my bot to do something useful!

I may show more example projects in time, but for the sake of this article, let’s work on a very simple task to give your bot: welcome new users to your Discord server!

The main driver behind this task is a different kind of listener, called a ServerMemberJoinListener. As the name entails, this waits and listens for a member to join any server the bot is in. We want to welcome new users to the server, so we want to use this listener to act when somebody joins.

As you can see in my code below, I’ve introduced something called an Optional. Javacord’s wiki has a great explanation of how to use this Java class, and I would highly recommend checking out the page to understand what I’m doing with channel.ifPresent().

import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
import org.javacord.api.entity.channel.TextChannel;
import java.util.Optional;public class Bot { public static void main(String[] args) {
DiscordApi api = new DiscordApiBuilder().setToken("yourtokenhere").login().join());
// Welcome new users to your server
api.addServerMemberJoinListener(event -> {
Optional<Textchannel> channel = api.getTextChannelById(yourchannelidL);
channel.ifPresent(textChannel -> textChannel.sendMessage("Welcome to the server, " + event.getUser().getMentionTag() + "!"));
});
// Print the invite url of your bot
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
}
}

Like I did earlier, let me give you a quick rundown on what the code is doing:

  • First: add a ServerMemberJoinListener to wait and listen to a Discord user joining the server the bot is on. This is the event trigger we’ll be using to mention the user in a moment.
  • Second: request an Optional object with the type parameter TextChannel, use the API instance to get a text channel by its ID (check out this post by Discord support on how to get a channel’s ID), and assign that value to the Optional. Because we’re just feeding in a string of numbers, this channel may or may not exist, and that’s why we’re using an Optional. (Note: the L at the end of the numbers indicate a long, a Java datatype. When hard-coding IDs, it is best practice to use this datatype as opposed to a String, as the natural form of IDs is long.)
  • Third: handle the Optional appropriately. Call the ifPresent() method of the Optional to check if the channel exists and if the bot can see it; if it does and if it can, use the lambda’s textChannel parameter to send the programmed message. Get the user who joined (the User is stored in the event variable, so we use event.getUser() to retrieve them) and get their mention tag to use in the message. The mention tag is, in the test below, where the user’s name is preceded by an @. Using the mention tag “pings” the user and lets them know someone is trying to get their attention; in our case, that’s our bot!
Testing the bot’s welcome message (supplied by author)

Congratulations x3! After you write all of this code and restart your bot, any user should be given a warm welcome in whatever channel you specified. It’s not the most spectacular first project, but it’s a very good introduction to the basics of the Javacord library and Discord bot development. It does have a practical application, as some server owners want to automate welcoming new users. If you want to pretty up the bot’s welcome message, I’d suggest checking out Javacord’s Embed FAQ and learning about embeds to make things look just a little neater.

That does it for your introduction to Discord Bots with Javacord! I’d like to thank the Javacord team for personally providing the proper information to me so I could make this article accurate and as high-quality as it can be. I’ll be happy to respond to any questions, comments, or suggestions you may have about this article or future ones. Make sure to subscribe to The Playground Digest newsletter to get the first word on new articles playing with Java, and make sure to give me a follow to see more like this in the future. If you know anybody who isn’t quite sure how to make a basic Discord bot in Java, share this article with them to give them a great place to start!

Want to see all of these concepts in action? Check out my Fiverr®️ Gig®️ to see how I can make a custom Discord bot for your server using everything I discussed in this article, and whatever else you want your bot to do!

--

--

Caleb Garcia
Java Playground

Hello! My name is Caleb Garcia and I’m a programmer who would love to give you some of his coding experience, so you can make better decisions in your projects.