home · contact · privacy
Split log directory.
[plomlombot-irc.git] / plomlombot.py
1 #!/usr/bin/python3
2
3 import argparse
4 import socket
5 import datetime
6 import select
7 import time
8 import re
9 import requests
10 import bs4
11 import random
12 import hashlib
13 import os
14 import plomsearch
15 import irclog
16
17 # Defaults, may be overwritten by command line arguments.
18 SERVER = "irc.freenode.net"
19 PORT = 6667
20 TIMEOUT = 240
21 USERNAME = "plomlombot"
22 NICKNAME = USERNAME
23 TWTFILE = ""
24 DBDIR = os.path.expanduser("~/plomlombot_db")
25
26
27 class ExceptionForRestart(Exception):
28     pass
29
30
31 class Line:
32
33     def __init__(self, line):
34         self.line = line
35         self.tokens = line.split(" ")
36         self.sender = ""
37         if self.tokens[0][0] == ":":
38             for rune in self.tokens[0][1:]:
39                 if rune in {"!", "@"}:
40                     break
41                 self.sender += rune
42         self.receiver = ""
43         if len(self.tokens) > 2:
44             for rune in self.tokens[2]:
45                 if rune in {"!", "@"}:
46                     break
47                 if rune != ":":
48                     self.receiver += rune
49
50
51 class IO:
52
53     def __init__(self, server, port, timeout):
54         self.timeout = timeout
55         self.socket = socket.socket()
56         self.socket.connect((server, port))
57         self.socket.setblocking(0)
58         self.line_buffer = []
59         self.rune_buffer = ""
60         self.last_pong = time.time()
61         self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
62
63     def _pingtest(self, send_ping=True):
64         if self.last_pong + self.timeout < time.time():
65             print("SERVER NOT ANSWERING")
66             raise ExceptionForRestart
67         if send_ping:
68             self.send_line("PING " + self.servername)
69
70     def send_line(self, msg):
71         msg = msg.replace("\r", " ")
72         msg = msg.replace("\n", " ")
73         if len(msg.encode("utf-8")) > 510:
74             print("NOT SENT LINE TO SERVER (too long): " + msg)
75         print("LINE TO SERVER: "
76               + str(datetime.datetime.now()) + ": " + msg)
77         msg = msg + "\r\n"
78         msg_len = len(msg)
79         total_sent_len = 0
80         while total_sent_len < msg_len:
81             sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
82             if sent_len == 0:
83                 print("SOCKET CONNECTION BROKEN")
84                 raise ExceptionForRestart
85             total_sent_len += sent_len
86
87     def _recv_line_wrapped(self, send_ping=True):
88         if len(self.line_buffer) > 0:
89             return self.line_buffer.pop(0)
90         while True:
91             ready = select.select([self.socket], [], [], int(self.timeout / 2))
92             if not ready[0]:
93                 self._pingtest(send_ping)
94                 return None
95             self.last_pong = time.time()
96             received_bytes = self.socket.recv(1024)
97             try:
98                 received_runes = received_bytes.decode("UTF-8")
99             except UnicodeDecodeError:
100                 received_runes = received_bytes.decode("latin1")
101             if len(received_runes) == 0:
102                 print("SOCKET CONNECTION BROKEN")
103                 raise ExceptionForRestart
104             self.rune_buffer += received_runes
105             lines_split = str.split(self.rune_buffer, "\r\n")
106             self.line_buffer += lines_split[:-1]
107             self.rune_buffer = lines_split[-1]
108             if len(self.line_buffer) > 0:
109                 return self.line_buffer.pop(0)
110
111     def recv_line(self, send_ping=True):
112         line = self._recv_line_wrapped(send_ping)
113         if line:
114             print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
115                   line)
116         return line
117
118
119 def handle_command(command, argument, notice, target, session):
120
121     def addquote():
122         if not os.access(session.quotesfile, os.F_OK):
123             quotesfile = open(session.quotesfile, "w")
124             quotesfile.write("QUOTES FOR " + target + ":\n")
125             quotesfile.close()
126         quotesfile = open(session.quotesfile, "a")
127         quotesfile.write(argument + "\n")
128         quotesfile.close()
129         quotesfile = open(session.quotesfile, "r")
130         lines = quotesfile.readlines()
131         quotesfile.close()
132         notice("ADDED QUOTE #" + str(len(lines) - 1))
133
134     def quote():
135
136         def help():
137             notice("SYNTAX: !quote [int] OR !quote search QUERY")
138             notice("QUERY may be a boolean grouping of quoted or unquoted " +
139                    "search terms, examples:")
140             notice("!quote search foo")
141             notice("!quote search foo AND (bar OR NOT baz)")
142             notice("!quote search \"foo\\\"bar\" AND ('NOT\"' AND \"'foo'\"" +
143                    " OR 'bar\\'baz')")
144
145         if "" == argument:
146             tokens = []
147         else:
148             tokens = argument.split(" ")
149         if (len(tokens) > 1 and tokens[0] != "search") or \
150             (len(tokens) == 1 and
151                 (tokens[0] == "search" or not tokens[0].isdigit())):
152             help()
153             return
154         if not os.access(session.quotesfile, os.F_OK):
155             notice("NO QUOTES AVAILABLE")
156             return
157         quotesfile = open(session.quotesfile, "r")
158         lines = quotesfile.readlines()
159         quotesfile.close()
160         lines = lines[1:]
161         if len(tokens) == 1:
162             i = int(tokens[0])
163             if i == 0 or i > len(lines):
164                 notice("THERE'S NO QUOTE OF THAT INDEX")
165                 return
166             i = i - 1
167         elif len(tokens) > 1:
168             query = str.join(" ", tokens[1:])
169             try:
170                 results = plomsearch.search(query, lines)
171             except plomsearch.LogicParserError as err:
172                 notice("FAILED QUERY PARSING: " + str(err))
173                 return
174             if len(results) == 0:
175                 notice("NO QUOTES MATCHING QUERY")
176             else:
177                 for result in results:
178                     notice("QUOTE #" + str(result[0] + 1) + " : "
179                            + result[1][-1])
180             return
181         else:
182             i = random.randrange(len(lines))
183         notice("QUOTE #" + str(i + 1) + ": " + lines[i][:-1])
184
185     def markov():
186         from random import choice, shuffle
187         select_length = 2
188         selections = []
189
190         def markov(snippet):
191             usable_selections = []
192             for i in range(select_length, 0, -1):
193                 for selection in selections:
194                     add = True
195                     for j in range(i):
196                         j += 1
197                         if snippet[-j] != selection[-(j+1)]:
198                             add = False
199                             break
200                     if add:
201                         usable_selections += [selection]
202                 if [] != usable_selections:
203                     break
204             if [] == usable_selections:
205                 usable_selections = selections
206             selection = choice(usable_selections)
207             return selection[select_length]
208
209         if not os.access(session.markovfile, os.F_OK):
210             notice("NOT ENOUGH TEXT TO MARKOV.")
211             return
212
213         # Lowercase incoming lines, ensure they end in a sentence end mark.
214         file = open(session.markovfile, "r")
215         lines = file.readlines()
216         file.close()
217         tokens = []
218         sentence_end_markers = ".!?)("
219         for line in lines:
220             line = line.lower().replace("\n", "")
221             if line[-1] not in sentence_end_markers:
222                 line += "."
223             tokens += line.split()
224         if len(tokens) <= select_length:
225             notice("NOT ENOUGH TEXT TO MARKOV.")
226             return
227
228         # Replace URLs with escape string for now, so that the Markov selector
229         # won't see them as different strings. Stash replaced URLs in urls.
230         urls = []
231         url_escape = "\nURL"
232         url_starts = ["http://", "https://", "<http://", "<https://"]
233         for i in range(len(tokens)):
234             for url_start in url_starts:
235                 if tokens[i][:len(url_start)] == url_start:
236                     length = len(tokens[i])
237                     if url_start[0] == "<":
238                         try:
239                             length = tokens[i].index(">") + 1
240                         except ValueError:
241                             pass
242                     urls += [tokens[i][:length]]
243                     tokens[i] = url_escape + tokens[i][length:]
244                     break
245
246         # For each snippet of select_length, use markov() to find continuation
247         # token from selections. Replace present users' names with malkovich.
248         # Start snippets with the beginning of a sentence, if possible.
249         for i in range(len(tokens) - select_length):
250             token_list = []
251             for j in range(select_length + 1):
252                 token_list += [tokens[i + j]]
253             selections += [token_list]
254         snippet = []
255         for i in range(select_length):
256             snippet += [""]
257         shuffle(selections)
258         for i in range(len(selections)):
259             if selections[i][0][-1] in sentence_end_markers:
260                 for i in range(select_length):
261                     snippet[i] = selections[i][i + 1]
262                 break
263         msg = ""
264         malkovich = "malkovich"
265         while 1:
266             new_end = markov(snippet)
267             for name in session.users_in_chan:
268                 if new_end[:len(name)] == name.lower():
269                     new_end = malkovich + new_end[len(name):]
270                     break
271             if len(msg) + len(new_end) > 200:
272                 break
273             msg += new_end + " "
274             for i in range(select_length - 1):
275                 snippet[i] = snippet[i + 1]
276             snippet[select_length - 1] = new_end
277
278         # Replace occurences of url escape string with random choice from urls.
279         while True:
280             index = msg.find(url_escape)
281             if index < 0:
282                 break
283             msg = msg.replace(url_escape, choice(urls), 1)
284
285         # More meaningful ways to randomly end sentences.
286         notice(msg + malkovich + ".")
287
288     def twt():
289         def try_open(mode):
290             try:
291                 twtfile = open(session.twtfile, mode)
292             except (PermissionError, FileNotFoundError) as err:
293                 notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
294                 return None
295             return twtfile
296
297         from datetime import datetime
298         if not os.access(session.twtfile, os.F_OK):
299             twtfile = try_open("w")
300             if None == twtfile:
301                 return
302             twtfile.close()
303         twtfile = try_open("a")
304         if None == twtfile:
305             return
306         twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
307         twtfile.close()
308         notice("WROTE TWT.")
309
310     if "addquote" == command:
311         addquote()
312     elif "quote" == command:
313         quote()
314     elif "markov" == command:
315         markov()
316     elif "twt" == command:
317         twt()
318
319
320 def handle_url(url, notice, show_url=False):
321
322     def mobile_twitter_hack(url):
323         re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
324         re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
325         m = re.search(re1, url)
326         if m and m.group(1) == 'mobile.twitter.com/' \
327                 and m.group(2) == '/status/':
328             m = re.search(re2, url)
329             url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
330             handle_url(url, notice, True)
331             return True
332
333     try:
334         r = requests.get(url, timeout=15)
335     except (requests.exceptions.TooManyRedirects,
336             requests.exceptions.ConnectionError,
337             requests.exceptions.InvalidURL,
338             UnicodeError,
339             requests.exceptions.InvalidSchema) as error:
340         notice("TROUBLE FOLLOWING URL: " + str(error))
341         return
342     if mobile_twitter_hack(url):
343         return
344     title = bs4.BeautifulSoup(r.text, "html5lib").title
345     if title and title.string:
346         prefix = "PAGE TITLE: "
347         if show_url:
348             prefix = "PAGE TITLE FOR <" + url + ">: "
349         notice(prefix + title.string.strip())
350     else:
351         notice("PAGE HAS NO TITLE TAG")
352
353
354 class Session:
355
356     def __init__(self, io, username, nickname, channel, twtfile, dbdir):
357         self.io = io
358         self.nickname = nickname
359         self.username = username
360         self.channel = channel
361         self.users_in_chan = []
362         self.twtfile = twtfile
363         self.dbdir = dbdir
364         self.io.send_line("NICK " + self.nickname)
365         self.io.send_line("USER " + self.username + " 0 * : ")
366         self.io.send_line("JOIN " + self.channel)
367         hash_channel = hashlib.md5(self.channel.encode("utf-8")).hexdigest()
368         self.chandir = self.dbdir + "/" + hash_channel + "/"
369         self.rawlogdir = self.chandir + "raw_logs/"
370         self.logdir = self.chandir + "logs/"
371         if not os.path.exists(self.logdir):
372             os.makedirs(self.logdir)
373         if not os.path.exists(self.rawlogdir):
374             os.makedirs(self.rawlogdir)
375         self.markovfile = self.chandir + "markovfeed"
376         self.quotesfile = self.chandir + "quotes"
377
378     def loop(self):
379
380         def log(line):
381             if type(line) == str:
382                 line = Line(":" + self.nickname + "!~" + self.username +
383                             "@localhost" + " " + line)
384             now = datetime.datetime.utcnow()
385             logfile = open(self.rawlogdir + now.strftime("%Y-%m-%d") + ".txt", "a")
386             form = "%Y-%m-%d %H:%M:%S UTC\t"
387             logfile.write(now.strftime(form) + " " + line.line + "\n")
388             logfile.close()
389             to_log = irclog.format_logline(line, self.channel)
390             if to_log != None:
391                 logfile = open(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a")
392                 logfile.write(now.strftime(form) + " " + to_log + "\n")
393                 logfile.close()
394
395         def handle_privmsg(line):
396
397             def notice(msg):
398                 line = "NOTICE " + target + " :" + msg
399                 self.io.send_line(line)
400                 log(line)
401
402             target = line.sender
403             if line.receiver != self.nickname:
404                 target = line.receiver
405             msg = str.join(" ", line.tokens[3:])[1:]
406             matches = re.findall("(https?://[^\s>]+)", msg)
407             for i in range(len(matches)):
408                 handle_url(matches[i], notice)
409             if "!" == msg[0]:
410                 tokens = msg[1:].split()
411                 argument = str.join(" ", tokens[1:])
412                 handle_command(tokens[0], argument, notice, target, self)
413                 return
414             file = open(self.markovfile, "a")
415             file.write(msg + "\n")
416             file.close()
417
418         while True:
419             line = self.io.recv_line()
420             if not line:
421                 continue
422             line = Line(line)
423             log(line)
424             if len(line.tokens) > 1:
425                 if line.tokens[0] == "PING":
426                     self.io.send_line("PONG " + line.tokens[1])
427                 elif line.tokens[1] == "PRIVMSG":
428                     handle_privmsg(line)
429                 elif line.tokens[1] == "353":
430                     names = line.tokens[5:]
431                     names[0] = names[0][1:]
432                     for i in range(len(names)):
433                         names[i] = names[i].replace("@", "").replace("+", "")
434                     self.users_in_chan += names
435                 elif line.tokens[1] == "JOIN" and line.sender != self.nickname:
436                     self.users_in_chan += [line.sender]
437                 elif line.tokens[1] == "PART":
438                     del(self.users_in_chan[self.users_in_chan.index(line.sender)])
439                 elif line.tokens[1] == "NICK":
440                     del(self.users_in_chan[self.users_in_chan.index(line.sender)])
441                     self.users_in_chan += [line.receiver]
442
443
444 def parse_command_line_arguments():
445     parser = argparse.ArgumentParser()
446     parser.add_argument("-s, --server", action="store", dest="server",
447                         default=SERVER,
448                         help="server or server net to connect to (default: "
449                         + SERVER + ")")
450     parser.add_argument("-p, --port", action="store", dest="port", type=int,
451                         default=PORT, help="port to connect to (default : "
452                         + str(PORT) + ")")
453     parser.add_argument("-w, --wait", action="store", dest="timeout",
454                         type=int, default=TIMEOUT,
455                         help="timeout in seconds after which to attempt " +
456                         "reconnect (default: " + str(TIMEOUT) + ")")
457     parser.add_argument("-u, --username", action="store", dest="username",
458                         default=USERNAME, help="username to use (default: "
459                         + USERNAME + ")")
460     parser.add_argument("-n, --nickname", action="store", dest="nickname",
461                         default=NICKNAME, help="nickname to use (default: "
462                         + NICKNAME + ")")
463     parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
464                         default=TWTFILE, help="twtxt file to use (default: "
465                         + TWTFILE + ")")
466     parser.add_argument("-d, --dbdir", action="store", dest="dbdir",
467                         default=DBDIR, help="directory to store DB files in")
468     parser.add_argument("CHANNEL", action="store", help="channel to join")
469     opts, unknown = parser.parse_known_args()
470     return opts
471
472
473 opts = parse_command_line_arguments()
474 while True:
475     try:
476         io = IO(opts.server, opts.port, opts.timeout)
477         hash_server = hashlib.md5(opts.server.encode("utf-8")).hexdigest()
478         dbdir = opts.dbdir + "/" + hash_server 
479         session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
480             opts.twtfile, dbdir)
481         session.loop()
482     except ExceptionForRestart:
483         io.socket.close()
484         continue