Java Discord机器人保持离线状态

5anewei6  于 2023-05-15  发布在  Java
关注(0)|答案(1)|浏览(235)

我正在尝试使用 Java JDAgradle 创建一个Discord bot。我试图让它上线,但它不工作。我尝试重新生成令牌并创建另一个项目。似乎什么都不管用。我用的是Java 11,没有任何错误。是什么导致了这个问题?
build.gradle:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    jcenter()
}
dependencies {
    compile("net.dv8tion:JDA:4.2.0_168")
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Main.java:

import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;

public class Main {
    public static void main(String args[]) throws Exception{

        JDA api = JDABuilder.createDefault("example").build();

        System.out.println("Hello World");
    }
}

输出:

9:53:30 PM: Executing task...

Starting Gradle Daemon...
Gradle Daemon started in 3 s 785 ms

> Task :help

Welcome to Gradle 6.1.1.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

For troubleshooting, visit https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.1.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 17s
1 actionable task: 1 executed
9:53:57 PM: Task execution finished.
t9aqgxwy

t9aqgxwy1#

首先,您需要创建一个具有默认设置的JDABuilder。这可以通过以下代码来实现:

public class Bot {
    
 public static void main( String[] args ) throws Exception {
     JDA jda = JDABuilder.createDefault("<token from discord>")
            .addEventListeners(new BotListeners())
            .build();
 }
}

如果您尝试切换出通过discord dev portal生成的实际令牌的示例,这可能会使您的bot在线。然后,您可以按如下方式实现EventListener:

// Must extend ListenerAdapter
public class BotListeners extends ListenerAdapter {

@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {

    if (!event.getAuthor().isBot()) {
        
        System.out.println("Hey, I have received a message!")
 }
}

相关问题