16 # Defaults, may be overwritten by command line arguments.
17 SERVER = "irc.freenode.net"
20 USERNAME = "plomlombot"
25 class ExceptionForRestart(Exception):
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)
38 self.last_pong = time.time()
39 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
41 def _pingtest(self, send_ping=True):
42 if self.last_pong + self.timeout < time.time():
43 print("SERVER NOT ANSWERING")
44 raise ExceptionForRestart
46 self.send_line("PING " + self.servername)
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)
58 while total_sent_len < msg_len:
59 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
61 print("SOCKET CONNECTION BROKEN")
62 raise ExceptionForRestart
63 total_sent_len += sent_len
65 def _recv_line_wrapped(self, send_ping=True):
66 if len(self.line_buffer) > 0:
67 return self.line_buffer.pop(0)
69 ready = select.select([self.socket], [], [], int(self.timeout / 2))
71 self._pingtest(send_ping)
73 self.last_pong = time.time()
74 received_bytes = self.socket.recv(1024)
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)
89 def recv_line(self, send_ping=True):
90 line = self._recv_line_wrapped(send_ping)
92 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
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
102 if not os.access(quotesfile_name, os.F_OK):
103 quotesfile = open(quotesfile_name, "w")
104 quotesfile.write("QUOTES FOR " + target + ":\n")
106 quotesfile = open(quotesfile_name, "a")
107 quotesfile.write(argument + "\n")
109 quotesfile = open(quotesfile_name, "r")
110 lines = quotesfile.readlines()
112 notice("ADDED QUOTE #" + str(len(lines) - 1))
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'\"" +
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())):
134 if not os.access(quotesfile_name, os.F_OK):
135 notice("NO QUOTES AVAILABLE")
137 quotesfile = open(quotesfile_name, "r")
138 lines = quotesfile.readlines()
143 if i == 0 or i > len(lines):
144 notice("THERE'S NO QUOTE OF THAT INDEX")
147 elif len(tokens) > 1:
148 query = str.join(" ", tokens[1:])
150 results = plomsearch.search(query, lines)
151 except plomsearch.LogicParserError as err:
152 notice("FAILED QUERY PARSING: " + str(err))
154 if len(results) == 0:
155 notice("NO QUOTES MATCHING QUERY")
157 for result in results:
158 notice("QUOTE #" + str(result[0] + 1) + " : " + result[1])
161 i = random.randrange(len(lines))
162 notice("QUOTE #" + str(i + 1) + ": " + lines[i])
165 from random import choice
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 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.")
194 # Lowercase incoming lines, ensure they end in a sentence end mark.
195 file = open(markovfeed_name, "r")
196 lines = file.readlines()
200 line = line.lower().replace("\n", "")
201 if line[-1] not in ".!?":
203 tokens += line.split()
204 if len(tokens) <= select_length:
205 notice("NOT ENOUGH TEXT TO MARKOV.")
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.
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] == "<":
219 length = tokens[i].index(">") + 1
222 urls += [tokens[i][:length]]
223 tokens[i] = url_escape + tokens[i][length:]
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):
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 malkovich = "malkovich"
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):]
244 if len(msg) + len(new_end) > 200:
247 for i in range(select_length - 1):
248 snippet[i] = snippet[i + 1]
249 snippet[select_length - 1] = new_end
251 # Replace occurences of url escape string with random choice from urls.
253 index = msg.find(url_escape)
256 msg = msg.replace(url_escape, choice(urls), 1)
258 # More meaningful ways to randomly end sentences.
259 notice(msg + malkovich + ".")
264 twtfile = open(session.twtfile, mode)
265 except (PermissionError, FileNotFoundError) as err:
266 notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
270 from datetime import datetime
271 if not os.access(session.twtfile, os.F_OK):
272 twtfile = try_open("w")
276 twtfile = try_open("a")
279 twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
283 if "addquote" == command:
285 elif "quote" == command:
287 elif "markov" == command:
289 elif "twt" == command:
293 def handle_url(url, notice, show_url=False):
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)
307 r = requests.get(url, timeout=15)
308 except (requests.exceptions.TooManyRedirects,
309 requests.exceptions.ConnectionError,
310 requests.exceptions.InvalidURL,
312 requests.exceptions.InvalidSchema) as error:
313 notice("TROUBLE FOLLOWING URL: " + str(error))
315 if mobile_twitter_hack(url):
317 title = bs4.BeautifulSoup(r.text, "html.parser").title
319 prefix = "PAGE TITLE: "
321 prefix = "PAGE TITLE FOR <" + url + ">: "
322 notice(prefix + title.string.strip())
324 notice("PAGE HAS NO TITLE TAG")
329 def __init__(self, io, username, nickname, channel, twtfile):
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)
341 def handle_privmsg(tokens):
343 def handle_input(msg, target):
346 self.io.send_line("NOTICE " + target + " :" + msg)
348 matches = re.findall("(https?://[^\s>]+)", msg)
349 for i in range(len(matches)):
350 handle_url(matches[i], notice)
352 tokens = msg[1:].split()
353 argument = str.join(" ", tokens[1:])
354 handle_command(tokens[0], argument, notice, target, self)
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")
363 for rune in tokens[0]:
369 for rune in tokens[2]:
375 if receiver != self.nickname:
377 msg = str.join(" ", tokens[3:])[1:]
378 handle_input(msg, target)
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:
386 return token[:index_cut]
389 line = self.io.recv_line()
392 tokens = line.split(" ")
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":
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)])
410 def parse_command_line_arguments():
411 parser = argparse.ArgumentParser()
412 parser.add_argument("-s, --server", action="store", dest="server",
414 help="server or server net to connect to (default: "
416 parser.add_argument("-p, --port", action="store", dest="port", type=int,
417 default=PORT, help="port to connect to (default : "
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: "
426 parser.add_argument("-n, --nickname", action="store", dest="nickname",
427 default=NICKNAME, help="nickname to use (default: "
429 parser.add_argument("-t, --twtfile", action="store", dest="twtfile",
430 default=TWTFILE, help="twtfile to use (default: "
432 parser.add_argument("CHANNEL", action="store", help="channel to join")
433 opts, unknown = parser.parse_known_args()
437 opts = parse_command_line_arguments()
440 io = IO(opts.server, opts.port, opts.timeout)
441 session = Session(io, opts.username, opts.nickname, opts.CHANNEL,
444 except ExceptionForRestart: