9 servernet = "irc.freenode.net"
13 username = "plomlombot"
19 def __init__(self, server, port):
20 self.socket = socket.socket()
21 self.socket.connect((server, port))
22 self.socket.setblocking(0)
25 self.last_pong = time.time()
28 if self.last_pong + timeout < time.time():
29 raise RuntimeError("server not answering")
30 self.send_line("PING " + nickname + " " + servername)
32 def send_line(self, msg):
33 msg = msg.replace("\r", " ")
34 msg = msg.replace("\n", " ")
35 if len(msg.encode("utf-8")) > 510:
36 print("NOT SENT LINE TO SERVER (too long): " + msg)
37 print("LINE TO SERVER: "
38 + str(datetime.datetime.now()) + ": " + msg)
42 while total_sent_len < msg_len:
43 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
45 raise RuntimeError("socket connection broken")
46 total_sent_len += sent_len
48 def recv_line_wrapped(self):
49 if len(self.line_buffer) > 0:
50 return self.line_buffer.pop(0)
52 ready = select.select([self.socket], [], [], int(timeout / 2))
56 self.last_pong = time.time()
57 received_runes = self.socket.recv(1024).decode("UTF-8")
58 if len(received_runes) == 0:
59 raise RuntimeError("socket connection broken")
60 self.rune_buffer += received_runes
61 lines_split = str.split(self.rune_buffer, "\r\n")
62 self.line_buffer += lines_split[:-1]
63 self.rune_buffer = lines_split[-1]
64 if len(self.line_buffer) > 0:
65 return self.line_buffer.pop(0)
68 line = self.recv_line_wrapped()
70 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
74 io = IO(servernet, port)
75 io.send_line("NICK " + nickname)
76 io.send_line("USER " + username + " 0 * : ")
77 io.send_line("JOIN " + channel)
78 servername = io.recv_line().split(" ")[0][1:]
83 tokens = line.split(" ")
85 if tokens[1] == "PRIVMSG":
87 for rune in tokens[0]:
93 for rune in tokens[2]:
99 if receiver != nickname:
101 msg = str.join(" ", tokens[3:])[1:]
102 matches = re.findall("(https?://[^\s]+)", msg)
103 for i in range(len(matches)):
105 webpage = urllib.request.urlopen(url)
106 charset = webpage.info().get_content_charset()
107 content = webpage.read().decode(charset)
108 title = str(content).split('<title>')[1].split('</title>')[0]
109 title = html.unescape(title)
110 io.send_line("PRIVMSG "
111 + target + " :page title for url: " + title)
112 if tokens[0] == "PING":
113 io.send_line("PONG " + tokens[1])