15 # Defaults, may be overwritten by command line arguments.
16 SERVER = "irc.freenode.net"
19 USERNAME = "plomlombot"
23 class ExceptionForRestart(Exception):
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)
36 self.last_pong = time.time()
37 self.servername = self.recv_line(send_ping=False).split(" ")[0][1:]
39 def _pingtest(self, send_ping=True):
40 if self.last_pong + self.timeout < time.time():
41 print("SERVER NOT ANSWERING")
42 raise ExceptionForRestart
44 self.send_line("PING " + self.servername)
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)
56 while total_sent_len < msg_len:
57 sent_len = self.socket.send(bytes(msg[total_sent_len:], "UTF-8"))
59 print("SOCKET CONNECTION BROKEN")
60 raise ExceptionForRestart
61 total_sent_len += sent_len
63 def _recv_line_wrapped(self, send_ping=True):
64 if len(self.line_buffer) > 0:
65 return self.line_buffer.pop(0)
67 ready = select.select([self.socket], [], [], int(self.timeout / 2))
69 self._pingtest(send_ping)
71 self.last_pong = time.time()
72 received_bytes = self.socket.recv(1024)
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)
87 def recv_line(self, send_ping=True):
88 line = self._recv_line_wrapped(send_ping)
90 print("LINE FROM SERVER " + str(datetime.datetime.now()) + ": " +
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)
104 def lineparser_loop(io, nickname):
106 def act_on_privmsg(tokens):
109 io.send_line("NOTICE " + target + " :" + msg)
112 matches = re.findall("(https?://[^\s>]+)", msg)
113 for i in range(len(matches)):
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))
123 title = bs4.BeautifulSoup(r.text).title
125 notice("PAGE TITLE: " + title.string.strip())
127 notice("PAGE HAS NO TITLE TAG")
129 def command_check(msg):
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")
140 quotesfile = open(quotesfile_name, "a")
141 quotesfile.write(str.join(" ", tokens[1:]) + "\n")
143 quotesfile = open(quotesfile_name, "r")
144 lines = quotesfile.readlines()
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")
151 quotesfile = open(quotesfile_name, "r")
152 lines = quotesfile.readlines()
155 i = random.randrange(len(lines))
156 notice("QUOTE #" + str(i + 1) + ": " + lines[i])
159 for rune in tokens[0]:
165 for rune in tokens[2]:
171 if receiver != nickname:
173 msg = str.join(" ", tokens[3:])[1:]
178 line = io.recv_line()
181 tokens = line.split(" ")
183 if tokens[1] == "PRIVMSG":
184 act_on_privmsg(tokens)
185 if tokens[0] == "PING":
186 io.send_line("PONG " + tokens[1])
189 def parse_command_line_arguments():
190 parser = argparse.ArgumentParser()
191 parser.add_argument("-s, --server", action="store", dest="server",
193 help="server or server net to connect to (default: "
195 parser.add_argument("-p, --port", action="store", dest="port", type=int,
196 default=PORT, help="port to connect to (default : "
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: "
205 parser.add_argument("-n, --nickname", action="store", dest="nickname",
206 default=NICKNAME, help="nickname to use (default: "
208 parser.add_argument("CHANNEL", action="store", help="channel to join")
209 opts, unknown = parser.parse_known_args()
212 opts = parse_command_line_arguments()
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: