まらんさんのチラ裏

その日暮らしのおじさん

暇だったのでpython用のIRC制御クラスを作ってみた。

python自体あんま経験がないのと夜中に暇つぶしで作ったものなのでバグだらけだったら直してください。
botとか作るのに便利そうな作りにしたつもり。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket, string

class IRCClient:
    def __init__(self, debug):
        self.debug = debug

    def dlog(self, text):
        if self.debug != 0:
            print("%s" % unicode(text, 'iso-2022-jp'))

    def connect(self, server, port):
        self.con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.con.connect((server, port))
        self.dlog("connected")

    def disconnect(self):
        self.con.send("QUIT\r\n")
        self.dlog("QUIT")
        self.con.close()

    def set_nick(self, nick):
        self.con.send("NICK %s\r\n" % nick)
        self.dlog("NICK %s" % nick)

    def set_userinfo(self, username, hostname, servername, realname):
        self.con.send("USER %s %s %s %s\r\n" % (username, hostname, servername, realname))
        self.dlog("USER %s %s %s %s" % (username, hostname, servername, realname))

    def join(self, channel):
        self.con.send("JOIN %s\r\n" % channel)
        self.dlog("JOIN %s" % channel)

    def leave(self, channel):
        self.con.send("PART %s\r\n" % channel)
        self.dlog("PART %s" % channel)

    def recv(self, byte):
        while (1):
            recv = self.con.recv(byte)
            msg = string.split(recv)
            if msg[0] == "PING":
                irc.send("PONG %s" % msg[1])
            else:
                self.dlog(recv)
                buf = string.split(recv)
                text = {"userinfo":buf[0],
                        "command":buf[1],
                        "channel":buf[2],
                        "message":buf[3]}
                if text["command"] == "PRIVMSG":
                    break
        return text

    def send(self, text):
        self.con.send("%s\r\n" % text)
        self.dlog("%s" % text)

    def send_msg(self, text, channel):
        self.con.send("PRIVMSG %s :%s\r\n" % (channel, text))
        self.dlog("PRIVMSG %s :%s" % (channel, text))

    def send_notice(self, text, channel):
        self.con.send("NOTICE %s :%s\r\n" % (channel, text))
        self.dlog("NOTICE %s :%s" % (channel, text))



if __name__ == '__main__':

    server = 'irc.media.kyoto-u.ac.jp'
    port = 6667
    nick = 'yournick'
    channel = '#hogech'

    irc = IRCClient(1)
    irc.connect(server, port)
    irc.set_nick(nick)
    irc.set_userinfo(nick, nick, nick, nick)
    irc.join(channel)

    irc.send_msg("test", channel)
    irc.send_notice("notice test", channel)

    while (1):
        recv = irc.recv(1024)
        #print recv
        """
        ここらへんに処理を追加するといいんじゃないかな!
        """

    irc.leave(channel)
    irc.disconnect()