12 # Defaults, may be overwritten by command line arguments.
13 SERVER = "irc.freenode.net"
16 USERNAME = "plomlombot"
20 class ExceptionForRestart(Exception):
26 def __init__(self, server, port, timeout):
27 self.timeout = timeout
28 self.socket = socket.socket()
29 self.socket.connect((server, port))
30 self.socket.setblocking(0)
33 self.last_pong = time.time()
34 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
36 def _pingtest(self, send_ping=True):
37 if self.last_pong + self.timeout < time.time():
38 print("SERVER NOT ANSWERING")
39 raise ExceptionForRestart
41 self.send_line("PING " + self.servername)
43 def send_line(self, msg):
44 msg = msg.replace("\r", " ")
45 msg = msg.replace("\n", " ")
46 if len(msg.encode("utf-8")) > 510:
47 print("NOT SENT LINE TO SERVER (too long): " + msg)
48 print("LINE TO SERVER: "
49 + str(datetime.datetime.now()) + ": " + msg)
53 while total_sent_len < msg_len:
54 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
56 print("SOCKET CONNECTION BROKEN")
57 raise ExceptionForRestart
58 total_sent_len += sent_len
60 def _recv_line_wrapped(self, send_ping=True):
61 if len(self.line_buffer) > 0:
62 return self.line_buffer.pop(0)
64 ready = select.select([self.socket], [], [], int(self.timeout / 2))
66 self._pingtest(send_ping)
68 self.last_pong = time.time()
69 received_runes = self.socket.recv(1024).decode("UTF-8")
70 if len(received_runes) == 0:
71 print("SOCKET CONNECTION BROKEN")
72 raise ExceptionForRestart
73 self.rune_buffer += received_runes
74 lines_split = str.split(self.rune_buffer, "\r\n")
75 self.line_buffer += lines_split[:-1]
76 self.rune_buffer = lines_split[-1]
77 if len(self.line_buffer) > 0:
78 return self.line_buffer.pop(0)
80 def recv_line(self, send_ping=True):
81 line = self._recv_line_wrapped(send_ping)
83 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
88 def init_session(server, port, timeout, nickname, username, channel):
89 print("CONNECTING TO " + server)
90 io = IO(server, port, timeout)
91 io.send_line("NICK " + nickname)
92 io.send_line("USER " + username + " 0 * : ")
93 io.send_line("JOIN " + channel)
97 def lineparser_loop(io, nickname):
99 def act_on_privmsg(tokens):
102 matches = re.findall("(https?://[^\s]+)", msg)
103 for i in range(len(matches)):
106 webpage = urllib.request.urlopen(url, timeout=15)
107 except (urllib.error.HTTPError, urllib.error.URLError,
108 UnicodeError) as error:
109 print("TROUBLE FOLLOWING URL: " + str(error))
111 charset = webpage.info().get_content_charset()
114 content_type = webpage.info().get_content_type()
115 if content_type not in ('text/html', 'text/xml',
116 'application/xhtml+xml'):
117 print("TROUBLE INTERPRETING URL: bad content type "
120 content = webpage.read().decode(charset)
121 title = str(content).split('<title>')[1].split('</title>')[0]
122 title = html.unescape(title)
123 io.send_line("PRIVMSG " + target + " :page title for url: "
127 for rune in tokens[0]:
133 for rune in tokens[2]:
139 if receiver != nickname:
141 msg = str.join(" ", tokens[3:])[1:]
145 line = io.recv_line()
148 tokens = line.split(" ")
150 if tokens[1] == "PRIVMSG":
151 act_on_privmsg(tokens)
152 if tokens[0] == "PING":
153 io.send_line("PONG " + tokens[1])
156 def parse_command_line_arguments():
157 parser = argparse.ArgumentParser()
158 parser.add_argument("-s, --server", action="store", dest="server",
160 help="server or server net to connect to (default: "
162 parser.add_argument("-p, --port", action="store", dest="port", type=int,
163 default=PORT, help="port to connect to (default : "
165 parser.add_argument("-t, --timeout", action="store", dest="timeout",
166 type=int, default=TIMEOUT,
167 help="timeout in seconds after which to attempt " +
168 "reconnect (default: " + str(TIMEOUT) + ")")
169 parser.add_argument("-u, --username", action="store", dest="username",
170 default=USERNAME, help="username to use (default: "
172 parser.add_argument("-n, --nickname", action="store", dest="nickname",
173 default=NICKNAME, help="nickname to use (default: "
175 parser.add_argument("CHANNEL", action="store", help="channel to join")
176 opts, unknown = parser.parse_known_args()
179 opts = parse_command_line_arguments()
182 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
183 opts.username, opts.CHANNEL)
184 lineparser_loop(io, opts.nickname)
185 except ExceptionForRestart: