Creating a Discord trivia bot in Java using Javacord

Why Javacord?

According to Javacord itself, it is “an easy to use multithreaded library for creating Discord bots in Java”. It describes the library perfectly, it is very simple to use and set up, even for people who have very limited experience with Java. Javacord reduces its functionality to standard Java classes which means that a developer does not need to deal with complex abstraction or learn a new framework syntax. Finally, like every other good library out there, it has great documentation and walks you through every kind of functionality you might need.

How do I set it up?

Before we get coding, we need a Discord application. Navigate to this link and follow the instructions here to set up your application https://discord.com/developers/applications

  1. Click the new application button on the top right of the page
Click the new application button on the top right

How do I get this project even started?

Okay in order to get started on this, we need to create a Gradle project. Gradle is basically a build automation tool which can be configured to run certain tasks like compilation, packaging, testing and deployment. It will help us set up our Javacord library as well as the Gson library (required while parsing through http json responses)

  1. Go to: File -> New -> Project
  2. Select Gradle on the left bar
  3. Click Next and run through the screens to create a project
  4. Locate your build.gradle file and open it
  5. Paste the following within your dependencies
Build.gradle file
First Bot message
//adds a listener when a message is deleted on your serverapi.addMessageDeleteListener(event -> { event.getChannel().sendMessage(“What are you hiding there bud?”);});
public class EmbedHelper {
private final String question;
private final String category;

public EmbedHelper(String question, String category) {
this.question = question;
this.category = category;
}

public EmbedBuilder createEmbed() {
//create an embed
EmbedBuilder embed = new EmbedBuilder()
.setTitle("Question")
.setDescription(question)
.addField("How to reply", "Type \"Trivia Answer: \" followed by true or false")
.addField("Category", category)
.setColor(Color.BLUE);
return embed;
}
}

Okay, so how does it look?

Here is a working demo:

Conclusion

Javacord is an awesome library for creating discord bots for any purposes. It has a lot more to be explored, you can create servers, channels and even webhooks with it. It is also really easy to implement because the naming is solid. I highly suggest looking over their documentation here: https://docs.javacord.org/api/v/3.3.0/overview-summary.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store