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