home · contact · privacy
cf6bae90864be27ec6a750876b72070e36287774
[plomlombot-irc.git] / plomlombot.py
1 import socket
2 import datetime
3 import select
4 import time
5 import re
6 import urllib.request
7 import html
8
9 servernet = "irc.freenode.net"
10 port = 6667
11 servername = ""
12 timeout = 240
13 username = "plomlombot"
14 nickname = username
15 channel = "#zrolaps-test"
16
17 class IO:
18
19     def __init__(self, server, port):
20         self.socket = socket.socket()
21         self.socket.connect((server, port))
22         self.socket.setblocking(0)
23         self.line_buffer = []
24         self.rune_buffer = ""
25         self.last_pong = time.time()
26
27     def _pingtest(self):
28         if self.last_pong + timeout < time.time():
29             raise RuntimeError("server not answering")
30         self.send_line("PING " + nickname + " " + servername)
31
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)
39         msg = msg + "\r\n"
40         msg_len = len(msg)
41         total_sent_len = 0
42         while total_sent_len < msg_len:
43             sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
44             if sent_len == 0:
45                 raise RuntimeError("socket connection broken")
46             total_sent_len += sent_len
47
48     def recv_line_wrapped(self):
49         if len(self.line_buffer) > 0:
50             return self.line_buffer.pop(0)
51         while True:
52             ready = select.select([self.socket], [], [], int(timeout / 2))
53             if not ready[0]:
54                 self._pingtest()
55                 return None
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)
66
67     def recv_line(self):
68         line = self.recv_line_wrapped()
69         if line:
70             print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
71             line)
72         return line
73
74 def url_check(msg):
75     matches = re.findall("(https?://[^\s]+)", msg)
76     for i in range(len(matches)):
77         url = matches[i]
78         webpage = urllib.request.urlopen(url)
79         content_type = webpage.info().get_content_type()
80         charset = webpage.info().get_content_charset()
81         if not charset or not content_type in ('text/html', 'text/xml',
82                 'application/xhtml+xml'):
83             continue
84         content = webpage.read().decode(charset)
85         title = str(content).split('<title>')[1].split('</title>')[0]
86         title = html.unescape(title)
87         io.send_line("PRIVMSG " + target + " :page title for url: " + title)
88
89 io = IO(servernet, port)
90 io.send_line("NICK " + nickname)
91 io.send_line("USER " + username + " 0 * : ")
92 io.send_line("JOIN " + channel)
93 servername = io.recv_line().split(" ")[0][1:]
94 while 1:
95     line = io.recv_line()
96     if not line:
97         continue
98     tokens = line.split(" ")
99     if len(tokens) > 1:
100         if tokens[1] == "PRIVMSG":
101             sender = ""
102             for rune in tokens[0]:
103                 if rune == "!":
104                     break
105                 if rune != ":":
106                     sender += rune
107             receiver = ""
108             for rune in tokens[2]:
109                 if rune == "!":
110                     break
111                 if rune != ":":
112                     receiver += rune
113             target = sender
114             if receiver != nickname:
115                 target = receiver
116             msg = str.join(" ", tokens[3:])[1:]
117             url_check(msg)
118         if tokens[0] == "PING":
119             io.send_line("PONG " + tokens[1])