13 # Defaults, may be overwritten by command line arguments.
14 SERVER = "irc.freenode.net"
17 USERNAME = "plomlombot"
21 class ExceptionForRestart(Exception):
27 def __init__(self, server, port, timeout):
28 self.timeout = timeout
29 self.socket = socket.socket()
30 self.socket.connect((server, port))
31 self.socket.setblocking(0)
34 self.last_pong = time.time()
35 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
37 def _pingtest(self, send_ping=True):
38 if self.last_pong + self.timeout < time.time():
39 print("SERVER NOT ANSWERING")
40 raise ExceptionForRestart
42 self.send_line("PING " + self.servername)
44 def send_line(self, msg):
45 msg = msg.replace("\r", " ")
46 msg = msg.replace("\n", " ")
47 if len(msg.encode("utf-8")) > 510:
48 print("NOT SENT LINE TO SERVER (too long): " + msg)
49 print("LINE TO SERVER: "
50 + str(datetime.datetime.now()) + ": " + msg)
54 while total_sent_len < msg_len:
55 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
57 print("SOCKET CONNECTION BROKEN")
58 raise ExceptionForRestart
59 total_sent_len += sent_len
61 def _recv_line_wrapped(self, send_ping=True):
62 if len(self.line_buffer) > 0:
63 return self.line_buffer.pop(0)
65 ready = select.select([self.socket], [], [], int(self.timeout / 2))
67 self._pingtest(send_ping)
69 self.last_pong = time.time()
70 received_runes = self.socket.recv(1024).decode("UTF-8")
71 if len(received_runes) == 0:
72 print("SOCKET CONNECTION BROKEN")
73 raise ExceptionForRestart
74 self.rune_buffer += received_runes
75 lines_split = str.split(self.rune_buffer, "\r\n")
76 self.line_buffer += lines_split[:-1]
77 self.rune_buffer = lines_split[-1]
78 if len(self.line_buffer) > 0:
79 return self.line_buffer.pop(0)
81 def recv_line(self, send_ping=True):
82 line = self._recv_line_wrapped(send_ping)
84 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
89 def init_session(server, port, timeout, nickname, username, channel):
90 print("CONNECTING TO " + server)
91 io = IO(server, port, timeout)
92 io.send_line("NICK " + nickname)
93 io.send_line("USER " + username + " 0 * : ")
94 io.send_line("JOIN " + channel)
98 def lineparser_loop(io, nickname):
100 def act_on_privmsg(tokens):
103 matches = re.findall("(https?://[^\s>]+)", msg)
104 for i in range(len(matches)):
107 webpage = urllib.request.urlopen(url, timeout=15)
108 except (urllib.error.HTTPError, urllib.error.URLError,
109 UnicodeError, http.client.BadStatusLine) as error:
110 print("TROUBLE FOLLOWING URL: " + str(error))
112 charset = webpage.info().get_content_charset()
115 content_type = webpage.info().get_content_type()
116 if content_type not in ('text/html', 'text/xml',
117 'application/xhtml+xml'):
118 print("TROUBLE INTERPRETING URL: bad content type "
121 content = webpage.read().decode(charset)
122 title = str(content).split('<title>')[1].split('</title>')[0]
123 title = html.unescape(title)
124 io.send_line("PRIVMSG " + target + " :page title for url: "
128 for rune in tokens[0]:
134 for rune in tokens[2]:
140 if receiver != nickname:
142 msg = str.join(" ", tokens[3:])[1:]
146 line = io.recv_line()
149 tokens = line.split(" ")
151 if tokens[1] == "PRIVMSG":
152 act_on_privmsg(tokens)
153 if tokens[0] == "PING":
154 io.send_line("PONG " + tokens[1])
157 def parse_command_line_arguments():
158 parser = argparse.ArgumentParser()
159 parser.add_argument("-s, --server", action="store", dest="server",
161 help="server or server net to connect to (default: "
163 parser.add_argument("-p, --port", action="store", dest="port", type=int,
164 default=PORT, help="port to connect to (default : "
166 parser.add_argument("-t, --timeout", action="store", dest="timeout",
167 type=int, default=TIMEOUT,
168 help="timeout in seconds after which to attempt " +
169 "reconnect (default: " + str(TIMEOUT) + ")")
170 parser.add_argument("-u, --username", action="store", dest="username",
171 default=USERNAME, help="username to use (default: "
173 parser.add_argument("-n, --nickname", action="store", dest="nickname",
174 default=NICKNAME, help="nickname to use (default: "
176 parser.add_argument("CHANNEL", action="store", help="channel to join")
177 opts, unknown = parser.parse_known_args()
180 opts = parse_command_line_arguments()
183 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
184 opts.username, opts.CHANNEL)
185 lineparser_loop(io, opts.nickname)
186 except ExceptionForRestart: