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)):
106 request = urllib.request.Request(url, headers={
107 "User-Agent": "plomlombot"
110 webpage = urllib.request.urlopen(request, timeout=15)
111 except (urllib.error.HTTPError, urllib.error.URLError,
112 UnicodeError, http.client.BadStatusLine) as error:
113 print("TROUBLE FOLLOWING URL: " + str(error))
115 charset = webpage.info().get_content_charset()
118 content_type = webpage.info().get_content_type()
119 if content_type not in ('text/html', 'text/xml',
120 'application/xhtml+xml'):
121 print("TROUBLE INTERPRETING URL: bad content type "
124 content = webpage.read().decode(charset)
125 title = str(content).split('<title>')[1].split('</title>')[0]
126 title = html.unescape(title)
127 io.send_line("PRIVMSG " + target + " :page title for url: "
131 for rune in tokens[0]:
137 for rune in tokens[2]:
143 if receiver != nickname:
145 msg = str.join(" ", tokens[3:])[1:]
149 line = io.recv_line()
152 tokens = line.split(" ")
154 if tokens[1] == "PRIVMSG":
155 act_on_privmsg(tokens)
156 if tokens[0] == "PING":
157 io.send_line("PONG " + tokens[1])
160 def parse_command_line_arguments():
161 parser = argparse.ArgumentParser()
162 parser.add_argument("-s, --server", action="store", dest="server",
164 help="server or server net to connect to (default: "
166 parser.add_argument("-p, --port", action="store", dest="port", type=int,
167 default=PORT, help="port to connect to (default : "
169 parser.add_argument("-t, --timeout", action="store", dest="timeout",
170 type=int, default=TIMEOUT,
171 help="timeout in seconds after which to attempt " +
172 "reconnect (default: " + str(TIMEOUT) + ")")
173 parser.add_argument("-u, --username", action="store", dest="username",
174 default=USERNAME, help="username to use (default: "
176 parser.add_argument("-n, --nickname", action="store", dest="nickname",
177 default=NICKNAME, help="nickname to use (default: "
179 parser.add_argument("CHANNEL", action="store", help="channel to join")
180 opts, unknown = parser.parse_known_args()
183 opts = parse_command_line_arguments()
186 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
187 opts.username, opts.CHANNEL)
188 lineparser_loop(io, opts.nickname)
189 except ExceptionForRestart: