【发布时间】:2019-05-28 20:09:14
【问题描述】:
我正在使用 discord api,我正在尝试让我的 java bot 根据发送到频道的内容来输出消息。然而,出于某种原因,机器人似乎正在遍历 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”输出到指定的不和谐通道遇到,它会向用户输出一条错误消息。出于某种原因,无论我是否符合要求,这两件事都会发生。我的代码中是否有一些错误导致它这样做?
编辑:它实际上只在我不符合要求时才同时做,但当我符合要求时它不会发送错误消息。
【问题讨论】: