def handler(self, **args): """adds larts and praises""" import priv from irclib import Event import database type = args["text"].split()[2] value = " ".join(args["text"].split()[3:]) self.debug(value) if args["type"] == "privmsg": from irclib import nm_to_n target = nm_to_n(args["source"]) else: target = args["channel"] if priv.checkPriv(args["source"], "add_lart_priv") == 0: return Event("privmsg", "", target, ["You do not have permission to do that. "]) value = value.replace("\\", "\\\\") value = value.replace("\"", "\\\"") value = value.replace("'", "\\'") database.doSQL("insert into data values('" + value + "', '" + type + "', '" + args["source"] + "')") return Event("privmsg", "", target, ["Adding: \"" + value + "\" as " + type + "."])
def check_logfile(): global logtype, template, logfile import database if logtype == "": line = database.doSQL("SELECT data FROM data WHERE type = 'logtype'") if len(line) > 0 and len(line[0]) > 0: logtype = line[0][0] if template == "": line = database.doSQL("SELECT data FROM data WHERE type = 'logfile'") if len(line) > 0 and len(line[0]) > 0: template = line[0][0] if logtype in ["date", "file"] and template == "": if (logfile != None): logfile.close() print "logtype is " + logtype + ", but there is no logfile entry." logfile = None return if logtype == "date": filename = time.strftime(template) elif logtype == "file": filename = template else: return if (logfile != None and filename != logfile.name): logfile.close() if (logfile == None or filename != logfile.name): logfile = open(filename, "a")
def handler(self, **args): """ revokes a privilege from a nick/host """ from irclib import Event from irclib import nm_to_n import database target = args["channel"] if args["type"] == "privmsg": target = nm_to_n(args["source"]) privilege = args["text"].split()[2] mask = args["text"].split()[4] if checkPriv(args["source"], "grant_priv") == 0 or checkPriv( args["source"], privilege) == 0: return Event("privmsg", "", target, ["You don't have permission to do that."]) mask = mask.replace("*", "%") if checkPriv(mask, privilege) == 0: return Event("privmsg", "", target, [mask + " does not have " + privilege + "."]) database.doSQL("delete from grants where hostmask = '" + self.sqlEscape(mask) + "' and priv_type = '" + self.sqlEscape(privilege) + "'") flushPriv() return Event("privmsg", "", target, ["Revoked " + privilege + " from " + mask + "."])
def handler(self, **args): """ gives a nick/host mask a privileve """ from irclib import Event from irclib import nm_to_n import database target = args["channel"] if args["type"] == "privmsg": target = nm_to_n(args["source"]) privilege = args["text"].split()[2] mask = args["text"].split()[4] if checkPriv(args["source"], "grant_priv") == 0 or checkPriv( args["source"], privilege) == 0: return Event("privmsg", "", target, ["You don't have permission to do that."]) mask = mask.replace("*", "%") if checkPriv(mask, privilege) != 0: return Event("privmsg", "", target, [mask + " already has " + privilege + "."]) database.doSQL("insert into grants(hostmask, priv_type) values('" + self.sqlEscape(mask) + "', '" + self.sqlEscape(privilege) + "')") flushPriv() return Event("privmsg", "", target, ["Granted " + privilege + " to " + mask])
def handler(self, **args): import database, priv from irclib import Event, nm_to_n # if we don't have a nick supplied, get the second most recent form the DB # (the most recent would be the person saying "~qg" try: user = args["text"].split()[2] # get name except IndexError: temp = database.doSQL("select nick from seen order by time desc limit 2") if len(temp) == 2: user=temp[1][0] else: user=temp[0][0] if nm_to_n(args["source"]).lower() == user.lower(): return Event("privmsg", "", self.return_to_sender(args), [ "Can't quotegrab yourself!" ]) if priv.checkPriv(args["source"], "quote_priv") == 0: #check if requester is allowed to do this return Event("privmsg", "", self.return_to_sender(args), [ "That requires quote_priv" ]) results = database.doSQL("select message, time, type from seen where nick = '%s'" % (user)) # check if they have a "seen" entry, act accordingly if len(results) > 0: quote, time, type = results[0] else: return Event("privmsg", "", self.return_to_sender(args), [ "No quote available for %s" % (user) ]) # If it's not a privmsg, spit it back if type not in ["privmsg", "action"]: return Event("privmsg", "", self.return_to_sender(args), [ "Last event seen was not a message or action, not grabbing quote for %s" % user ]) #update their webstats entry with the new info database.doSQL("update webstats set quote = '%s', quote_time = %s, type= '%s' where nick = '%s' and channel = '%s'" % (quote.replace("\\", "\\\\").replace("'", "\\'"), str(time), type, user, args["channel"])) return Event("privmsg", "", self.return_to_sender(args), [ "Grabbing quote for %s" % (user) ])
def handler(self, **args): """Report when someone was last seen.""" import database from alias import whois result = "" nick = " ".join(args["text"].split()[2:]) safenick = escape_quotes(nick.lower()) line = database.doSQL("SELECT nick, time, message, type " + \ "FROM seen WHERE nick = '" + safenick + \ "'") if (len(line) == 0): seentime = 0 joiner = "However, " result += "I don't think I've ever seen " + nick + ".\n" else: seentime = int(line[0][1]) joiner = "Also, " result += makeseenline("", line) realnick = escape_quotes(whois(nick)) line = database.doSQL( "SELECT seen.nick, seen.time, seen.message, seen.type FROM seen, alias WHERE seen.time > " + str(seentime) + " AND seen.nick = alias.nick AND alias.realnick = '" + realnick + "' ORDER BY seen.time DESC LIMIT 1") if (len(line) > 0): result += makeseenline(joiner, line) from irclib import Event return Event("privmsg", "", self.return_to_sender(args), [result])
def handler(self, **args): """votes on a poll.""" import database from irclib import Event from irclib import nm_to_h, nm_to_u target=args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target=nm_to_n(args["source"]) poll_num = args["text"].split()[2] option_key = " ".join(args["text"].split()[3:]) #first we check to make sure the requested poll exists. if database.doSQL("select count(poll_num) from poll where poll_num =" +poll_num)[0][0] == 0: return Event("privmsg", "", target, [ "No such poll." ]) #now we check to make sure the user hasn't voted in that poll checkmask = "%!" + nm_to_u(args["source"]) + "@%" + nm_to_h(args["source"])[nm_to_h(args["source"]).find("."):] if database.doSQL("select count(option_key) from poll_votes where poll_num =" + poll_num + " and voter_nickmask like '" + checkmask + "'")[0][0] != 0: return Event("privmsg", "", target, [ "You already voted in that poll." ]) #next we check to make sure the poll option exists. option_key = self.sqlEscape(option_key) if database.doSQL("select count(option_key) from poll_options where poll_num =" + poll_num + " and option_key = '" + option_key + "'")[0][0] == 0: return Event("privmsg", "", target, [ "No such poll option." ]) # register the vote. database.doSQL("insert into poll_votes values('" + args["source"] + "', '" + option_key + "', " + poll_num + ")") return Event("privmsg", "", target, [ "Vote registered." ])
def handler(self, **args): """ remove a poll option to an existing poll. Format: moobot: remove option <pollnum> <option> """ import database import priv import string from irclib import Event target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target = nm_to_n(args["source"]) if priv.checkPriv(args["source"], "poll_priv") == 0: return Event("privmsg", "", target, ["You are not authorized to do that."]) option_key = string.join(args["text"].split()[4:]) poll_num = escape_slashes(args["text"].split()[3]) database.doSQL( "delete from poll_options where poll_num = " + poll_num + " and option_key = '" + option_key + "'" ) return Event("privmsg", "", target, ["Option deleted."])
def handler(self, **args): """ Adds a poll option to an existing poll. Format: moobot: add option 1 a: yes""" import database import priv from irclib import Event target=args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target=nm_to_n(args["source"]) if priv.checkPriv(args["source"], "poll_priv") == 0: return Event("privmsg", "", target, [ "You are not authorized to do that." ]) poll_num = args["text"].split()[3] option = " ".join(args["text"].split()[4:]) option_key = self.sqlEscape(option.split(":")[0]) option_text = self.sqlEscape(" ".join(option.split(":")[1:])) if database.doSQL("select count(poll_num) from poll where poll_num =" + poll_num )[0][0] == 0: return Event("privmsg", "", target, [ "No such poll." ]) self.debug("Insert into poll_options(poll_num, option_key, option_text) values(" + poll_num + ", \"" + option_key + "\", \"" + option_text + "\")") database.doSQL("Insert into poll_options(poll_num, option_key, option_text) values(" + poll_num + ", '" + option_key + "', '" + option_text + "')") return Event("privmsg", "", target, [ "Option added." ])
def _getByKey(fields, factoid_key, requested_by=None): # Query the database for the factoid value for the given key sql = "select %s from factoids "\ "where (factoid_key) = "\ "'%s'" % (fields, sqlEscape(factoid_key)) result = database.doSQL(sql) if requested_by: # Now that we are sure we have a factoid that got requested, increment # the count, set the new requester, etc. NOTE: even for "literal" # requests, this is set. Whether or not this is really is wanted is # ... debatable, but we don't really care. import time sql = "update factoids set "\ "requested_count = requested_count + 1, "\ "requested_by = '%s', "\ "requested_time = %s "\ "where (factoid_key) = '%s'" % ( sqlEscape(requested_by), str(int(time.time())), sqlEscape(factoid_key) ) database.doSQL(sql) if result: return result[0] # first row else: return None
def _getByKey(fields, factoid_key, requested_by = None): # Query the database for the factoid value for the given key sql = "select %s from factoids "\ "where (factoid_key) = "\ "'%s'" % (fields, sqlEscape(factoid_key)) result = database.doSQL(sql) if requested_by: # Now that we are sure we have a factoid that got requested, increment # the count, set the new requester, etc. NOTE: even for "literal" # requests, this is set. Whether or not this is really is wanted is # ... debatable, but we don't really care. import time sql = "update factoids set "\ "requested_count = requested_count + 1, "\ "requested_by = '%s', "\ "requested_time = %s "\ "where (factoid_key) = '%s'" % ( sqlEscape(requested_by), str(int(time.time())), sqlEscape(factoid_key) ) database.doSQL(sql) if result: return result[0] # first row else: return None
def handler(self, **args): """grabs a random reply from the database""" from irclib import Event import database, string, random from irclib import nm_to_n if database.type == "pgsql": # For postgres, we find the number of dunnos, calculate a random # offset into the table based on that number (the offset is # a zero-index offset), and then select the dunno at that offset # into the data table. random.seed() num_query = "select count(data) from data where type='dunno'" num_dunnos = database.doSQL(num_query)[0][0] offset = random.randint(1, num_dunnos) - 1 dunno_query = "select data from data where type='dunno' order " \ + "by data limit 1 offset " + str(offset) line = database.doSQL(dunno_query)[0][0] elif database.type == "mysql": # For MySQL we simply use the rand() function to pick a random # dunno for us dunno_query = "select data from data where type='dunno' order " \ + "by rand() limit 1" line = database.doSQL(dunno_query)[0][0] line = string.replace(line, "WHO", nm_to_n(args["source"])) target = self.return_to_sender(args) return Event("privmsg", "", target, [ line ])
def handler(self, **args): """Report when someone was last seen.""" import database from alias import whois result = "" nick = " ".join(args["text"].split()[2:]) safenick = escape_quotes(nick.lower()) line = database.doSQL("SELECT nick, time, message, type " + \ "FROM seen WHERE nick = '" + safenick + \ "'") if (len(line) == 0): seentime = 0 joiner = "However, " result += "I don't think I've ever seen " + nick + ".\n" else: seentime = int(line[0][1]) joiner = "Also, " result += makeseenline("", line) realnick = escape_quotes(whois(nick)) line = database.doSQL("SELECT seen.nick, seen.time, seen.message, seen.type FROM seen, alias WHERE seen.time > " + str(seentime) + " AND seen.nick = alias.nick AND alias.realnick = '" + realnick + "' ORDER BY seen.time DESC LIMIT 1") if (len(line) > 0): result += makeseenline(joiner, line) from irclib import Event return Event("privmsg", "", self.return_to_sender(args), [ result ])
def addUrl(self, url, hash, source, target, str): id, title = self.getUrl(url, hash) if id: if not title: title = self.fetchTitle(url) if title: database.doSQL("UPDATE url SET title='%s' WHERE url='%s' AND hash='%s'" % (self.sqlEscape(title), self.sqlEscape(url), self.sqlEscape(hash))) return title urlInfo = urlparse.urlparse(url) scheme = urlInfo.scheme port = urlInfo.port if not port: if scheme == 'http': port = 80 elif scheme == 'https': port = 443 host = urlInfo.hostname if not host: return hostId = self.addHost(scheme, host, port) chanId = 0 if is_channel(target): chanId = self.addChan(target[1:]) # Strip mIRC color codes str = re.sub('\003\d{1,2},\d{1,2}', '', str) str = re.sub('\003\d{0,2}', '', str) # Strip mIRC bold, plain, reverse and underline codes str = re.sub('[\002\017\026\037]', '', str) values = {} values["nickid"] = "%d" % int(self.addNick(nm_to_n(source))) values["string"] = "'%s'" % self.sqlEscape(str) values["url"] = "'%s'" % self.sqlEscape(url) values["hash"] = "'%s'" % self.sqlEscape(hash) values["hostid"] = "%d" % int(hostId) values["chanid"] = "%d" % int(chanId) values["time"] = "CURRENT_TIMESTAMP()" values["type"] = "'%s'" % self.sqlEscape(self.rImageUrl.search(url) and "image" or "html") if database.type == "mysql": pass elif database.type == "pgsql": values['time'] = 'CURRENT_TIMESTAMP' elif database.type == "sqlite3": values['time'] = 'time()' title = self.fetchTitle(url) or "" values['title'] = "'%s'" % self.sqlEscape(title) sql = "insert into url(%s) values(%s)" % (','.join(values.keys()), ','.join(values.values())) database.doSQL(sql) return title
def __init__(self): import os, database, time self.regex = "^uptime$" self.ppid = os.getppid() database.doSQL("delete from data where type = 'uptime' and created_by != '" + str(os.getppid()) + "'"); if len(database.doSQL("select * from data where type = 'uptime' and created_by ='" + str(os.getppid()) + "'")) == 0: database.doSQL("insert into data values('" + str(int(time.time())) + "', 'uptime', '" + str(os.getppid()) + "')")
def update(factoid_key, factoid_value, requested_by=None): import time sql = "update factoids set factoid_value='%s', " \ "modified_time='%s', modified_by='%s' " \ "where (factoid_key)='%s'" % ( sqlEscape(factoid_value), str(time.time()), sqlEscape(requested_by), sqlEscape(factoid_key)) database.doSQL(sql)
def update(factoid_key, factoid_value, requested_by = None): import time sql = "update factoids set factoid_value='%s', " \ "modified_time='%s', modified_by='%s' " \ "where (factoid_key)='%s'" % ( sqlEscape(factoid_value), str(time.time()), sqlEscape(requested_by), sqlEscape(factoid_key)) database.doSQL(sql)
def delete(self, *args): if self.selected_index != -1: fields = [] for column in range(len(self.table.headings)): fields.append(self.listBox.get_text(self.selected_index, column)) self.listBox.remove(self.selected_index) database.doSQL(self.table.makeSQL(fields)) self.selected_index = -1
def add(factoid_key, factoid_value, requested_by=None): import time sql = "insert into factoids("\ "factoid_key, factoid_value, created_by, created_time, "\ "requested_count) values ('%s', '%s', '%s', %s, 0)" % ( sqlEscape(factoid_key), sqlEscape(factoid_value), requested_by and sqlEscape(requested_by) or 'me', str(time.time())) database.doSQL(sql)
def add(factoid_key, factoid_value, requested_by = None): import time sql = "insert into factoids("\ "factoid_key, factoid_value, created_by, created_time, "\ "requested_count) values ('%s', '%s', '%s', %s, 0)" % ( sqlEscape(factoid_key), sqlEscape(factoid_value), requested_by and sqlEscape(requested_by) or 'me', str(time.time())) database.doSQL(sql)
def handler(self, **args): """Search for a certain string having either a given stat or any stat at all ("statfind foo")""" import database from irclib import Event target = self.return_to_sender(args) # Remove bot name text = args["text"].split()[1:] stat = text[0][:-4] # First word, strip "find" from the end name = text[1] if stat == "stat": # Build the message prefix msg = "Matching for any stat, matching on '" + name + "' " # Get the number first query = "select count(counter) from stats where nick " \ + "like '%" + name + "%'" count = database.doSQL(query)[0][0] if count > 15: msg += "(" + str(count) + " found, 15 shown): " else: msg += "(" + str(count) + " found): " # Now the actual nicks and types query = "select nick, type, counter from stats where nick " \ + "like '%" + name + "%' limit 15" results = database.doSQL(query) for tuple in results: msg += "%s (%s: %s) ;; " % tuple # Remove the last " ;; " if count != 0: msg = msg[:-4] return Event("privmsg", "", target, [msg]) else: # Build the message prefix msg = "Matching " + stat + "stats for '" + name + "' " # Get the number first query = "select count(counter) from stats where nick " \ + "like '%" + name + "%' and type='" + stat + "'" count = database.doSQL(query)[0][0] if count > 15: msg += "(" + str(count) + " found, 15 shown): " else: msg += "(" + str(count) + " found): " # Now the actual nicks for that type query = "select nick, counter from stats where nick like " \ + "'%" + name + "%' and type='" + stat + "' limit 15" results = database.doSQL(query) for tuple in results: msg += "%s: %s ;; " % tuple # Remove the last " ;; " if count != 0: msg = msg[:-4] return Event("privmsg", "", target, [msg])
def handler(self, **args): """Search for a certain string having either a given stat or any stat at all ("statfind foo")""" import database from irclib import Event target = self.return_to_sender(args) # Remove bot name text = args["text"].split()[1:] stat = text[0][:-4] # First word, strip "find" from the end name = text[1] if stat == "stat": # Build the message prefix msg = "Matching for any stat, matching on '" + name + "' " # Get the number first query = "select count(counter) from stats where nick " \ + "like '%" + name + "%'" count = database.doSQL(query)[0][0] if count > 15: msg += "(" + str(count) + " found, 15 shown): " else: msg += "(" + str(count) + " found): " # Now the actual nicks and types query = "select nick, type from stats where nick " \ + "like '%" + name + "%' limit 15" results = database.doSQL(query) for tuple in results: msg += tuple[0] + " [" + tuple[1] + "] ;; " # Remove the last " ;; " if count != 0: msg = msg[:-4] return Event("privmsg", "", target, [msg]) else: # Build the message prefix msg = "Matching " + stat + "stats for '" + name + "' " # Get the number first query = "select count(counter) from stats where nick " \ + "like '%" + name + "%' and type='" + stat + "'" count = database.doSQL(query)[0][0] if count > 15: msg += "(" + str(count) + " found, 15 shown): " else: msg += "(" + str(count) + " found): " # Now the actual nicks for that type query = "select nick from stats where nick like " \ + "'%" + name + "%' and type='" + stat + "' limit 15" results = database.doSQL(query) for tuple in results: msg += tuple[0] + " ;; " # Remove the last " ;; " if count != 0: msg = msg[:-4] return Event("privmsg", "", target, [msg])
def lock(factoid_key, requested_by=None): import time sql = "update factoids "\ "set locked_by = '%s', "\ "locked_time = '%s' "\ "where (factoid_key) = '%s'" % ( requested_by and sqlEscape(requested_by) or 'me', str(time.time()), sqlEscape(factoid_key)) database.doSQL(sql)
def lock(factoid_key, requested_by = None): import time sql = "update factoids "\ "set locked_by = '%s', "\ "locked_time = '%s' "\ "where (factoid_key) = '%s'" % ( requested_by and sqlEscape(requested_by) or 'me', str(time.time()), sqlEscape(factoid_key)) database.doSQL(sql)
def handle_tz(self, input, request_nick): """change or reset the time zone setting .valid input list format ---------------------- [0] [1] [2] ---------------------- datestz nick +/-offset datestz +/-offset ---------------------- """ assert input[0] == "datestz" tz_offset = None tz_is_valid = False qnick = request_nick show_offset = False input_len = len(input) if input_len == 1: show_offset = True elif input_len == 2: tz_offset, tz_is_valid = self.tz_validate(input[1]) if not tz_is_valid: qnick = input[1] if not qnick == "help": show_offset = True elif input_len == 3: tz_offset, tz_is_valid = self.tz_validate(input[2]) qnick = input[1] if not tz_is_valid: if not show_offset: return self.help_message_datestz else: return self.show_tz(qnick) else: tmp_data = database.doSQL( "select nick, tz_offset from bottime " "where nick = '%s'" % self.sqlEscape(qnick) ) if tmp_data: sql_string = ( "update bottime " "set tz_offset = %s " "where nick = '%s'" % (tz_offset, self.sqlEscape(qnick)) ) else: sql_string = "insert into bottime (nick, tz_offset) " "values ('%s', %s)" % ( self.sqlEscape(qnick), tz_offset, ) database.doSQL(sql_string) return "datastz: done!"
def makeline(type): """eightball. usage: Moobot: eightball <question>?""" import database if database.type == "mysql": line = database.doSQL("select data from data where type='" + type + "' order by rand() limit 1")[0][0] elif database.type == "pgsql": line = database.doSQL("select data from data where type='" + type + "' order by random() limit 1")[0][0] elif database.type == "sqlite3": line = database.doSQL("select data from data " "where type = '%s' " "order by random(*)" "limit 1" % type)[0][0] return line
def link(linkfrom, linkto, linktype, weight, requested_by=None): unlink(linkfrom, linkto) import time sql = "insert into factoidlink("\ "linkfrom, linkto, linktype, weight, created_by, created_time)"\ " values ('%s', '%s', '%s', %s, '%s', %s)" % ( sqlEscape(linkfrom), sqlEscape(linkto), sqlEscape(linktype), str(int(weight)), requested_by and sqlEscape(requested_by) or 'me', str(time.time())) database.doSQL(sql)
def link(linkfrom, linkto, linktype, weight, requested_by = None): unlink(linkfrom, linkto) import time sql = "insert into factoidlink("\ "linkfrom, linkto, linktype, weight, created_by, created_time)"\ " values ('%s', '%s', '%s', %s, '%s', %s)" % ( sqlEscape(linkfrom), sqlEscape(linkto), sqlEscape(linktype), str(int(weight)), requested_by and sqlEscape(requested_by) or 'me', str(time.time())) database.doSQL(sql)
def __init__(self): self.regex = "^uptime$" self.pid = os.getpid() database.doSQL("DELETE FROM data WHERE type = 'uptime' AND " + \ "created_by != '" + str(self.pid) + "'") if len(database.doSQL("SELECT * FROM data WHERE " + \ "type = 'uptime' AND " + \ "created_by ='" + str(self.pid) + "'")) == 0: database.doSQL("INSERT INTO data (data, type, created_by) "+\ "VALUES('" + str(int(time.time())) + "', "+\ "'uptime', '" + str(self.pid) + "')")
def handler(self, **args): import database, priv from irclib import Event, nm_to_n # The target will always be a privmsg, and always to the person # we are telling it to. target = args["text"].split()[2] sender = nm_to_n(args["source"]) # Check if this is faketell or not faketell = 0 if args["text"].split()[1] == "faketell": if priv.checkPriv(args["source"], "faketell_priv"): faketell = 1 # Get the factoid factoid_key = " ".join(args["text"].split()[4:]) # Check if it exists first count_query = "select count(factoid_key) from" \ + " factoids where lower(factoid_key) = '" + factoid_key.lower() + "'" count = database.doSQL(count_query)[0][0] if count == 0: # Send the sender a message that it doesn't exist target = sender message = "Factoid '" + factoid_key + "' does not exist" return Event("privmsg", "", target, [message]) # Grab it and parse it factoid_query = "select factoid_value from factoids where" \ + " lower(factoid_key) = '" + factoid_key.lower() + "'" factoid = self.parse_sar(database.doSQL(factoid_query)[0][0]) # Replace $who and $nick with the target factoid = factoid.replace("$who", target) factoid = factoid.replace("$nick", target) # If the factoid begins with <reply> then just tell it to them # otherwise, tell them what factoid and who sent it if faketell: if factoid.lower()[:7] == "<reply>": message = factoid[7:] else: message = factoid_key + " is " + factoid else: if factoid.lower()[:7] == "<reply>": factoid = factoid[7:] message = sender + " wanted you to know: " + factoid else: message = sender + " wanted you to know: " + factoid_key \ + " is " + factoid return Event("privmsg", "", target, [message])
def get_score(self, who): """ retrieve a single nick,score pair from the database """ import database results=database.doSQL("select counter from stats where nick = '" + who + "' and type = '" + WGTYPE + "'") if len(results) == 0: database.doSQL("insert into stats values( '" + who + "', '" + WGTYPE + "', 0)") score = 0 else: score = int(results[0][0]) return score
def handle_tz(self, input, request_nick): """change or reset the time zone setting .valid input list format ---------------------- [0] [1] [2] ---------------------- datestz nick +/-offset datestz +/-offset ---------------------- """ assert input[0] == "datestz" tz_offset = None tz_is_valid = False qnick = request_nick show_offset = False input_len = len(input) if input_len == 1: show_offset = True elif input_len == 2: tz_offset, tz_is_valid = self.tz_validate(input[1]) if not tz_is_valid: qnick = input[1] if not qnick == "help": show_offset = True elif input_len == 3: tz_offset, tz_is_valid = self.tz_validate(input[2]) qnick = input[1] if not tz_is_valid: if not show_offset: return self.help_message_datestz else: return self.show_tz(qnick) else: tmp_data = database.doSQL("select nick, tz_offset from bottime "\ "where nick = '%s'" % self.sqlEscape(qnick)) if tmp_data: sql_string = "update bottime "\ "set tz_offset = %s "\ "where nick = '%s'" % (tz_offset, self.sqlEscape(qnick)) else: sql_string = "insert into bottime (nick, tz_offset) "\ "values ('%s', %s)" % (self.sqlEscape(qnick), tz_offset) database.doSQL(sql_string) return "datastz: done!"
def score(self, who, type, opt=0): """ modify score for a user """ import database current = self.get_score(who) if type == 'WIN': current = current + (opt*10) + 15 elif type == 'LOSE': current -= 15 elif type == 'GUESS': current = (current - 5) + (opt*10) database.doSQL("update stats set counter = "+ str(current)+" where nick = '" + who + "' and type= '" + WGTYPE+"'")
def get_score(self, who): """ retrieve a single nick,score pair from the database """ import database results = database.doSQL("select counter from stats where nick = '" + who + "' and type = '" + WGTYPE + "'") if len(results) == 0: database.doSQL("insert into stats values( '" + who + "', '" + WGTYPE + "', 0)") score = 0 else: score = int(results[0][0]) return score
def handler(self, **args): """searches factoid keys""" import database, string from irclib import Event # {{{ Strip bot name and "listkeys" from the text we get # }}} search_string = self.strip_words(args["text"], 2) type = args["text"].split()[1] # have type search the appropriate attribute in the database if type == "listkeys": type="factoid_key" elif type == "listvalues": type="factoid_value" elif type == "listauth": type="created_by" # {{{ matchcount simply gets the number of matches for the SQL query that counts # factoids that are "like" the one given to us, and keys gets the actual list # (which is in the form of a list of one-element tuples) }}} matchcount=database.doSQL("select count("+ type + ") from factoids where " + type + " like '%" + search_string + "%'")[0][0] if database.type == "mysql": matchcount=database.doSQL("select count("+ type + ") from factoids where " + type + " like '%" + search_string + "%'")[0][0] keys=database.doSQL("select factoid_key from factoids where "+ type + " like \"%" + search_string + "%\" order by rand() LIMIT 15") elif database.type == "pgsql": matchcount=database.doSQL("select count("+ type + ") from factoids where lower(" + type + ") = '" + search_string.lower() + "'")[0][0] keys=database.doSQL("select factoid_key from factoids where lower("+ type + ") = '" + search_string.lower() + "' LIMIT 15") # {{{ Printing out SQL query to show what is being looked up # }}} #print "select "+ type + " from factoids where "+ type + " like \"%" + search_string + "%\"" # {{{ Add a nifty little preface to the list showing what was searched and how many match and # (if applicable, how many we are showing) }}} text = "Factoid search of '" + search_string + "' by "+ type + " (" + str(matchcount) + " matching" # {{{ If we match more than fifteen, they only see fifteen (LIMIT 15, above), so # we'll tell them there are more there, but they only see fifteen }}} if matchcount > 15: text += "; 15 shown" text +="): " # {{{ Append on each of the fifteen terms and a separator # }}} index = 0 while index < len(keys): text += keys[index][0] + " ;; " index += 1 target = self.return_to_sender(args) return Event("privmsg", "", target, [ text ])
def checkPriv(hostmask, privilege): """checks if the user identified by hostmask has privilege privilege returns 0 if the nick/hostmask doesn't have that privilege returns 1 if they do""" import database value=database.doSQL("select count(hostmask) from grants where '" + hostmask + "' LIKE hostmask and (priv_type = '" + privilege + "' or priv_type = 'all_priv')") return value[0][0]
def lookup(dk): import database rs = database.doSQL("SELECT d_value FROM dict WHERE d_key='%s'" % sqlEscape(dk)) try: return rs[0][0] or False except: return False
def getUserAbilities(self, nick, channel): import database return database.doSQL("SELECT ab.name,score \ FROM userability ua \ LEFT JOIN ability ab ON ab.abilityid=ua.abilityid \ WHERE nick='%s' AND channel='%s' \ ORDER BY score DESC" % (self.sqlEscape(nick), self.sqlEscape(channel)))
def getUrl(self, url, hash): sql = "SELECT urlid,title FROM url WHERE url='%s' AND hash='%s'" % (self.sqlEscape(url), self.sqlEscape(hash)) ret = database.doSQL(sql) if ret and ret[0]: return ret[0] else: return (None, None)
def handler(self, **args): import database, priv, string from irclib import nm_to_n, Event user = args["text"].split()[2] # get name if priv.checkPriv(args["source"], "quote_priv") == 0: #check if requester is allowed to do this return Event("privmsg", "", self.return_to_sender(args), [ "That requires quote_priv" ]) results = database.doSQL("select message, time from seen where nick = '%s'" % (user)) # check if they have a "seen" entry, act accordingly if len(results) > 0: quote, time = results[0] else: return Event("privmsg", "", self.return_to_sender(args), [ "No quote available for %s" % (user) ]) #update their webstats entry with the new info database.doSQL("update webstats set quote = '%s', quote_time = %s where nick = '%s' and channel = '%s'" % (string.replace(string.replace(quote, "\\", "\\\\"), "'", "\\'"), str(time), user, args["channel"])) return Event("privmsg", "", self.return_to_sender(args), [ "Grabbing quote for %s" % (user) ])
def getNames(): import database rsses = database.doSQL("SELECT r_name FROM rss ORDER BY r_name") names = [] for rss in rsses: names.append(rss[0]) return names
def getPriv(hostmask, privilege): global privCache if not privCache: privCache = {} import database, re privs = database.doSQL( "SELECT priv_type,hostmask FROM grants ORDER BY priv_type") for priv in privs: ptype, pmask = priv regex = re.compile(re.escape(pmask).replace("\\%", ".*"), re.I) if not privCache.has_key(ptype): privCache[ptype] = [] privCache[ptype].append(regex) if privCache.has_key(privilege): for regex in privCache[privilege]: if regex.match(hostmask): return hostmask if privilege != 'all_priv' and privCache.has_key('all_priv'): for regex in privCache['all_priv']: if regex.match(hostmask): return hostmask return False
def handler(self, **args): """ gets a random factoid from the database""" from irclib import nm_to_n, Event import database, string, random target = self.return_to_sender(args) if database.type == "mysql": factoid = database.doSQL("select factoid_key, factoid_value from factoids order by rand() limit 1")[0] elif database.type == "pgsql": random.seed() offset = random.randint(0, database.doSQL("select count(factoid_key) from factoids")[0][0]-1) factoid = database.doSQL("select factoid_key, factoid_value from factoids order by factoid_key limit 1 offset " + str(offset) )[0] factoid_key = factoid[0] factoid_value = self.parse_sar(string.lstrip(factoid[1])) factoid_value = string.replace(factoid_value, "$who", nm_to_n(args["source"])) return Event("privmsg" , "", target, [ "Random factoid: " +factoid_key + " is " + string.strip(factoid_value) ])
def handler(self, **args): import database, priv from irclib import Event, nm_to_n # if we don't have a nick supplied, get the second most recent form the DB # (the most recent would be the person saying "~qg" try: user = args["text"].split()[2] # get name except IndexError: temp = database.doSQL( "select nick from seen order by time desc limit 2") if len(temp) == 2: user = temp[1][0] else: user = temp[0][0] if nm_to_n(args["source"]).lower() == user.lower(): return Event("privmsg", "", self.return_to_sender(args), ["Can't quotegrab yourself!"]) if priv.checkPriv( args["source"], "quote_priv") == 0: #check if requester is allowed to do this return Event("privmsg", "", self.return_to_sender(args), ["That requires quote_priv"]) results = database.doSQL( "select message, time, type from seen where nick = '%s'" % (user)) # check if they have a "seen" entry, act accordingly if len(results) > 0: quote, time, type = results[0] else: return Event("privmsg", "", self.return_to_sender(args), ["No quote available for %s" % (user)]) # If it's not a privmsg, spit it back if type not in ["privmsg", "action"]: return Event("privmsg", "", self.return_to_sender(args), [ "Last event seen was not a message or action, not grabbing quote for %s" % user ]) #update their webstats entry with the new info database.doSQL( "update webstats set quote = '%s', quote_time = %s, type= '%s' where nick = '%s' and channel = '%s'" % (quote.replace("\\", "\\\\").replace( "'", "\\'"), str(time), type, user, args["channel"])) return Event("privmsg", "", self.return_to_sender(args), ["Grabbing quote for %s" % (user)])
def handler(self, **args): """deletes a specific stat for a given user""" import database import priv from irclib import Event target = self.return_to_sender(args) type = args["text"].split()[1] type = type[:len(type)-5] who = args["text"].split()[2] if priv.checkPriv(args["source"], "reset_stats_priv") == 0: return Event("privmsg", "", target, [ "You aren't allowed to do that" ]) self.debug(type, who) database.doSQL("delete from stats where type = '" + type + "' and nick = '" + who + "'") return Event("privmsg", "", target, [ "Reset " + who + "'s " + type + " stats." ])
def getLinkCreatedBy(linkfrom, linkto): sql = "select created_by from factoidlink"\ " where linkfrom = '%s' and linkto = '%s'" % (sqlEscape(linkfrom), sqlEscape(linkto)) linkinfo = database.doSQL(sql) if not linkinfo: return None return linkinfo[0] or ""
def makeline(type): """eightball. usage: Moobot: eightball <question>?""" import database if database.type == "mysql": line = database.doSQL("select data from data where type='" + \ type + "' order by rand() limit 1")[0][0] elif database.type == "pgsql": line = database.doSQL("select data from data where type='" + \ type + "' order by random() limit 1")[0][0] elif database.type == "sqlite3": line = database.doSQL("select data from data "\ "where type = '%s' "\ "order by random(*)"\ "limit 1" % type)[0][0] return line
def score(self, who, type, opt=0): """ modify score for a user """ import database current = self.get_score(who) if type == 'WIN': current = current + (opt * 10) + 15 elif type == 'LOSE': current -= 15 elif type == 'GUESS': current = (current - 5) + (opt * 10) database.doSQL("update stats set counter = " + str(current) + " where nick = '" + who + "' and type= '" + WGTYPE + "'")
def handler(self, **args): """Set someone's stats to a specific number""" import priv, database from irclib import Event target = self.return_to_sender(args) # Remove bot name text = args["text"].split()[1:] type = text[0][:-3] # First element is the stat type names = text[1:-1] # All but the first and last elements are names count = text[-1] # Last one is the number to set it to # Check privs if priv.checkPriv(args["source"], "reset_stats_priv") == 0: return Event("privmsg", "", target, [ "You aren't allowed to do that" ]) # Since some of these may already be set, but some may not, we can't # simply use "update". The easiest way to do it is to delete all of # them and re-insert them. # # Delete first query = "delete from stats where type='" + \ type + "' and " for name in names: query += "nick='" + name + "' or " # Remove the last " or " query = query[:-4] # Do it to it database.doSQL(query) # # Now re-insert one by one # FIXME: is there a way to do this all in one - like build a huge # query and then just make one call? for name in names: query = "insert into stats(counter, nick, type) values(" \ + count + ", '" + name + "', '" + type + "')" database.doSQL(query) msg = "Set " + type + " to " + str(count) + " for: " for name in names: msg += name + ", " # Remove the last ", " msg = msg[:-2] return Event("privmsg", "", target, [ msg ])
def get(self): """return timestamp""" import database b = database.doSQL("SELECT birthday FROM birthday WHERE nick='%s'" % (self.sqlEscape(self.nick))) if not b or not b[0]: return False b = b[0][0] try: return ND((b.year, b.month, b.day)) except: return False
def setUserAbilityScore(self, nick, channel, abilityid, score, bynick): import database rs = database.doSQL("REPLACE INTO userability \ SET nick='%s', channel='%s', abilityid=%d, score=%d, bynick='%s'" % (self.sqlEscape(nick), self.sqlEscape(channel), abilityid, score, self.sqlEscape(bynick))) try: return rs[0][0] or 0 except: return None
def handler(self, **args): from irclib import Event from seen import time2str start_time = database.doSQL("SELECT data FROM data WHERE " + \ "type = 'uptime' and " + \ "created_by ='" + str(self.pid) + \ "'")[0][0] result = "I've been awake for " + time2str(int(start_time)) return Event("privmsg", "", self.return_to_sender(args), [result])