2013年12月14日土曜日

簡単なIRC Botの作り方

おはようございます。学部3年のmocchiです。 

僕は、簡単なIRC Botの作り方について紹介したいと思います。

使用する言語は、Javaです。
工科大生は、よくJavaを使う人がいるので、今回はそれでいきます。
そして、簡単に作る為に、PircBotというフレームワークを使用します。
これを使用すると 、IRCのプロトコルを知らなくても作ることができます!

準備
http://www.jibble.org/pircbot.phpからPircBot 1.5.0をダウンロードして、Build Pathに通しておいてください。

作り方
PircBotのクラスを継承したBotクラスを作ります。
package bot;

import org.jibble.pircbot.PircBot;

public class Bot extends PircBot {
}

次にPircBotのonMessageをOverrideをして、発言があった時のイベントを横取りしましょう。

package bot;
import org.jibble.pircbot.PircBot;

public class Bot extends PircBot {
    @Override
    public void onMessage(String channel, String sender, String login,String hostname, String message) {
    }
}

onMdssageの引数にあるString messageが発言された内容なので、それによって反応をするようにします。
sendNotice(String channel,String message)では、channelを指定してmessageを通知します。
sendMessage(String channel,String message)では、channelを指定してmessageを発言します。

package bot;

import org.jibble.pircbot.PircBot;

public class Bot extends PircBot {
    @Override
    public void onMessage(String channel, String sender, String login,String hostname, String message) {
        if (message.matches(".*?mocchi.*")) {
            this.sendMessage(channel, "おはようございます.");
        } else if (message.matches("time")) {
            this.sendNotice(channel, Long.toString(System.currentTimeMillis()));
        }
    }
}

それでは、Botを動かしたいと思います。
動かすためには、IRC サーバと動作させたいchanneI、RC上での名前が必要です。
setName(String name)で名前を渡します
connect(String hostname, int port) で、IRCサーバのアドレスとポートを渡します。
joinChannel(String channel) でchannelに参加します。

以下のコードで、Botが完成しました。
package bot;

import java.io.IOException;

import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.jibble.pircbot.PircBot;

public class Bot extends PircBot {
    @Override   
    public void onMessage(String channel, String sender, String login,String hostname, String message) {
        if (message.matches(".*?mocchi.*")) {
            this.sendMessage(channel, "おはようございます.");
        } else if (message.matches("time")) {
            this.sendNotice(channel, Long.toString(System.currentTimeMillis()));
        }
    }

    public static void main(String[] args) {
        Bot bot = new Bot();
        bot.setName("mocchi_bot");
        try {
            bot.connect("chat.freenode.net", 6667);
            bot.joinChannel("#mocchi");
        } catch (NickAlreadyInUseException e) {
            System.err.println("既に使われているnickです.");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IrcException e) {
            e.printStackTrace();
        }
    }
}

実際にためしたところ






ではでは!

3 件のコメント: