java - Discord bot 在 if/else 语句中通过两条路径?
问题描述
我正在使用 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”输出到指定的不和谐通道,如果不满足这些要求,它向用户输出错误消息。出于某种原因,无论我是否符合要求,这两件事都会发生。我的代码中是否有一些错误导致它这样做?
编辑:它实际上只在我不符合要求时才做,但当我做时它不会发送错误消息。
解决方案
我认为方法 onMessageReceived(MessageReceivedEvent event) 运行了两次,一个长度的调用条件匹配,另一个调用条件不匹配,所以你得到了两个输出。
推荐阅读
- symfony - Symfony 自动装配事件监听器
- java - 为什么我不能在 j_spring_security_check 页面上创建“链接”?
- django - 用聚合连接 DJANGO 中的两个表
- c# - 关于单元测试的问题
- reactjs - socket.io 反应 heroku 405
- python - 在Python中将具有重复键的嵌套JSON文件转换为数据框
- javascript - 加载/卸载 HTML5 时还存在 iOS Safari 内存泄漏
- swift - Swift DispatchQueue concurrentPerform OpenGL 并行渲染
- c++ - 模板函数在 VS 2015 中给出错误
- c++ - 关于初始化指向指针的引用的问题