home · contact · privacy
c32b6dd3c0c42b79f86bb00c96d6f8b7d9017fd2
[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 requests
10 import bs4
11 import random
12 import hashlib
13 import os
14 import plomsearch
15
16 # Defaults, may be overwritten by command line arguments.
17 SERVER = "irc.freenode.net"
18 PORT = 6667
19 TIMEOUT = 240
20 USERNAME = "plomlombot"
21 NICKNAME = USERNAME
22
23
24 class ExceptionForRestart(Exception):
25     pass
26
27
28 class IO:
29
30     def __init__(self, server, port, timeout):
31         self.timeout = timeout
32         self.socket = socket.socket()
33         self.socket.connect((server, port))
34         self.socket.setblocking(0)
35         self.line_buffer = []
36         self.rune_buffer = ""
37         self.last_pong = time.time()
38         self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
39
40     def _pingtest(self, send_ping=True):
41         if self.last_pong + self.timeout < time.time():
42             print("SERVER NOT ANSWERING")
43             raise ExceptionForRestart
44         if send_ping:
45             self.send_line("PING " + self.servername)
46
47     def send_line(self, msg):
48         msg = msg.replace("\r", " ")
49         msg = msg.replace("\n", " ")
50         if len(msg.encode("utf-8")) > 510:
51             print("NOT SENT LINE TO SERVER (too long): " + msg)
52         print("LINE TO SERVER: "
53               + str(datetime.datetime.now()) + ": " + msg)
54         msg = msg + "\r\n"
55         msg_len = len(msg)
56         total_sent_len = 0
57         while total_sent_len < msg_len:
58             sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
59             if sent_len == 0:
60                 print("SOCKET CONNECTION BROKEN")
61                 raise ExceptionForRestart
62             total_sent_len += sent_len
63
64     def _recv_line_wrapped(self, send_ping=True):
65         if len(self.line_buffer) > 0:
66             return self.line_buffer.pop(0)
67         while True:
68             ready = select.select([self.socket], [], [], int(self.timeout / 2))
69             if not ready[0]:
70                 self._pingtest(send_ping)
71                 return None
72             self.last_pong = time.time()
73             received_bytes = self.socket.recv(1024)
74             try:
75                 received_runes = received_bytes.decode("UTF-8")
76             except UnicodeDecodeError:
77                 received_runes = received_bytes.decode("latin1")
78             if len(received_runes) == 0:
79                 print("SOCKET CONNECTION BROKEN")
80                 raise ExceptionForRestart
81             self.rune_buffer += received_runes
82             lines_split = str.split(self.rune_buffer, "\r\n")
83             self.line_buffer += lines_split[:-1]
84             self.rune_buffer = lines_split[-1]
85             if len(self.line_buffer) > 0:
86                 return self.line_buffer.pop(0)
87
88     def recv_line(self, send_ping=True):
89         line = self._recv_line_wrapped(send_ping)
90         if line:
91             print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
92                   line)
93         return line
94
95
96 def init_session(server, port, timeout, nickname, username, channel):
97     print("CONNECTING TO " + server)
98     io = IO(server, port, timeout)
99     io.send_line("NICK " + nickname)
100     io.send_line("USER " + username + " 0 * : ")
101     io.send_line("JOIN " + channel)
102     return io
103
104
105 def lineparser_loop(io, nickname):
106
107     def act_on_privmsg(tokens):
108
109         def notice(msg):
110             io.send_line("NOTICE " + target + " :" + msg)
111
112         def url_check(msg):
113
114             def handle_url(url, show_url=False):
115
116                 def mobile_twitter_hack(url):
117                     re1 = 'https?://(mobile.twitter.com/)[^/]+(/status/)'
118                     re2 = 'https?://mobile.twitter.com/([^/]+)/status/' \
119                         + '([^\?/]+)'
120                     m = re.search(re1, url)
121                     if m and m.group(1) == 'mobile.twitter.com/' \
122                             and m.group(2) == '/status/':
123                         m = re.search(re2, url)
124                         url = 'https://twitter.com/' + m.group(1) + '/status/' \
125                                 + m.group(2)
126                         handle_url(url, True)
127                         return True
128
129                 try:
130                     r = requests.get(url, timeout=15)
131                 except (requests.exceptions.TooManyRedirects,
132                         requests.exceptions.ConnectionError,
133                         requests.exceptions.InvalidURL,
134                         requests.exceptions.InvalidSchema) as error:
135                     notice("TROUBLE FOLLOWING URL: " + str(error))
136                     return
137                 if mobile_twitter_hack(url):
138                     return
139                 title = bs4.BeautifulSoup(r.text).title
140                 if title:
141                     prefix = "PAGE TITLE: "
142                     if show_url:
143                         prefix = "PAGE TITLE FOR <" + url + ">: "
144                     notice(prefix + title.string.strip())
145                 else:
146                     notice("PAGE HAS NO TITLE TAG")
147
148             matches = re.findall("(https?://[^\s>]+)", msg)
149             for i in range(len(matches)):
150                 handle_url(matches[i])
151
152         def command_check(msg):
153             if msg[0] != "!":
154                 return
155             tokens = msg[1:].split()
156             hash_string = hashlib.md5(target.encode("utf-8")).hexdigest()
157             quotesfile_name = "quotes_" + hash_string
158             if tokens[0] == "addquote":
159                 if not os.access(quotesfile_name, os.F_OK):
160                     quotesfile = open(quotesfile_name, "w")
161                     quotesfile.write("QUOTES FOR " + target + ":\n")
162                     quotesfile.close()
163                 quotesfile = open(quotesfile_name, "a")
164                 quotesfile.write(str.join(" ", tokens[1:]) + "\n")
165                 quotesfile.close()
166                 quotesfile = open(quotesfile_name, "r")
167                 lines = quotesfile.readlines()
168                 quotesfile.close()
169                 notice("ADDED QUOTE #" + str(len(lines) - 1))
170             elif tokens[0] == "quote":
171                 if (len(tokens) > 2 and tokens[1] != "search") or \
172                     (len(tokens) < 3 and tokens[1] == "search") or \
173                     (len(tokens) == 2 and not tokens[1].isdigit()):
174                     notice("SYNTAX: !quote [int] OR !quote search QUERY")
175                     notice("QUERY may be a boolean grouping of quoted or "\
176                         + "unquoted search terms, examples:")
177                     notice("!quote search foo")
178                     notice("!quote search foo AND (bar OR NOT baz)")
179                     notice("!quote search \"foo\\\"bar\" AND "\
180                             + "('NOT\"' AND \"'foo'\" OR 'bar\\'baz')")
181                     return
182                 if not os.access(quotesfile_name, os.F_OK):
183                     notice("NO QUOTES AVAILABLE")
184                     return
185                 quotesfile = open(quotesfile_name, "r")
186                 lines = quotesfile.readlines()
187                 quotesfile.close()
188                 lines = lines[1:]
189                 if len(tokens) == 2:
190                     i = int(tokens[1])
191                     if i == 0 or i > len(lines):
192                         notice("THERE'S NO QUOTE OF THAT INDEX")
193                         return
194                     i = i - 1
195                 elif len(tokens) > 2:
196                     query = str.join(" ", tokens[2:])
197                     try:
198                         results = plomsearch.search(query, lines)
199                     except plomsearch.LogicParserError as err:
200                         notice("FAILED QUERY PARSING: " + str(err))
201                         return
202                     if len(results) == 0:
203                         notice("NO QUOTES MATCHING QUERY")
204                     else:
205                         for result in results:
206                             notice("QUOTE #" + str(result[0] + 1) + " : "
207                                 + result[1])
208                     return
209                 else:
210                     i = random.randrange(len(lines))
211                 notice("QUOTE #" + str(i + 1) + ": " + lines[i])
212
213         sender = ""
214         for rune in tokens[0]:
215             if rune == "!":
216                 break
217             if rune != ":":
218                 sender += rune
219         receiver = ""
220         for rune in tokens[2]:
221             if rune == "!":
222                 break
223             if rune != ":":
224                 receiver += rune
225         target = sender
226         if receiver != nickname:
227             target = receiver
228         msg = str.join(" ", tokens[3:])[1:]
229         command_check(msg)
230         url_check(msg)
231
232     while True:
233         line = io.recv_line()
234         if not line:
235             continue
236         tokens = line.split(" ")
237         if len(tokens) > 1:
238             if tokens[1] == "PRIVMSG":
239                 act_on_privmsg(tokens)
240             if tokens[0] == "PING":
241                 io.send_line("PONG " + tokens[1])
242
243
244 def parse_command_line_arguments():
245     parser = argparse.ArgumentParser()
246     parser.add_argument("-s, --server", action="store", dest="server",
247                         default=SERVER,
248                         help="server or server net to connect to (default: "
249                         + SERVER + ")")
250     parser.add_argument("-p, --port", action="store", dest="port", type=int,
251                         default=PORT, help="port to connect to (default : "
252                         + str(PORT) + ")")
253     parser.add_argument("-t, --timeout", action="store", dest="timeout",
254                         type=int, default=TIMEOUT,
255                         help="timeout in seconds after which to attempt " +
256                         "reconnect (default: " + str(TIMEOUT) + ")")
257     parser.add_argument("-u, --username", action="store", dest="username",
258                         default=USERNAME, help="username to use (default: "
259                         + USERNAME + ")")
260     parser.add_argument("-n, --nickname", action="store", dest="nickname",
261                         default=NICKNAME, help="nickname to use (default: "
262                         + NICKNAME + ")")
263     parser.add_argument("CHANNEL", action="store", help="channel to join")
264     opts, unknown = parser.parse_known_args()
265     return opts
266
267 opts = parse_command_line_arguments()
268 while True:
269     try:
270         io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
271                           opts.username, opts.CHANNEL)
272         lineparser_loop(io, opts.nickname)
273     except ExceptionForRestart:
274         io.socket.close()
275         continue