18 # Defaults, may be overwritten by command line arguments.
19 SERVER = "irc.freenode.net"
22 USERNAME = "plomlombot"
25 DBDIR = os.path.expanduser("~/plomlombot_db")
28 def write_to_file(path, mode, text):
34 class ExceptionForRestart(Exception):
40 def __init__(self, line):
42 self.tokens = line.split(" ")
44 if self.tokens[0][0] == ":":
45 for rune in self.tokens[0][1:]:
46 if rune in {"!", "@"}:
50 if len(self.tokens) > 2:
51 for rune in self.tokens[2]:
52 if rune in {"!", "@"}:
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)
73 def log(self, line, sent=False):
78 line = Line("< " + line)
79 line.sender = self.nickname
80 identity = self.username + "@localhost"
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)
90 write_to_file(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a",
91 now.strftime(form) + " " + to_log + "\n")
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:
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")
109 def __init__(self, server, port, timeout):
111 self.timeout = timeout
112 self.socket = socket.socket()
114 self.socket.connect((server, port))
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:]
126 def _pingtest(self, send_ping=True):
127 if self.last_pong + self.timeout < time.time():
128 print("SERVER NOT ANSWERING")
129 raise ExceptionForRestart
131 self.send_line("PING " + self.servername)
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)
141 self.log.log(msg, True)
145 while total_sent_len < msg_len:
146 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
148 print("SOCKET CONNECTION BROKEN")
149 raise ExceptionForRestart
150 total_sent_len += sent_len
152 def _recv_line_wrapped(self, send_ping=True):
153 if len(self.line_buffer) > 0:
154 return self.line_buffer.pop(0)
156 ready = select.select([self.socket], [], [], int(self.timeout / 2))
158 self._pingtest(send_ping)
160 self.last_pong = time.time()
161 received_bytes = self.socket.recv(1024)
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)
176 def recv_line(self, send_ping=True):
177 line = self._recv_line_wrapped(send_ping)
181 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
186 def handle_command(command, argument, notice, target, session):
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()
196 notice("added quote #" + str(len(lines) - 1))
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'\"" +
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())):
218 if not os.access(session.quotesfile, os.F_OK):
219 notice("no quotes available")
221 quotesfile = open(session.quotesfile, "r")
222 lines = quotesfile.readlines()
227 if i == 0 or i > len(lines):
228 notice("there's no quote of that index")
231 elif len(tokens) > 1:
232 query = str.join(" ", tokens[1:])
234 results = plomsearch.search(query, lines)
235 except plomsearch.LogicParserError as err:
236 notice("failed query parsing: " + str(err))
238 if len(results) == 0:
239 notice("no quotes matching query")
242 notice("showing 3 of " + str(len(results)) + " quotes")
243 for result in results[:3]:
244 notice("quote #" + str(result[0] + 1) + ": "
248 i = random.randrange(len(lines))
249 notice("quote #" + str(i + 1) + ": " + lines[i][:-1])
254 notice("syntax: !markov [integer from 1 to infinite]")
257 usable_selections = []
258 for i in range(select_length, 0, -1):
259 for selection in selections:
263 if snippet[-j] != selection[-(j+1)]:
267 usable_selections += [selection]
268 if [] != usable_selections:
270 if [] == usable_selections:
271 usable_selections = selections
272 selection = choice(usable_selections)
273 return selection[select_length]
278 tokens = argument.split(" ")
279 if (len(tokens) > 1 or (len(tokens) == 1 and not tokens[0].isdigit())):
283 from random import choice, shuffle
290 notice("bad value, using default: " + str(select_length))
293 if not os.access(session.markovfile, os.F_OK):
294 notice("not enough text to markov for selection length")
297 # Lowercase incoming lines, ensure they end in a sentence end mark.
298 file = open(session.markovfile, "r")
299 lines = file.readlines()
302 sentence_end_markers = ".!?)("
304 line = line.lower().replace("\n", "")
305 if line[-1] not in sentence_end_markers:
307 tokens += line.split()
308 if len(tokens) - 1 <= select_length:
309 notice("not enough text to markov")
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.
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] == "<":
323 length = tokens[i].index(">") + 1
326 urls += [tokens[i][:length]]
327 tokens[i] = url_escape + tokens[i][length:]
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):
335 for j in range(select_length + 1):
336 token_list += [tokens[i + j]]
337 selections += [token_list]
339 for i in range(select_length):
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]
348 malkovich = "malkovich"
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):]
355 if len(msg) + len(new_end) > 200:
358 for i in range(select_length - 1):
359 snippet[i] = snippet[i + 1]
360 snippet[select_length - 1] = new_end
362 # Replace occurences of url escape string with random choice from urls.
364 index = msg.find(url_escape)
367 msg = msg.replace(url_escape, choice(urls), 1)
369 # More meaningful ways to randomly end sentences.
370 notice(msg + malkovich + ".")
375 twtfile = open(session.twtfile, mode)
376 except (PermissionError, FileNotFoundError) as err:
377 notice("can't access or create twt file: " + str(err))
381 from datetime import datetime
382 if not os.access(session.twtfile, os.F_OK):
383 twtfile = try_open("w")
387 twtfile = try_open("a")
390 twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
394 if "addquote" == command:
396 elif "quote" == command:
398 elif "markov" == command:
400 elif "twt" == command:
404 def handle_url(url, notice, show_url=False):
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)
417 class TimeOut(Exception):
420 def timeout_handler(ignore1, ignore2):
421 raise TimeOut("timeout")
423 signal.signal(signal.SIGALRM, timeout_handler)
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,
437 requests.exceptions.InvalidSchema) as error:
439 notice("trouble following url: " + str(error))
442 if mobile_twitter_hack(url):
444 title = bs4.BeautifulSoup(text, "html5lib").title
445 if title and title.string:
446 prefix = "page title: "
448 prefix = "page title for <" + url + ">: "
449 notice(prefix + title.string.strip())
451 notice("page has no title tag")
457 def __init__(self, io, username, nickname, channel, twtfile, dbdir, rmlogs,
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()
477 def handle_privmsg(line):
480 line = "NOTICE " + target + " :" + msg
481 self.io.send_line(line)
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)
489 for i in range(len(matches)):
490 if handle_url(matches[i], notice):
493 notice("maximum number of urls to parse per message "
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)
501 if self.markov_input:
502 write_to_file(self.markovfile, "a", msg + "\n")
506 line = self.io.recv_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":
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]
530 def parse_command_line_arguments():
531 parser = argparse.ArgumentParser()
532 parser.add_argument("-s, --server", action="store", dest="server",
534 help="server or server net to connect to (default: "
536 parser.add_argument("-p, --port", action="store", dest="port", type=int,
537 default=PORT, help="port to connect to (default : "
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: "
546 parser.add_argument("-n, --nickname", action="store", dest="nickname",
547 default=NICKNAME, help="nickname to use (default: "
549 parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
550 default=TWTFILE, help="twtxt file to use (default: "
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",
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",
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()
566 opts = parse_command_line_arguments()
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)
575 except ExceptionForRestart: