16 URLREGEX = "(https?://[^\s>]+)"
18 # Defaults, may be overwritten by command line arguments.
19 SERVER = "irc.freenode.net"
22 USERNAME = "plomlombot"
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):
99 hash_string = hashlib.md5(target.encode("utf-8")).hexdigest()
100 quotesfile_name = "quotes_" + hash_string
103 if not os.access(quotesfile_name, os.F_OK):
104 quotesfile = open(quotesfile_name, "w")
105 quotesfile.write("QUOTES FOR " + target + ":\n")
107 quotesfile = open(quotesfile_name, "a")
108 quotesfile.write(argument + "\n")
110 quotesfile = open(quotesfile_name, "r")
111 lines = quotesfile.readlines()
113 notice("ADDED QUOTE #" + str(len(lines) - 1))
118 notice("SYNTAX: !quote [int] OR !quote search QUERY")
119 notice("QUERY may be a boolean grouping of quoted or unquoted " +
120 "search terms, examples:")
121 notice("!quote search foo")
122 notice("!quote search foo AND (bar OR NOT baz)")
123 notice("!quote search \"foo\\\"bar\" AND ('NOT\"' AND \"'foo'\"" +
129 tokens = argument.split(" ")
130 if (len(tokens) > 1 and tokens[0] != "search") or \
131 (len(tokens) == 1 and
132 (tokens[0] == "search" or not tokens[0].isdigit())):
135 if not os.access(quotesfile_name, os.F_OK):
136 notice("NO QUOTES AVAILABLE")
138 quotesfile = open(quotesfile_name, "r")
139 lines = quotesfile.readlines()
144 if i == 0 or i > len(lines):
145 notice("THERE'S NO QUOTE OF THAT INDEX")
148 elif len(tokens) > 1:
149 query = str.join(" ", tokens[1:])
151 results = plomsearch.search(query, lines)
152 except plomsearch.LogicParserError as err:
153 notice("FAILED QUERY PARSING: " + str(err))
155 if len(results) == 0:
156 notice("NO QUOTES MATCHING QUERY")
158 for result in results:
159 notice("QUOTE #" + str(result[0] + 1) + " : " + result[1])
162 i = random.randrange(len(lines))
163 notice("QUOTE #" + str(i + 1) + ": " + lines[i])
166 from random import shuffle
171 usable_selections = []
172 for i in range(select_length, 0, -1):
173 for selection in selections:
176 if snippet[j] != selection[j]:
180 usable_selections += [selection]
181 if [] != usable_selections:
183 if [] == usable_selections:
184 usable_selections = selections
185 shuffle(usable_selections)
186 return usable_selections[0][select_length]
188 def purge_undesired(tokens):
190 if None != re.match("^" + URLREGEX, token):
191 del(tokens[tokens.index(token)])
192 for name in session.uses_in_chan:
195 del(tokens[tokens.index(name)])
200 hash_string = hashlib.md5(target.encode("utf-8")).hexdigest()
201 markovfeed_name = "markovfeed_" + hash_string
202 if not os.access(markovfeed_name, os.F_OK):
203 notice("NOT ENOUGH TEXT TO MARKOV.")
205 file = open(markovfeed_name, "r")
206 lines = file.readlines()
210 line = line.replace("\n", "")
211 tokens += line.split()
212 tokens = purge_undesired(tokens)
213 if len(tokens) <= select_length:
214 notice("NOT ENOUGH TEXT TO MARKOV.")
216 for i in range(len(tokens) - select_length):
218 for j in range(select_length + 1):
219 token_list += [tokens[i + j]]
220 selections += [token_list]
222 for i in range(select_length):
226 new_end = markov(snippet)
227 if len(msg) + len(new_end) > 200:
230 for i in range(select_length - 1):
231 snippet[i] = snippet[i + 1]
232 snippet[select_length - 1] = new_end
233 notice(msg.lower() + "malkovich.")
235 if "addquote" == command:
237 elif "quote" == command:
239 elif "markov" == command:
243 def handle_url(url, notice, show_url=False):
245 def mobile_twitter_hack(url):
246 re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
247 re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
248 m = re.search(re1, url)
249 if m and m.group(1) == 'mobile.twitter.com/' \
250 and m.group(2) == '/status/':
251 m = re.search(re2, url)
252 url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
253 handle_url(url, notice, True)
257 r = requests.get(url, timeout=15)
258 except (requests.exceptions.TooManyRedirects,
259 requests.exceptions.ConnectionError,
260 requests.exceptions.InvalidURL,
261 requests.exceptions.InvalidSchema) as error:
262 notice("TROUBLE FOLLOWING URL: " + str(error))
264 if mobile_twitter_hack(url):
266 title = bs4.BeautifulSoup(r.text, "html.parser").title
268 prefix = "PAGE TITLE: "
270 prefix = "PAGE TITLE FOR <" + url + ">: "
271 notice(prefix + title.string.strip())
273 notice("PAGE HAS NO TITLE TAG")
278 def __init__(self, io, username, nickname, channel):
280 self.nickname = nickname
281 self.channel = channel
282 self.uses_in_chan = []
283 self.io.send_line("NICK " + self.nickname)
284 self.io.send_line("USER " + username + " 0 * : ")
285 self.io.send_line("JOIN " + self.channel)
289 def handle_privmsg(tokens):
291 def handle_input(msg, target):
294 self.io.send_line("NOTICE " + target + " :" + msg)
296 matches = re.findall(URLREGEX, msg)
297 for i in range(len(matches)):
298 handle_url(matches[i], notice)
300 tokens = msg[1:].split()
301 argument = str.join(" ", tokens[1:])
302 handle_command(tokens[0], argument, notice, target, self)
304 hash_string = hashlib.md5(target.encode("utf-8")).hexdigest()
305 markovfeed_name = "markovfeed_" + hash_string
306 file = open(markovfeed_name, "a")
307 file.write(msg + "\n")
311 for rune in tokens[0]:
317 for rune in tokens[2]:
323 if receiver != self.nickname:
325 msg = str.join(" ", tokens[3:])[1:]
326 handle_input(msg, target)
328 def name_from_join_or_part(tokens):
329 token = tokens[0][1:]
330 index_cut = token.find("@")
331 index_ex = token.find("!")
332 if index_ex > 0 and index_ex < index_cut:
334 return token[:index_cut]
337 line = self.io.recv_line()
340 tokens = line.split(" ")
342 if tokens[0] == "PING":
343 self.io.send_line("PONG " + tokens[1])
344 elif tokens[1] == "PRIVMSG":
345 handle_privmsg(tokens)
346 elif tokens[1] == "353":
348 names[0] = names[0][1:]
349 self.uses_in_chan += names
350 elif tokens[1] == "JOIN":
351 name = name_from_join_or_part(tokens)
352 if name != self.nickname:
353 self.uses_in_chan += [name]
354 elif tokens[1] == "PART":
355 name = name_from_join_or_part(tokens)
356 del(self.uses_in_chan[self.uses_in_chan.index(name)])
358 def parse_command_line_arguments():
359 parser = argparse.ArgumentParser()
360 parser.add_argument("-s, --server", action="store", dest="server",
362 help="server or server net to connect to (default: "
364 parser.add_argument("-p, --port", action="store", dest="port", type=int,
365 default=PORT, help="port to connect to (default : "
367 parser.add_argument("-t, --timeout", action="store", dest="timeout",
368 type=int, default=TIMEOUT,
369 help="timeout in seconds after which to attempt " +
370 "reconnect (default: " + str(TIMEOUT) + ")")
371 parser.add_argument("-u, --username", action="store", dest="username",
372 default=USERNAME, help="username to use (default: "
374 parser.add_argument("-n, --nickname", action="store", dest="nickname",
375 default=NICKNAME, help="nickname to use (default: "
377 parser.add_argument("CHANNEL", action="store", help="channel to join")
378 opts, unknown = parser.parse_known_args()
382 opts = parse_command_line_arguments()
385 io = IO(opts.server, opts.port, opts.timeout)
386 session = Session(io, opts.username, opts.nickname, opts.CHANNEL)
388 except ExceptionForRestart: