12 # Defaults, may be overwritten by command line arguments.
13 SERVER = "irc.freenode.net"
16 USERNAME = "plomlombot"
19 class ExceptionForRestart(Exception):
24 def __init__(self, server, port, timeout):
25 self.timeout = timeout
26 self.socket = socket.socket()
27 self.socket.connect((server, port))
28 self.socket.setblocking(0)
31 self.last_pong = time.time()
32 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
34 def _pingtest(self, send_ping=True):
35 if self.last_pong + self.timeout < time.time():
36 print("SERVER NOT ANSWERING")
37 raise ExceptionForRestart
39 self.send_line("PING " + self.servername)
41 def send_line(self, msg):
42 msg = msg.replace("\r", " ")
43 msg = msg.replace("\n", " ")
44 if len(msg.encode("utf-8")) > 510:
45 print("NOT SENT LINE TO SERVER (too long): " + msg)
46 print("LINE TO SERVER: "
47 + str(datetime.datetime.now()) + ": " + msg)
51 while total_sent_len < msg_len:
52 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
54 print("SOCKET CONNECTION BROKEN")
55 raise ExceptionForRestart
56 total_sent_len += sent_len
58 def _recv_line_wrapped(self, send_ping=True):
59 if len(self.line_buffer) > 0:
60 return self.line_buffer.pop(0)
62 ready = select.select([self.socket], [], [], int(self.timeout / 2))
64 self._pingtest(send_ping)
66 self.last_pong = time.time()
67 received_runes = self.socket.recv(1024).decode("UTF-8")
68 if len(received_runes) == 0:
69 print("SOCKET CONNECTION BROKEN")
70 raise ExceptionForRestart
71 self.rune_buffer += received_runes
72 lines_split = str.split(self.rune_buffer, "\r\n")
73 self.line_buffer += lines_split[:-1]
74 self.rune_buffer = lines_split[-1]
75 if len(self.line_buffer) > 0:
76 return self.line_buffer.pop(0)
78 def recv_line(self, send_ping=True):
79 line = self._recv_line_wrapped(send_ping)
81 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
85 def init_session(server, port, timeout, nickname, username, channel):
86 print("CONNECTING TO " + server)
87 io = IO(server, port, timeout)
88 io.send_line("NICK " + nickname)
89 io.send_line("USER " + username + " 0 * : ")
90 io.send_line("JOIN " + channel)
93 def lineparser_loop(io, nickname):
95 def act_on_privmsg(tokens):
98 matches = re.findall("(https?://[^\s]+)", msg)
99 for i in range(len(matches)):
102 webpage = urllib.request.urlopen(url, timeout=15)
103 except urllib.error.HTTPError as error:
104 print("TROUBLE FOLLOWING URL: " + str(error))
106 charset = webpage.info().get_content_charset()
109 content_type = webpage.info().get_content_type()
110 if not content_type in ('text/html', 'text/xml',
111 'application/xhtml+xml'):
112 print("TROUBLE INTERPRETING URL: bad content type "
115 content = webpage.read().decode(charset)
116 title = str(content).split('<title>')[1].split('</title>')[0]
117 title = html.unescape(title)
118 io.send_line("PRIVMSG " + target + " :page title for url: "
122 for rune in tokens[0]:
128 for rune in tokens[2]:
134 if receiver != nickname:
136 msg = str.join(" ", tokens[3:])[1:]
140 line = io.recv_line()
143 tokens = line.split(" ")
145 if tokens[1] == "PRIVMSG":
146 act_on_privmsg(tokens)
147 if tokens[0] == "PING":
148 io.send_line("PONG " + tokens[1])
150 def parse_command_line_arguments():
151 parser = argparse.ArgumentParser()
152 parser.add_argument("-s, --server", action="store", dest="server",
154 help="server or server net to connect to (default: " + SERVER +
156 parser.add_argument("-p, --port", action="store", dest="port", type=int,
157 default=PORT, help="port to connect to (default : " + str(PORT) +
159 parser.add_argument("-t, --timeout", action="store", dest="timeout",
160 type=int, default=TIMEOUT,
161 help="timeout in seconds after which to attempt reconnect " +
162 "(default: " + str(TIMEOUT) + ")")
163 parser.add_argument("-u, --username", action="store", dest="username",
164 default=USERNAME, help="username to use (default: " + USERNAME +
166 parser.add_argument("-n, --nickname", action="store", dest="nickname",
167 default=NICKNAME, help="nickname to use (default: " + NICKNAME +
169 parser.add_argument("CHANNEL", action="store", help="channel to join")
170 opts, unknown = parser.parse_known_args()
173 opts = parse_command_line_arguments()
176 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
177 opts.username, opts.CHANNEL)
178 lineparser_loop(io, opts.nickname)
179 except ExceptionForRestart: