15 # Defaults, may be overwritten by command line arguments.
16 SERVER = "irc.freenode.net"
19 USERNAME = "plomlombot"
23 class ExceptionForRestart(Exception):
29 def __init__(self, server, port, timeout):
30 self.timeout = timeout
31 self.socket = socket.socket()
32 self.socket.connect((server, port))
33 self.socket.setblocking(0)
36 self.last_pong = time.time()
37 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
39 def _pingtest(self, send_ping=True):
40 if self.last_pong + self.timeout < time.time():
41 print("SERVER NOT ANSWERING")
42 raise ExceptionForRestart
44 self.send_line("PING " + self.servername)
46 def send_line(self, msg):
47 msg = msg.replace("\r", " ")
48 msg = msg.replace("\n", " ")
49 if len(msg.encode("utf-8")) > 510:
50 print("NOT SENT LINE TO SERVER (too long): " + msg)
51 print("LINE TO SERVER: "
52 + str(datetime.datetime.now()) + ": " + msg)
56 while total_sent_len < msg_len:
57 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
59 print("SOCKET CONNECTION BROKEN")
60 raise ExceptionForRestart
61 total_sent_len += sent_len
63 def _recv_line_wrapped(self, send_ping=True):
64 if len(self.line_buffer) > 0:
65 return self.line_buffer.pop(0)
67 ready = select.select([self.socket], [], [], int(self.timeout / 2))
69 self._pingtest(send_ping)
71 self.last_pong = time.time()
72 received_bytes = self.socket.recv(1024)
74 received_runes = received_bytes.decode("UTF-8")
75 except UnicodeDecodeError:
76 received_runes = received_bytes.decode("latin1")
77 if len(received_runes) == 0:
78 print("SOCKET CONNECTION BROKEN")
79 raise ExceptionForRestart
80 self.rune_buffer += received_runes
81 lines_split = str.split(self.rune_buffer, "\r\n")
82 self.line_buffer += lines_split[:-1]
83 self.rune_buffer = lines_split[-1]
84 if len(self.line_buffer) > 0:
85 return self.line_buffer.pop(0)
87 def recv_line(self, send_ping=True):
88 line = self._recv_line_wrapped(send_ping)
90 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
95 def init_session(server, port, timeout, nickname, username, channel):
96 print("CONNECTING TO " + server)
97 io = IO(server, port, timeout)
98 io.send_line("NICK " + nickname)
99 io.send_line("USER " + username + " 0 * : ")
100 io.send_line("JOIN " + channel)
104 def lineparser_loop(io, nickname):
106 def act_on_privmsg(tokens):
109 io.send_line("NOTICE " + target + " :" + msg)
113 def handle_url(url, show_url=False):
115 def mobile_twitter_hack(url):
116 re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
117 re2 = 'https?://mobile.twitter.com/([^/]+)/status/' \
119 m = re.search(re1, url)
120 if m and m.group(1) == 'mobile.twitter.com/' \
121 and m.group(2) == '/status/':
122 m = re.search(re2, url)
123 url = 'https://twitter.com/' + m.group(1) + '/status/' \
125 handle_url(url, True)
129 r = requests.get(url, timeout=15)
130 except (requests.exceptions.TooManyRedirects,
131 requests.exceptions.ConnectionError,
132 requests.exceptions.InvalidURL,
133 requests.exceptions.InvalidSchema) as error:
134 notice("TROUBLE FOLLOWING URL: " + str(error))
136 if mobile_twitter_hack(url):
138 title = bs4.BeautifulSoup(r.text).title
140 prefix = "PAGE TITLE: "
142 prefix = "PAGE TITLE FOR <" + url + ">: "
143 notice(prefix + title.string.strip())
145 notice("PAGE HAS NO TITLE TAG")
147 matches = re.findall("(https?://[^\s>]+)", msg)
148 for i in range(len(matches)):
149 handle_url(matches[i])
151 def command_check(msg):
154 tokens = msg[1:].split()
155 hash_string = hashlib.md5(target.encode("utf-8")).hexdigest()
156 quotesfile_name = "quotes_" + hash_string
157 if tokens[0] == "addquote":
158 if not os.access(quotesfile_name, os.F_OK):
159 quotesfile = open(quotesfile_name, "w")
160 quotesfile.write("QUOTES FOR " + target + ":\n")
162 quotesfile = open(quotesfile_name, "a")
163 quotesfile.write(str.join(" ", tokens[1:]) + "\n")
165 quotesfile = open(quotesfile_name, "r")
166 lines = quotesfile.readlines()
168 notice("ADDED QUOTE #" + str(len(lines) - 1))
169 elif tokens[0] == "quote":
170 if len(tokens) > 2 or \
171 (len(tokens) == 2 and not tokens[1].isdigit()):
172 notice("SYNTAX: !quote [int]")
174 if not os.access(quotesfile_name, os.F_OK):
175 notice("NO QUOTES AVAILABLE")
177 quotesfile = open(quotesfile_name, "r")
178 lines = quotesfile.readlines()
183 if i == 0 or i > len(lines):
184 notice("THERE'S NO QUOTE OF THAT INDEX")
188 i = random.randrange(len(lines))
189 notice("QUOTE #" + str(i + 1) + ": " + lines[i])
192 for rune in tokens[0]:
198 for rune in tokens[2]:
204 if receiver != nickname:
206 msg = str.join(" ", tokens[3:])[1:]
211 line = io.recv_line()
214 tokens = line.split(" ")
216 if tokens[1] == "PRIVMSG":
217 act_on_privmsg(tokens)
218 if tokens[0] == "PING":
219 io.send_line("PONG " + tokens[1])
222 def parse_command_line_arguments():
223 parser = argparse.ArgumentParser()
224 parser.add_argument("-s, --server", action="store", dest="server",
226 help="server or server net to connect to (default: "
228 parser.add_argument("-p, --port", action="store", dest="port", type=int,
229 default=PORT, help="port to connect to (default : "
231 parser.add_argument("-t, --timeout", action="store", dest="timeout",
232 type=int, default=TIMEOUT,
233 help="timeout in seconds after which to attempt " +
234 "reconnect (default: " + str(TIMEOUT) + ")")
235 parser.add_argument("-u, --username", action="store", dest="username",
236 default=USERNAME, help="username to use (default: "
238 parser.add_argument("-n, --nickname", action="store", dest="nickname",
239 default=NICKNAME, help="nickname to use (default: "
241 parser.add_argument("CHANNEL", action="store", help="channel to join")
242 opts, unknown = parser.parse_known_args()
245 opts = parse_command_line_arguments()
248 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
249 opts.username, opts.CHANNEL)
250 lineparser_loop(io, opts.nickname)
251 except ExceptionForRestart: