17 # Defaults, may be overwritten by command line arguments.
18 SERVER = "irc.freenode.net"
21 USERNAME = "plomlombot"
24 DBDIR = os.path.expanduser("~/plomlombot_db")
27 class ExceptionForRestart(Exception):
33 def __init__(self, line):
35 self.tokens = line.split(" ")
37 if self.tokens[0][0] == ":":
38 for rune in self.tokens[0][1:]:
39 if rune in {"!", "@"}:
43 if len(self.tokens) > 2:
44 for rune in self.tokens[2]:
45 if rune in {"!", "@"}:
53 def __init__(self, server, port, timeout):
54 self.timeout = timeout
55 self.socket = socket.socket()
56 self.socket.connect((server, port))
57 self.socket.setblocking(0)
60 self.last_pong = time.time()
61 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
63 def _pingtest(self, send_ping=True):
64 if self.last_pong + self.timeout < time.time():
65 print("SERVER NOT ANSWERING")
66 raise ExceptionForRestart
68 self.send_line("PING " + self.servername)
70 def send_line(self, msg):
71 msg = msg.replace("\r", " ")
72 msg = msg.replace("\n", " ")
73 if len(msg.encode("utf-8")) > 510:
74 print("NOT SENT LINE TO SERVER (too long): " + msg)
75 print("LINE TO SERVER: "
76 + str(datetime.datetime.now()) + ": " + msg)
80 while total_sent_len < msg_len:
81 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
83 print("SOCKET CONNECTION BROKEN")
84 raise ExceptionForRestart
85 total_sent_len += sent_len
87 def _recv_line_wrapped(self, send_ping=True):
88 if len(self.line_buffer) > 0:
89 return self.line_buffer.pop(0)
91 ready = select.select([self.socket], [], [], int(self.timeout / 2))
93 self._pingtest(send_ping)
95 self.last_pong = time.time()
96 received_bytes = self.socket.recv(1024)
98 received_runes = received_bytes.decode("UTF-8")
99 except UnicodeDecodeError:
100 received_runes = received_bytes.decode("latin1")
101 if len(received_runes) == 0:
102 print("SOCKET CONNECTION BROKEN")
103 raise ExceptionForRestart
104 self.rune_buffer += received_runes
105 lines_split = str.split(self.rune_buffer, "\r\n")
106 self.line_buffer += lines_split[:-1]
107 self.rune_buffer = lines_split[-1]
108 if len(self.line_buffer) > 0:
109 return self.line_buffer.pop(0)
111 def recv_line(self, send_ping=True):
112 line = self._recv_line_wrapped(send_ping)
114 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
119 def handle_command(command, argument, notice, target, session):
122 if not os.access(session.quotesfile, os.F_OK):
123 quotesfile = open(session.quotesfile, "w")
124 quotesfile.write("QUOTES FOR " + target + ":\n")
126 quotesfile = open(session.quotesfile, "a")
127 quotesfile.write(argument + "\n")
129 quotesfile = open(session.quotesfile, "r")
130 lines = quotesfile.readlines()
132 notice("ADDED QUOTE #" + str(len(lines) - 1))
137 notice("SYNTAX: !quote [int] OR !quote search QUERY")
138 notice("QUERY may be a boolean grouping of quoted or unquoted " +
139 "search terms, examples:")
140 notice("!quote search foo")
141 notice("!quote search foo AND (bar OR NOT baz)")
142 notice("!quote search \"foo\\\"bar\" AND ('NOT\"' AND \"'foo'\"" +
148 tokens = argument.split(" ")
149 if (len(tokens) > 1 and tokens[0] != "search") or \
150 (len(tokens) == 1 and
151 (tokens[0] == "search" or not tokens[0].isdigit())):
154 if not os.access(session.quotesfile, os.F_OK):
155 notice("NO QUOTES AVAILABLE")
157 quotesfile = open(session.quotesfile, "r")
158 lines = quotesfile.readlines()
163 if i == 0 or i > len(lines):
164 notice("THERE'S NO QUOTE OF THAT INDEX")
167 elif len(tokens) > 1:
168 query = str.join(" ", tokens[1:])
170 results = plomsearch.search(query, lines)
171 except plomsearch.LogicParserError as err:
172 notice("FAILED QUERY PARSING: " + str(err))
174 if len(results) == 0:
175 notice("NO QUOTES MATCHING QUERY")
177 for result in results:
178 notice("QUOTE #" + str(result[0] + 1) + " : "
182 i = random.randrange(len(lines))
183 notice("QUOTE #" + str(i + 1) + ": " + lines[i][:-1])
186 from random import choice, shuffle
191 usable_selections = []
192 for i in range(select_length, 0, -1):
193 for selection in selections:
197 if snippet[-j] != selection[-(j+1)]:
201 usable_selections += [selection]
202 if [] != usable_selections:
204 if [] == usable_selections:
205 usable_selections = selections
206 selection = choice(usable_selections)
207 return selection[select_length]
209 if not os.access(session.markovfile, os.F_OK):
210 notice("NOT ENOUGH TEXT TO MARKOV.")
213 # Lowercase incoming lines, ensure they end in a sentence end mark.
214 file = open(session.markovfile, "r")
215 lines = file.readlines()
218 sentence_end_markers = ".!?)("
220 line = line.lower().replace("\n", "")
221 if line[-1] not in sentence_end_markers:
223 tokens += line.split()
224 if len(tokens) <= select_length:
225 notice("NOT ENOUGH TEXT TO MARKOV.")
228 # Replace URLs with escape string for now, so that the Markov selector
229 # won't see them as different strings. Stash replaced URLs in urls.
232 url_starts = ["http://", "https://", "<http://", "<https://"]
233 for i in range(len(tokens)):
234 for url_start in url_starts:
235 if tokens[i][:len(url_start)] == url_start:
236 length = len(tokens[i])
237 if url_start[0] == "<":
239 length = tokens[i].index(">") + 1
242 urls += [tokens[i][:length]]
243 tokens[i] = url_escape + tokens[i][length:]
246 # For each snippet of select_length, use markov() to find continuation
247 # token from selections. Replace present users' names with malkovich.
248 # Start snippets with the beginning of a sentence, if possible.
249 for i in range(len(tokens) - select_length):
251 for j in range(select_length + 1):
252 token_list += [tokens[i + j]]
253 selections += [token_list]
255 for i in range(select_length):
258 for i in range(len(selections)):
259 if selections[i][0][-1] in sentence_end_markers:
260 for i in range(select_length):
261 snippet[i] = selections[i][i + 1]
264 malkovich = "malkovich"
266 new_end = markov(snippet)
267 for name in session.users_in_chan:
268 if new_end[:len(name)] == name.lower():
269 new_end = malkovich + new_end[len(name):]
271 if len(msg) + len(new_end) > 200:
274 for i in range(select_length - 1):
275 snippet[i] = snippet[i + 1]
276 snippet[select_length - 1] = new_end
278 # Replace occurences of url escape string with random choice from urls.
280 index = msg.find(url_escape)
283 msg = msg.replace(url_escape, choice(urls), 1)
285 # More meaningful ways to randomly end sentences.
286 notice(msg + malkovich + ".")
291 twtfile = open(session.twtfile, mode)
292 except (PermissionError, FileNotFoundError) as err:
293 notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
297 from datetime import datetime
298 if not os.access(session.twtfile, os.F_OK):
299 twtfile = try_open("w")
303 twtfile = try_open("a")
306 twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
310 if "addquote" == command:
312 elif "quote" == command:
314 elif "markov" == command:
316 elif "twt" == command:
320 def handle_url(url, notice, show_url=False):
322 def mobile_twitter_hack(url):
323 re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
324 re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
325 m = re.search(re1, url)
326 if m and m.group(1) == 'mobile.twitter.com/' \
327 and m.group(2) == '/status/':
328 m = re.search(re2, url)
329 url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
330 handle_url(url, notice, True)
334 r = requests.get(url, timeout=15)
335 except (requests.exceptions.TooManyRedirects,
336 requests.exceptions.ConnectionError,
337 requests.exceptions.InvalidURL,
339 requests.exceptions.InvalidSchema) as error:
340 notice("TROUBLE FOLLOWING URL: " + str(error))
342 if mobile_twitter_hack(url):
344 title = bs4.BeautifulSoup(r.text, "html5lib").title
345 if title and title.string:
346 prefix = "PAGE TITLE: "
348 prefix = "PAGE TITLE FOR <" + url + ">: "
349 notice(prefix + title.string.strip())
351 notice("PAGE HAS NO TITLE TAG")
356 def __init__(self, io, username, nickname, channel, twtfile, dbdir):
358 self.nickname = nickname
359 self.username = username
360 self.channel = channel
361 self.users_in_chan = []
362 self.twtfile = twtfile
364 self.io.send_line("NICK " + self.nickname)
365 self.io.send_line("USER " + self.username + " 0 * : ")
366 self.io.send_line("JOIN " + self.channel)
367 hash_channel = hashlib.md5(self.channel.encode("utf-8")).hexdigest()
368 self.chandir = self.dbdir + "/" + hash_channel + "/"
369 self.rawlogdir = self.chandir + "raw_logs/"
370 self.logdir = self.chandir + "logs/"
371 if not os.path.exists(self.logdir):
372 os.makedirs(self.logdir)
373 if not os.path.exists(self.rawlogdir):
374 os.makedirs(self.rawlogdir)
375 self.markovfile = self.chandir + "markovfeed"
376 self.quotesfile = self.chandir + "quotes"
381 if type(line) == str:
382 line = Line(":" + self.nickname + "!~" + self.username +
383 "@localhost" + " " + line)
384 now = datetime.datetime.utcnow()
385 logfile = open(self.rawlogdir + now.strftime("%Y-%m-%d") + ".txt", "a")
386 form = "%Y-%m-%d %H:%M:%S UTC\t"
387 logfile.write(now.strftime(form) + " " + line.line + "\n")
389 to_log = irclog.format_logline(line, self.channel)
391 logfile = open(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a")
392 logfile.write(now.strftime(form) + " " + to_log + "\n")
395 def handle_privmsg(line):
398 line = "NOTICE " + target + " :" + msg
399 self.io.send_line(line)
403 if line.receiver != self.nickname:
404 target = line.receiver
405 msg = str.join(" ", line.tokens[3:])[1:]
406 matches = re.findall("(https?://[^\s>]+)", msg)
407 for i in range(len(matches)):
408 handle_url(matches[i], notice)
410 tokens = msg[1:].split()
411 argument = str.join(" ", tokens[1:])
412 handle_command(tokens[0], argument, notice, target, self)
414 file = open(self.markovfile, "a")
415 file.write(msg + "\n")
419 line = self.io.recv_line()
424 if len(line.tokens) > 1:
425 if line.tokens[0] == "PING":
426 self.io.send_line("PONG " + line.tokens[1])
427 elif line.tokens[1] == "PRIVMSG":
429 elif line.tokens[1] == "353":
430 names = line.tokens[5:]
431 names[0] = names[0][1:]
432 for i in range(len(names)):
433 names[i] = names[i].replace("@", "").replace("+", "")
434 self.users_in_chan += names
435 elif line.tokens[1] == "JOIN" and line.sender != self.nickname:
436 self.users_in_chan += [line.sender]
437 elif line.tokens[1] == "PART":
438 del(self.users_in_chan[self.users_in_chan.index(line.sender)])
439 elif line.tokens[1] == "NICK":
440 del(self.users_in_chan[self.users_in_chan.index(line.sender)])
441 self.users_in_chan += [line.receiver]
444 def parse_command_line_arguments():
445 parser = argparse.ArgumentParser()
446 parser.add_argument("-s, --server", action="store", dest="server",
448 help="server or server net to connect to (default: "
450 parser.add_argument("-p, --port", action="store", dest="port", type=int,
451 default=PORT, help="port to connect to (default : "
453 parser.add_argument("-w, --wait", action="store", dest="timeout",
454 type=int, default=TIMEOUT,
455 help="timeout in seconds after which to attempt " +
456 "reconnect (default: " + str(TIMEOUT) + ")")
457 parser.add_argument("-u, --username", action="store", dest="username",
458 default=USERNAME, help="username to use (default: "
460 parser.add_argument("-n, --nickname", action="store", dest="nickname",
461 default=NICKNAME, help="nickname to use (default: "
463 parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
464 default=TWTFILE, help="twtxt file to use (default: "
466 parser.add_argument("-d, --dbdir", action="store", dest="dbdir",
467 default=DBDIR, help="directory to store DB files in")
468 parser.add_argument("CHANNEL", action="store", help="channel to join")
469 opts, unknown = parser.parse_known_args()
473 opts = parse_command_line_arguments()
476 io = IO(opts.server, opts.port, opts.timeout)
477 hash_server = hashlib.md5(opts.server.encode("utf-8")).hexdigest()
478 dbdir = opts.dbdir + "/" + hash_server
479 session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
482 except ExceptionForRestart: