raw
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
sept_fixes.kv 17 Ver = 596907
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
logotron_genesis.kv 132 # Init socket:
logotron_genesis.kv 133 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logotron_genesis.kv 134
logotron_genesis.kv 135 # Set keepalive:
logotron_genesis.kv 136 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
logotron_genesis.kv 137
logotron_genesis.kv 138 # Initially we are not connected to anything
logotron_genesis.kv 139 connected = False
logotron_genesis.kv 140
logotron_genesis.kv 141 # Connect to given host:port; return whether connected
logotron_genesis.kv 142 def connect(host, port):
logotron_genesis.kv 143 logging.info("Connecting to %s:%s" % (host, port))
logotron_genesis.kv 144 sock.settimeout(Timeout)
logotron_genesis.kv 145 try:
logotron_genesis.kv 146 sock.connect((host, port))
logotron_genesis.kv 147 except (socket.timeout, socket.error) as e:
logotron_genesis.kv 148 logging.warning(e)
logotron_genesis.kv 149 return False
logotron_genesis.kv 150 except Exception as e:
logotron_genesis.kv 151 logging.exception(e)
logotron_genesis.kv 152 return False
logotron_genesis.kv 153 else:
logotron_genesis.kv 154 logging.info("Connected.")
logotron_genesis.kv 155 return True
logotron_genesis.kv 156
logotron_genesis.kv 157
logotron_genesis.kv 158 # Attempt connect to each of hosts, in order, on port; return whether connected
logotron_genesis.kv 159 def connect_any(hosts, port):
logotron_genesis.kv 160 for host in hosts:
logotron_genesis.kv 161 if connect(host, port):
logotron_genesis.kv 162 return True
logotron_genesis.kv 163 return False
logotron_genesis.kv 164
logotron_genesis.kv 165
logotron_genesis.kv 166 # Transmit IRC message
logotron_genesis.kv 167 def send(message):
logotron_genesis.kv 168 global connected
logotron_genesis.kv 169 if not connected:
logotron_genesis.kv 170 logging.warning("Tried to send while disconnected?")
logotron_genesis.kv 171 return False
logotron_genesis.kv 172 time.sleep(TX_Delay)
logotron_genesis.kv 173 logging.debug("> '%s'" % message)
logotron_genesis.kv 174 message = "%s\r\n" % message
logotron_genesis.kv 175 try:
logotron_genesis.kv 176 sock.send(message.encode("utf-8"))
logotron_genesis.kv 177 except (socket.timeout, socket.error) as e:
logotron_genesis.kv 178 logging.warning("Socket could not send! Disconnecting.")
logotron_genesis.kv 179 connected = False
logotron_genesis.kv 180 return False
logotron_genesis.kv 181 except Exception as e:
logotron_genesis.kv 182 logging.exception(e)
logotron_genesis.kv 183 return False
logotron_genesis.kv 184
logotron_genesis.kv 185
logotron_genesis.kv 186 # Speak given message on a selected channel
logotron_genesis.kv 187 def speak(channel, message):
logotron_genesis.kv 188 send("PRIVMSG #%s :%s" % (channel, message))
logotron_genesis.kv 189 # Now save what the bot spoke:
logotron_genesis.kv 190 save_line(datetime.now(), channel, Nick, False, message)
logotron_genesis.kv 191
logotron_genesis.kv 192
logotron_genesis.kv 193 # Standard incoming IRC line (excludes fleanode liquishit, etc)
logotron_genesis.kv 194 irc_line_re = re.compile("""^:([^!]+)\!\S+\s+PRIVMSG\s+\#(\S+)\s+\:(.*)""")
logotron_genesis.kv 195
logotron_genesis.kv 196 # The '#' prevents interaction via PM, this is not a PM-able bot.
logotron_genesis.kv 197
logotron_genesis.kv 198 # 'Actions'
logotron_genesis.kv 199 irc_act_re = re.compile(""".*ACTION\s+(.*)""")
logotron_genesis.kv 200
logotron_genesis.kv 201
logotron_genesis.kv 202 # A line was received from IRC
logotron_genesis.kv 203 def received_line(line):
logotron_genesis.kv 204 # Process the traditional pingpong
logotron_genesis.kv 205 if line.startswith("PING"):
logotron_genesis.kv 206 send("PONG " + line.split()[1])
logotron_genesis.kv 207 else:
logotron_genesis.kv 208 logging.debug("< '%s'" % line)
logotron_genesis.kv 209 standard_line = re.search(irc_line_re, line)
logotron_genesis.kv 210 if standard_line:
logotron_genesis.kv 211 # Break this line into the standard segments
logotron_genesis.kv 212 (user, chan, text) = [s.strip() for s in standard_line.groups()]
logotron_genesis.kv 213 # Determine whether this line is an 'action' :
logotron_genesis.kv 214 action = False
logotron_genesis.kv 215 act = re.search(irc_act_re, line)
logotron_genesis.kv 216 if act:
logotron_genesis.kv 217 action = True
logotron_genesis.kv 218 text = act.group(1)
sept_fixes.kv 219 # Remove turd if present:
sept_fixes.kv 220 if text[-1:] == '\x01':
sept_fixes.kv 221 text = text[:-1]
logotron_genesis.kv 222 # This line is edible, process it.
logotron_genesis.kv 223 eat_logline(user, chan, text, action)
logotron_genesis.kv 224
logotron_genesis.kv 225
logotron_genesis.kv 226 # IRCate until we get disconnected
logotron_genesis.kv 227 def irc():
logotron_genesis.kv 228 global connected
uptimefix_bye_cac... 229 global time_last_conn
logotron_genesis.kv 230
logotron_genesis.kv 231 # Connect to one among the specified servers, in given priority :
logotron_genesis.kv 232 while not connected:
logotron_genesis.kv 233 connected = connect_any(Servers, Port)
logotron_genesis.kv 234
logotron_genesis.kv 235 # Save time of last successful connect
logotron_genesis.kv 236 time_last_conn = datetime.now()
logotron_genesis.kv 237
logotron_genesis.kv 238 # Auth to server
logotron_genesis.kv 239 send("NICK %s\r\n" % Nick)
logotron_genesis.kv 240 send("USER %s %s %s :%s\r\n" % (Nick, Nick, Nick, Nick))
uniturds_etc.kv 241
uniturds_etc.kv 242 # If this is a production bot, rather than test, there will be a PW:
uniturds_etc.kv 243 if Pass != "":
uniturds_etc.kv 244 send("NICKSERV IDENTIFY %s %s\r\n" % (Nick, Pass))
logotron_genesis.kv 245
logotron_genesis.kv 246 time.sleep(Join_Delay) # wait to join until fleanode eats auth
logotron_genesis.kv 247
logotron_genesis.kv 248 # Join selected channels
logotron_genesis.kv 249 for chan in Channels:
logotron_genesis.kv 250 logging.info("Joining channel '%s'..." % chan)
logotron_genesis.kv 251 send("JOIN #%s\r\n" % chan)
logotron_genesis.kv 252
logotron_genesis.kv 253 while connected:
logotron_genesis.kv 254 try:
logotron_genesis.kv 255 data = sock.recv(Buf_Size)
logotron_genesis.kv 256 except socket.timeout as e:
logotron_genesis.kv 257 logging.debug("Listen timed out")
logotron_genesis.kv 258 continue
logotron_genesis.kv 259 except socket.error as e:
logotron_genesis.kv 260 logging.warning("Listen socket error, disconnecting.")
logotron_genesis.kv 261 connected = False
logotron_genesis.kv 262 continue
logotron_genesis.kv 263 except Exception as e:
logotron_genesis.kv 264 logging.exception(e)
logotron_genesis.kv 265 connected = False
logotron_genesis.kv 266 continue
logotron_genesis.kv 267 else:
logotron_genesis.kv 268 if len(data) == 0:
logotron_genesis.kv 269 logging.warning("Listen socket closed, disconnecting.")
logotron_genesis.kv 270 connected = False
logotron_genesis.kv 271 continue
logotron_genesis.kv 272 try:
uniturds_etc.kv 273 try:
uniturds_etc.kv 274 data = data.strip(b'\r\n').decode("utf-8")
uniturds_etc.kv 275 except UnicodeDecodeError:
uniturds_etc.kv 276 data = data.strip(b'\r\n').decode('latin-1')
logotron_genesis.kv 277 for l in data.splitlines():
logotron_genesis.kv 278 received_line(l)
logotron_genesis.kv 279 continue
logotron_genesis.kv 280 except Exception as e:
logotron_genesis.kv 281 logging.exception(e)
logotron_genesis.kv 282 continue
logotron_genesis.kv 283
logotron_genesis.kv 284 ##############################################################################
logotron_genesis.kv 285
logotron_genesis.kv 286 html_escape_table = {
logotron_genesis.kv 287 "&": "&amp;",
logotron_genesis.kv 288 '"': "&quot;",
logotron_genesis.kv 289 "'": "&apos;",
logotron_genesis.kv 290 ">": "&gt;",
logotron_genesis.kv 291 "<": "&lt;",
logotron_genesis.kv 292 }
logotron_genesis.kv 293
logotron_genesis.kv 294 def html_escape(text):
logotron_genesis.kv 295 res = ("".join(html_escape_table.get(c,c) for c in text))
logotron_genesis.kv 296 return urllib.quote(res.encode('utf-8'))
logotron_genesis.kv 297
logotron_genesis.kv 298
logotron_genesis.kv 299 searcher_re = re.compile("""(\d+) Results""")
logotron_genesis.kv 300
logotron_genesis.kv 301 # Retrieve a search result count using the WWWistic frontend.
logotron_genesis.kv 302 # This way it is not necessary to have query parser in two places.
logotron_genesis.kv 303 # However it is slightly wasteful of CPU (requires actually loading results.)
logotron_genesis.kv 304 def get_search_res(chan, query):
logotron_genesis.kv 305 try:
logotron_genesis.kv 306 esc_q = html_escape(query)
logotron_genesis.kv 307 url = Base_URL + "log-search?q=" + esc_q + "&chan=" + chan
logotron_genesis.kv 308 res = requests.get(url).text
logotron_genesis.kv 309 t = res[res.find('<title>') + 7 : res.find('</title>')].strip()
logotron_genesis.kv 310 found = searcher_re.match(t)
logotron_genesis.kv 311 if found:
logotron_genesis.kv 312 output = "[" + url + "]" + "[" + found.group(1)
logotron_genesis.kv 313 output += """ results for "%s" in #%s]""" % (query, chan)
logotron_genesis.kv 314 return output
logotron_genesis.kv 315 else:
logotron_genesis.kv 316 return """No results found for "%s" in #%s""" % (query, chan)
logotron_genesis.kv 317 except Exception as e:
logotron_genesis.kv 318 logging.exception(e)
logotron_genesis.kv 319 return "No results returned (is logotron WWW up ?)"
logotron_genesis.kv 320
logotron_genesis.kv 321 ##############################################################################
logotron_genesis.kv 322
sept_fixes.kv 323 # Get perma-URL corresponding to given log line
sept_fixes.kv 324 def line_url(l):
sept_fixes.kv 325 return "{0}log/{1}/{2}#{3}".format(Base_URL,
sept_fixes.kv 326 l['chan'],
sept_fixes.kv 327 l['t'].strftime(Date_Short_Format),
sept_fixes.kv 328 l['idx'])
sept_fixes.kv 329
sept_fixes.kv 330 ##############################################################################
sept_fixes.kv 331
logotron_genesis.kv 332 # Commands:
logotron_genesis.kv 333
logotron_genesis.kv 334 def cmd_help(arg, user, chan):
logotron_genesis.kv 335 # Speak the 'help' text
logotron_genesis.kv 336 speak(chan, "%s: my valid commands are: %s" %
logotron_genesis.kv 337 (user, ', '.join(Commands.keys())));
logotron_genesis.kv 338
logotron_genesis.kv 339 def cmd_search(arg, user, chan):
logotron_genesis.kv 340 logging.debug("search: '%s'" % arg)
logotron_genesis.kv 341 speak(chan, get_search_res(chan, arg))
logotron_genesis.kv 342
logotron_genesis.kv 343 def cmd_seen(arg, user, chan):
sept_fixes.kv 344 # Empty query is prohibited:
sept_fixes.kv 345 if arg == "":
sept_fixes.kv 346 speak(chan, "Required argument: USER")
sept_fixes.kv 347 return
sept_fixes.kv 348
sept_fixes.kv 349 # Perform query:
sept_fixes.kv 350 seen_line = query_db(
sept_fixes.kv 351 '''select t, idx, payload, chan from loglines where
sept_fixes.kv 352 chan=%s and speaker=%s order by t desc limit 1;''',
sept_fixes.kv 353 [chan, arg], one=True)
sept_fixes.kv 354
sept_fixes.kv 355 # Where output will go
sept_fixes.kv 356 result = ""
sept_fixes.kv 357
sept_fixes.kv 358 # If user has been seen in THE CURRENT chan:
sept_fixes.kv 359 if seen_line != None:
sept_fixes.kv 360 time_txt = seen_line['t'].strftime(Date_Long_Format)
sept_fixes.kv 361 time_link = "[%s][%s]" % (line_url(seen_line), time_txt)
sept_fixes.kv 362 seen_line = "%s last seen here on %s: %s" % (arg,
sept_fixes.kv 363 time_link,
sept_fixes.kv 364 seen_line['payload'])
sept_fixes.kv 365 result = seen_line
sept_fixes.kv 366 else:
sept_fixes.kv 367 # If user has never been seen in this chan:
sept_fixes.kv 368 result = "The user %s has never been seen in #%s." % (arg, chan)
sept_fixes.kv 369
sept_fixes.kv 370 # Speak the result into the chan where command was issued
sept_fixes.kv 371 speak(chan, result)
sept_fixes.kv 372
sept_fixes.kv 373 def cmd_seen_anywhere(arg, user, chan):
sept_fixes.kv 374 # Empty query is prohibited:
sept_fixes.kv 375 if arg == "":
sept_fixes.kv 376 speak(chan, "Required argument: USER")
sept_fixes.kv 377 return
sept_fixes.kv 378
sept_fixes.kv 379 # Perform query:
sept_fixes.kv 380 seen_line = query_db(
sept_fixes.kv 381 '''select t, idx, payload, chan from loglines where speaker=%s
sept_fixes.kv 382 order by t desc limit 1;''',
sept_fixes.kv 383 [arg], one=True)
sept_fixes.kv 384
sept_fixes.kv 385 # Where output will go
sept_fixes.kv 386 result = ""
sept_fixes.kv 387
sept_fixes.kv 388 # If user has been seen in ANY logged chan:
sept_fixes.kv 389 if seen_line != None:
sept_fixes.kv 390 time_txt = seen_line['t'].strftime(Date_Long_Format)
sept_fixes.kv 391 time_link = "[%s][%s]" % (line_url(seen_line), time_txt)
sept_fixes.kv 392 seen_line = "%s last seen in #%s on %s: %s" % (arg,
sept_fixes.kv 393 seen_line['chan'],
sept_fixes.kv 394 time_link,
sept_fixes.kv 395 seen_line['payload'])
sept_fixes.kv 396 result = seen_line
sept_fixes.kv 397 else:
sept_fixes.kv 398 # If user has never been seen at all:
sept_fixes.kv 399 result = "The user %s has never been seen by this logger." % arg
sept_fixes.kv 400
sept_fixes.kv 401 # Speak the result into the chan where command was issued
sept_fixes.kv 402 speak(chan, result)
sept_fixes.kv 403
sept_fixes.kv 404 def cmd_version(arg, user, chan):
sept_fixes.kv 405 speak(chan, "I am bot version %s." % Ver);
logotron_genesis.kv 406
logotron_genesis.kv 407 def cmd_src(arg, user, chan):
logotron_genesis.kv 408 speak(chan, "%s: my source code can be seen at: %s" % (user, Src_URL));
logotron_genesis.kv 409
logotron_genesis.kv 410 def cmd_uptime(arg, user, chan):
logotron_genesis.kv 411 uptime_txt = ""
logotron_genesis.kv 412 uptime = (datetime.now() - time_last_conn)
logotron_genesis.kv 413 days = uptime.days
logotron_genesis.kv 414 hours = uptime.seconds/3600
logotron_genesis.kv 415 minutes = (uptime.seconds%3600)/60
logotron_genesis.kv 416 uptime_txt += '%dd ' % days
logotron_genesis.kv 417 uptime_txt += '%dh ' % hours
logotron_genesis.kv 418 uptime_txt += '%dm' % minutes
logotron_genesis.kv 419 # Speak the uptime
logotron_genesis.kv 420 speak(chan, "%s: time since my last reconnect : %s" %
logotron_genesis.kv 421 (user, uptime_txt));
logotron_genesis.kv 422
logotron_genesis.kv 423 Commands = {
sept_fixes.kv 424 "help" : cmd_help,
sept_fixes.kv 425 "s" : cmd_search,
sept_fixes.kv 426 "seen" : cmd_seen,
sept_fixes.kv 427 "seen-anywhere" : cmd_seen_anywhere,
sept_fixes.kv 428 "uptime" : cmd_uptime,
sept_fixes.kv 429 "src" : cmd_src,
sept_fixes.kv 430 "version" : cmd_version
logotron_genesis.kv 431 }
logotron_genesis.kv 432
logotron_genesis.kv 433 ##############################################################################
logotron_genesis.kv 434
logotron_genesis.kv 435 # Save given line to perma-log
logotron_genesis.kv 436 def save_line(time, chan, speaker, action, payload):
logotron_genesis.kv 437 ## Put in DB:
logotron_genesis.kv 438 try:
logotron_genesis.kv 439 # Get index of THIS new line to be saved
logotron_genesis.kv 440 last_idx = query_db(
logotron_genesis.kv 441 '''select idx from loglines where chan=%s
logotron_genesis.kv 442 and idx = (select max(idx) from loglines where chan=%s) ;''',
logotron_genesis.kv 443 [chan, chan], one=True)
logotron_genesis.kv 444
logotron_genesis.kv 445 # Was this chan unseen previously?
logotron_genesis.kv 446 if last_idx == None:
logotron_genesis.kv 447 cur_idx = NewChan_Idx # Then use the config'd start index
logotron_genesis.kv 448 else:
logotron_genesis.kv 449 cur_idx = last_idx['idx'] + 1 # Otherwise, get the next idx
logotron_genesis.kv 450
logotron_genesis.kv 451 logging.debug("Adding log line with index: %s" % cur_idx)
logotron_genesis.kv 452
logotron_genesis.kv 453 # Set up the insert
logotron_genesis.kv 454 exec_db('''insert into loglines (idx, t, chan, era,
logotron_genesis.kv 455 speaker, self, payload) values (%s, %s, %s, %s, %s, %s, %s) ; ''',
logotron_genesis.kv 456 [cur_idx, time, chan, Era, speaker, action, payload])
logotron_genesis.kv 457
logotron_genesis.kv 458 # Fire
logotron_genesis.kv 459 commit_db()
logotron_genesis.kv 460 except Exception as e:
logotron_genesis.kv 461 rollback_db()
logotron_genesis.kv 462 logging.warning("DB add failed, rolled back.")
logotron_genesis.kv 463 logging.exception(e)
logotron_genesis.kv 464
logotron_genesis.kv 465
logotron_genesis.kv 466 # RE for finding log refs
sept_fixes.kv 467 logref_re = re.compile(Base_URL + """log\/([^/]+)/[^/]+#(\d+)""")
logotron_genesis.kv 468
logotron_genesis.kv 469 # All valid received lines end up here
logotron_genesis.kv 470 def eat_logline(user, chan, text, action):
logotron_genesis.kv 471 # If somehow received line from channel which isn't in the set:
logotron_genesis.kv 472 if chan not in Channels:
logotron_genesis.kv 473 logging.warning(
logotron_genesis.kv 474 "Received martian : '%s' : '%s'" % (chan, text))
logotron_genesis.kv 475 return
logotron_genesis.kv 476
logotron_genesis.kv 477 # First, add the line to the log:
logotron_genesis.kv 478 save_line(datetime.now(), chan, user, action, text)
logotron_genesis.kv 479
logotron_genesis.kv 480 # Then, see if the line was a command for this bot:
logotron_genesis.kv 481 if text.startswith(Prefix):
logotron_genesis.kv 482 cmd = text.partition(Prefix)[2].strip()
logotron_genesis.kv 483 cmd = [x.strip() for x in cmd.split(' ', 1)]
logotron_genesis.kv 484 if len(cmd) == 1:
logotron_genesis.kv 485 arg = ""
logotron_genesis.kv 486 else:
logotron_genesis.kv 487 arg = cmd[1]
logotron_genesis.kv 488 # Dispatch this command...
logotron_genesis.kv 489 command = cmd[0]
logotron_genesis.kv 490 logging.debug("Dispatching command '%s' with arg '%s'.." %
logotron_genesis.kv 491 (command, arg))
logotron_genesis.kv 492 func = Commands.get(command)
logotron_genesis.kv 493 # If this command is undefined:
logotron_genesis.kv 494 if func == None:
logotron_genesis.kv 495 logging.debug("Invalid command: %s" % command)
logotron_genesis.kv 496 # Utter the 'help' text as response to the sad command
logotron_genesis.kv 497 cmd_help("", user, chan)
logotron_genesis.kv 498 else:
logotron_genesis.kv 499 # Is defined command, dispatch it:
logotron_genesis.kv 500 func(arg, user, chan)
logotron_genesis.kv 501 else:
logotron_genesis.kv 502 # Finally, see if contains log refs:
logotron_genesis.kv 503 for ref in re.findall(logref_re, text):
sept_fixes.kv 504 ref_chan, ref_idx = ref
logotron_genesis.kv 505 # Find this line in DB:
logotron_genesis.kv 506 ref_line = query_db(
logotron_genesis.kv 507 '''select t, speaker, payload from loglines
logotron_genesis.kv 508 where chan=%s and idx=%s;''',
logotron_genesis.kv 509 [ref_chan, ref_idx], one=True)
logotron_genesis.kv 510 # If retrieved line is valid, echo it:
logotron_genesis.kv 511 if ref_line != None:
sept_fixes.kv 512 # If referred line was spoken in THIS chan:
sept_fixes.kv 513 if ref_chan == chan:
sept_fixes.kv 514 time_txt = ref_line['t'].strftime(Date_Long_Format)
sept_fixes.kv 515 my_line = "Logged on %s %s: %s" % (time_txt,
sept_fixes.kv 516 ref_line['speaker'],
sept_fixes.kv 517 ref_line['payload'])
sept_fixes.kv 518 else:
sept_fixes.kv 519 # If this is a cross-chan echo:
sept_fixes.kv 520 time_txt = ref_line['t'].strftime(Date_Short_Format)
sept_fixes.kv 521 my_line = "(%s) %s %s: %s" % (ref_chan,
sept_fixes.kv 522 time_txt,
sept_fixes.kv 523 ref_line['speaker'],
sept_fixes.kv 524 ref_line['payload'])
sept_fixes.kv 525
logotron_genesis.kv 526 # Speak the line echo into the chan where ref was seen
logotron_genesis.kv 527 speak(chan, my_line)
logotron_genesis.kv 528
logotron_genesis.kv 529 ##############################################################################
logotron_genesis.kv 530
logotron_genesis.kv 531 # IRCate; if disconnected, reconnect
logotron_genesis.kv 532 def run():
logotron_genesis.kv 533 while 1:
logotron_genesis.kv 534 irc()
logotron_genesis.kv 535 logging.warning("Disconnected, will reconnect...")
logotron_genesis.kv 536
logotron_genesis.kv 537 ##############################################################################
logotron_genesis.kv 538
logotron_genesis.kv 539 # Run continuously.
logotron_genesis.kv 540 run()
logotron_genesis.kv 541
logotron_genesis.kv 542 ##############################################################################