home · contact · privacy
Minor improvements to markov generator.
[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
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         for line in lines:
200             line = line.lower().replace("\n", "")
201             if line[-1] not in ".!?":
202                 line += "."
203             tokens += line.split()
204         if len(tokens) <= select_length:
205             notice("NOT ENOUGH TEXT TO MARKOV.")
206             return
207
208         # Replace URLs with escape string for now, so that the Markov selector
209         # won't see them as different strings. Stash replaced URLs in urls.
210         urls = []
211         url_escape = "\nURL"
212         url_starts = ["http://", "https://", "<http://", "<https://"]
213         for i in range(len(tokens)):
214             for url_start in url_starts:
215                 if tokens[i][:len(url_start)] == url_start:
216                     length = len(tokens[i])
217                     if url_start[0] == "<":
218                         try:
219                             length = tokens[i].index(">") + 1
220                         except ValueError:
221                             pass
222                     urls += [tokens[i][:length]]
223                     tokens[i] = url_escape + tokens[i][length:]
224                     break
225
226         # For each snippet of select_length, use markov() to find continuation
227         # token from selections. Replace present users' names with malkovich.
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         msg = ""
237         malkovich = "malkovich"
238         while 1:
239             new_end = markov(snippet)
240             for name in session.users_in_chan:
241                 if new_end[:len(name)] == name.lower():
242                     new_end = malkovich + new_end[len(name):]
243                     break
244             if len(msg) + len(new_end) > 200:
245                 break
246             msg += new_end + " "
247             for i in range(select_length - 1):
248                 snippet[i] = snippet[i + 1]
249             snippet[select_length - 1] = new_end
250
251         # Replace occurences of url escape string with random choice from urls.
252         while True:
253             index = msg.find(url_escape)
254             if index < 0:
255                 break
256             msg = msg.replace(url_escape, choice(urls), 1)
257
258         # More meaningful ways to randomly end sentences.
259         notice(msg + malkovich + ".")
260
261     def twt():
262         def try_open(mode):
263             try:
264                 twtfile = open(session.twtfile, mode)
265             except (PermissionError, FileNotFoundError) as err:
266                 notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
267                 return None
268             return twtfile
269
270         from datetime import datetime
271         if not os.access(session.twtfile, os.F_OK):
272             twtfile = try_open("w")
273             if None == twtfile:
274                 return
275             twtfile.close()
276         twtfile = try_open("a")
277         if None == twtfile:
278             return
279         twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
280         twtfile.close()
281         notice("WROTE TWT.")
282
283     if "addquote" == command:
284         addquote()
285     elif "quote" == command:
286         quote()
287     elif "markov" == command:
288         markov()
289     elif "twt" == command:
290         twt()
291
292
293 def handle_url(url, notice, show_url=False):
294
295     def mobile_twitter_hack(url):
296         re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
297         re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
298         m = re.search(re1, url)
299         if m and m.group(1) == 'mobile.twitter.com/' \
300                 and m.group(2) == '/status/':
301             m = re.search(re2, url)
302             url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
303             handle_url(url, notice, True)
304             return True
305
306     try:
307         r = requests.get(url, timeout=15)
308     except (requests.exceptions.TooManyRedirects,
309             requests.exceptions.ConnectionError,
310             requests.exceptions.InvalidURL,
311             UnicodeError,
312             requests.exceptions.InvalidSchema) as error:
313         notice("TROUBLE FOLLOWING URL: " + str(error))
314         return
315     if mobile_twitter_hack(url):
316         return
317     title = bs4.BeautifulSoup(r.text, "html.parser").title
318     if title:
319         prefix = "PAGE TITLE: "
320         if show_url:
321             prefix = "PAGE TITLE FOR <" + url + ">: "
322         notice(prefix + title.string.strip())
323     else:
324         notice("PAGE HAS NO TITLE TAG")
325
326
327 class Session:
328
329     def __init__(self, io, username, nickname, channel, twtfile):
330         self.io = io
331         self.nickname = nickname
332         self.channel = channel
333         self.users_in_chan = []
334         self.twtfile = twtfile
335         self.io.send_line("NICK " + self.nickname)
336         self.io.send_line("USER " + username + " 0 * : ")
337         self.io.send_line("JOIN " + self.channel)
338
339     def loop(self):
340
341         def handle_privmsg(tokens):
342
343             def handle_input(msg, target):
344
345                 def notice(msg):
346                     self.io.send_line("NOTICE " + target + " :" + msg)
347
348                 matches = re.findall("(https?://[^\s>]+)", msg)
349                 for i in range(len(matches)):
350                     handle_url(matches[i], notice)
351                 if "!" == msg[0]:
352                     tokens = msg[1:].split()
353                     argument = str.join(" ", tokens[1:])
354                     handle_command(tokens[0], argument, notice, target, self)
355                     return
356                 hash_string = hashlib.md5(target.encode("utf-8")).hexdigest()
357                 markovfeed_name = "markovfeed_" + hash_string
358                 file = open(markovfeed_name, "a")
359                 file.write(msg + "\n")
360                 file.close()
361
362             sender = ""
363             for rune in tokens[0]:
364                 if rune == "!":
365                     break
366                 if rune != ":":
367                     sender += rune
368             receiver = ""
369             for rune in tokens[2]:
370                 if rune == "!":
371                     break
372                 if rune != ":":
373                     receiver += rune
374             target = sender
375             if receiver != self.nickname:
376                 target = receiver
377             msg = str.join(" ", tokens[3:])[1:]
378             handle_input(msg, target)
379
380         def name_from_join_or_part(tokens):
381             token = tokens[0][1:]
382             index_cut = token.find("@")
383             index_ex = token.find("!")
384             if index_ex > 0 and index_ex < index_cut:
385                 index_cut = index_ex
386             return token[:index_cut]
387
388         while True:
389             line = self.io.recv_line()
390             if not line:
391                 continue
392             tokens = line.split(" ")
393             if len(tokens) > 1:
394                 if tokens[0] == "PING":
395                     self.io.send_line("PONG " + tokens[1])
396                 elif tokens[1] == "PRIVMSG":
397                     handle_privmsg(tokens)
398                 elif tokens[1] == "353":
399                     names = tokens[5:]
400                     names[0] = names[0][1:]
401                     self.users_in_chan += names
402                 elif tokens[1] == "JOIN":
403                     name = name_from_join_or_part(tokens)
404                     if name != self.nickname:
405                         self.users_in_chan += [name]
406                 elif tokens[1] == "PART":
407                     name = name_from_join_or_part(tokens)
408                     del(self.users_in_chan[self.users_in_chan.index(name)])
409
410 def parse_command_line_arguments():
411     parser = argparse.ArgumentParser()
412     parser.add_argument("-s, --server", action="store", dest="server",
413                         default=SERVER,
414                         help="server or server net to connect to (default: "
415                         + SERVER + ")")
416     parser.add_argument("-p, --port", action="store", dest="port", type=int,
417                         default=PORT, help="port to connect to (default : "
418                         + str(PORT) + ")")
419     parser.add_argument("-w, --wait", action="store", dest="timeout",
420                         type=int, default=TIMEOUT,
421                         help="timeout in seconds after which to attempt " +
422                         "reconnect (default: " + str(TIMEOUT) + ")")
423     parser.add_argument("-u, --username", action="store", dest="username",
424                         default=USERNAME, help="username to use (default: "
425                         + USERNAME + ")")
426     parser.add_argument("-n, --nickname", action="store", dest="nickname",
427                         default=NICKNAME, help="nickname to use (default: "
428                         + NICKNAME + ")")
429     parser.add_argument("-t, --twtfile", action="store", dest="twtfile",
430                         default=TWTFILE, help="twtfile to use (default: "
431                         + TWTFILE + ")")
432     parser.add_argument("CHANNEL", action="store", help="channel to join")
433     opts, unknown = parser.parse_known_args()
434     return opts
435
436
437 opts = parse_command_line_arguments()
438 while True:
439     try:
440         io = IO(opts.server, opts.port, opts.timeout)
441         session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
442             opts.twtfile)
443         session.loop()
444     except ExceptionForRestart:
445         io.socket.close()
446         continue