我按照 YouTube 上的视频教程制作了一个 Discord 机器人。我被困在机器人不回复命令的部分。
如果有人知道如何解决这个问题,我将不胜感激。
这是源代码:
Night.java:
package ch.teraflash;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.security.auth.login.LoginException;
import ch.teraflash.listener.CommandListener;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
import net.dv8tion.jda.api.sharding.ShardManager;
public class Night {
public ShardManager shardMan;
public static void main(String[] args) {
try {
new Night();
} catch (LoginException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public Night() throws LoginException, IllegalArgumentException {
DefaultShardManagerBuilder builder = new DefaultShardManagerBuilder();
builder.setToken("XXX");
builder.setActivity(Activity.playing("die Nacht."));
builder.setStatus(OnlineStatus.ONLINE);
builder.addEventListeners(new CommandListener());
shardMan = builder.build();
System.out.println("Bot online.");
shutdown();
}
public void shutdown() {
new Thread(() -> {
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while((line = reader.readLine()) != null) {
if(line.equalsIgnoreCase("exit")) {
if(shardMan != null) {
shardMan.setStatus(OnlineStatus.OFFLINE);
shardMan.shutdown();
System.out.println("Bot offline.");
}
reader.close();
}
else {
System.out.println("Use 'exit' to shutdown.");
}
}
}catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
CommandListener.java:
package ch.teraflash.listener;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class CommandListener extends ListenerAdapter {
@Override
public void onMessageReceived(MessageReceivedEvent event) {
String message = event.getMessage().getContentDisplay();
if(event.isFromType(ChannelType.TEXT)) {
TextChannel channel = event.getTextChannel();
//!tut arg0 arg1 arg 2 ...
if(message.startsWith("!tut ")) {
String[] args = message.substring(5).split(" ");
if(args.length == 1) {
if(args[0].equalsIgnoreCase("Hallo")) {
channel.sendMessage("Hallo " + event.getMember().getAsMention() + "! ").queue();
}
}
}
}
}