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