您好,我目前正在为我的 twitch 流制作一个聊天机器人,但我遇到了一个问题,只有一个命令正在工作,那就是 !song
命令,所有其他命令由于某种原因都无法工作,我检查了我的代码,我找不到任何错误
因此,如果有人发现我的代码有什么问题,请告诉我
import org.jibble.pircbot.*;
import java.io.*;
import java.lang.System.*;
public class HyperBotZ extends PircBot {
// Get song title from Txt file AND return it!
public String getSong() throws Exception {
FileReader file = new FileReader ("H:/Stream_Soft/Snip/Snip.txt");
BufferedReader reader = new BufferedReader(file);
String song = "";
String line = reader.readLine();
while (line != null){
song += line;
line = reader.readLine();
}
return song;
}
// Write info to txt file
// IRC Commands_
public HyperBotZ() {
this.setName("HyperBotZ");
}
public static String ip = "";
public static String dual = "";
public void onMessage(String channel, String sender,
String login, String hostname, String message) {
String owner = "hypergainz";
if (message.startsWith("!songrequest")) {
sendMessage(channel, "Sorry i cant do that atm HyperGainZ need to learn me that, to see the current song use !song :D");
}
if (message.startsWith("!ip ")) {
if(sender.equals(owner))
{
ip = message.split(" ")[1];
sendMessage(channel, " the ip is set to " + ip);
}
} else {
if (message.equalsIgnoreCase("!ip")){
sendMessage(channel, "HyperGainZ is currently playing on : " + ip );
}
}
if (message.startsWith("!dual ")) {
if(sender.equals(owner))
{
dual = message.split(" ")[1];
}
} else {
if (message.equalsIgnoreCase("!dual")){
sendMessage(channel, "http://multitwitch.tv/hypergainz/" + dual );
}
}
if (message.equalsIgnoreCase("!song")){
String song = "";
try {
song = getSong();
} catch (Exception e) { e.printStackTrace(); }
sendMessage(channel, song);
}
}
}
最佳答案
首先,您应该移动您的
String owner = "hypergainz";
进入类变量,因为您不需要每次收到消息时都进行设置。
接下来,一个好主意可能是将消息分解为字符串数组,以便您可以将命令与(可能的)参数分解。您可以通过以下方式做到这一点:
String[] messageArray = message.split(" ");
完成此操作后,您可以更轻松地比较消息的第一部分。
如果您要使用一些命令(最多大约 10 个),我建议使用开关来尝试保持整洁。例如:
public void onMessage(String channel, String sender,
String login, String hostname, String message) {
String[] messageArray = message.split(" ");
String command = messageArray[0];
switch(command){
default:break;
case: "!songrequest":
sendMessage(channel, "Sorry i cant do that atm HyperGainZ need to learn me that, to see the current song use !song :D");
return;
case "!song":
String song = "";
try {
song = getSong();
} catch (Exception e) { e.printStackTrace(); }
sendMessage(channel, song);
return;
}
但是,如果您要制作一个(大型)实用机器人,那么创建您自己的分发方法可能是一个好主意,因为 onMessage(...) 方法很快就会填满。
关于java - PircBot 未在抽搐聊天中发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23741368/