+
+ # For each snippet of select_length, use markov() to find continuation
+ # token from selections. Replace present users' names with malkovich.
+ # Start snippets with the beginning of a sentence, if possible.
+ for i in range(len(tokens) - select_length):
+ token_list = []
+ for j in range(select_length + 1):
+ token_list += [tokens[i + j]]
+ selections += [token_list]
+ snippet = []
+ for i in range(select_length):
+ snippet += [""]
+ shuffle(selections)
+ for i in range(len(selections)):
+ if selections[i][0][-1] in sentence_end_markers:
+ for i in range(select_length):
+ snippet[i] = selections[i][i + 1]
+ break
+ msg = ""
+ malkovich = "malkovich"
+ while 1:
+ new_end = markov(snippet)
+ for name in session.users_in_chan:
+ if new_end[:len(name)] == name.lower():
+ new_end = malkovich + new_end[len(name):]
+ break
+ if len(msg) + len(new_end) > 200:
+ break
+ msg += new_end + " "
+ for i in range(select_length - 1):
+ snippet[i] = snippet[i + 1]
+ snippet[select_length - 1] = new_end
+
+ # Replace occurences of url escape string with random choice from urls.
+ while True:
+ index = msg.find(url_escape)
+ if index < 0:
+ break
+ msg = msg.replace(url_escape, choice(urls), 1)
+
+ # More meaningful ways to randomly end sentences.
+ notice(msg + malkovich + ".")
+
+ def twt():
+ def try_open(mode):
+ try:
+ twtfile = open(session.twtfile, mode)
+ except (PermissionError, FileNotFoundError) as err:
+ notice("CAN'T ACCESS OR CREATE TWT FILE: " + str(err))
+ return None
+ return twtfile
+
+ from datetime import datetime
+ if not os.access(session.twtfile, os.F_OK):
+ twtfile = try_open("w")
+ if None == twtfile:
+ return
+ twtfile.close()
+ twtfile = try_open("a")
+ if None == twtfile:
+ return
+ twtfile.write(datetime.utcnow().isoformat() + "\t" + argument + "\n")
+ twtfile.close()
+ notice("WROTE TWT.")
+
+ if "addquote" == command:
+ addquote()
+ elif "quote" == command:
+ quote()
+ elif "markov" == command:
+ markov()
+ elif "twt" == command:
+ twt()
+
+
+def handle_url(url, notice, show_url=False):
+
+ def mobile_twitter_hack(url):
+ re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
+ re2 = 'https?://mobile.twitter.com/([^/]+)/status/([^\?/]+)'
+ m = re.search(re1, url)
+ if m and m.group(1) == 'mobile.twitter.com/' \
+ and m.group(2) == '/status/':
+ m = re.search(re2, url)
+ url = 'https://twitter.com/' + m.group(1) + '/status/' + m.group(2)
+ handle_url(url, notice, True)
+ return True
+
+ try:
+ r = requests.get(url, timeout=5, stream=True)
+ r.raw.decode_content = True
+ text = r.raw.read(10000000+1)
+ if len(text) > 10000000:
+ raise ValueError('Too large a response')
+ except (requests.exceptions.TooManyRedirects,
+ requests.exceptions.ConnectionError,
+ requests.exceptions.InvalidURL,
+ UnicodeError,
+ ValueError,
+ requests.exceptions.InvalidSchema) as error:
+ notice("TROUBLE FOLLOWING URL: " + str(error))
+ return
+ if mobile_twitter_hack(url):
+ return
+ title = bs4.BeautifulSoup(text, "html5lib").title
+ if title and title.string:
+ prefix = "PAGE TITLE: "
+ if show_url:
+ prefix = "PAGE TITLE FOR <" + url + ">: "
+ notice(prefix + title.string.strip())
+ else:
+ notice("PAGE HAS NO TITLE TAG")
+
+
+class Session:
+
+ def __init__(self, io, username, nickname, channel, twtfile, dbdir, rmlogs):
+ self.io = io
+ self.nickname = nickname
+ self.username = username
+ self.channel = channel
+ self.users_in_chan = []
+ self.twtfile = twtfile
+ self.dbdir = dbdir
+ self.rmlogs = rmlogs
+ self.io.send_line("NICK " + self.nickname)
+ self.io.send_line("USER " + self.username + " 0 * : ")
+ self.io.send_line("JOIN " + self.channel)
+ hash_channel = hashlib.md5(self.channel.encode("utf-8")).hexdigest()
+ self.chandir = self.dbdir + "/" + hash_channel + "/"
+ self.rawlogdir = self.chandir + "raw_logs/"
+ self.logdir = self.chandir + "logs/"
+ if not os.path.exists(self.logdir):
+ os.makedirs(self.logdir)
+ if not os.path.exists(self.rawlogdir):
+ os.makedirs(self.rawlogdir)
+ self.markovfile = self.chandir + "markovfeed"
+ self.quotesfile = self.chandir + "quotes"
+
+ def loop(self):
+
+ def log(line):
+ if type(line) == str:
+ line = Line(":" + self.nickname + "!~" + self.username +
+ "@localhost" + " " + line)
+ now = datetime.datetime.utcnow()
+ form = "%Y-%m-%d %H:%M:%S UTC\t"
+ write_to_file(self.rawlogdir + now.strftime("%Y-%m-%d") + ".txt",
+ "a", now.strftime(form) + " " + line.line + "\n")
+ to_log = irclog.format_logline(line, self.channel)
+ if to_log != None:
+ write_to_file(self.logdir + now.strftime("%Y-%m-%d") + ".txt",
+ "a", now.strftime(form) + " " + to_log + "\n")
+
+ def handle_privmsg(line):
+
+ def notice(msg):
+ line = "NOTICE " + target + " :" + msg
+ self.io.send_line(line)
+ log(line)
+
+ target = line.sender
+ if line.receiver != self.nickname:
+ target = line.receiver
+ msg = str.join(" ", line.tokens[3:])[1:]
+ matches = re.findall("(https?://[^\s>]+)", msg)