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) + " : " + result[1])
160 i = random.randrange(len(lines))
161 notice("QUOTE #" + str(i + 1) + ": " + lines[i])
164 from random import choice, shuffle
169 usable_selections = []
170 for i in range(select_length, 0, -1):
171 for selection in selections:
175 if snippet[-j] != selection[-(j+1)]:
179 usable_selections += [selection]
180 if [] != usable_selections:
182 if [] == usable_selections:
183 usable_selections = selections
184 selection = choice(usable_selections)
185 return selection[select_length]
187 if not os.access(session.markovfile, os.F_OK):
188 notice("NOT ENOUGH TEXT TO MARKOV.")
191 # Lowercase incoming lines, ensure they end in a sentence end mark.
192 file = open(session.markovfile, "r")
193 lines = file.readlines()
196 sentence_end_markers = ".!?)("
198 line = line.lower().replace("\n", "")
199 if line[-1] not in sentence_end_markers:
201 tokens += line.split()
202 if len(tokens) <= select_length:
203 notice("NOT ENOUGH TEXT TO MARKOV.")
206 # Replace URLs with escape string for now, so that the Markov selector
207 # won't see them as different strings. Stash replaced URLs in urls.
210 url_starts = ["http://", "https://", "<http://", "<https://"]
211 for i in range(len(tokens)):
212 for url_start in url_starts:
213 if tokens[i][:len(url_start)] == url_start:
214 length = len(tokens[i])
215 if url_start[0] == "<":
217 length = tokens[i].index(">") + 1
220 urls += [tokens[i][:length]]
221 tokens[i] = url_escape + tokens[i][length:]
224 # For each snippet of select_length, use markov() to find continuation
225 # token from selections. Replace present users' names with malkovich.
226 # Start snippets with the beginning of a sentence, if possible.
227 for i in range(len(tokens) - select_length):
229 for j in range(select_length + 1):
230 token_list += [tokens[i + j]]
231 selections += [token_list]
233 for i in range(select_length):
236 for i in range(len(selections)):
237 if selections[i][0][-1] in sentence_end_markers:
238 for i in range(select_length):
239 snippet[i] = selections[i][i + 1]
242 malkovich = "malkovich"
244 new_end = markov(snippet)
245 for name in session.users_in_chan:
246 if new_end[:len(name)] == name.lower():
247 new_end = malkovich + new_end[len(name):]
249 if len(msg) + len(new_end) > 200:
252 for i in range(select_length - 1):
253 snippet[i] = snippet[i + 1]
254 snippet[select_length - 1] = new_end
256 # Replace occurences of url escape string with random choice from urls.
258 index = msg.find(url_escape)
261 msg = msg.replace(url_escape, choice(urls), 1)
263 # More meaningful ways to randomly end sentences.
264 notice(msg + malkovich + ".")
269 twtfile = open(session.twtfile, mode)
270 except (PermissionError, FileNotFoundError) as err:
271 notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
275 from datetime import datetime
276 if not os.access(session.twtfile, os.F_OK):
277 twtfile = try_open("w")
281 twtfile = try_open("a")
284 twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
288 if "addquote" == command:
290 elif "quote" == command:
292 elif "markov" == command:
294 elif "twt" == command:
298 def handle_url(url, notice, show_url=False):
300 def mobile_twitter_hack(url):
301 re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
302 re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
303 m = re.search(re1, url)
304 if m and m.group(1) == 'mobile.twitter.com/' \
305 and m.group(2) == '/status/':
306 m = re.search(re2, url)
307 url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
308 handle_url(url, notice, True)
312 r = requests.get(url, timeout=15)
313 except (requests.exceptions.TooManyRedirects,
314 requests.exceptions.ConnectionError,
315 requests.exceptions.InvalidURL,
317 requests.exceptions.InvalidSchema) as error:
318 notice("TROUBLE FOLLOWING URL: " + str(error))
320 if mobile_twitter_hack(url):
322 title = bs4.BeautifulSoup(r.text, "html5lib").title
323 if title and title.string:
324 prefix = "PAGE TITLE: "
326 prefix = "PAGE TITLE FOR <" + url + ">: "
327 notice(prefix + title.string.strip())
329 notice("PAGE HAS NO TITLE TAG")
334 def __init__(self, io, username, nickname, channel, twtfile, dbdir):
336 self.nickname = nickname
337 self.channel = channel
338 self.users_in_chan = []
339 self.twtfile = twtfile
341 self.io.send_line("NICK " + self.nickname)
342 self.io.send_line("USER " + username + " 0 * : ")
343 self.io.send_line("JOIN " + self.channel)
344 hash_channel = hashlib.md5(self.channel.encode("utf-8")).hexdigest()
345 self.chandir = self.dbdir + "/" + hash_channel + "/"
346 self.logdir = self.chandir + "logs/"
347 if not os.path.exists(self.logdir):
348 os.makedirs(self.logdir)
349 self.markovfile = self.chandir + "markovfeed"
350 self.quotesfile = self.chandir + "quotes"
355 now = datetime.datetime.utcnow()
356 logfile = open(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a")
357 form = "%Y-%m-%d %H:%M:%S UTC\t"
358 logfile.write(now.strftime(form) + " " + line + "\n")
361 def handle_privmsg(tokens):
363 def handle_input(msg, target):
366 self.io.send_line("NOTICE " + target + " :" + msg)
368 matches = re.findall("(https?://[^\s>]+)", msg)
369 for i in range(len(matches)):
370 handle_url(matches[i], notice)
372 tokens = msg[1:].split()
373 argument = str.join(" ", tokens[1:])
374 handle_command(tokens[0], argument, notice, target, self)
376 file = open(self.markovfile, "a")
377 file.write(msg + "\n")
381 for rune in tokens[0]:
387 for rune in tokens[2]:
393 if receiver != self.nickname:
395 msg = str.join(" ", tokens[3:])[1:]
396 if target == self.channel:
397 log("<" + sender + "> " + msg)
398 handle_input(msg, target)
400 def name_from_join_or_part(tokens):
401 token = tokens[0][1:]
402 index_cut = token.find("@")
403 index_ex = token.find("!")
404 if index_ex > 0 and index_ex < index_cut:
406 return token[:index_cut]
409 line = self.io.recv_line()
412 tokens = line.split(" ")
414 if tokens[0] == "PING":
415 self.io.send_line("PONG " + tokens[1])
416 elif tokens[1] == "PRIVMSG":
417 handle_privmsg(tokens)
418 elif tokens[1] == "353":
420 names[0] = names[0][1:]
421 for i in range(len(names)):
422 names[i] = names[i].replace("@", "").replace("+", "")
423 self.users_in_chan += names
425 elif tokens[1] == "JOIN":
426 name = name_from_join_or_part(tokens)
427 if name != self.nickname:
428 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)])
438 def parse_command_line_arguments():
439 parser = argparse.ArgumentParser()
440 parser.add_argument("-s, --server", action="store", dest="server",
442 help="server or server net to connect to (default: "
444 parser.add_argument("-p, --port", action="store", dest="port", type=int,
445 default=PORT, help="port to connect to (default : "
447 parser.add_argument("-w, --wait", action="store", dest="timeout",
448 type=int, default=TIMEOUT,
449 help="timeout in seconds after which to attempt " +
450 "reconnect (default: " + str(TIMEOUT) + ")")
451 parser.add_argument("-u, --username", action="store", dest="username",
452 default=USERNAME, help="username to use (default: "
454 parser.add_argument("-n, --nickname", action="store", dest="nickname",
455 default=NICKNAME, help="nickname to use (default: "
457 parser.add_argument("-t, --twtxtfile", action="store", dest="twtfile",
458 default=TWTFILE, help="twtxt file to use (default: "
460 parser.add_argument("-d, --dbdir", action="store", dest="dbdir",
461 default=DBDIR, help="directory to store DB files in")
462 parser.add_argument("CHANNEL", action="store", help="channel to join")
463 opts, unknown = parser.parse_known_args()
467 opts = parse_command_line_arguments()
470 io = IO(opts.server, opts.port, opts.timeout)
471 hash_server = hashlib.md5(opts.server.encode("utf-8")).hexdigest()
472 dbdir = opts.dbdir + "/" + hash_server
473 session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
476 except ExceptionForRestart: