0

您好,我目前正在为我的 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);
    }
}

}

4

1 回答 1

4

首先,您应该移动您的

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(...) 方法很快就会被填满。

于 2014-05-23T06:28:18.043 回答