我正在使用Discord api,并且试图让我的Java机器人根据发送到通道的内容输出一条消息。但是由于某种原因,该机器人似乎正在遍历if / else语句的两个分支,而我认为这是不可能的。我在课堂上的代码是:
import java.util.ArrayList;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
//channel.sendMessage("Pong ").queue();
//Default Message sender. ^
public class EListener extends ListenerAdapter
{
ArrayList<String> list = new ArrayList<String>();
public void onMessageReceived(MessageReceivedEvent event)
{
if (event.getAuthor().isBot()) return; //This helps the bot ignore other bots who send messages that would interfere for some reason. If it is a bot, returns to start.
Message message = event.getMessage(); //Sets the message equal to the variable type 'Message' so it can be modified within the program.
String content = message.getContentRaw(); //Gets the raw content of the message and sets it equal to a string (best way to convert types Message to String).
MessageChannel channel = event.getChannel(); //Gets the channel the message was sent in (useful for sending error messages).
if(content.startsWith("!suspend"))//Pretty self explanatory. Enters the loop if the message begins with !suspend.
{
String[] spliced = content.split("\\s+"); //Splits the message into an array based on the spaces in the message.
TextChannel textChannel = event.getGuild().getTextChannelsByName("ranked-ms_punishments",true).get(0); //If there is a channel called ranked-ms_punishments which there should be set the value of it equal to the variable.
int length = spliced.length;//Sets 'length' equal to the number of items in the array.
if(length == 3)//If the number of items in the array is 3 then...
{
if(spliced[1].startsWith("<"))
{
textChannel.sendMessage("nab").queue();//Sends the message in the quotations.
}
}else {
channel.sendMessage("Please use the following format for suspending a user: '!suspend' <@user> (length)").queue(); //If length doesn't equal 3 then it sends the message in quotations.
}
}
}
}
如您所见,如果满足循环中的要求(数组的长度等于3),并且如果不满足这些要求,则机器人应根据代码将“ nab”输出到指定的不和谐通道。遇到错误,它会向用户输出错误消息。由于某种原因,无论我是否满足要求,这两种情况都在发生。我的代码中是否有某些错误导致其执行此操作?
编辑:实际上,只有当我不满足要求时,这两种方法都会同时执行,但是当我这样做时,它不会发送错误消息。
答案 0 :(得分:1)
我认为onMessageReceived(MessageReceivedEvent event)方法运行两次,在一个长度匹配的调用条件匹配,而在另一个调用条件不匹配的情况下,则同时获得两个输出。