How to make a Discord bot (Java)

__2020 / 5/19 Addendum __ Here introduces how to make the latest bot.

__ 2019/10/27 Addendum __ It seems that the Discord 4J library handled on this page has been discontinued and replaced with another library. Therefore, it is very difficult or impossible to develop a bot by this method at present. Thank you very much for reading this as a reference when developing bots. If I have time, I would like to write an article about how to develop with the new Discord 4J.

This time, I will develop a simple DiscordBot using the Discord4j library published on GitHub.

To use Bot, you need to register the app on Discord and get a token, which is introduced in the extra edition at the bottom of the page.

Procure the library

Maven repository (README quote)

...
<repositories>
  ...
  <repository> <!-- This repo fixes issues with transitive dependencies -->
    <id>jcenter</id>
    <url>http://jcenter.bintray.com</url>
  </repository>
  <repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
  </repository>
</repositories>
...
<dependencies>
  ...
  <dependency>
    <groupId>com.github.austinv11</groupId>
    <artifactId>Discord4J</artifactId>
    <version>@VERSION@</version>
  </dependency>
</dependencies>
...

Gradle (README quote)

...
repositories {
  ...
  jcenter() //This prevents issues with transitive dependencies
  maven {
    url  "https://jitpack.io"
  }
}
...
dependencies {
  ...
  compile "com.github.austinv11:Discord4J:@VERSION@"
}
...

Library jar

https://austinv11.github.io/Discord4J/downloads.html

Play with the library (API)

Log in to Discord

    public static IDiscordClient login(String token) {
        ClientBuilder clientBuilder = new ClientBuilder();
        clientBuilder.withToken(token);
        return clientBuilder.login();
    }

Event handling

Listener registration

To process an event, you must first register a listener. Please add the code below after logging in. Please put the instance of the class used for the listener in the argument.

In addition, this time we will introduce the registration of listeners using annotations.

client.getDispatcher().registerListener(Object listener);

processing

@EventSubscriber
public void onReady(ReadyEvent event) {
    System.out.println("The bot is ready!");
}

@EventSubscriber
public void onMessage(MessageReceivedEvent event) throws RateLimitException, DiscordException, MissingPermissionsException {
    System.out.println(event.getAuthor().getName() + """ + event.getMessage().getContent() + "I posted.");
}

The onReady method will be called once the login is complete and the onMessage method will be called when the chat is posted to the channel.

You can pick up an event by adding the EventSubscriber annotation.

Information that can be obtained from MessageReceivedEvent

message.getAuthor() //IUser object of the user who posted
message.getMessage() //Posted chat IMessage object
message.getChannel() //IChannel object of the channel to which the posted bit belongs
//Such.

Post a message

It is provided by the IChannel class.

IChannel#sendMessage(String);

Acquisition related sample

Get user name

IUser#getName()

Get message content

IMessage#getMessage()

Subject: Make a simple bot

As this sample, I would like to make a Bot to answer if it is posted "Hello".

import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.api.events.EventSubscriber;
import sx.blah.discord.handle.impl.events.ReadyEvent;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.MissingPermissionsException;
import sx.blah.discord.util.RateLimitException;

public class Example {
	
	private static String TOKEN = "TOKEN"; //Discord Bot token
	
	private static IDiscordClient client;
	
	public static void main(String args[]) {
		Example main = new Example();
		
		System.out.println("Starting Bot...");
		
		client = new ClientBuilder().withToken(TOKEN).build();
		client.getDispatcher().registerListener(main);
		client.login();
	}
	
	@EventSubscriber
	public void onReady(ReadyEvent event) {
		System.out.println("The bot is ready!");
	}

	@EventSubscriber
	public void onMessage(MessageReceivedEvent event) throws RateLimitException, DiscordException, MissingPermissionsException {
		IMessage message = event.getMessage();
		IUser user = message.getAuthor();
		if (user.isBot()) return;

		IChannel channel = message.getChannel();
		String mes = message.getContent();

		if (mes.contains("Hello")) {
			channel.sendMessage("Hello," + user.getName() + "San!");
		}
	}

}

Extra: App registration & token acquisition

  1. Go to https: //discordapp.com/developers/applications/me

  2. Click New App 1.PNG

  3. Enter an appropriate name in APP NAME and click Create App 2.PNG

  4. Make a note of the tokens in the red frame (will be used later) 3.PNG

  5. Scroll a little to find this and click Create a Bot User 4.PNG

  6. After Yes, do it !, click click to reveal and make a note of the token that appears. (Check also for Public Bot) 5.PNG

  7. Replace [CLIENT_ID] in the URL below with the Client Id you wrote down in step 4 to access.

https://discordapp.com/api/oauth2/authorize?client_id=[CLIENT_ID]&permissions=0&scope=bot
  1. Select the server where you want the bot to join and click the Authenticate button. 6.PNG

Recommended Posts

How to make a Discord bot (Java)
How to make a Java container
How to make a Java array
How to make a Java calendar Summary
Java --How to make JTable
How to make a JDBC driver
[Java] How to create a folder
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
Easy to make Slack Bot in Java
[Introduction to Java] How to write a Java program
How to print a Java Word document
How to make a groundbreaking diamond using Java for statement wwww
How to make shaded-jar
Java Discord Bot creation
How to display a web page in Java
I did Java to make (a == 1 && a == 2 && a == 3) always true
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
How to convert a solidity contract to a Java contract class
How to make a lightweight JRE for distribution
How to make a follow function in Rails
Easy to make LINE BOT with Java Servlet
[Java] How to make multiple for loops single
[Java / kotlin] Kai-How to make a Discord Bot-Let's implement a command to say hello-
How to make an app with a plugin mechanism [C # and Java]
[Java] How to use Map
How to make a factory with a model with polymorphic association
How to create a Java environment in just 3 seconds
How to lower java version
How to uninstall Java 8 (Mac)
How to jump from Eclipse Java to a SQL file
How to use java Optional
java: How to write a generic type list [Note]
[Java] How to play rock-paper-scissors (equivalent to paiza rank A)
How to make Java unit tests (JUnit & Mockito & PowerMock)
How to minimize Java images
How to write java comments
How to leave a comment
How to make JavaScript work on a specific page
How to use java class
[Java] How to use Optional ②
How to create a data URI (base64) in Java
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to get a request by HTTP communication
I tried to make a login function in Java
[Java] How to use string.format
How to use Java Map
[Java] Make it a constant
[Java] How to execute tasks on a regular basis
How to set Java constants
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
How to use Java variables
How to convert Java radix
[Rails] How to make seed
How to make a cache without thinking too much
How to make a mod for Slay the Spire