home · contact · privacy
Fix typo.
[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 signal
15 import plomsearch
16 import irclog
17
18 # Defaults, may be overwritten by command line arguments.
19 SERVER = "irc.freenode.net"
20 PORT = 6667
21 TIMEOUT = 240
22 USERNAME = "plomlombot"
23 NICKNAME = USERNAME
24 TWTFILE = ""
25 DBDIR = os.path.expanduser("~/plomlombot_db")
26
27
28 def write_to_file(path, mode, text):
29     f = open(path, mode)
30     f.write(text)
31     f.close()
32
33
34 class ExceptionForRestart(Exception):
35     pass
36
37
38 class Line:
39
40     def __init__(self, line):
41         self.line = line
42         self.tokens = line.split(" ")
43         self.sender = ""
44         if self.tokens[0][0] == ":":
45             for rune in self.tokens[0][1:]:
46                 if rune in {"!", "@"}:
47                     break
48                 self.sender += rune
49         self.receiver = ""
50         if len(self.tokens) > 2:
51             for rune in self.tokens[2]:
52                 if rune in {"!", "@"}:
53                     break
54                 if rune != ":":
55                     self.receiver += rune
56
57
58 class Log:
59
60     def __init__(self, chandir, nickname, username, channel, rmlogs):
61         self.nickname = nickname
62         self.username = username
63         self.channel = channel
64         self.chandir = chandir
65         self.rmlogcycle = rmlogs
66         self.rawlogdir = chandir + "raw_logs/"
67         self.logdir = chandir + "logs/"
68         if not os.path.exists(self.logdir):
69             os.makedirs(self.logdir)
70         if not os.path.exists(self.rawlogdir):
71             os.makedirs(self.rawlogdir)
72
73     def log(self, line, sent=False):
74         identity = ""
75         separator = " > "
76         if sent:
77             separator = " "
78             line = Line("< " + line)
79             line.sender = self.nickname
80             identity = self.username + "@localhost"
81         else:
82             if type(line) == str:
83                 line = Line(line)
84         now = datetime.datetime.utcnow()
85         form = "%Y-%m-%d %H:%M:%S UTC"
86         write_to_file(self.rawlogdir + now.strftime("%Y-%m-%d") + ".txt", "a",
87                       now.strftime(form) + separator + line.line + "\n")
88         to_log = irclog.format_logline(line, self.channel, identity)
89         if to_log != None:
90             write_to_file(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a",
91                           now.strftime(form) + " " + to_log + "\n")
92
93     def rmlogs(self):
94         if self.rmlogcycle > 0:
95             for f in os.listdir(self.logdir):
96                 f = os.path.join(self.logdir, f)
97                 if os.path.isfile(f) and \
98                         os.stat(f).st_mtime < time.time() - self.rmlogcycle:
99                     os.remove(f)
100
101     def separator_line(self):
102         now = datetime.datetime.utcnow()
103         write_to_file(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a",
104                       "-----------------------\n")
105
106
107 class IO:
108
109     def __init__(self, server, port, timeout):
110         self.log = None
111         self.timeout = timeout
112         self.socket = socket.socket()
113         try:
114             self.socket.connect((server, port))
115         except TimeoutError:
116             raise ExceptionForRestart
117         self.socket.setblocking(0)
118         self.line_buffer = []
119         self.rune_buffer = ""
120         self.last_pong = time.time()
121         line = self.recv_line(send_ping=False)
122         if not line or len(line) < 1:
123             raise ExceptionForRestart
124         self.servername = line.split(" ")[0][1:]
125
126     def _pingtest(self, send_ping=True):
127         if self.last_pong + self.timeout < time.time():
128             print("SERVER NOT ANSWERING")
129             raise ExceptionForRestart
130         if send_ping:
131             self.send_line("PING " + self.servername)
132
133     def send_line(self, msg):
134         msg = msg.replace("\r", " ")
135         msg = msg.replace("\n", " ")
136         if len(msg.encode("utf-8")) > 510:
137             print("NOT SENT LINE TO SERVER (too long): " + msg)
138         print("LINE TO SERVER: "
139               + str(datetime.datetime.now()) + ": " + msg)
140         if self.log != None:
141             self.log.log(msg, True)
142         msg = msg + "\r\n"
143         msg_len = len(msg)
144         total_sent_len = 0
145         while total_sent_len < msg_len:
146             sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
147             if sent_len == 0:
148                 print("SOCKET CONNECTION BROKEN")
149                 raise ExceptionForRestart
150             total_sent_len += sent_len
151
152     def _recv_line_wrapped(self, send_ping=True):
153         if len(self.line_buffer) > 0:
154             return self.line_buffer.pop(0)
155         while True:
156             ready = select.select([self.socket], [], [], int(self.timeout / 2))
157             if not ready[0]:
158                 self._pingtest(send_ping)
159                 return None
160             self.last_pong = time.time()
161             received_bytes = self.socket.recv(1024)
162             try:
163                 received_runes = received_bytes.decode("UTF-8")
164             except UnicodeDecodeError:
165                 received_runes = received_bytes.decode("latin1")
166             if len(received_runes) == 0:
167                 print("SOCKET CONNECTION BROKEN")
168                 raise ExceptionForRestart
169             self.rune_buffer += received_runes
170             lines_split = str.split(self.rune_buffer, "\r\n")
171             self.line_buffer += lines_split[:-1]
172             self.rune_buffer = lines_split[-1]
173             if len(self.line_buffer) > 0:
174                 return self.line_buffer.pop(0)
175
176     def recv_line(self, send_ping=True):
177         line = self._recv_line_wrapped(send_ping)
178         if line:
179             if self.log != None:
180                 self.log.log(line)
181             print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
182                   line)
183         return line
184
185
186 def handle_command(command, argument, notice, target, session):
187
188     def addquote():
189         if not os.access(session.quotesfile, os.F_OK):
190             write_to_file(session.quotesfile, "w",
191                           "QUOTES FOR " + target + ":\n")
192         write_to_file(session.quotesfile, "a", argument + "\n")
193         quotesfile = open(session.quotesfile, "r")
194         lines = quotesfile.readlines()
195         quotesfile.close()
196         notice("added quote #" + str(len(lines) - 1))
197
198     def quote():
199
200         def help():
201             notice("syntax: !quote [int] OR !quote search QUERY")
202             notice("QUERY may be a boolean grouping of quoted or unquoted " +
203                    "search terms, examples:")
204             notice("!quote search foo")
205             notice("!quote search foo AND (bar OR NOT baz)")
206             notice("!quote search \"foo\\\"bar\" AND ('NOT\"' AND \"'foo'\"" +
207                    " OR 'bar\\'baz')")
208
209         if "" == argument:
210             tokens = []
211         else:
212             tokens = argument.split(" ")
213         if (len(tokens) > 1 and tokens[0] != "search") or \
214             (len(tokens) == 1 and
215                 (tokens[0] == "search" or not tokens[0].isdigit())):
216             help()
217             return
218         if not os.access(session.quotesfile, os.F_OK):
219             notice("no quotes available")
220             return
221         quotesfile = open(session.quotesfile, "r")
222         lines = quotesfile.readlines()
223         quotesfile.close()
224         lines = lines[1:]
225         if len(tokens) == 1:
226             i = int(tokens[0])
227             if i == 0 or i > len(lines):
228                 notice("there's no quote of that index")
229                 return
230             i = i - 1
231         elif len(tokens) > 1:
232             query = str.join(" ", tokens[1:])
233             try:
234                 results = plomsearch.search(query, lines)
235             except plomsearch.LogicParserError as err:
236                 notice("failed query parsing: " + str(err))
237                 return
238             if len(results) == 0:
239                 notice("no quotes matching query")
240             else:
241                 if len(results) > 3:
242                     notice("showing 3 of " + str(len(results)) + " quotes")
243                 for result in results[:3]:
244                     notice("quote #" + str(result[0] + 1) + ": "
245                            + result[1][:-1])
246             return
247         else:
248             i = random.randrange(len(lines))
249         notice("quote #" + str(i + 1) + ": " + lines[i][:-1])
250
251     def markov():
252
253         def help():
254             notice("syntax: !markov [integer from 1 to infinite]")
255
256         def markov(snippet):
257             usable_selections = []
258             for i in range(select_length, 0, -1):
259                 for selection in selections:
260                     add = True
261                     for j in range(i):
262                         j += 1
263                         if snippet[-j] != selection[-(j+1)]:
264                             add = False
265                             break
266                     if add:
267                         usable_selections += [selection]
268                 if [] != usable_selections:
269                     break
270             if [] == usable_selections:
271                 usable_selections = selections
272             selection = choice(usable_selections)
273             return selection[select_length]
274
275         if "" == argument:
276             tokens = []
277         else:
278             tokens = argument.split(" ")
279         if (len(tokens) > 1 or (len(tokens) == 1 and not tokens[0].isdigit())):
280             help()
281             return
282
283         from random import choice, shuffle
284         select_length = 2
285         if len(tokens) == 1:
286             n = int(tokens[0])
287             if n > 0:
288                 select_length = n
289             else:
290                 notice("bad value, using default: " + str(select_length))
291         selections = []
292
293         if not os.access(session.markovfile, os.F_OK):
294             notice("not enough text to markov for selection length")
295             return
296
297         # Lowercase incoming lines, ensure they end in a sentence end mark.
298         file = open(session.markovfile, "r")
299         lines = file.readlines()
300         file.close()
301         tokens = []
302         sentence_end_markers = ".!?)("
303         for line in lines:
304             line = line.lower().replace("\n", "")
305             if line[-1] not in sentence_end_markers:
306                 line += "."
307             tokens += line.split()
308         if len(tokens) - 1 <= select_length:
309             notice("not enough text to markov")
310             return
311
312         # Replace URLs with escape string for now, so that the Markov selector
313         # won't see them as different strings. Stash replaced URLs in urls.
314         urls = []
315         url_escape = "\nURL"
316         url_starts = ["http://", "https://", "<http://", "<https://"]
317         for i in range(len(tokens)):
318             for url_start in url_starts:
319                 if tokens[i][:len(url_start)] == url_start:
320                     length = len(tokens[i])
321                     if url_start[0] == "<":
322                         try:
323                             length = tokens[i].index(">") + 1
324                         except ValueError:
325                             pass
326                     urls += [tokens[i][:length]]
327                     tokens[i] = url_escape + tokens[i][length:]
328                     break
329
330         # For each snippet of select_length, use markov() to find continuation
331         # token from selections. Replace present users' names with malkovich.
332         # Start snippets with the beginning of a sentence, if possible.
333         for i in range(len(tokens) - select_length):
334             token_list = []
335             for j in range(select_length + 1):
336                 token_list += [tokens[i + j]]
337             selections += [token_list]
338         snippet = []
339         for i in range(select_length):
340             snippet += [""]
341         shuffle(selections)
342         for i in range(len(selections)):
343             if selections[i][0][-1] in sentence_end_markers:
344                 for j in range(select_length):
345                     snippet[j] = selections[j][j + 1]
346                 break
347         msg = ""
348         malkovich = "malkovich"
349         while 1:
350             new_end = markov(snippet)
351             for name in session.users_in_chan:
352                 if new_end[:len(name)] == name.lower():
353                     new_end = malkovich + new_end[len(name):]
354                     break
355             if len(msg) + len(new_end) > 200:
356                 break
357             msg += new_end + " "
358             for i in range(select_length - 1):
359                 snippet[i] = snippet[i + 1]
360             snippet[select_length - 1] = new_end
361
362         # Replace occurences of url escape string with random choice from urls.
363         while True:
364             index = msg.find(url_escape)
365             if index < 0:
366                 break
367             msg = msg.replace(url_escape, choice(urls), 1)
368
369         # More meaningful ways to randomly end sentences.
370         notice(msg + malkovich + ".")
371
372     def twt():
373         def try_open(mode):
374             try:
375                 twtfile = open(session.twtfile, mode)
376             except (PermissionError, FileNotFoundError) as err:
377                 notice("can't access or create twt file: " + str(err))
378                 return None
379             return twtfile
380
381         from datetime import datetime
382         if not os.access(session.twtfile, os.F_OK):
383             twtfile = try_open("w")
384             if None == twtfile:
385                 return
386             twtfile.close()
387         twtfile = try_open("a")
388         if None == twtfile:
389             return
390         twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
391         twtfile.close()
392         notice("wrote twt.")
393
394     if "addquote" == command:
395         addquote()
396     elif "quote" == command:
397         quote()
398     elif "markov" == command:
399         markov()
400     elif "twt" == command:
401         twt()
402
403
404 def handle_url(url, notice, show_url=False):
405
406     def mobile_twitter_hack(url):
407         re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
408         re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
409         m = re.search(re1, url)
410         if m and m.group(1) == 'mobile.twitter.com/' \
411                 and m.group(2) == '/status/':
412             m = re.search(re2, url)
413             url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
414             handle_url(url, notice, True)
415             return True
416
417     class TimeOut(Exception):
418         pass
419
420     def timeout_handler(ignore1, ignore2):
421         raise TimeOut("timeout")
422
423     signal.signal(signal.SIGALRM, timeout_handler)
424     signal.alarm(15)
425     try:
426         r = requests.get(url, headers = {'User-Agent': 'plomlombot'}, stream=True)
427         r.raw.decode_content = True
428         text = r.raw.read(10000000+1)
429         if len(text) > 10000000:
430             raise ValueError('Too large a response')
431     except (requests.exceptions.TooManyRedirects,
432             requests.exceptions.ConnectionError,
433             requests.exceptions.InvalidURL,
434             TimeOut,
435             UnicodeError,
436             ValueError,
437             requests.exceptions.InvalidSchema) as error:
438         signal.alarm(0)
439         notice("trouble following url: " + str(error))
440         return False
441     signal.alarm(0)
442     if mobile_twitter_hack(url):
443         return True
444     title = bs4.BeautifulSoup(text, "html5lib").title
445     if title and title.string:
446         prefix = "page title: "
447         if show_url:
448             prefix = "page title for <" + url + ">: "
449         notice(prefix + title.string.strip())
450     else:
451         notice("page has no title tag")
452     return True
453
454
455 class Session:
456
457     def __init__(self, io, username, nickname, channel, twtfile, dbdir, rmlogs,
458                  markov_input):
459         self.io = io
460         self.nickname = nickname
461         self.users_in_chan = []
462         self.twtfile = twtfile
463         hash_channel = hashlib.md5(channel.encode("utf-8")).hexdigest()
464         chandir = dbdir + "/" + hash_channel + "/"
465         self.markov_input = markov_input
466         self.markovfile = chandir + "markovfeed"
467         self.quotesfile = chandir + "quotes"
468         self.log = Log(chandir, self.nickname, username, channel, rmlogs)
469         self.io.send_line("NICK " + self.nickname)
470         self.io.send_line("USER " + username + " 0 * : ")
471         self.io.send_line("JOIN " + channel)
472         self.io.log = self.log
473         self.log.separator_line()
474
475     def loop(self):
476
477         def handle_privmsg(line):
478
479             def notice(msg):
480                 line = "NOTICE " + target + " :" + msg
481                 self.io.send_line(line)
482
483             target = line.sender
484             if line.receiver != self.nickname:
485                 target = line.receiver
486             msg = str.join(" ", line.tokens[3:])[1:]
487             matches = re.findall("(https?://[^\s>]+)", msg)
488             url_count = 0
489             for i in range(len(matches)):
490                 if handle_url(matches[i], notice):
491                     url_count += 1
492                     if url_count == 3:
493                         notice("maximum number of urls to parse per message "
494                                "reached")
495                         break
496             if "!" == msg[0] and len(msg) > 1:
497                 tokens = msg[1:].split()
498                 argument = str.join(" ", tokens[1:])
499                 handle_command(tokens[0], argument, notice, target, self)
500                 return
501             if self.markov_input:
502                 write_to_file(self.markovfile, "a", msg + "\n")
503
504         while True:
505             self.log.rmlogs()
506             line = self.io.recv_line()
507             if not line:
508                 continue
509             line = Line(line)
510             if len(line.tokens) > 1:
511                 if line.tokens[0] == "PING":
512                     self.io.send_line("PONG " + line.tokens[1])
513                 elif line.tokens[1] == "PRIVMSG":
514                     handle_privmsg(line)
515                 elif line.tokens[1] == "353":
516                     names = line.tokens[5:]
517                     names[0] = names[0][1:]
518                     for i in range(len(names)):
519                         names[i] = names[i].replace("@", "").replace("+", "")
520                     self.users_in_chan += names
521                 elif line.tokens[1] == "JOIN" and line.sender != self.nickname:
522                     self.users_in_chan += [line.sender]
523                 elif line.tokens[1] == "PART":
524                     del(self.users_in_chan[self.users_in_chan.index(line.sender)])
525                 elif line.tokens[1] == "NICK":
526                     del(self.users_in_chan[self.users_in_chan.index(line.sender)])
527                     self.users_in_chan += [line.receiver]
528
529
530 def parse_command_line_arguments():
531     parser = argparse.ArgumentParser()
532     parser.add_argument("-s, --server", action="store", dest="server",
533                         default=SERVER,
534                         help="server or server net to connect to (default: "
535                         + SERVER + ")")
536     parser.add_argument("-p, --port", action="store", dest="port", type=int,
537                         default=PORT, help="port to connect to (default : "
538                         + str(PORT) + ")")
539     parser.add_argument("-w, --wait", action="store", dest="timeout",
540                         type=int, default=TIMEOUT,
541                         help="timeout in seconds after which to attempt "
542                         "reconnect (default: " + str(TIMEOUT) + ")")
543     parser.add_argument("-u, --username", action="store", dest="username",
544                         default=USERNAME, help="username to use (default: "
545                         + USERNAME + ")")
546     parser.add_argument("-n, --nickname", action="store", dest="nickname",
547                         default=NICKNAME, help="nickname to use (default: "
548                         + NICKNAME + ")")
549     parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
550                         default=TWTFILE, help="twtxt file to use (default: "
551                         + TWTFILE + ")")
552     parser.add_argument("-d, --dbdir", action="store", dest="dbdir",
553                         default=DBDIR, help="directory to store DB files in")
554     parser.add_argument("-r, --rmlogs", action="store", dest="rmlogs",
555                         type=int, default=0,
556                         help="maximum age in seconds for logfiles in logs/ "
557                         "(0 means: never delete, and is default)")
558     parser.add_argument("-m, --markov_store", action="store_true",
559                         dest="markov_store",
560                         help="log channel discussions for !markov input")
561     parser.add_argument("CHANNEL", action="store", help="channel to join")
562     opts, unknown = parser.parse_known_args()
563     return opts
564
565
566 opts = parse_command_line_arguments()
567 while True:
568     try:
569         io = IO(opts.server, opts.port, opts.timeout)
570         hash_server = hashlib.md5(opts.server.encode("utf-8")).hexdigest()
571         dbdir = opts.dbdir + "/" + hash_server
572         session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
573                           opts.twtfile, dbdir, opts.rmlogs, opts.markov_store)
574         session.loop()
575     except ExceptionForRestart:
576         io.socket.close()
577         continue