14 # Defaults, may be overwritten by command line arguments.
15 SERVER = "irc.freenode.net"
18 USERNAME = "plomlombot"
22 class HTMLParser(html.parser.HTMLParser):
23 def __init__(self, html, tag):
25 self._tag_to_check = tag
29 def handle_starttag(self, tag, attrs):
30 if self.data == "" and tag == self._tag_to_check:
32 def handle_endtag(self, tag):
34 def handle_data(self, data):
39 class ExceptionForRestart(Exception):
45 def __init__(self, server, port, timeout):
46 self.timeout = timeout
47 self.socket = socket.socket()
48 self.socket.connect((server, port))
49 self.socket.setblocking(0)
52 self.last_pong = time.time()
53 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
55 def _pingtest(self, send_ping=True):
56 if self.last_pong + self.timeout < time.time():
57 print("SERVER NOT ANSWERING")
58 raise ExceptionForRestart
60 self.send_line("PING " + self.servername)
62 def send_line(self, msg):
63 msg = msg.replace("\r", " ")
64 msg = msg.replace("\n", " ")
65 if len(msg.encode("utf-8")) > 510:
66 print("NOT SENT LINE TO SERVER (too long): " + msg)
67 print("LINE TO SERVER: "
68 + str(datetime.datetime.now()) + ": " + msg)
72 while total_sent_len < msg_len:
73 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
75 print("SOCKET CONNECTION BROKEN")
76 raise ExceptionForRestart
77 total_sent_len += sent_len
79 def _recv_line_wrapped(self, send_ping=True):
80 if len(self.line_buffer) > 0:
81 return self.line_buffer.pop(0)
83 ready = select.select([self.socket], [], [], int(self.timeout / 2))
85 self._pingtest(send_ping)
87 self.last_pong = time.time()
88 received_bytes = self.socket.recv(1024)
90 received_runes = received_bytes.decode("UTF-8")
91 except UnicodeDecodeError:
92 received_runes = received_bytes.decode("latin1")
93 if len(received_runes) == 0:
94 print("SOCKET CONNECTION BROKEN")
95 raise ExceptionForRestart
96 self.rune_buffer += received_runes
97 lines_split = str.split(self.rune_buffer, "\r\n")
98 self.line_buffer += lines_split[:-1]
99 self.rune_buffer = lines_split[-1]
100 if len(self.line_buffer) > 0:
101 return self.line_buffer.pop(0)
103 def recv_line(self, send_ping=True):
104 line = self._recv_line_wrapped(send_ping)
106 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
111 def init_session(server, port, timeout, nickname, username, channel):
112 print("CONNECTING TO " + server)
113 io = IO(server, port, timeout)
114 io.send_line("NICK " + nickname)
115 io.send_line("USER " + username + " 0 * : ")
116 io.send_line("JOIN " + channel)
120 def lineparser_loop(io, nickname):
122 def act_on_privmsg(tokens):
127 io.send_line("NOTICE " + target + " :" + msg)
129 matches = re.findall("(https?://[^\s>]+)", msg)
130 for i in range(len(matches)):
132 request = urllib.request.Request(url, headers={
133 "User-Agent": "plomlombot"
136 webpage = urllib.request.urlopen(request, timeout=15)
137 except (urllib.error.HTTPError, urllib.error.URLError,
138 UnicodeError, http.client.BadStatusLine) as error:
139 notice("TROUBLE FOLLOWING URL: " + str(error))
141 charset = webpage.info().get_content_charset()
143 notice("TROUBLE READING PAGE TITLE: no charset in header")
145 content_type = webpage.info().get_content_type()
146 if content_type not in ('text/html', 'text/xml',
147 'application/xhtml+xml'):
148 notice("TROUBLE READING PAGE TITLE: bad content type "
151 content = webpage.read().decode(charset)
152 title = HTMLParser(content, "title").data
153 title = html.unescape(title)
154 notice("PAGE TITLE FOR URL: " + title)
157 for rune in tokens[0]:
163 for rune in tokens[2]:
169 if receiver != nickname:
171 msg = str.join(" ", tokens[3:])[1:]
175 line = io.recv_line()
178 tokens = line.split(" ")
180 if tokens[1] == "PRIVMSG":
181 act_on_privmsg(tokens)
182 if tokens[0] == "PING":
183 io.send_line("PONG " + tokens[1])
186 def parse_command_line_arguments():
187 parser = argparse.ArgumentParser()
188 parser.add_argument("-s, --server", action="store", dest="server",
190 help="server or server net to connect to (default: "
192 parser.add_argument("-p, --port", action="store", dest="port", type=int,
193 default=PORT, help="port to connect to (default : "
195 parser.add_argument("-t, --timeout", action="store", dest="timeout",
196 type=int, default=TIMEOUT,
197 help="timeout in seconds after which to attempt " +
198 "reconnect (default: " + str(TIMEOUT) + ")")
199 parser.add_argument("-u, --username", action="store", dest="username",
200 default=USERNAME, help="username to use (default: "
202 parser.add_argument("-n, --nickname", action="store", dest="nickname",
203 default=NICKNAME, help="nickname to use (default: "
205 parser.add_argument("CHANNEL", action="store", help="channel to join")
206 opts, unknown = parser.parse_known_args()
209 opts = parse_command_line_arguments()
212 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
213 opts.username, opts.CHANNEL)
214 lineparser_loop(io, opts.nickname)
215 except ExceptionForRestart: