#!/usr/bin/env python3 from sys import argv import re import requests as rq from lxml import html from subprocess import Popen, PIPE if len(argv) != 2: print('Usage:', argv[0], '#channel') exit(1) chan = argv[1] def cmd(args): proc = Popen(args, stdout=PIPE) while True: line = proc.stdout.readline() if line: try: yield str(line[:-1], 'utf-8', 'ignore') except: pass else: break fdir = '/home/zgrep/offtopiabday/irc.freenode.net/' + chan fin = fdir + '/in' fout = fdir + '/out' def irc(): for line in cmd(['tail', '-n', '0', '-f', fout]): date, time, nick, line = line.split(' ', 3) print(line) m = re.match(r'(?i)((happy|hate)bot[:,]\s+ichi|ハピロボット[:,])\s(.+)', line) if m: q = m.group(3) print('Matched!', q) r = get(q) print('Result!', r) with open(fin, 'w') as fh: fh.write(r + '\n') omitnum = 3 def ichi(q, extra=False): r = rq.get('http://ichi.moe/cl/qr/', params={'q': q}) if r.status_code != 200: return 'Non-200 status code. Bug zgrep.' t = html.fromstring(r.content) ichi = ''.join(t.xpath('//span[@class="ds-text"]//text()')) more = '' if extra: e = t.xpath('//span[@class="gloss-desc"]//text()') more = ' - '.join(e[:omitnum]) if len(e) > omitnum: more += ' - \x1dmore omitted\x0f' if more: more = ' (' + more + ')' return '"' + ichi + '"' + more def kanji(q): r = rq.get('http://ichi.moe/cl/kanji/', params={'q': q}) if r.status_code != 200: return None if 'No kanji found' in r.text: return None t = html.fromstring(r.content) return 'Not yet implemented.' def get(q): if len(q) == 1: # k = kanji(q) # if k: return k return ichi(q, True) return ichi(q) irc()