Java Discord Bot creation

Introduction

There are many articles that introduce Python or JavaScript rather than Java, so I think it's easier to make. I don't understand Python or JavaScript, so I write it in Java If you understand Python or JavaScript, don't read this article and write in Python or JavaScript.

environment

jre 1.8.0_241 jdk 1.8.0_241 Intellij idea community 2019.3.3 Anything you can write

Preparation

When you create a bot, you will need a token, so prepare that side

  1. Go to the Discord Developer Portal (https://discordapp.com/developers) Maybe it's your first time to log in so please log in with your account

  2. Select New Application from the Applications field New Application.png

  3. Enter the application name (anything is acceptable as long as it can be distinguished) in the NAME field and create it. TestBot.png

  4. Select Bot from the left column and select Add Bot Bot.png

  5. Username icon Required authority Change bot settings such as whether it is a public bot

  6. Finally, select Copy from Bot's TOKEN and paste it in Notepad. ** If this token leaks to the outside, the bot can be abused, so be careful when handling it ** Especially when publishing the source code on GitHub etc., you only have to put the token when you use it separately for properties etc.

Creating a project

Now open the long-awaited coding Intellij

Easy to write in Maven or Gradle

Lord makes with Maven

I will rewrite pom for the time being

This time it starts with a batch file, so rewrite it like making an executable jar with a manifest

Dependent library may be Discord4j or JDA, but event processing etc. is a storm of lambda expression etc. I'm going to use a library called JavaCord this time because the dependencies are annoying.

For the time being, the pom with dependencies etc. is like this

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.javacord</groupId>
            <artifactId>javacord</artifactId>
            <version>3.0.5</version>
            <type>pom</type>
        </dependency>
    </dependencies>
    
    <build>
        <defaultGoal>clean package</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <id>default-jar</id>
                        <phase>none</phase>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <finalName>${project.build.finalName}</finalName>
                    <archive>
                        <manifest>
                            <mainClass></mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <appendAssemblyId>false</appendAssemblyId>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>
</project>

Change the basic elements and manifest content to suit your project

The src package also fits that

Bot creation

It's finally the main subject

What kind of bot to make depends on the person, so I will explain only the basics

Get API

Get the API from JavaCord Basically it's like interacting with Discord using this

Use the token you wrote down when creating the bot If you do not publish the source, you can write it directly in the class

Use DiscordApiBuilder

    String token = "My token";
    DiscordApi api = new DiscordApiBuilder().setToken(token).login().join();

If you don't change the language level, you will probably get a red line. Alt + Enter solves it.

Event detection

Just give the api a listener for the event, but on a small scale you can write a lambda If you consider maintainability, you should create another listener class

MessageCreateListener can detect the transmission of messages, which is the heart of the command system. It is easier to use the command system if you make it yourself

     api.addMessageCreateListener(messageCreateEvent -> {
            Message message = messageCreateEvent.getMessage();
            MessageAuthor author = messageCreateEvent.getMessageAuthor();
            if(author.isBotUser()) return;
            message.getChannel().sendMessage("Content of remark:"+message.getContent());
        });

In the above example, if the speaker is not a bot, the statement is repeated. It is written in lambda, but the same is true for MessageCreateListener.

Repeat.java


public class Repeat implements MessageCreateListener {

    @Override
    public void onMessageCreate(MessageCreateEvent messageCreateEvent) {
        Message message = messageCreateEvent.getMessage();
        MessageAuthor author = messageCreateEvent.getMessageAuthor();
        if(author.isBotUser()) return;
        message.getChannel().sendMessage("Content of remark:"+message.getContent());
    }
}
    api.addMessageCreateListener(new Repeat());

This is OK, and all other events can be detected with this.

Send Messege

I have already written it at the event, but you can send it by getting the Channel you want to send and using sendMessage ()

The rest is up to you

To be honest, if you know the Event processing, you can go by yourself If you don't understand, you can solve everything by reading JavaDoc in JavaCord.

Finally

Discord 4j or JDA should be used for voice-related and more advanced operations JavaCord is probably out of development and will not be updated in the future

Then why did you use it! It's just that the API was easy to use. It's a thin article, but thank you for reading

reference

JavaCord https://github.com/Javacord/Javacord JavaDoc https://docs.javacord.org/api/v/3.0.5/overview-summary.html

Postscript

As of July 21, 2020 The Discord API domain has changed recently I'm not sure if this library can't be used, maybe it's okay to pull it from discord4j

Recommended Posts

Java Discord Bot creation
java file creation
java directory creation
How to make a Discord bot (Java)
Eclipse ~ Java project creation ~
[Java] Calculator program creation 1
Java multi-project creation with Gradle
Play Framework 2.6 (Java) development environment creation
Arbitrary string creation code by Java
Java
Java
Easy to make Slack Bot in Java
[Improvement] Learn Java through simple tool creation