def handler(self, **args): """returns a continue if the user is not to be ignored, otherwise returns a "do nothing" handler""" import priv from irclib import Event if priv.checkPriv(args["source"], "notalk_priv") != 0 and priv.checkPriv(args["source"], "all_priv") == 0: self.debug("ignoring message by " + args["source"]) return Event("do nothing", "", "" , [ ]) return Event("continue", "", "" , [])
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 handler(self, **args): """ replaces an existing factoid (no factoid is text> """ import priv from irclib import Event from time import time target = self.return_to_sender(args) # Strip the bot name and "no" from the factoid factoid_text = self.strip_words(args["text"], 2) # Separate the factoid_keu (the word(s) before "is") from the # factoid value (anything after the first "is") data = factoid_text.split(" is ", 1) factoid_key = data[0] factoid_value = data[1] locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: message = "Factoid '" + factoid_key + "' does not exist." return Event("privmsg", "", target, [message]) # Check if they can modify factoids, and if they can modify THIS # particular factoid (ie, it's not locked) if priv.checkPriv(args["source"], "delete_priv") == 0 and locked_by != "": return Event( "privmsg", "", target, ["Factoid \"%s\" locked by %s" % (factoid_key, locked_by)]) FactoIds.replace(factoid_key, factoid_value, args["source"]) return Event("privmsg", "", target, ["ok"])
def handler(self, **args): """ replaces an existing factoid (no factoid is text> """ import priv from irclib import Event from time import time target = self.return_to_sender(args) # Strip the bot name and "no" from the factoid factoid_text = self.strip_words(args["text"], 2) # Separate the factoid_keu (the word(s) before "is") from the # factoid value (anything after the first "is") data = factoid_text.split(" is ", 1) factoid_key = data[0] factoid_value = data[1] locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: message = "Factoid '" + factoid_key + "' does not exist." return Event("privmsg", "", target, [message]) # Check if they can modify factoids, and if they can modify THIS # particular factoid (ie, it's not locked) if priv.checkPriv(args["source"], "delete_priv") == 0 and locked_by != "": return Event("privmsg","", target, [ "Factoid \"%s\" locked by %s" % (factoid_key, locked_by)]) FactoIds.replace(factoid_key, factoid_value, args["source"]) return Event("privmsg", "", target, [ "ok" ])
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): """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 handler(self, **args): """Allows someone to add material onto a factoid (that isn't locked) by saying "foo is also bar", for example""" import priv from irclib import Event from time import time target = self.return_to_sender(args) # args["text"] should look something like: # "moobot: foo is also bar blatz qux" # Grab the factoid to change: factoid_key = self.strip_words(args["text"], 1).split(" is ")[0] # Grab the stuff to tack on: to_add = self.strip_words(args["text"], 1).split(" is also ")[1] # Check if the factoid is locked or not locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: message = "Factoid '%s' does not exist." % factoid_key return Event("privmsg", "", target, [message]) if priv.checkPriv(args["source"], "delete_priv") == 0 and ( locked_by != "" and locked_by != args["source"]): message = "You do not have permission to delete factoid '%s." % factoid_key return Event("privmsg", "", target, [message]) # Since we don't have delete_priv, we just delete and recreate the factoid orig_factoid = FactoIds.getValueByKey(factoid_key) new_factoid = orig_factoid + ", or " + to_add FactoIds.update(factoid_key, new_factoid, args["source"]) return Event("privmsg", "", target, ["ok"])
def handler(self, **args): """Allows someone to add material onto a factoid (that isn't locked) by saying "foo is also bar", for example""" import priv from irclib import Event from time import time target = self.return_to_sender(args) # args["text"] should look something like: # "moobot: foo is also bar blatz qux" # Grab the factoid to change: factoid_key = self.strip_words(args["text"], 1).split(" is ")[0] # Grab the stuff to tack on: to_add = self.strip_words(args["text"], 1).split(" is also ")[1] # Check if the factoid is locked or not locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: message = "Factoid '%s' does not exist." % factoid_key return Event("privmsg", "", target, [message]) if priv.checkPriv(args["source"], "delete_priv") == 0 and (locked_by != "" and locked_by != args["source"]): message = "You do not have permission to delete factoid '%s." % factoid_key return Event("privmsg", "", target, [message]) # Since we don't have delete_priv, we just delete and recreate the factoid orig_factoid = FactoIds.getValueByKey(factoid_key) new_factoid = orig_factoid + ", or " + to_add FactoIds.update(factoid_key, new_factoid, args["source"]) return Event("privmsg", "", target, ["ok"])
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): import priv, string from irclib import Event if (priv.checkPriv(args["source"], "all_priv") == 0): return Event("privmsg", "", self.return_to_sender(args), ["You can't do that!"]) print string.split(args["text"], " ", 3)[3] return Event("internal", "send_raw", "", ["send_raw", string.split(args["text"], " ", 3)[3] ])
def handler(self, **args): """ lock and unlock factoids """ import priv, time from irclib import Event, nm_to_n # Change the target based on how we were called target = self.return_to_sender(args) # Strip off the first word and then take the first word of # what's left to get our action, lock or unlock action = self.strip_words(args["text"], 1).split(" ", 1)[0] # Every word after the first two is the factoid key factoid_key = self.strip_words(args["text"], 2) if action == "lock": # We allow people to lock their own factoid, or, if they have # lock_priv, whatever they want if factoid_key == nm_to_n(args["source"]) \ or priv.checkPriv(args["source"], "lock_priv") == 1: FactoIds.lock(factoid_key, args["source"]) msg = "Factoid \"%s\" locked." % factoid_key else: msg = "You can't lock this factoid." elif action == "unlock": # For unlocking, first check who locked the factoid we are # talking about locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: msg = "Factoid \"%s\" not found." % factoid_key else: # if we aren't locked, tell them, otherwise, check if the factoid # is for the requester's nick or if they have lock_priv (which # allows unlocking as well) if not locked_by: msg = "Factoid \"%s\" is not locked." % factoid_key elif locked_by != args["source"] and not priv.checkPriv( args["source"], "lock_priv"): msg = "You cannot unlock this factoid." else: FactoIds.unlock(factoid_key, args["source"]) msg = "Factoid \"%s\" unlocked." % factoid_key return Event("privmsg", "", target, [msg])
def handler(self, **args): """ lock and unlock factoids """ import priv, time from irclib import Event, nm_to_n # Change the target based on how we were called target = self.return_to_sender(args) # Strip off the first word and then take the first word of # what's left to get our action, lock or unlock action = self.strip_words(args["text"], 1).split(" ", 1)[0] # Every word after the first two is the factoid key factoid_key = self.strip_words(args["text"], 2) if action == "lock": # We allow people to lock their own factoid, or, if they have # lock_priv, whatever they want if factoid_key == nm_to_n(args["source"]) \ or priv.checkPriv(args["source"], "lock_priv") == 1: FactoIds.lock(factoid_key, args["source"]) msg = "Factoid \"%s\" locked." % factoid_key else: msg = "You can't lock this factoid." elif action == "unlock": # For unlocking, first check who locked the factoid we are # talking about locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: msg = "Factoid \"%s\" not found." % factoid_key else: # if we aren't locked, tell them, otherwise, check if the factoid # is for the requester's nick or if they have lock_priv (which # allows unlocking as well) if not locked_by: msg = "Factoid \"%s\" is not locked." % factoid_key elif locked_by != args["source"] and not priv.checkPriv(args["source"], "lock_priv"): msg = "You cannot unlock this factoid." else: FactoIds.unlock(factoid_key, args["source"]) msg = "Factoid \"%s\" unlocked." % factoid_key return Event("privmsg", "", target, [ msg ])
def handler(self, **args): import priv from irclib import Event module_list = [] for module in args["text"].split()[2:]: module_list.append(module) if priv.checkPriv(args["source"], 'module_priv') != 0: return [Event("internal", "", "", [ "unload" ] + module_list), Event("privmsg", "", self.return_to_sender(args), [ "unloading " + " ".join(module_list)] )] else: return Event("privmsg", "", self.return_to_sender(args), [ "that requires module_priv." ])
def handler(self, **args): import priv from irclib import Event if (priv.checkPriv(args["source"], "all_priv") == 0): return Event("privmsg", "", self.return_to_sender(args), ["You can't do that!"]) self.Debug(args["text"].split(" ", 3)[3]) return Event("internal", "send_raw", "", ["send_raw", args["text"].split(" ", 3)[3]])
def handler(self, **args): """handles "op" commands""" from irclib import Event import priv if priv.checkPriv(args["source"], "op_priv") == 0: return Event("privmsg", "", self.return_to_sender(args), [ "You do not have permission to do that." ]) user = args["text"] user = user[user.find(" ")+1:] user = user[user.find(" ")+1:] result = Event("internal", "", user.split()[1], [ "op", user.split()[0]] ) return result
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 handler(self, **args): """handles "op" commands""" from irclib import Event import priv if priv.checkPriv(args["source"], "op_priv") == 0: return Event("privmsg", "", self.return_to_sender(args), ["You do not have permission to do that."]) user = args["text"] user = user[user.find(" ") + 1:] user = user[user.find(" ") + 1:] result = Event("internal", "", user.split()[1], ["op", user.split()[0]]) return result
def handler(self, **args): """ lock and unlock factoids """ import string, database, priv, time from irclib import Event, nm_to_n # {{{ Change the target based on how we were called # }}} target = self.return_to_sender(args) # {{{ Strip off the first word and then take the first word of # what's left to get our action, lock or unlock }}} action = self.strip_words(args["text"], 1).split(" ", 1)[0] # {{{ Every word after the first two is the factoid key # }}} factoid_key = self.strip_words(args["text"], 2) factoid_key = self.escape_slashes(factoid_key) #print action + "ing:", factoid_key if action == "lock": # {{{ We allow people to lock their own factoid, or, if they have lock_priv, whatever they want # }}} if factoid_key == nm_to_n(args["source"]) or priv.checkPriv(args["source"], "lock_priv") == 1: database.doSQL("update factoids set locked_by = '" + args["source"] + "', locked_time = " + str(time.time()) + " where lower(factoid_key) = '" + factoid_key.lower() + "'") return Event("privmsg", "", target, [ "Factoid \"" + factoid_key + "\" locked." ]) else: return Event("privmsg", "", target, [ "You aren't allowed to do that." ]) else: # {{{ For unlocking, first check who locked the factoid we are talking about # }}} locked_by = database.doSQL("select locked_by from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'") # {{{ if we aren't locked, tell them, otherwise, check if the factoid is for the requester's nick # or if they have lock_priv (which allows unlocking as well) }}} if len(locked_by) == 0 or len(locked_by[0]) == 0 or locked_by[0][0] == None: return Event("privmsg", "", target, [ "Factoid \"" + factoid_key + "\" is not locked." ]) elif locked_by[0][0] != args["source"] and not priv.checkPriv(args["source"], "lock_priv"): print locked_by[0][0], args["source"], priv.checkPriv(args["source"], "lock_priv") return Event("privmsg", "", target, [ "No." ]) else: database.doSQL("update factoids set locked_by = NULL where lower(factoid_key) = '" + factoid_key.lower() + "'") return Event("privmsg", "", target, [ "Factoid \"" + factoid_key + "\" unlocked." ])
def handler(self, **args): """handles "kick" commands -- need to implement permission checking on this""" from irclib import Event import priv if priv.checkPriv(args["source"], "kick_priv") == 0: target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target=nm_to_n(args["source"]) return Event("privmsg", "", target, [ "You do not have permission to do that." ]) user = args["text"] user = user[user.find(" ")+1:] user = user[user.find(" ")+1:] result = Event("internal", "", user.split()[1], [ "kick" ,user.split()[0]] ) return result
def handler(self, **args): """handles "part" commands with priv checking""" from irclib import Event import priv if priv.checkPriv(args["source"], "part_priv") == 0: target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target=nm_to_n(args["source"]) return Event("privmsg", "", target, [ "You do not have permission to do that." ]) channel = args["text"] channel = channel[channel.find(" ")+1:] channel = channel[channel.find(" ")+1:] result = Event("internal", "", channel, [ "part" ] ) return result
def handler(self, **args): """ replaces an existing factoid (no factoid is text> """ import string, database, priv from irclib import Event from time import time target = self.return_to_sender(args) # {{{ Strip the bot name and "no" from the factoid # }}} factoid_text = self.strip_words(args["text"], 2) # {{{ Separate the factoid_keu (the word(s) before "is") from the # factoid value (anything after the first "is") }}} data = factoid_text.split(" is ", 1) factoid_key = data[0] factoid_value = data[1] # {{{ Prepare the stuff for SQL by escaping slashes # }}} factoid_key = self.escape_slashes(factoid_key) factoid_value = self.escape_slashes(factoid_value) if database.doSQL("select count(factoid_key) from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'")[0][0] != 0: locked_by = database.doSQL("select locked_by from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'")[0][0] created_by = database.doSQL("select created_by from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'")[0][0] else: locked_by = "" created_by = "" # First make sure the factoid exists count_query = "select count(factoid_key) from factoids where" \ + " lower(factoid_key) = '" + factoid_key.lower() + "'" if database.doSQL(count_query)[0][0] == 0: message = "Factoid '" + factoid_key + "' does not exist." return Event("privmsg", "", target, [message]) # {{{ Check if they can modify factoids, and if they can modify THIS # particular factoid (ie, it's not locked) }}} if priv.checkPriv(args["source"], "delete_priv") == 0 and locked_by != "" and locked_by != None: return Event("privmsg","", target, [ "Factoid is locked."]) if database.doSQL("select count(factoid_key) from factoids where lower(factoid_key) = '" + factoid_key.lower() + "' and (locked_by is null or locked_by = '')")[0][0] == 0: return Event("privmsg","", target, [ "Factoid \"" + factoid_key + "\" is locked."]) # {{{ If we make it here, we simply delete and recreate the factoid # }}} database.doSQL("delete from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'") database.doSQL("insert into factoids(factoid_key, created_by, created_time, factoid_value, requested_count) values('" + factoid_key + "', '" + args["source"] + "', " + str(int(time())) + ", '"+ factoid_value +"', 0)") return Event("privmsg", "", target, [ "ok"])
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 handler(self, **args): """handles "part" commands with priv checking""" from irclib import Event import priv if priv.checkPriv(args["source"], "part_priv") == 0: target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target = nm_to_n(args["source"]) return Event("privmsg", "", target, ["You do not have permission to do that."]) channel = args["text"] channel = channel[channel.find(" ") + 1:] channel = channel[channel.find(" ") + 1:] result = Event("internal", "", channel, ["part"]) return result
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): """handles "kick" commands -- need to implement permission checking on this""" from irclib import Event import priv if priv.checkPriv(args["source"], "kick_priv") == 0: target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target = nm_to_n(args["source"]) return Event("privmsg", "", target, ["You do not have permission to do that."]) user = args["text"] user = user[user.find(" ") + 1:] user = user[user.find(" ") + 1:] result = Event("internal", "", user.split()[1], ["kick", user.split()[0]]) return result
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 handler(self, **args): """handles "join" commands with priv checking""" from irclib import Event import priv if priv.checkPriv(args["source"], "join_priv") == 0: target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target=nm_to_n(args["source"]) return Event("privmsg", "", target, [ "You do not have permission to do that." ]) channel = args["text"] channel = channel[channel.find(" ")+1:] channel = channel[channel.find(" ")+1:] result = [Event("internal", "", channel, [ "join" ] )] result.append(Event("privmsg","", channel, ["Ok, I'm here, now what are your other two wishes?"])) return result
def handler(self, **args): "Remove a factoid from the database" import string, database, priv, re from irclib import Event, nm_to_n # {{{ We are normally called with "moobot: forget foo", but the factoid key # is just the part after "moobot: forget", so we strip that here }}} factoid_key = self.strip_words(args["text"], 2) # {{{ Escape slashes within the factoid so they don't accidentally escape things # we don't want them to escape later on }}} factoid_key = self.escape_slashes(factoid_key) # {{{ If we got this via a /msg, /msg back, otherwise back to the channel it goes # }}} target = self.return_to_sender(args) requester = args["source"] # {{{ We will always get back a (non-empty) list from this that is of the format: # [(<some number>,)] # That number is the number of instances of the factoid_key in the factoid # database (which should be 0 or 1). If it's 0, tell them we don't have the # factoid. }}} if database.doSQL("select count(factoid_key) from factoids where factoid_key = '" + factoid_key + "'")[0][0] == 0: return Event("privmsg", "", target, [ "factoid \"" + factoid_key + "\" does not exist."]) # {{{ This SQL query gets back a list similar to the one before: # [(<person who locked the factoid>,)] # Only, if the locked_by value is NULL in SQL, we get None in our tuple. }}} locked = database.doSQL("select locked_by from factoids where lower(factoid_key) = '" + factoid_key.lower() +"'") locked_by = locked[0][0] author = database.doSQL("select created_by from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'") created_by = author[0][0] print "created_by = ", created_by print "requester = ", requester # {{{ If the factoid is locked, or the person doesn't have the right to delete # things anyway, tell them they can't. ... unless they created it. }}} if locked_by != None: return Event("privmsg", "", target, [ "factoid \"" + factoid_key + "\" is locked"]) if (priv.checkPriv(requester, "delete_priv") == 0) and (created_by != requester): return Event("privmsg", "", target, [ "You do not have delete privileges" ]) # {{{ If we made it here, they can delete it. So delete it, and tell them. # }}} database.doSQL("delete from factoids where lower(factoid_key) = '" + factoid_key.lower() + "'") return Event("privmsg", "", target, [ "factoid \"" + factoid_key + "\" deleted."])
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 handler(self, **args): """ Adds a new poll. """ 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_question = " ".join(args["text"].split()[3:]) poll_question = self.sqlEscape(poll_question) database.doSQL("Insert into poll(question) values('" + poll_question + "')") poll_num = database.doSQL("select poll_num from poll where question = '" + poll_question + "'")[0][0] return Event("privmsg", "", target, [ "Poll added. as number " + str(poll_num) + "." ])
def do_chan(self, mask, input): import priv if priv.checkPriv(mask, "all_priv") == 0: return "I don't have to listen to you." else: try: if input[0] == '+': for chan in input[1:]: self.channels.append(chan) elif input[0] == '-': for chan in input[1:]: try: self.channels.remove(chan) except ValueError: pass message = 'ok' except IndexError: message = "you didn't seem to provide valid input." return message
def handler(self, **args): from irclib import Event if args["source"] in self.messages.keys(): if self.messages[args["source"]].message == args["text"] and \ self.messages[args["source"]].time + 5 >= time.time() and \ priv.checkPriv(args["source"], "flood_priv") == 0: self.messages[args["source"]].time = time.time() self.debug("ignoring duplicate message") return Event("do nothing", "", "", [ ]) self.messages[args["source"]].message = args["text"] self.messages[args["source"]].time = time.time() else: temp = self.message() temp.time = time.time(); temp.message = args["text"] self.messages[args["source"]] = temp return Event("continue", "", "", [ ])
def handler(self, **args): from irclib import Event if args["source"] in self.messages.keys(): if self.messages[args["source"]].message == args["text"] and \ self.messages[args["source"]].time + 5 >= time.time() and \ priv.checkPriv(args["source"], "flood_priv") == 0: self.messages[args["source"]].time = time.time() print "ignoring duplicate message" return Event("do nothing", "", "", [ ]) self.messages[args["source"]].message = args["text"] self.messages[args["source"]].time = time.time() else: temp = self.message() temp.time = time.time(); temp.message = args["text"] self.messages[args["source"]] = temp return Event("continue", "", "", [ ])
def handler(self, **args): "Remove a factoid" import priv from irclib import Event # If we got this via a /msg, /msg back, otherwise back to the channel # it goes target = self.return_to_sender(args) # We are normally called with "moobot: forget foo", but the factoid key # is just the part after "moobot: forget", so we strip that here factoid_key = self.strip_words(args["text"], 2) requester = args["source"] locked_by = FactoIds.getLockedBy(factoid_key) created_by = FactoIds.getCreatedBy(factoid_key) if locked_by == None or created_by == None: msg = "Factoid \"%s\" does not exist." % factoid_key return Event("privmsg", "", target, [ msg ]) self.debug("created_by = ", created_by) self.debug("requester = ", requester) # If the factoid is locked, or the person doesn't have the right to # delete things anyway, tell them they can't. ... unless they created # it. if locked_by: msg = "Factoid \"%s\" is locked." % factoid_key return Event("privmsg", "", target, [ msg ]) if (priv.checkPriv(requester, "delete_priv") == 0) \ and (created_by != requester): msg = "You do not have delete privileges." return Event("privmsg", "", target, [ msg ]) # If we made it here, they can delete it. So delete it, and tell # them. FactoIds.delete(factoid_key) msg = "Factoid \"%s\" deleted." % factoid_key return Event("privmsg", "", target, [ msg ])
def handler(self, **args): """ removes a poll. Syntax: moobot: remove poll #""" import database, 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] database.doSQL("delete from poll_votes where poll_num = " + poll_num) database.doSQL("delete from poll_options where poll_num = " + poll_num) database.doSQL("delete from poll where poll_num = " + poll_num) return Event("privmsg", "", target, [ "Poll deleted." ])
def handler(self, **args): "Remove a factoid" import priv from irclib import Event # If we got this via a /msg, /msg back, otherwise back to the channel # it goes target = self.return_to_sender(args) # We are normally called with "moobot: forget foo", but the factoid key # is just the part after "moobot: forget", so we strip that here factoid_key = self.strip_words(args["text"], 2) requester = args["source"] locked_by = FactoIds.getLockedBy(factoid_key) created_by = FactoIds.getCreatedBy(factoid_key) if locked_by == None or created_by == None: msg = "Factoid \"%s\" does not exist." % factoid_key return Event("privmsg", "", target, [msg]) self.debug("created_by = ", created_by) self.debug("requester = ", requester) # If the factoid is locked, or the person doesn't have the right to # delete things anyway, tell them they can't. ... unless they created # it. if locked_by: msg = "Factoid \"%s\" is locked." % factoid_key return Event("privmsg", "", target, [msg]) if (priv.checkPriv(requester, "delete_priv") == 0) \ and (created_by != requester): msg = "You do not have delete privileges." return Event("privmsg", "", target, [msg]) # If we made it here, they can delete it. So delete it, and tell # them. FactoIds.delete(factoid_key) msg = "Factoid \"%s\" deleted." % factoid_key return Event("privmsg", "", target, [msg])
def handler(self, **args): """handles "join" commands with priv checking""" from irclib import Event import priv if priv.checkPriv(args["source"], "join_priv") == 0: target = args["channel"] if args["type"] == "privmsg": from irclib import nm_to_n target = nm_to_n(args["source"]) return Event("privmsg", "", target, ["You do not have permission to do that."]) channel = args["text"] channel = channel[channel.find(" ") + 1:] channel = channel[channel.find(" ") + 1:] result = [Event("internal", "", channel, ["join"])] result.append( Event("privmsg", "", channel, ["Ok, I'm here, now what are your other two wishes?"])) return result
def handler (self, **args): """adds larts and praises""" import priv import string from irclib import Event import database type = string.split(args["text"])[2] value = string.join(string.split(args["text"])[3:]) print 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 = string.replace (value, "\\", "\\\\") value = string.replace (value, "\"", "\\\"") value = string.replace (value, "'", "\\'") database.doSQL("insert into data values('" + value + "', '" + type + "', '" + args["source"] + "')") return Event("privmsg", "", target, [ "Adding: \"" + value + "\" as " + type + "." ])
def handler(self, **args): import priv, imp from irclib import Event module_list = [] for module in args["text"].split()[2:]: module_list.append(module) fail = 0 failedMessage = "Unable to find : " if priv.checkPriv(args["source"], 'module_priv') != 0: # check if they all exist first for name in module_list: try: fp, pathname, description = imp.find_module(name) fp.close() except: fail = 1 failedMessage += name +" " if (fail == 1): return Event("privmsg", "", self.return_to_sender(args), [ failedMessage ]) else: return [Event("internal", "", "", [ "load" ] + module_list), Event("privmsg", "", self.return_to_sender(args), [ "loading " + " ".join(module_list)] )] else: return Event("privmsg", "", self.return_to_sender(args), [ "that requires module_priv." ])
def handler(self, **args): """Allows someone to alter material in a factoid by using a regular expression. Invoked like: "moobot: foo =~ s/moo/bar/".""" import priv, database, re, string from irclib import Event target = self.return_to_sender(args) # Grab the factoid to change: # first, drop the bot name factoid_key = string.join(args["text"].split()[1:]) # Now split on " =~ " and take the left half factoid_key = factoid_key.split(" =~ ", 1)[0] # Check if the factoid exists 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: message = "Factoid '" + factoid_key + "' does not exist." return Event("privmsg", "", target, [message]) # Now check and make sure we can modify this factoid # Locked? lock_query = "select locked_by from factoids where lower(factoid_key) = '"\ + factoid_key.lower() + "'" locked_by = database.doSQL(lock_query)[0][0] if locked_by != None and not priv.checkPriv(args["source"], "delete_priv"): message = "That factoid is locked." return Event("privmsg", "", target, [message]) # Check for the appropriate privilege (delete_priv, even # though we aren't deleting - we are modifying, and there # is no modify priv) if priv.checkPriv(args["source"], "delete_priv") == 0 and locked_by != None and locked_by != "" and locked_by != args["source"]: message = "You do not have permission to modify" return Event("privmsg", "", target, [message]) # get the original factoid value orig_factoid_query = "select factoid_value from factoids where" \ + " lower(factoid_key) = '" + factoid_key.lower() + "'" factoid = database.doSQL(orig_factoid_query)[0][0] # Grab the regex(es) to apply # First split on =~, then split on spaces for the RHS regexes_str = args["text"].split(" =~ ", 1)[1] # Now we can't split just on spaces, because the regex itself # can have spaces in it. We gotta grab each one individually # because a regex to get them all (potentially each having # unique separators, like "s/foo/bar blatz/g s:moo:mooooo!:i # s%this%makes it hard to parse%". # # The basic algorithm is: # 1 - find out the separator character (2nd char) # 2 - find the index of the third occurrence of this character # 3 - find the next space, chop off everything before it and # append it to the regex_list regex_list = [] # regex for removing leading spaces, compiling it first lead_spaces = re.compile("^\s+") while len(regexes_str) > 2: # Strip leading spaces first (so regexes with many spaces # between them don't mess things up when we assume the separator # is the second character) regexes_str = lead_spaces.sub("", regexes_str) # Separator = 2nd char separator = regexes_str[1] # Find it once, then use that as a low range # NOTE - if there is garbage at any point, ignore everything # after it second_sep = regexes_str.find(separator, 2) if second_sep == 0: break third_sep = regexes_str.find(separator, second_sep+1) if third_sep == 0: break # now the space space_index = regexes_str.find(" ", third_sep) if space_index == -1: # no space found regex_list.append(regexes_str) break else: regex_list.append(regexes_str[:space_index]) regexes_str = regexes_str[space_index:] # apply each of the regexes in order # For now we are assuming all of the regexes are search and replace # s/foo/bar/[gi] ACCEPTABLE_PREFIXES = "sy" ACCEPTABLE_SUFFIXES = "gi" for regex_string in regex_list: # Split the regex into parts - strictly, we split on the second # character, as s:foo:bar: is valid as well try: parts = regex_string.split(regex_string[1]) except IndexError: break # If we don't get four parts (even if the last is empty) # then it's not a valid regex - chastise them ... also, # if it's not one of the valid prefixes/suffixes, chastise them :) if len(parts) != 4 or \ parts[0] not in ACCEPTABLE_PREFIXES: message = "Invalid regular expression: " + regex_string return Event("privmsg", "", target, [message]) for letter in parts[3]: if letter not in ACCEPTABLE_SUFFIXES: message = "Invalid regular expression: " + regex_string return Event("privmsg", "", target, [message]) # Get some flags before we compile a regex if "g" in parts[3]: count = 0 else: count = 1 if "i" in parts[3]: case_sensitive = 0 else: case_sensitive = 1 # Make a regex object for the first pattern try: str = self.escape_slashes(parts[1]) if case_sensitive: regex = re.compile(str) else: regex = re.compile(str, re.I) except re.error: message = "Invalid regular expression: " + regex_string return Event("privmsg", "", target, [message]) # Actually perform the transformation if parts[0] == "s": factoid = regex.sub(parts[2], factoid) elif parts[0] == "y": message = "This regex not yet supported. Sorry :(" return Event("privmsg", "", target, [message]) # When all the regexes are applied, store the factoid again factoid = self.escape_slashes(factoid) insert_query = "update factoids set factoid_value = '" + factoid + "'" \ + " where lower(factoid_key) = '" + factoid_key.lower() + "'" database.doSQL(insert_query) return Event("privmsg", "", target, ["ok"])
def handler(self, **args): """Allows someone to add material onto a factoid (that isn't locked) by saying "foo is also bar", for example""" import priv, database from irclib import Event from time import time target = self.return_to_sender(args) # args["text"] should look something like: # "moobot: foo is also bar blatz qux" # Grab the factoid to change: factoid_key = self.strip_words(args["text"], 1).split(" is ")[0] # Grab the stuff to tack on: to_add = self.strip_words(args["text"], 1).split(" is also ")[1] # Check if the factoid exists, if it doesn't tell the user query = "select count(factoid_key) from factoids where" \ " lower(factoid_key) = '" + factoid_key.lower() + "'" if database.doSQL(query)[0][0] == 0: message = "Factoid '" + factoid_key + "' does not exist." return Event("privmsg", "", target, [message]) # Check if the factoid is locked or not lock_query = "select locked_by from factoids where lower(factoid_key) = '"\ + factoid_key.lower() + "'" locked_by = database.doSQL(lock_query)[0][0] if priv.checkPriv(args["source"], "delete_priv") == 0 and (locked_by != None and locked_by != "" and locked_by != args["source"]): message = "You do not have permission to delete this factoid." return Event("privmsg", "", target, [message]) if locked_by != None: message = "That factoid is locked." return Event("privmsg", "", target, [message]) # Since we don't have delete_priv, we just delete and recreate the factoid orig_factoid_query = "select factoid_value, requested_by," \ + " requested_time, requested_count, created_by, created_time"\ + " from factoids where" \ + " lower(factoid_key) = '" + factoid_key.lower() + "'" result = database.doSQL(orig_factoid_query) orig_factoid, orig_req_by, orig_req_time, orig_req_count, orig_cre_by, \ orig_cre_time = result[0] if orig_req_by == None: orig_req_by = "NULL" orig_req_time = "NULL" orig_req_count = 0 else: orig_req_by = "'" + orig_req_by + "'" orig_req_time = "'" + str(orig_req_time) + "'" new_factoid = self.escape_slashes(orig_factoid + ", or " + to_add) # Delete the factoid delete_query = "delete from factoids where lower(factoid_key) = '" \ + factoid_key.lower() + "'" database.doSQL(delete_query) # Re-create create_query = "insert into factoids(factoid_key, requested_by," \ + " requested_time, requested_count, created_by, created_time," \ + " modified_by, modified_time, factoid_value) values('" \ + factoid_key + "', " + orig_req_by + ", " + str(orig_req_time) \ + ", " + str(orig_req_count) + ", '" + orig_cre_by + "', " \ + str(orig_cre_time) + ", '" + args["source"] + "', " \ + str(int(time())) + ", '" + new_factoid + "')" database.doSQL(create_query) return Event("privmsg", "", target, ["ok"])
def handler(self, **args): from irclib import Event import priv argv = self.spaces.split((args["text"]).strip()) # case: ~ab if len(argv) < 3: cmd = None argv = [] argc = 0 # case ~ab ... else: cmd = argv[2].lower() argv = argv[3:] argc = len(argv) reply = None channel = self.return_to_sender(args) from irclib import nm_to_n yournick = nm_to_n(args['source']) try: from irclib import is_channel from ValueModifier import IntValueModifier if not is_channel(channel): reply = "this is a channel only command" elif cmd == "grant": if argc != 3: raise StopReply() import priv nick, ability, score = argv try: score = IntValueModifier(score) except ValueError: reply = "%s: score must be number" % yournick raise StopReply() curscore = self.getUserAbilityScore(nick, channel, ability) or 0 score = score.apply(curscore) # normal users? if priv.checkPriv(args["source"], "ab_admin_priv") == 0 \ and priv.checkPriv(args["source"], "all_priv") == 0: if nick == yournick: reply = "You're so proud, %s" % yournick raise StopReply() yourscore = self.getUserAbilityScore(yournick, channel, ability) # apply rules if not yourscore or yourscore < score: yourscore = self.getUserAbilityScore(yournick, channel, '*') if not yourscore or yourscore < score: reply = "You don't have enough ability score, %s" % yournick raise StopReply() if curscore >= score: reply = "%s's %s ability is %d already" % (nick, ability, curscore) raise StopReply() abilityid = self.getAbilityId(ability, True) self.setUserAbilityScore(nick, channel, abilityid, score, yournick) reply = "%s's %s ability is set to %d" % (nick, ability, score) elif cmd == "despise": if argc != 2: raise StopReply() ability, score = argv try: score = IntValueModifier(score) except ValueError: reply = "%s: score must be number" % yournick raise StopReply() curscore = self.getUserAbilityScore(yournick, channel, ability) if not curscore: reply = "%s: You have no %s ability despise for" % (ability, yournick) raise StopReply() score = score.apply(curscore) if curscore == score: reply = "%s: You're yourself" % yournick elif curscore <= score: reply = "%s: Are you conceited?" % yournick else: abilityid = self.getAbilityId(ability, True) self.setUserAbilityScore(yournick, channel, abilityid, score, yournick) reply = "%s has despise him/herself to %d on %s ability" % (yournick, score, ability) elif cmd == "top" or cmd == "help": if cmd == "help": if argc != 1: # module help raise StopReply() reply = "This function is in TODO" raise StopReply() from irclib import IrcStringIO if argc == 1: ability = argv[0] user_scores = self.getTopAbilityUsers(channel, ability) if not user_scores: reply = "no one is capable of %s" % ability raise StopReply() buffer = IrcStringIO("top user(s) that capable of %s:" % ability) for user_score in user_scores: buffer.write(" %s*%s" % user_score) elif argc == 0: abilityScoreUsers = self.getTopAbilities(channel) if not abilityScoreUsers: reply = "no one is superman" raise StopReply() from irclib import IrcStringIO buffer = IrcStringIO("top abilities:") for abilityScoreUser in abilityScoreUsers: buffer.write(" %s*%s/%s" % abilityScoreUser) reply = buffer.getvalue() else: nick = None ability = None name = None # name to guess if argc == 0: # quick query if cmd: name = cmd else: nick = yournick elif cmd != "query": raise StopReply() elif argc == 1: # "query $nick" name = argv[0] elif argc == 2: # "query $nick $ability" [nick, ability] = argv else: raise StopReply() # guess if it's nick or ability if name: abilityid = self.getAbilityId(name) if abilityid: ability = name nick = yournick else: nick = name ability = None if nick: if ability: score = self.getUserAbilityScore(nick, channel, ability) or 0 if yournick == nick: reply = "Your %s ability is %d" % (ability, score) if score < 0: reply = reply + ". rats!" else: reply = "%s's %s ability is %d" % (nick, ability, score) else: ability_scores = self.getUserAbilities(nick, channel) if not ability_scores: reply = nick + " doesn't have any ability, is he/she disabled?" else: from irclib import IrcStringIO buffer = IrcStringIO(nick + " is capable of") for ability_score in ability_scores: buffer.write(" %s*%s" % ability_score) reply = buffer.getvalue() else: reply = nick + " not found" except StopReply: pass if not reply: if cmd == "help" and argc == 0 or not self.helps.has_key(cmd): reply = "AbilityProfile: " + " ;; ".join(self.helps.values()) else: reply = "AbilityProfile: " + self.helps[cmd] result = Event("privmsg", "", channel, [reply]) return result
def handler(self, **args): """Allows someone to alter material in a factoid by using a regular expression. Invoked like: "moobot: foo =~ s/moo/bar/".""" import priv, re, time from irclib import Event target = self.return_to_sender(args) # Grab the factoid to change: # first, drop the bot name factoid_key = " ".join(args["text"].split()[1:]) # Now split on " =~ " and take the left half factoid_key = factoid_key.split(" =~ ", 1)[0] locked_by = FactoIds.getLockedBy(factoid_key) if locked_by == None: message = "Factoid '%s' does not exist." % factoid_key return Event("privmsg", "", target, [message]) # Check for the appropriate privilege (delete_priv, even # though we aren't deleting - we are modifying, and there # is no modify priv) if priv.checkPriv(args["source"], "delete_priv") == 0 and ( locked_by != "" and locked_by != args["source"]): message = "You do not have permission to modify factoid '%s." % factoid_key return Event("privmsg", "", target, [message]) # get the original factoid value factoid = FactoIds.getValueByKey(factoid_key) # Grab the regex(es) to apply # First split on =~, then split on spaces for the RHS regexes_str = args["text"].split(" =~ ", 1)[1] # Now we can't split just on spaces, because the regex itself # can have spaces in it. We gotta grab each one individually # because a regex to get them all (potentially each having # unique separators, like "s/foo/bar blatz/g s:moo:mooooo!:i # s%this%makes it hard to parse%". # # The basic algorithm is: # 1 - find out the separator character (2nd) # 2 - find the index of the third occurrence of this character # 3 - find the next space, chop off everything before it and # append it to the regex_list regex_list = [] # regex for removing leading spaces, compiling it first lead_spaces = re.compile("^\s+") while len(regexes_str) > 2: # Strip leading spaces first (so regexes with many spaces # between them don't mess things up when we assume the separator # is the second character) regexes_str = lead_spaces.sub("", regexes_str) # Separator = 2nd char separator = regexes_str[1] # Find it once, then use that as a low range # NOTE - if there is garbage at any point, ignore everything # after it second_sep = regexes_str.find(separator, 2) if second_sep == 0: break third_sep = regexes_str.find(separator, second_sep + 1) if third_sep == 0: break # now the space space_index = regexes_str.find(" ", third_sep) if space_index == -1: # no space found regex_list.append(regexes_str) break else: regex_list.append(regexes_str[:space_index]) regexes_str = regexes_str[space_index:] # apply each of the regexes in order # For now we are assuming all of the regexes are search and replace # s/foo/bar/[gi] ACCEPTABLE_PREFIXES = "sy" ACCEPTABLE_SUFFIXES = "gi" for regex_string in regex_list: # Split the regex into parts - strictly, we split on the second # character, as s:foo:bar: is valid as well try: parts = regex_string.split(regex_string[1]) except IndexError: break # If we don't get four parts (even if the last is empty) # then it's not a valid regex - chastise them ... also, # if it's not one of the valid prefixes/suffixes, chastise them :) if len(parts) != 4 or \ parts[0] not in ACCEPTABLE_PREFIXES: message = "Invalid regular expression: " + regex_string return Event("privmsg", "", target, [message]) for letter in parts[3]: if letter not in ACCEPTABLE_SUFFIXES: message = "Invalid regular expression: " + regex_string return Event("privmsg", "", target, [message]) # Get some flags before we compile a regex if "g" in parts[3]: count = 0 else: count = 1 if "i" in parts[3]: case_sensitive = 0 else: case_sensitive = 1 # Make a regex object for the first pattern try: re_str = parts[1] if case_sensitive: regex = re.compile(re_str) else: regex = re.compile(re_str, re.I) except re.error: message = "Invalid regular expression: " + regex_string return Event("privmsg", "", target, [message]) # Actually perform the transformation if parts[0] == "s": factoid = regex.sub(parts[2], factoid) elif parts[0] == "y": message = "This regex not yet supported. Sorry :(" return Event("privmsg", "", target, [message]) # When all the regexes are applied, store the factoid again # with the new date as the modification date. FactoIds.update(factoid_key, factoid, args["source"]) return Event("privmsg", "", target, ["ok"])
def handler(self, **args): from irclib import Event import priv argv = self.spaces.split((args["text"]).strip()) # case: ~ab if len(argv) < 3: cmd = None argv = [] argc = 0 # case ~ab ... else: cmd = argv[2].lower() argv = argv[3:] argc = len(argv) reply = None channel = self.return_to_sender(args) from irclib import nm_to_n yournick = nm_to_n(args['source']) try: from irclib import is_channel from ValueModifier import IntValueModifier if not is_channel(channel): reply = "this is a channel only command" elif cmd == "grant": if argc != 3: raise StopReply() import priv nick, ability, score = argv try: score = IntValueModifier(score) except ValueError: reply = "%s: score must be number" % yournick raise StopReply() curscore = self.getUserAbilityScore(nick, channel, ability) or 0 score = score.apply(curscore) # normal users? if priv.checkPriv(args["source"], "ab_admin_priv") == 0 \ and priv.checkPriv(args["source"], "all_priv") == 0: if nick == yournick: reply = "You're so proud, %s" % yournick raise StopReply() yourscore = self.getUserAbilityScore( yournick, channel, ability) # apply rules if not yourscore or yourscore < score: yourscore = self.getUserAbilityScore( yournick, channel, '*') if not yourscore or yourscore < score: reply = "You don't have enough ability score, %s" % yournick raise StopReply() if curscore >= score: reply = "%s's %s ability is %d already" % ( nick, ability, curscore) raise StopReply() abilityid = self.getAbilityId(ability, True) self.setUserAbilityScore(nick, channel, abilityid, score, yournick) reply = "%s's %s ability is set to %d" % (nick, ability, score) elif cmd == "despise": if argc != 2: raise StopReply() ability, score = argv try: score = IntValueModifier(score) except ValueError: reply = "%s: score must be number" % yournick raise StopReply() curscore = self.getUserAbilityScore(yournick, channel, ability) if not curscore: reply = "%s: You have no %s ability despise for" % ( ability, yournick) raise StopReply() score = score.apply(curscore) if curscore == score: reply = "%s: You're yourself" % yournick elif curscore <= score: reply = "%s: Are you conceited?" % yournick else: abilityid = self.getAbilityId(ability, True) self.setUserAbilityScore(yournick, channel, abilityid, score, yournick) reply = "%s has despise him/herself to %d on %s ability" % ( yournick, score, ability) elif cmd == "top" or cmd == "help": if cmd == "help": if argc != 1: # module help raise StopReply() reply = "This function is in TODO" raise StopReply() from irclib import IrcStringIO if argc == 1: ability = argv[0] user_scores = self.getTopAbilityUsers(channel, ability) if not user_scores: reply = "no one is capable of %s" % ability raise StopReply() buffer = IrcStringIO("top user(s) that capable of %s:" % ability) for user_score in user_scores: buffer.write(" %s*%s" % user_score) elif argc == 0: abilityScoreUsers = self.getTopAbilities(channel) if not abilityScoreUsers: reply = "no one is superman" raise StopReply() from irclib import IrcStringIO buffer = IrcStringIO("top abilities:") for abilityScoreUser in abilityScoreUsers: buffer.write(" %s*%s/%s" % abilityScoreUser) reply = buffer.getvalue() else: nick = None ability = None name = None # name to guess if argc == 0: # quick query if cmd: name = cmd else: nick = yournick elif cmd != "query": raise StopReply() elif argc == 1: # "query $nick" name = argv[0] elif argc == 2: # "query $nick $ability" [nick, ability] = argv else: raise StopReply() # guess if it's nick or ability if name: abilityid = self.getAbilityId(name) if abilityid: ability = name nick = yournick else: nick = name ability = None if nick: if ability: score = self.getUserAbilityScore( nick, channel, ability) or 0 if yournick == nick: reply = "Your %s ability is %d" % (ability, score) if score < 0: reply = reply + ". rats!" else: reply = "%s's %s ability is %d" % (nick, ability, score) else: ability_scores = self.getUserAbilities(nick, channel) if not ability_scores: reply = nick + " doesn't have any ability, is he/she disabled?" else: from irclib import IrcStringIO buffer = IrcStringIO(nick + " is capable of") for ability_score in ability_scores: buffer.write(" %s*%s" % ability_score) reply = buffer.getvalue() else: reply = nick + " not found" except StopReply: pass if not reply: if cmd == "help" and argc == 0 or not self.helps.has_key(cmd): reply = "AbilityProfile: " + " ;; ".join(self.helps.values()) else: reply = "AbilityProfile: " + self.helps[cmd] result = Event("privmsg", "", channel, [reply]) return result
class RssQuery(MooBotModule): inqueries = {} def __init__(self): names = None # RssRecord.getNames() if names: names = "|" + "|".join(names) else: names = "" self.regex = "^((rss|rssflush|rssadd|rssdel) .+|rss%s)" % (names) import re self.pdescstrip = re.compile("(<[^>]+>|\r|\n)") def handler(self, **args): from irclib import Event import priv msg = "Huh?" dummy, cmd = args["text"].split(" ", 1) if cmd.find(" ") != -1: cmd, text = cmd.split(" ", 1) else: text = None cmd = cmd.lower() if cmd == 'rss' or cmd != 'rssadd' and cmd != 'rssdel' and cmd != 'rssflush': # add back if cmd != 'rss': text = cmd + " " + text if text: if text.find(' ') != -1: text, cmd = text.split(" ", 1) try: int(cmd) cmd = int(cmd) except: pass else: cmd = "no" rss = RssRecord(text) if not rss.exists: msg = "%s not exists" % text elif cmd == "url": msg = "%s: url is %s" % (text, rss.getUrl()) else: name = rss.getName() # TODO. no lock implemented yet error = None if self.inqueries.has_key(name): cmd = "busy" else: self.inqueries[name] = True try: datas = rss.getDatas() except Exception, e: error = e del self.inqueries[name] if error: msg = str(error) elif cmd == "busy": msg = "%s is already in query, please standby" % name elif cmd == "no": msg = text + ": " i = 0 for i in range(len(datas)): title, nil, nil = datas[i] msg += " /%d/ %s" % (i + 1, title) if len(msg) > 400: break msg = msg[0:400] elif cmd == 0: msg = "%s: count=%d" % (text, len(datas)) elif cmd: # TODO. Send this kinda long result to requester. id = cmd - 1 if id < 0 or id > len(datas): msg = "out of ubound" else: title, link, desc = datas[id] msg = "%s: %s // %s // %s" % \ (text, link, title, desc) else: names = RssRecord.getNames() or "oops, None" msg = 'RssQuery: "rss $key [ |$num|url]" or "rssadd $key $url" or "rssdel $key" or "rssflush". Note: CacheTtl=1 hour. $key can be one of: ' l = len(msg) for name in names: if l + len(name) + 1 > 400: msg += "\r\n" l -= 500 l += len(name) + 1 msg += " " + name elif priv.checkPriv(args["source"], cmd) == 0 and priv.checkPriv(args["source"], "rss") == 0: msg = "Sorry, you don't have permission to do that."