logotron_genesis.kv 1 #!/usr/bin/python
logotron_genesis.kv 2
logotron_genesis.kv 3 import ConfigParser, sys, logging, socket, time, re, requests, urllib
logotron_genesis.kv 4 from urllib import quote
logotron_genesis.kv 5
logotron_genesis.kv 6 # DBism
logotron_genesis.kv 7 import psycopg2, psycopg2.extras
logotron_genesis.kv 8 import psycopg2.extensions
logotron_genesis.kv 9 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
logotron_genesis.kv 10 psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
logotron_genesis.kv 11 import time, datetime
logotron_genesis.kv 12 from datetime import datetime
logotron_genesis.kv 13
logotron_genesis.kv 14 ##############################################################################
logotron_genesis.kv 15
sept_fixes.kv 16 # Version. If changing this program, always set this to same # as in MANIFEST
active_disconnect... 17 Ver = 597604
sept_fixes.kv 18
sept_fixes.kv 19 ##############################################################################
sept_fixes.kv 20
logotron_genesis.kv 21 cfg = ConfigParser.ConfigParser()
logotron_genesis.kv 22
logotron_genesis.kv 23 ##############################################################################
logotron_genesis.kv 24
logotron_genesis.kv 25 # Single mandatory arg: config file path
logotron_genesis.kv 26 if len(sys.argv[1:]) != 1:
logotron_genesis.kv 27 # If no args, print usage and exit:
logotron_genesis.kv 28 print sys.argv[0] + " CONFIG"
logotron_genesis.kv 29 exit(0)
logotron_genesis.kv 30
logotron_genesis.kv 31 # Read Config
logotron_genesis.kv 32 cfg.readfp(open(sys.argv[1]))
logotron_genesis.kv 33
logotron_genesis.kv 34 # Get log path
logotron_genesis.kv 35 logpath = cfg.get("bofh", "log")
logotron_genesis.kv 36
logotron_genesis.kv 37 # Get IRCism debug toggle
logotron_genesis.kv 38 irc_dbg = cfg.get("irc", "irc_dbg")
logotron_genesis.kv 39 if irc_dbg == 1:
logotron_genesis.kv 40 log_lvl = logging.DEBUG
logotron_genesis.kv 41 else:
logotron_genesis.kv 42 log_lvl = logging.INFO
logotron_genesis.kv 43
logotron_genesis.kv 44 # Init logo
logotron_genesis.kv 45 logging.basicConfig(filename=logpath, filemode='a', level=log_lvl,
logotron_genesis.kv 46 format='%(asctime)s %(levelname)s %(message)s',
logotron_genesis.kv 47 datefmt='%d-%b-%y %H:%M:%S')
logotron_genesis.kv 48
logotron_genesis.kv 49 # Date format used in log lines
logotron_genesis.kv 50 Date_Short_Format = "%Y-%m-%d"
logotron_genesis.kv 51
logotron_genesis.kv 52 # Date format used in echoes
logotron_genesis.kv 53 Date_Long_Format = "%Y-%m-%d %H:%M:%S"
logotron_genesis.kv 54
logotron_genesis.kv 55 ##############################################################################
logotron_genesis.kv 56 # Get the remaining knob values:
logotron_genesis.kv 57
logotron_genesis.kv 58 try:
logotron_genesis.kv 59 # IRCism:
logotron_genesis.kv 60 Buf_Size = int(cfg.get("tcp", "bufsize"))
logotron_genesis.kv 61 Timeout = int(cfg.get("tcp", "timeout"))
logotron_genesis.kv 62 TX_Delay = float(cfg.get("tcp", "t_delay"))
logotron_genesis.kv 63 Servers = [x.strip() for x in cfg.get("irc", "servers").split(',')]
logotron_genesis.kv 64 Port = int(cfg.get("irc", "port"))
logotron_genesis.kv 65 Nick = cfg.get("irc", "nick")
logotron_genesis.kv 66 Pass = cfg.get("irc", "pass")
logotron_genesis.kv 67 Channels = [x.strip() for x in cfg.get("irc", "chans").split(',')]
logotron_genesis.kv 68 Join_Delay = int(cfg.get("irc", "join_t"))
logotron_genesis.kv 69 Prefix = cfg.get("control", "prefix")
logotron_genesis.kv 70 # DBism:
logotron_genesis.kv 71 DB_Name = cfg.get("db", "db_name")
logotron_genesis.kv 72 DB_User = cfg.get("db", "db_user")
logotron_genesis.kv 73 DB_DEBUG = cfg.get("db", "db_debug")
logotron_genesis.kv 74 # Logism:
logotron_genesis.kv 75 Base_URL = cfg.get("logotron", "base_url")
logotron_genesis.kv 76 Era = int(cfg.get("logotron", "era"))
logotron_genesis.kv 77 NewChan_Idx = int(cfg.get("logotron", "newchan_idx"))
logotron_genesis.kv 78 Src_URL = cfg.get("logotron", "src_url")
logotron_genesis.kv 79
logotron_genesis.kv 80 except Exception as e:
logotron_genesis.kv 81 print "Invalid config: ", e
logotron_genesis.kv 82 exit(1)
logotron_genesis.kv 83
logotron_genesis.kv 84 ##############################################################################
logotron_genesis.kv 85
logotron_genesis.kv 86 # Connect to the given DB
logotron_genesis.kv 87 try:
logotron_genesis.kv 88 db = psycopg2.connect("dbname=%s user=%s" % (DB_Name, DB_User))
logotron_genesis.kv 89 except Exception:
logotron_genesis.kv 90 print "Could not connect to DB!"
logotron_genesis.kv 91 logging.error("Could not connect to DB!")
logotron_genesis.kv 92 exit(1)
logotron_genesis.kv 93 else:
logotron_genesis.kv 94 logging.info("Connected to DB!")
logotron_genesis.kv 95
logotron_genesis.kv 96 ##############################################################################
logotron_genesis.kv 97
logotron_genesis.kv 98 def close_db():
logotron_genesis.kv 99 db.close()
logotron_genesis.kv 100
logotron_genesis.kv 101 def exec_db(query, args=()):
logotron_genesis.kv 102 cur = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
logotron_genesis.kv 103 if (DB_DEBUG): logging.debug("query: '{0}'".format(query))
logotron_genesis.kv 104 if (DB_DEBUG): logging.debug("args: '{0}'".format(args))
logotron_genesis.kv 105 cur.execute(query, args)
logotron_genesis.kv 106
logotron_genesis.kv 107 def query_db(query, args=(), one=False):
logotron_genesis.kv 108 cur = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
logotron_genesis.kv 109 if (DB_DEBUG): logging.debug("query: '{0}'".format(query))
logotron_genesis.kv 110 cur.execute(query, args)
logotron_genesis.kv 111 rv = cur.fetchone() if one else cur.fetchall()
logotron_genesis.kv 112 if (DB_DEBUG): logging.debug("query res: '{0}'".format(rv))
logotron_genesis.kv 113 return rv
logotron_genesis.kv 114
logotron_genesis.kv 115 def rollback_db():
logotron_genesis.kv 116 cur = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
logotron_genesis.kv 117 cur.execute("ROLLBACK")
logotron_genesis.kv 118 db.commit()
logotron_genesis.kv 119
logotron_genesis.kv 120 def commit_db():
logotron_genesis.kv 121 cur = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
logotron_genesis.kv 122 db.commit()
logotron_genesis.kv 123
logotron_genesis.kv 124
logotron_genesis.kv 125 ##############################################################################
logotron_genesis.kv 126 # IRCism
logotron_genesis.kv 127 ##############################################################################
logotron_genesis.kv 128
logotron_genesis.kv 129 # Used to compute 'uptime'
logotron_genesis.kv 130 time_last_conn = datetime.now()
logotron_genesis.kv 131
active_disconnect... 132 # Socket will be here:
active_disconnect... 133 sock = None;
logotron_genesis.kv 134
logotron_genesis.kv 135 # Initially we are not connected to anything
logotron_genesis.kv 136 connected = False
logotron_genesis.kv 137
active_disconnect... 138 def init_socket():
active_disconnect... 139 global sock
active_disconnect... 140 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
active_disconnect... 141
active_disconnect... 142 # Disable Nagle's algorithm for transmit operations
active_disconnect... 143 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
active_disconnect... 144 # Disable Nagle's algorithm for receive operation, Linux-only
active_disconnect... 145 try:
active_disconnect... 146 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
active_disconnect... 147 except Exception as e:
active_disconnect... 148 logging.warning(e)
active_disconnect... 149
active_disconnect... 150 connected = False
active_disconnect... 151
active_disconnect... 152 def deinit_socket():
active_disconnect... 153 global connected
active_disconnect... 154 global sock
active_disconnect... 155 sock.close()
active_disconnect... 156 connected = False
active_disconnect... 157
logotron_genesis.kv 158 # Connect to given host:port; return whether connected
logotron_genesis.kv 159 def connect(host, port):
logotron_genesis.kv 160 logging.info("Connecting to %s:%s" % (host, port))
logotron_genesis.kv 161 sock.settimeout(Timeout)
logotron_genesis.kv 162 try:
logotron_genesis.kv 163 sock.connect((host, port))
logotron_genesis.kv 164 except (socket.timeout, socket.error) as e:
logotron_genesis.kv 165 logging.warning(e)
logotron_genesis.kv 166 return False
logotron_genesis.kv 167 except Exception as e:
logotron_genesis.kv 168 logging.exception(e)
logotron_genesis.kv 169 return False
logotron_genesis.kv 170 else:
logotron_genesis.kv 171 logging.info("Connected.")
logotron_genesis.kv 172 return True
logotron_genesis.kv 173
logotron_genesis.kv 174
logotron_genesis.kv 175 # Attempt connect to each of hosts, in order, on port; return whether connected
logotron_genesis.kv 176 def connect_any(hosts, port):
logotron_genesis.kv 177 for host in hosts:
logotron_genesis.kv 178 if connect(host, port):
logotron_genesis.kv 179 return True
logotron_genesis.kv 180 return False
logotron_genesis.kv 181
logotron_genesis.kv 182
logotron_genesis.kv 183 # Transmit IRC message
logotron_genesis.kv 184 def send(message):
logotron_genesis.kv 185 global connected
logotron_genesis.kv 186 if not connected:
logotron_genesis.kv 187 logging.warning("Tried to send while disconnected?")
logotron_genesis.kv 188 return False
logotron_genesis.kv 189 time.sleep(TX_Delay)
logotron_genesis.kv 190 logging.debug("> '%s'" % message)
logotron_genesis.kv 191 message = "%s\r\n" % message
logotron_genesis.kv 192 try:
logotron_genesis.kv 193 sock.send(message.encode("utf-8"))
logotron_genesis.kv 194 except (socket.timeout, socket.error) as e:
logotron_genesis.kv 195 logging.warning("Socket could not send! Disconnecting.")
active_disconnect... 196 deinit_socket()
logotron_genesis.kv 197 return False
logotron_genesis.kv 198 except Exception as e:
logotron_genesis.kv 199 logging.exception(e)
logotron_genesis.kv 200 return False
logotron_genesis.kv 201
logotron_genesis.kv 202
logotron_genesis.kv 203 # Speak given message on a selected channel
logotron_genesis.kv 204 def speak(channel, message):
logotron_genesis.kv 205 send("PRIVMSG #%s :%s" % (channel, message))
logotron_genesis.kv 206 # Now save what the bot spoke:
logotron_genesis.kv 207 save_line(datetime.now(), channel, Nick, False, message)
logotron_genesis.kv 208
logotron_genesis.kv 209
logotron_genesis.kv 210 # Standard incoming IRC line (excludes fleanode liquishit, etc)
logotron_genesis.kv 211 irc_line_re = re.compile("""^:([^!]+)\!\S+\s+PRIVMSG\s+\#(\S+)\s+\:(.*)""")
logotron_genesis.kv 212
logotron_genesis.kv 213 # The '#' prevents interaction via PM, this is not a PM-able bot.
logotron_genesis.kv 214
logotron_genesis.kv 215 # 'Actions'
logotron_genesis.kv 216 irc_act_re = re.compile(""".*ACTION\s+(.*)""")
logotron_genesis.kv 217
logotron_genesis.kv 218
logotron_genesis.kv 219 # A line was received from IRC
logotron_genesis.kv 220 def received_line(line):
logotron_genesis.kv 221 # Process the traditional pingpong
logotron_genesis.kv 222 if line.startswith("PING"):
logotron_genesis.kv 223 send("PONG " + line.split()[1])
logotron_genesis.kv 224 else:
logotron_genesis.kv 225 logging.debug("< '%s'" % line)
logotron_genesis.kv 226 standard_line = re.search(irc_line_re, line)
logotron_genesis.kv 227 if standard_line:
logotron_genesis.kv 228 # Break this line into the standard segments
logotron_genesis.kv 229 (user, chan, text) = [s.strip() for s in standard_line.groups()]
logotron_genesis.kv 230 # Determine whether this line is an 'action' :
logotron_genesis.kv 231 action = False
logotron_genesis.kv 232 act = re.search(irc_act_re, line)
logotron_genesis.kv 233 if act:
logotron_genesis.kv 234 action = True
logotron_genesis.kv 235 text = act.group(1)
sept_fixes.kv 236 # Remove turd if present:
sept_fixes.kv 237 if text[-1:] == '\x01':
sept_fixes.kv 238 text = text[:-1]
logotron_genesis.kv 239 # This line is edible, process it.
logotron_genesis.kv 240 eat_logline(user, chan, text, action)
logotron_genesis.kv 241
logotron_genesis.kv 242
logotron_genesis.kv 243 # IRCate until we get disconnected
logotron_genesis.kv 244 def irc():
logotron_genesis.kv 245 global connected
uptimefix_bye_cac... 246 global time_last_conn
active_disconnect... 247 global sock
active_disconnect... 248
active_disconnect... 249 # Initialize a socket
active_disconnect... 250 init_socket()
logotron_genesis.kv 251
logotron_genesis.kv 252 # Connect to one among the specified servers, in given priority :
logotron_genesis.kv 253 while not connected:
logotron_genesis.kv 254 connected = connect_any(Servers, Port)
logotron_genesis.kv 255
logotron_genesis.kv 256 # Save time of last successful connect
logotron_genesis.kv 257 time_last_conn = datetime.now()
logotron_genesis.kv 258
logotron_genesis.kv 259 # Auth to server
logotron_genesis.kv 260 send("NICK %s\r\n" % Nick)
logotron_genesis.kv 261 send("USER %s %s %s :%s\r\n" % (Nick, Nick, Nick, Nick))
uniturds_etc.kv 262
uniturds_etc.kv 263 # If this is a production bot, rather than test, there will be a PW:
uniturds_etc.kv 264 if Pass != "":
uniturds_etc.kv 265 send("NICKSERV IDENTIFY %s %s\r\n" % (Nick, Pass))
logotron_genesis.kv 266
logotron_genesis.kv 267 time.sleep(Join_Delay) # wait to join until fleanode eats auth
logotron_genesis.kv 268
logotron_genesis.kv 269 # Join selected channels
logotron_genesis.kv 270 for chan in Channels:
logotron_genesis.kv 271 logging.info("Joining channel '%s'..." % chan)
logotron_genesis.kv 272 send("JOIN #%s\r\n" % chan)
logotron_genesis.kv 273
logotron_genesis.kv 274 while connected:
logotron_genesis.kv 275 try:
logotron_genesis.kv 276 data = sock.recv(Buf_Size)
logotron_genesis.kv 277 except socket.timeout as e:
active_disconnect... 278 logging.debug("Receive timed out")
logotron_genesis.kv 279 continue
logotron_genesis.kv 280 except socket.error as e:
active_disconnect... 281 logging.warning("Receive socket error, disconnecting.")
active_disconnect... 282 deinit_socket()
logotron_genesis.kv 283 continue
logotron_genesis.kv 284 except Exception as e:
logotron_genesis.kv 285 logging.exception(e)
active_disconnect... 286 deinit_socket()
logotron_genesis.kv 287 continue
logotron_genesis.kv 288 else:
logotron_genesis.kv 289 if len(data) == 0:
active_disconnect... 290 logging.warning("Receive socket closed, disconnecting.")
active_disconnect... 291 deinit_socket()
logotron_genesis.kv 292 continue
logotron_genesis.kv 293 try:
uniturds_etc.kv 294 try:
uniturds_etc.kv 295 data = data.strip(b'\r\n').decode("utf-8")
uniturds_etc.kv 296 except UnicodeDecodeError:
uniturds_etc.kv 297 data = data.strip(b'\r\n').decode('latin-1')
logotron_genesis.kv 298 for l in data.splitlines():
logotron_genesis.kv 299 received_line(l)
logotron_genesis.kv 300 continue
logotron_genesis.kv 301 except Exception as e:
logotron_genesis.kv 302 logging.exception(e)
logotron_genesis.kv 303 continue
logotron_genesis.kv 304
logotron_genesis.kv 305 ##############################################################################
logotron_genesis.kv 306
logotron_genesis.kv 307 html_escape_table = {
logotron_genesis.kv 308 "&": "&",
logotron_genesis.kv 309 '"': """,
logotron_genesis.kv 310 "'": "'",
logotron_genesis.kv 311 ">": ">",
logotron_genesis.kv 312 "<": "<",
logotron_genesis.kv 313 }
logotron_genesis.kv 314
logotron_genesis.kv 315 def html_escape(text):
logotron_genesis.kv 316 res = ("".join(html_escape_table.get(c,c) for c in text))
logotron_genesis.kv 317 return urllib.quote(res.encode('utf-8'))
logotron_genesis.kv 318
logotron_genesis.kv 319
logotron_genesis.kv 320 searcher_re = re.compile("""(\d+) Results""")
logotron_genesis.kv 321
logotron_genesis.kv 322 # Retrieve a search result count using the WWWistic frontend.
logotron_genesis.kv 323 # This way it is not necessary to have query parser in two places.
logotron_genesis.kv 324 # However it is slightly wasteful of CPU (requires actually loading results.)
logotron_genesis.kv 325 def get_search_res(chan, query):
logotron_genesis.kv 326 try:
logotron_genesis.kv 327 esc_q = html_escape(query)
logotron_genesis.kv 328 url = Base_URL + "log-search?q=" + esc_q + "&chan=" + chan
logotron_genesis.kv 329 res = requests.get(url).text
logotron_genesis.kv 330 t = res[res.find('<title>') + 7 : res.find('</title>')].strip()
logotron_genesis.kv 331 found = searcher_re.match(t)
logotron_genesis.kv 332 if found:
logotron_genesis.kv 333 output = "[" + url + "]" + "[" + found.group(1)
logotron_genesis.kv 334 output += """ results for "%s" in #%s]""" % (query, chan)
logotron_genesis.kv 335 return output
logotron_genesis.kv 336 else:
logotron_genesis.kv 337 return """No results found for "%s" in #%s""" % (query, chan)
logotron_genesis.kv 338 except Exception as e:
logotron_genesis.kv 339 logging.exception(e)
logotron_genesis.kv 340 return "No results returned (is logotron WWW up ?)"
logotron_genesis.kv 341
logotron_genesis.kv 342 ##############################################################################
logotron_genesis.kv 343
sept_fixes.kv 344 # Get perma-URL corresponding to given log line
sept_fixes.kv 345 def line_url(l):
sept_fixes.kv 346 return "{0}log/{1}/{2}#{3}".format(Base_URL,
sept_fixes.kv 347 l['chan'],
sept_fixes.kv 348 l['t'].strftime(Date_Short_Format),
sept_fixes.kv 349 l['idx'])
sept_fixes.kv 350
sept_fixes.kv 351 ##############################################################################
sept_fixes.kv 352
logotron_genesis.kv 353 # Commands:
logotron_genesis.kv 354
logotron_genesis.kv 355 def cmd_help(arg, user, chan):
logotron_genesis.kv 356 # Speak the 'help' text
logotron_genesis.kv 357 speak(chan, "%s: my valid commands are: %s" %
logotron_genesis.kv 358 (user, ', '.join(Commands.keys())));
logotron_genesis.kv 359
logotron_genesis.kv 360 def cmd_search(arg, user, chan):
logotron_genesis.kv 361 logging.debug("search: '%s'" % arg)
logotron_genesis.kv 362 speak(chan, get_search_res(chan, arg))
logotron_genesis.kv 363
logotron_genesis.kv 364 def cmd_seen(arg, user, chan):
sept_fixes.kv 365 # Empty query is prohibited:
sept_fixes.kv 366 if arg == "":
sept_fixes.kv 367 speak(chan, "Required argument: USER")
sept_fixes.kv 368 return
sept_fixes.kv 369
sept_fixes.kv 370 # Perform query:
sept_fixes.kv 371 seen_line = query_db(
sept_fixes.kv 372 '''select t, idx, payload, chan from loglines where
sept_fixes.kv 373 chan=%s and speaker=%s order by t desc limit 1;''',
sept_fixes.kv 374 [chan, arg], one=True)
sept_fixes.kv 375
sept_fixes.kv 376 # Where output will go
sept_fixes.kv 377 result = ""
sept_fixes.kv 378
sept_fixes.kv 379 # If user has been seen in THE CURRENT chan:
sept_fixes.kv 380 if seen_line != None:
sept_fixes.kv 381 time_txt = seen_line['t'].strftime(Date_Long_Format)
sept_fixes.kv 382 time_link = "[%s][%s]" % (line_url(seen_line), time_txt)
sept_fixes.kv 383 seen_line = "%s last seen here on %s: %s" % (arg,
sept_fixes.kv 384 time_link,
sept_fixes.kv 385 seen_line['payload'])
sept_fixes.kv 386 result = seen_line
sept_fixes.kv 387 else:
sept_fixes.kv 388 # If user has never been seen in this chan:
sept_fixes.kv 389 result = "The user %s has never been seen in #%s." % (arg, chan)
sept_fixes.kv 390
sept_fixes.kv 391 # Speak the result into the chan where command was issued
sept_fixes.kv 392 speak(chan, result)
sept_fixes.kv 393
sept_fixes.kv 394 def cmd_seen_anywhere(arg, user, chan):
sept_fixes.kv 395 # Empty query is prohibited:
sept_fixes.kv 396 if arg == "":
sept_fixes.kv 397 speak(chan, "Required argument: USER")
sept_fixes.kv 398 return
sept_fixes.kv 399
sept_fixes.kv 400 # Perform query:
sept_fixes.kv 401 seen_line = query_db(
sept_fixes.kv 402 '''select t, idx, payload, chan from loglines where speaker=%s
sept_fixes.kv 403 order by t desc limit 1;''',
sept_fixes.kv 404 [arg], one=True)
sept_fixes.kv 405
sept_fixes.kv 406 # Where output will go
sept_fixes.kv 407 result = ""
sept_fixes.kv 408
sept_fixes.kv 409 # If user has been seen in ANY logged chan:
sept_fixes.kv 410 if seen_line != None:
sept_fixes.kv 411 time_txt = seen_line['t'].strftime(Date_Long_Format)
sept_fixes.kv 412 time_link = "[%s][%s]" % (line_url(seen_line), time_txt)
sept_fixes.kv 413 seen_line = "%s last seen in #%s on %s: %s" % (arg,
sept_fixes.kv 414 seen_line['chan'],
sept_fixes.kv 415 time_link,
sept_fixes.kv 416 seen_line['payload'])
sept_fixes.kv 417 result = seen_line
sept_fixes.kv 418 else:
sept_fixes.kv 419 # If user has never been seen at all:
sept_fixes.kv 420 result = "The user %s has never been seen by this logger." % arg
sept_fixes.kv 421
sept_fixes.kv 422 # Speak the result into the chan where command was issued
sept_fixes.kv 423 speak(chan, result)
sept_fixes.kv 424
sept_fixes.kv 425 def cmd_version(arg, user, chan):
sept_fixes.kv 426 speak(chan, "I am bot version %s." % Ver);
logotron_genesis.kv 427
logotron_genesis.kv 428 def cmd_src(arg, user, chan):
logotron_genesis.kv 429 speak(chan, "%s: my source code can be seen at: %s" % (user, Src_URL));
logotron_genesis.kv 430
logotron_genesis.kv 431 def cmd_uptime(arg, user, chan):
logotron_genesis.kv 432 uptime_txt = ""
logotron_genesis.kv 433 uptime = (datetime.now() - time_last_conn)
logotron_genesis.kv 434 days = uptime.days
logotron_genesis.kv 435 hours = uptime.seconds/3600
logotron_genesis.kv 436 minutes = (uptime.seconds%3600)/60
logotron_genesis.kv 437 uptime_txt += '%dd ' % days
logotron_genesis.kv 438 uptime_txt += '%dh ' % hours
logotron_genesis.kv 439 uptime_txt += '%dm' % minutes
logotron_genesis.kv 440 # Speak the uptime
logotron_genesis.kv 441 speak(chan, "%s: time since my last reconnect : %s" %
logotron_genesis.kv 442 (user, uptime_txt));
logotron_genesis.kv 443
logotron_genesis.kv 444 Commands = {
sept_fixes.kv 445 "help" : cmd_help,
sept_fixes.kv 446 "s" : cmd_search,
sept_fixes.kv 447 "seen" : cmd_seen,
sept_fixes.kv 448 "seen-anywhere" : cmd_seen_anywhere,
sept_fixes.kv 449 "uptime" : cmd_uptime,
sept_fixes.kv 450 "src" : cmd_src,
sept_fixes.kv 451 "version" : cmd_version
logotron_genesis.kv 452 }
logotron_genesis.kv 453
logotron_genesis.kv 454 ##############################################################################
logotron_genesis.kv 455
logotron_genesis.kv 456 # Save given line to perma-log
logotron_genesis.kv 457 def save_line(time, chan, speaker, action, payload):
logotron_genesis.kv 458 ## Put in DB:
logotron_genesis.kv 459 try:
logotron_genesis.kv 460 # Get index of THIS new line to be saved
logotron_genesis.kv 461 last_idx = query_db(
logotron_genesis.kv 462 '''select idx from loglines where chan=%s
logotron_genesis.kv 463 and idx = (select max(idx) from loglines where chan=%s) ;''',
logotron_genesis.kv 464 [chan, chan], one=True)
logotron_genesis.kv 465
logotron_genesis.kv 466 # Was this chan unseen previously?
logotron_genesis.kv 467 if last_idx == None:
logotron_genesis.kv 468 cur_idx = NewChan_Idx # Then use the config'd start index
logotron_genesis.kv 469 else:
logotron_genesis.kv 470 cur_idx = last_idx['idx'] + 1 # Otherwise, get the next idx
logotron_genesis.kv 471
logotron_genesis.kv 472 logging.debug("Adding log line with index: %s" % cur_idx)
logotron_genesis.kv 473
logotron_genesis.kv 474 # Set up the insert
logotron_genesis.kv 475 exec_db('''insert into loglines (idx, t, chan, era,
logotron_genesis.kv 476 speaker, self, payload) values (%s, %s, %s, %s, %s, %s, %s) ; ''',
logotron_genesis.kv 477 [cur_idx, time, chan, Era, speaker, action, payload])
logotron_genesis.kv 478
logotron_genesis.kv 479 # Fire
logotron_genesis.kv 480 commit_db()
logotron_genesis.kv 481 except Exception as e:
logotron_genesis.kv 482 rollback_db()
logotron_genesis.kv 483 logging.warning("DB add failed, rolled back.")
logotron_genesis.kv 484 logging.exception(e)
logotron_genesis.kv 485
logotron_genesis.kv 486
logotron_genesis.kv 487 # RE for finding log refs
sept_fixes.kv 488 logref_re = re.compile(Base_URL + """log\/([^/]+)/[^/]+#(\d+)""")
logotron_genesis.kv 489
logotron_genesis.kv 490 # All valid received lines end up here
logotron_genesis.kv 491 def eat_logline(user, chan, text, action):
logotron_genesis.kv 492 # If somehow received line from channel which isn't in the set:
logotron_genesis.kv 493 if chan not in Channels:
logotron_genesis.kv 494 logging.warning(
logotron_genesis.kv 495 "Received martian : '%s' : '%s'" % (chan, text))
logotron_genesis.kv 496 return
logotron_genesis.kv 497
logotron_genesis.kv 498 # First, add the line to the log:
logotron_genesis.kv 499 save_line(datetime.now(), chan, user, action, text)
logotron_genesis.kv 500
logotron_genesis.kv 501 # Then, see if the line was a command for this bot:
logotron_genesis.kv 502 if text.startswith(Prefix):
logotron_genesis.kv 503 cmd = text.partition(Prefix)[2].strip()
logotron_genesis.kv 504 cmd = [x.strip() for x in cmd.split(' ', 1)]
logotron_genesis.kv 505 if len(cmd) == 1:
logotron_genesis.kv 506 arg = ""
logotron_genesis.kv 507 else:
logotron_genesis.kv 508 arg = cmd[1]
logotron_genesis.kv 509 # Dispatch this command...
logotron_genesis.kv 510 command = cmd[0]
logotron_genesis.kv 511 logging.debug("Dispatching command '%s' with arg '%s'.." %
logotron_genesis.kv 512 (command, arg))
logotron_genesis.kv 513 func = Commands.get(command)
logotron_genesis.kv 514 # If this command is undefined:
logotron_genesis.kv 515 if func == None:
logotron_genesis.kv 516 logging.debug("Invalid command: %s" % command)
logotron_genesis.kv 517 # Utter the 'help' text as response to the sad command
logotron_genesis.kv 518 cmd_help("", user, chan)
logotron_genesis.kv 519 else:
logotron_genesis.kv 520 # Is defined command, dispatch it:
logotron_genesis.kv 521 func(arg, user, chan)
logotron_genesis.kv 522 else:
logotron_genesis.kv 523 # Finally, see if contains log refs:
logotron_genesis.kv 524 for ref in re.findall(logref_re, text):
sept_fixes.kv 525 ref_chan, ref_idx = ref
logotron_genesis.kv 526 # Find this line in DB:
logotron_genesis.kv 527 ref_line = query_db(
logotron_genesis.kv 528 '''select t, speaker, payload from loglines
logotron_genesis.kv 529 where chan=%s and idx=%s;''',
logotron_genesis.kv 530 [ref_chan, ref_idx], one=True)
logotron_genesis.kv 531 # If retrieved line is valid, echo it:
logotron_genesis.kv 532 if ref_line != None:
sept_fixes.kv 533 # If referred line was spoken in THIS chan:
sept_fixes.kv 534 if ref_chan == chan:
sept_fixes.kv 535 time_txt = ref_line['t'].strftime(Date_Long_Format)
sept_fixes.kv 536 my_line = "Logged on %s %s: %s" % (time_txt,
sept_fixes.kv 537 ref_line['speaker'],
sept_fixes.kv 538 ref_line['payload'])
sept_fixes.kv 539 else:
sept_fixes.kv 540 # If this is a cross-chan echo:
sept_fixes.kv 541 time_txt = ref_line['t'].strftime(Date_Short_Format)
sept_fixes.kv 542 my_line = "(%s) %s %s: %s" % (ref_chan,
sept_fixes.kv 543 time_txt,
sept_fixes.kv 544 ref_line['speaker'],
sept_fixes.kv 545 ref_line['payload'])
sept_fixes.kv 546
logotron_genesis.kv 547 # Speak the line echo into the chan where ref was seen
logotron_genesis.kv 548 speak(chan, my_line)
logotron_genesis.kv 549
logotron_genesis.kv 550 ##############################################################################
logotron_genesis.kv 551
logotron_genesis.kv 552 # IRCate; if disconnected, reconnect
logotron_genesis.kv 553 def run():
logotron_genesis.kv 554 while 1:
logotron_genesis.kv 555 irc()
logotron_genesis.kv 556 logging.warning("Disconnected, will reconnect...")
logotron_genesis.kv 557
logotron_genesis.kv 558 ##############################################################################
logotron_genesis.kv 559
logotron_genesis.kv 560 # Run continuously.
logotron_genesis.kv 561 run()
logotron_genesis.kv 562
logotron_genesis.kv 563 ##############################################################################