読者です 読者をやめる 読者になる 読者になる

はわわーっ

はわわわわっ

pythonでircのログとるやつ

python

いちおう動くようになったっぽいのでメモ。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import datetime
import http.server
import irc.client
import os
import sys
import threading



class IRCLogger(irc.client.SimpleIRCClient):
    def __init__(self, channel, logroot):
        irc.client.SimpleIRCClient.__init__(self)
        self.channel = channel
        self.logroot = logroot

    def on_welcome(self, c, e):
        c.join(self.channel)

    def on_disconnect(self, c, e):
        sys.exit(0)


    def on_pubmsg(self, c, e):
        nick = irc.client.NickMask(e.source).nick
        message = e.arguments[0]
        entry = "({0:>10s}) {1}".format(nick, message)
        self.log_message(entry)

    on_pubnotice = on_pubmsg

    def on_join(self, c, e):
        nick = irc.client.NickMask(e.source).nick
        entry = "* {0} join {1} ({2})".format(nick, e.target, e.source)
        self.log_message(entry)

    def on_quit(self, c, e):
        nick = irc.client.NickMask(e.source).nick
        entry = "* {0} {1} ({2})".format(nick, e.type, e.arguments[0])
        self.log_message(entry)

    on_part = on_quit

    def on_nick(self, c, e):
        nick = irc.client.NickMask(e.source).nick
        new = e.target
        entry = "* nick: {0} -> {1}".format(nick, new)
        self.log_message(entry)

    def on_topic(self, c, e):
        nick = irc.client.NickMask(e.source).nick
        topic = e.arguments[0]
        entry = "* {0} topic: {1}".format(nick, topic)
        self.log_message(entry)


    def log_message(self, entry):
        logdir = self.logroot + '/' + self.channel
        if not os.path.isdir(logdir):
            os.makedirs(logdir)
        now = datetime.datetime.now()
        logfile = logdir + '/' + now.strftime('%F') + '.txt'
        message = now.strftime('%F %T') + ': ' + entry + '\n'
        with open(logfile, 'a', encoding='utf-8') as f:
            f.write(message)



def start_logger():
    server = os.getenv('IRCLOGD_SERVER')
    channel = os.getenv('IRCLOGD_CHANNEL')
    nick = os.getenv('IRCLOGD_NICK')
    logroot = os.getenv('IRCLOGD_LOGROOT')
    c = IRCLogger(channel, logroot)
    c.connect(server, 6667, nick)
    c.start()

def start_logviewer():
    logroot = os.getenv('IRCLOGD_LOGROOT')
    os.chdir(logroot)
    httpd = http.server.HTTPServer(('', 8086), http.server.SimpleHTTPRequestHandler)
    httpd.serve_forever()

def main():
    logger = threading.Thread(target=start_logger, name='logger')
    logger.start()
    logviewer = threading.Thread(target=start_logviewer, name='logviewer')
    logviewer.start()


if __name__ == '__main__':
    main()