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