home · contact · privacy
Send user agent in URL parser requests.
[plomlombot-irc.git] / plomlombot.py
1 #!/usr/bin/python3
2
3 import argparse
4 import socket
5 import datetime
6 import select
7 import time
8 import re
9 import urllib.request
10 import http.client
11 import html
12
13 # Defaults, may be overwritten by command line arguments.
14 SERVER = "irc.freenode.net"
15 PORT = 6667
16 TIMEOUT = 240
17 USERNAME = "plomlombot"
18 NICKNAME = USERNAME
19
20
21 class ExceptionForRestart(Exception):
22     pass
23
24
25 class IO:
26
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)
32         self.line_buffer = []
33         self.rune_buffer = ""
34         self.last_pong = time.time()
35         self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
36
37     def _pingtest(self, send_ping=True):
38         if self.last_pong + self.timeout < time.time():
39             print("SERVER NOT ANSWERING")
40             raise ExceptionForRestart
41         if send_ping:
42             self.send_line("PING " + self.servername)
43
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)
51         msg = msg + "\r\n"
52         msg_len = len(msg)
53         total_sent_len = 0
54         while total_sent_len < msg_len:
55             sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
56             if sent_len == 0:
57                 print("SOCKET CONNECTION BROKEN")
58                 raise ExceptionForRestart
59             total_sent_len += sent_len
60
61     def _recv_line_wrapped(self, send_ping=True):
62         if len(self.line_buffer) > 0:
63             return self.line_buffer.pop(0)
64         while True:
65             ready = select.select([self.socket], [], [], int(self.timeout / 2))
66             if not ready[0]:
67                 self._pingtest(send_ping)
68                 return None
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)
80
81     def recv_line(self, send_ping=True):
82         line = self._recv_line_wrapped(send_ping)
83         if line:
84             print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
85                   line)
86         return line
87
88
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)
95     return io
96
97
98 def lineparser_loop(io, nickname):
99
100     def act_on_privmsg(tokens):
101
102         def url_check(msg):
103             matches = re.findall("(https?://[^\s>]+)", msg)
104             for i in range(len(matches)):
105                 url = matches[i]
106                 request = urllib.request.Request(url, headers={
107                     "User-Agent": "plomlombot"
108                 })
109                 try:
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))
114                     continue
115                 charset = webpage.info().get_content_charset()
116                 if not charset:
117                     charset = "utf-8"
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 "
122                           + content_type)
123                     continue
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: "
128                              + title)
129
130         sender = ""
131         for rune in tokens[0]:
132             if rune == "!":
133                 break
134             if rune != ":":
135                 sender += rune
136         receiver = ""
137         for rune in tokens[2]:
138             if rune == "!":
139                 break
140             if rune != ":":
141                 receiver += rune
142         target = sender
143         if receiver != nickname:
144             target = receiver
145         msg = str.join(" ", tokens[3:])[1:]
146         url_check(msg)
147
148     while True:
149         line = io.recv_line()
150         if not line:
151             continue
152         tokens = line.split(" ")
153         if len(tokens) > 1:
154             if tokens[1] == "PRIVMSG":
155                 act_on_privmsg(tokens)
156             if tokens[0] == "PING":
157                 io.send_line("PONG " + tokens[1])
158
159
160 def parse_command_line_arguments():
161     parser = argparse.ArgumentParser()
162     parser.add_argument("-s, --server", action="store", dest="server",
163                         default=SERVER,
164                         help="server or server net to connect to (default: "
165                         + SERVER + ")")
166     parser.add_argument("-p, --port", action="store", dest="port", type=int,
167                         default=PORT, help="port to connect to (default : "
168                         + str(PORT) + ")")
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: "
175                         + USERNAME + ")")
176     parser.add_argument("-n, --nickname", action="store", dest="nickname",
177                         default=NICKNAME, help="nickname to use (default: "
178                         + NICKNAME + ")")
179     parser.add_argument("CHANNEL", action="store", help="channel to join")
180     opts, unknown = parser.parse_known_args()
181     return opts
182
183 opts = parse_command_line_arguments()
184 while True:
185     try:
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:
190         io.socket.close()
191         continue