12 # Defaults, may be overwritten by command line arguments.
13 SERVER = "irc.freenode.net"
16 USERNAME = "plomlombot"
20 class ExceptionForRestart(Exception):
26 def __init__(self, server, port, timeout):
27 self.timeout = timeout
28 self.socket = socket.socket()
29 self.socket.connect((server, port))
30 self.socket.setblocking(0)
33 self.last_pong = time.time()
34 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
36 def _pingtest(self, send_ping=True):
37 if self.last_pong + self.timeout < time.time():
38 print("SERVER NOT ANSWERING")
39 raise ExceptionForRestart
41 self.send_line("PING " + self.servername)
43 def send_line(self, msg):
44 msg = msg.replace("\r", " ")
45 msg = msg.replace("\n", " ")
46 if len(msg.encode("utf-8")) > 510:
47 print("NOT SENT LINE TO SERVER (too long): " + msg)
48 print("LINE TO SERVER: "
49 + str(datetime.datetime.now()) + ": " + msg)
53 while total_sent_len < msg_len:
54 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
56 print("SOCKET CONNECTION BROKEN")
57 raise ExceptionForRestart
58 total_sent_len += sent_len
60 def _recv_line_wrapped(self, send_ping=True):
61 if len(self.line_buffer) > 0:
62 return self.line_buffer.pop(0)
64 ready = select.select([self.socket], [], [], int(self.timeout / 2))
66 self._pingtest(send_ping)
68 self.last_pong = time.time()
69 received_bytes = self.socket.recv(1024)
71 received_runes = received_bytes.decode("UTF-8")
72 except UnicodeDecodeError:
73 received_runes = received_bytes.decode("latin1")
74 if len(received_runes) == 0:
75 print("SOCKET CONNECTION BROKEN")
76 raise ExceptionForRestart
77 self.rune_buffer += received_runes
78 lines_split = str.split(self.rune_buffer, "\r\n")
79 self.line_buffer += lines_split[:-1]
80 self.rune_buffer = lines_split[-1]
81 if len(self.line_buffer) > 0:
82 return self.line_buffer.pop(0)
84 def recv_line(self, send_ping=True):
85 line = self._recv_line_wrapped(send_ping)
87 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
92 def init_session(server, port, timeout, nickname, username, channel):
93 print("CONNECTING TO " + server)
94 io = IO(server, port, timeout)
95 io.send_line("NICK " + nickname)
96 io.send_line("USER " + username + " 0 * : ")
97 io.send_line("JOIN " + channel)
101 def lineparser_loop(io, nickname):
103 def act_on_privmsg(tokens):
108 io.send_line("NOTICE " + target + " :" + msg)
110 matches = re.findall("(https?://[^\s>]+)", msg)
111 for i in range(len(matches)):
114 r = requests.get(url, timeout=15)
115 except (requests.exceptions.TooManyRedirects,
116 requests.exceptions.ConnectionError,
117 requests.exceptions.InvalidURL,
118 requests.exceptions.InvalidSchema) as error:
119 notice("TROUBLE FOLLOWING URL: " + str(error))
121 title = bs4.BeautifulSoup(r.text).title
123 notice("PAGE TITLE FOR URL: " + title.string)
125 notice("PAGE HAS NO TITLE TAG")
128 for rune in tokens[0]:
134 for rune in tokens[2]:
140 if receiver != nickname:
142 msg = str.join(" ", tokens[3:])[1:]
146 line = io.recv_line()
149 tokens = line.split(" ")
151 if tokens[1] == "PRIVMSG":
152 act_on_privmsg(tokens)
153 if tokens[0] == "PING":
154 io.send_line("PONG " + tokens[1])
157 def parse_command_line_arguments():
158 parser = argparse.ArgumentParser()
159 parser.add_argument("-s, --server", action="store", dest="server",
161 help="server or server net to connect to (default: "
163 parser.add_argument("-p, --port", action="store", dest="port", type=int,
164 default=PORT, help="port to connect to (default : "
166 parser.add_argument("-t, --timeout", action="store", dest="timeout",
167 type=int, default=TIMEOUT,
168 help="timeout in seconds after which to attempt " +
169 "reconnect (default: " + str(TIMEOUT) + ")")
170 parser.add_argument("-u, --username", action="store", dest="username",
171 default=USERNAME, help="username to use (default: "
173 parser.add_argument("-n, --nickname", action="store", dest="nickname",
174 default=NICKNAME, help="nickname to use (default: "
176 parser.add_argument("CHANNEL", action="store", help="channel to join")
177 opts, unknown = parser.parse_known_args()
180 opts = parse_command_line_arguments()
183 io = init_session(opts.server, opts.port, opts.timeout, opts.nickname,
184 opts.username, opts.CHANNEL)
185 lineparser_loop(io, opts.nickname)
186 except ExceptionForRestart: