16 # Defaults, may be overwritten by command line arguments.
17 SERVER = "irc.freenode.net"
20 USERNAME = "plomlombot"
23 DBDIR = os.path.expanduser("~/plomlombot_db")
26 class ExceptionForRestart(Exception):
32 def __init__(self, server, port, timeout):
33 self.timeout = timeout
34 self.socket = socket.socket()
35 self.socket.connect((server, port))
36 self.socket.setblocking(0)
39 self.last_pong = time.time()
40 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
42 def _pingtest(self, send_ping=True):
43 if self.last_pong + self.timeout < time.time():
44 print("SERVER NOT ANSWERING")
45 raise ExceptionForRestart
47 self.send_line("PING " + self.servername)
49 def send_line(self, msg):
50 msg = msg.replace("\r", " ")
51 msg = msg.replace("\n", " ")
52 if len(msg.encode("utf-8")) > 510:
53 print("NOT SENT LINE TO SERVER (too long): " + msg)
54 print("LINE TO SERVER: "
55 + str(datetime.datetime.now()) + ": " + msg)
59 while total_sent_len < msg_len:
60 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
62 print("SOCKET CONNECTION BROKEN")
63 raise ExceptionForRestart
64 total_sent_len += sent_len
66 def _recv_line_wrapped(self, send_ping=True):
67 if len(self.line_buffer) > 0:
68 return self.line_buffer.pop(0)
70 ready = select.select([self.socket], [], [], int(self.timeout / 2))
72 self._pingtest(send_ping)
74 self.last_pong = time.time()
75 received_bytes = self.socket.recv(1024)
77 received_runes = received_bytes.decode("UTF-8")
78 except UnicodeDecodeError:
79 received_runes = received_bytes.decode("latin1")
80 if len(received_runes) == 0:
81 print("SOCKET CONNECTION BROKEN")
82 raise ExceptionForRestart
83 self.rune_buffer += received_runes
84 lines_split = str.split(self.rune_buffer, "\r\n")
85 self.line_buffer += lines_split[:-1]
86 self.rune_buffer = lines_split[-1]
87 if len(self.line_buffer) > 0:
88 return self.line_buffer.pop(0)
90 def recv_line(self, send_ping=True):
91 line = self._recv_line_wrapped(send_ping)
93 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
98 def handle_command(command, argument, notice, target, session):
101 if not os.access(session.quotesfile, os.F_OK):
102 quotesfile = open(session.quotesfile, "w")
103 quotesfile.write("QUOTES FOR " + target + ":\n")
105 quotesfile = open(session.quotesfile, "a")
106 quotesfile.write(argument + "\n")
108 quotesfile = open(session.quotesfile, "r")
109 lines = quotesfile.readlines()
111 notice("ADDED QUOTE #" + str(len(lines) - 1))
116 notice("SYNTAX: !quote [int] OR !quote search QUERY")
117 notice("QUERY may be a boolean grouping of quoted or unquoted " +
118 "search terms, examples:")
119 notice("!quote search foo")
120 notice("!quote search foo AND (bar OR NOT baz)")
121 notice("!quote search \"foo\\\"bar\" AND ('NOT\"' AND \"'foo'\"" +
127 tokens = argument.split(" ")
128 if (len(tokens) > 1 and tokens[0] != "search") or \
129 (len(tokens) == 1 and
130 (tokens[0] == "search" or not tokens[0].isdigit())):
133 if not os.access(session.quotesfile, os.F_OK):
134 notice("NO QUOTES AVAILABLE")
136 quotesfile = open(session.quotesfile, "r")
137 lines = quotesfile.readlines()
142 if i == 0 or i > len(lines):
143 notice("THERE'S NO QUOTE OF THAT INDEX")
146 elif len(tokens) > 1:
147 query = str.join(" ", tokens[1:])
149 results = plomsearch.search(query, lines)
150 except plomsearch.LogicParserError as err:
151 notice("FAILED QUERY PARSING: " + str(err))
153 if len(results) == 0:
154 notice("NO QUOTES MATCHING QUERY")
156 for result in results:
157 notice("QUOTE #" + str(result[0] + 1) + " : "
161 i = random.randrange(len(lines))
162 notice("QUOTE #" + str(i + 1) + ": " + lines[i][:-1])
165 from random import choice, shuffle
170 usable_selections = []
171 for i in range(select_length, 0, -1):
172 for selection in selections:
176 if snippet[-j] != selection[-(j+1)]:
180 usable_selections += [selection]
181 if [] != usable_selections:
183 if [] == usable_selections:
184 usable_selections = selections
185 selection = choice(usable_selections)
186 return selection[select_length]
188 if not os.access(session.markovfile, os.F_OK):
189 notice("NOT ENOUGH TEXT TO MARKOV.")
192 # Lowercase incoming lines, ensure they end in a sentence end mark.
193 file = open(session.markovfile, "r")
194 lines = file.readlines()
197 sentence_end_markers = ".!?)("
199 line = line.lower().replace("\n", "")
200 if line[-1] not in sentence_end_markers:
202 tokens += line.split()
203 if len(tokens) <= select_length:
204 notice("NOT ENOUGH TEXT TO MARKOV.")
207 # Replace URLs with escape string for now, so that the Markov selector
208 # won't see them as different strings. Stash replaced URLs in urls.
211 url_starts = ["http://", "https://", "<http://", "<https://"]
212 for i in range(len(tokens)):
213 for url_start in url_starts:
214 if tokens[i][:len(url_start)] == url_start:
215 length = len(tokens[i])
216 if url_start[0] == "<":
218 length = tokens[i].index(">") + 1
221 urls += [tokens[i][:length]]
222 tokens[i] = url_escape + tokens[i][length:]
225 # For each snippet of select_length, use markov() to find continuation
226 # token from selections. Replace present users' names with malkovich.
227 # Start snippets with the beginning of a sentence, if possible.
228 for i in range(len(tokens) - select_length):
230 for j in range(select_length + 1):
231 token_list += [tokens[i + j]]
232 selections += [token_list]
234 for i in range(select_length):
237 for i in range(len(selections)):
238 if selections[i][0][-1] in sentence_end_markers:
239 for i in range(select_length):
240 snippet[i] = selections[i][i + 1]
243 malkovich = "malkovich"
245 new_end = markov(snippet)
246 for name in session.users_in_chan:
247 if new_end[:len(name)] == name.lower():
248 new_end = malkovich + new_end[len(name):]
250 if len(msg) + len(new_end) > 200:
253 for i in range(select_length - 1):
254 snippet[i] = snippet[i + 1]
255 snippet[select_length - 1] = new_end
257 # Replace occurences of url escape string with random choice from urls.
259 index = msg.find(url_escape)
262 msg = msg.replace(url_escape, choice(urls), 1)
264 # More meaningful ways to randomly end sentences.
265 notice(msg + malkovich + ".")
270 twtfile = open(session.twtfile, mode)
271 except (PermissionError, FileNotFoundError) as err:
272 notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
276 from datetime import datetime
277 if not os.access(session.twtfile, os.F_OK):
278 twtfile = try_open("w")
282 twtfile = try_open("a")
285 twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
289 if "addquote" == command:
291 elif "quote" == command:
293 elif "markov" == command:
295 elif "twt" == command:
299 def handle_url(url, notice, show_url=False):
301 def mobile_twitter_hack(url):
302 re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
303 re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
304 m = re.search(re1, url)
305 if m and m.group(1) == 'mobile.twitter.com/' \
306 and m.group(2) == '/status/':
307 m = re.search(re2, url)
308 url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
309 handle_url(url, notice, True)
313 r = requests.get(url, timeout=15)
314 except (requests.exceptions.TooManyRedirects,
315 requests.exceptions.ConnectionError,
316 requests.exceptions.InvalidURL,
318 requests.exceptions.InvalidSchema) as error:
319 notice("TROUBLE FOLLOWING URL: " + str(error))
321 if mobile_twitter_hack(url):
323 title = bs4.BeautifulSoup(r.text, "html5lib").title
324 if title and title.string:
325 prefix = "PAGE TITLE: "
327 prefix = "PAGE TITLE FOR <" + url + ">: "
328 notice(prefix + title.string.strip())
330 notice("PAGE HAS NO TITLE TAG")
335 def __init__(self, io, username, nickname, channel, twtfile, dbdir):
337 self.nickname = nickname
338 self.channel = channel
339 self.users_in_chan = []
340 self.twtfile = twtfile
342 self.io.send_line("NICK " + self.nickname)
343 self.io.send_line("USER " + username + " 0 * : ")
344 self.io.send_line("JOIN " + self.channel)
345 hash_channel = hashlib.md5(self.channel.encode("utf-8")).hexdigest()
346 self.chandir = self.dbdir + "/" + hash_channel + "/"
347 self.logdir = self.chandir + "logs/"
348 if not os.path.exists(self.logdir):
349 os.makedirs(self.logdir)
350 self.markovfile = self.chandir + "markovfeed"
351 self.quotesfile = self.chandir + "quotes"
356 now = datetime.datetime.utcnow()
357 logfile = open(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a")
358 form = "%Y-%m-%d %H:%M:%S UTC\t"
359 logfile.write(now.strftime(form) + " " + line + "\n")
362 def handle_privmsg(tokens):
364 def handle_input(msg, target):
367 line = "NOTICE " + target + " :" + msg
368 self.io.send_line(line)
371 matches = re.findall("(https?://[^\s>]+)", msg)
372 for i in range(len(matches)):
373 handle_url(matches[i], notice)
375 tokens = msg[1:].split()
376 argument = str.join(" ", tokens[1:])
377 handle_command(tokens[0], argument, notice, target, self)
379 file = open(self.markovfile, "a")
380 file.write(msg + "\n")
384 for rune in tokens[0]:
390 for rune in tokens[2]:
396 if receiver != self.nickname:
398 msg = str.join(" ", tokens[3:])[1:]
399 handle_input(msg, target)
401 def name_from_join_or_part(tokens):
402 token = tokens[0][1:]
403 index_cut = token.find("@")
404 index_ex = token.find("!")
405 if index_ex > 0 and index_ex < index_cut:
407 return token[:index_cut]
410 line = self.io.recv_line()
414 tokens = line.split(" ")
416 if tokens[0] == "PING":
417 self.io.send_line("PONG " + tokens[1])
418 elif tokens[1] == "PRIVMSG":
419 handle_privmsg(tokens)
420 elif tokens[1] == "353":
422 names[0] = names[0][1:]
423 for i in range(len(names)):
424 names[i] = names[i].replace("@", "").replace("+", "")
425 self.users_in_chan += names
426 elif tokens[1] == "JOIN":
427 name = name_from_join_or_part(tokens)
428 if name != self.nickname:
429 self.users_in_chan += [name]
430 elif tokens[1] == "PART":
431 name = name_from_join_or_part(tokens)
432 del(self.users_in_chan[self.users_in_chan.index(name)])
435 def parse_command_line_arguments():
436 parser = argparse.ArgumentParser()
437 parser.add_argument("-s, --server", action="store", dest="server",
439 help="server or server net to connect to (default: "
441 parser.add_argument("-p, --port", action="store", dest="port", type=int,
442 default=PORT, help="port to connect to (default : "
444 parser.add_argument("-w, --wait", action="store", dest="timeout",
445 type=int, default=TIMEOUT,
446 help="timeout in seconds after which to attempt " +
447 "reconnect (default: " + str(TIMEOUT) + ")")
448 parser.add_argument("-u, --username", action="store", dest="username",
449 default=USERNAME, help="username to use (default: "
451 parser.add_argument("-n, --nickname", action="store", dest="nickname",
452 default=NICKNAME, help="nickname to use (default: "
454 parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
455 default=TWTFILE, help="twtxt file to use (default: "
457 parser.add_argument("-d, --dbdir", action="store", dest="dbdir",
458 default=DBDIR, help="directory to store DB files in")
459 parser.add_argument("CHANNEL", action="store", help="channel to join")
460 opts, unknown = parser.parse_known_args()
464 opts = parse_command_line_arguments()
467 io = IO(opts.server, opts.port, opts.timeout)
468 hash_server = hashlib.md5(opts.server.encode("utf-8")).hexdigest()
469 dbdir = opts.dbdir + "/" + hash_server
470 session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
473 except ExceptionForRestart: