+ 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=15)
+ except (requests.exceptions.TooManyRedirects,
+ requests.exceptions.ConnectionError,
+ requests.exceptions.InvalidURL,
+ UnicodeError,
+ requests.exceptions.InvalidSchema) as error:
+ notice("TROUBLE FOLLOWING URL: " + str(error))
+ return
+ if mobile_twitter_hack(url):
+ return
+ title = bs4.BeautifulSoup(r.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):
+ self.io = io
+ self.nickname = nickname
+ self.username = username
+ self.channel = channel
+ self.users_in_chan = []
+ self.twtfile = twtfile
+ self.dbdir = dbdir
+ 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()
+ logfile = open(self.rawlogdir + now.strftime("%Y-%m-%d") + ".txt", "a")
+ form = "%Y-%m-%d %H:%M:%S UTC\t"
+ logfile.write(now.strftime(form) + " " + line.line + "\n")
+ logfile.close()
+ to_log = irclog.format_logline(line, self.channel)
+ if to_log != None:
+ logfile = open(self.logdir + now.strftime("%Y-%m-%d") + ".txt", "a")
+ logfile.write(now.strftime(form) + " " + to_log + "\n")
+ logfile.close()
+
+ 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)
+ for i in range(len(matches)):
+ handle_url(matches[i], notice)
+ if "!" == msg[0]:
+ tokens = msg[1:].split()
+ argument = str.join(" ", tokens[1:])
+ handle_command(tokens[0], argument, notice, target, self)
+ return
+ file = open(self.markovfile, "a")
+ file.write(msg + "\n")
+ file.close()
+
+ while True:
+ line = self.io.recv_line()
+ if not line:
+ continue
+ line = Line(line)
+ log(line)
+ if len(line.tokens) > 1:
+ if line.tokens[0] == "PING":
+ self.io.send_line("PONG " + line.tokens[1])
+ elif line.tokens[1] == "PRIVMSG":
+ handle_privmsg(line)
+ elif line.tokens[1] == "353":
+ names = line.tokens[5:]
+ names[0] = names[0][1:]
+ for i in range(len(names)):
+ names[i] = names[i].replace("@", "").replace("+", "")
+ self.users_in_chan += names
+ elif line.tokens[1] == "JOIN" and line.sender != self.nickname:
+ self.users_in_chan += [line.sender]
+ elif line.tokens[1] == "PART":
+ del(self.users_in_chan[self.users_in_chan.index(line.sender)])
+ elif line.tokens[1] == "NICK":
+ del(self.users_in_chan[self.users_in_chan.index(line.sender)])
+ self.users_in_chan += [line.receiver]