def handler(self, **args): encoding = args['encoding'].replace('-', '') if not self.translations.has_key(encoding): return Event("continue", "", "") (skipmatch, regex, fromencoding) = self.translations[encoding] rawmsg = args['event'].rawdata() if len(rawmsg) > 100: return Event("continue", "", "") if not regex.search(rawmsg): return Event("continue", "", "") if skipmatch: # skip if it match try: msg = rawmsg.decode(encoding) # well, no translation return Event("continue", "", "") except: pass try: msg = rawmsg.decode(fromencoding) except Exception, e: self.Debug(e) return Event("continue", "", "")
def handler(self, **args): target_back = self.return_to_sender(args) target_nick = self.return_to_sender(args, 'nick') args = args["text"].split()[2:] args_l = len(args) if args_l != 1 and args_l != 2: return Event( "privmsg", "", target_back, ["syntax: quake <roomid> [invite-nick], roomid in (0...5)"]) try: roomid = int(args[0]) except: return Event("privmsg", "", target_back, ["invalid roomid"]) if roomid < 1 or roomid >= 6: return Event("privmsg", "", target_back, ["roomid %d not in (0....5) " % roomid]) text = "DCC CHAT chat %d %d" % (ip, firstport + roomid - 1) if args_l == 2: return Event("ctcp", "", args[1], [text]) elif args_l == 1: return Event("ctcp", "", target_nick, [text])
def handler(self, **args): """ gets kernel status """ # self.debug("kernelStatus") connect=httplib.HTTPConnection("www.kernel.org", 80) connect.request('GET', '/kdist/finger_banner') response = connect.getresponse() if response.status != 200: msg = '%d: %s' % (response.status, response.reason) self.debug(msg) return Event("privmsg", "", target, [msg]) text = response.read() # Extract just the version numbers, instead of flooding # the channel with everything. result = "" for line in text.split("\n"): if len(line.split(":")) > 1: line = line.split(" ", 2)[2] version = '%s ;; ' % line.split(":")[1].strip() line = line.split("of", 2)[0] line = line.split("for", 2)[0] line = line.split("to", 2)[0] result += '%s: %s' % (line.strip(), version) target = self.return_to_sender(args) return Event("privmsg", "", target, [ result ])
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): """ 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): """ 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): """adds a factoid link""" from irclib import Event target = self.return_to_sender(args) # Strip the bots name text = self.strip_words(args["text"], 1) linkfrom, dummy, linktype, linkto = self.rMatch.match(text).groups() linkfrom = linkfrom.strip() linktype = linktype.strip() linkto = linkto.strip() weight = 100 if linktype.find("*") != -1: linktype, weight = linktype.split("*", 1) try: weight = int(weight) if weight < 0: weight = 0 elif weight > 1000: weight = 1000 except ValueError: weight = 100 # Check and make sure the factoid isn't there for factoid_key in [linkfrom, linktype, linkto]: if not FactoIds.exists(factoid_key): message = "Factoid \"%s\" must be defined first." % factoid_key return Event("privmsg", "", target, [message]) FactoIds.link(linkfrom, linkto, linktype, weight, args["source"]) FactoIds.link(linkto, linkfrom, linktype, weight, args["source"]) return Event("privmsg", "", target, ["ok"])
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): """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): """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): 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): 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): """Looks for haiku in each line of text. If found, mentions the haiku to the channel.""" from irclib import Event result = check_for_haiku(args["text"]) if (result != ""): from irclib import nm_to_n return [ Event("privmsg", "", self.return_to_sender(args), [ result + " -- a haiku by " + nm_to_n(args["source"]) ]), Event("continue", "", "", [ ])] return Event("continue", "", "", [])
def handler(self, **args): """Return information about a factoid to the person requesting it""" import time from irclib import Event target = self.return_to_sender(args) # Grab the factoid_key name requested factoid_key = self.strip_words(args["text"], 2) factinfo = FactoIds.getFactoInfoByKey(factoid_key) if not factinfo: return Event("continue", "", target, [""]) # Convert timestamps to ASCII time strings # Makes "1030123142124L" into a long int # That gets converted into a special time tuple # That gets converted to a nice ASCII string try: requested_time_str = time.asctime( time.localtime(factinfo["requested_time"])) except: requested_time_str = "never" try: created_time_str = time.asctime( time.localtime(factinfo["created_time"])) except: created_time_str = "never" try: modified_time_str = time.asctime( time.localtime(factinfo["modified_time"])) except: modified_time_str = "never" #if locked_time == None: # locked_time_str = "Not locked." #else: # locked_time_str = time.asctime(time.localtime(locked_time)) reply = factoid_key + ": created by " + self.str( factinfo["created_by"]) + " on " + created_time_str if (factinfo["modified_by"] is not None): reply += ". Last modified by " + self.str( factinfo["modified_by"]) + " on " + modified_time_str reply += ". Last requested by " + self.str(factinfo["requested_by"]) + " on " + requested_time_str + \ ", requested a total of " + str(factinfo["requested_count"]) + " times." if (factinfo["locked_by"] is not None and factinfo["locked_time"] != None): reply += " Locked by " + self.str( factinfo["locked_by"]) + " on " + time.ctime( factinfo["locked_time"]) + "." return Event("privmsg", "", target, [reply])
def handler(self, **args): self.return_to_sender(args) keyword = " ".join(args["text"].split(" ")[3:]) target = self.return_to_sender(args) try: response = self.search(keyword) except: msg = "error" return Event("privmsg", "", target, [ msg ]) return Event("privmsg", "", target, [ response ])
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): text = " ".join(args["text"].split(" ", 2)[1:]) if text == 'languages': return self.helpLanguages(args) # get parameter match = self.re.match(text) text = match.group(5) if text is None: return self.help(args) type = match.group(1) if type: type = type.lower() if match.group(2) is not None: fromLang, toLang = (match.group(2).lower(), match.group(3).lower()) elif match.group(4): fromLang, toLang = self.shortcuts[match.group(4)].lower().split("_", 2) # language if fromLang in self.languageToLangs: fromLang = self.languageToLangs[fromLang] if toLang in self.languageToLangs: toLang = self.languageToLangs[toLang] fromLanguage = self.langToLanguages[fromLang] toLanguage = self.langToLanguages[toLang] # redirect stupid query if text.find(' ') == -1 and self.reWord.search(text): return Event("privmsg", "", self.return_to_sender(args), [ "use: dict " + text + " or ~~" + text]) # which translator(s)? translators = None for translator in self.translators: if translator.command == type: translators = (translator, ) if not translators: translators = self.translators # dispatch it for translator in translators: result = translator.translate(text, translator.mapLanguage(fromLang), translator.mapLanguage(toLang), fromLanguage, toLanguage) if result: return Event("privmsg", "", self.return_to_sender(args), [ "%s translation: %s" % (translator.name.capitalize(), result) ]) # check if we know the languages they want to use return Event("privmsg", "", self.return_to_sender(args), [ "translating from %s to %s is not supported" % (fromLanguage, toLanguage) ])
def handler(self, **args): """ it's just dirty """ from irclib import Event self.problem = args["text"].split(None, 2)[2] if self.r.match(self.problem): text = "Problem %s is at http://acm.zju.edu.cn/show_problem.php?pid=%s\n" % ( self.problem, self.problem) import urllib2 self.feed( urllib2.urlopen( "http://acm.zju.edu.cn/user_status.php?user=intx").read()) if self.problem in self.DoneList: text += "Oops, The problem %s was already done." % ( self.problem, ) else: text += "Hey, problem %s wasn't done. Let's hack it~" % ( self.problem, ) else: text = "%s is not a valid PROBLEM ID, see http://acm.zju.edu.cn/ for details" % ( self.problem, ) text += " TOTAL RESOLVED: %d" % (len(self.DoneList)) target = self.return_to_sender(args) result = Event("privmsg", "", target, [text]) return result
def handler(self, **args): """weather query from http://weather.com.cn/ .""" result = None target = self.return_to_sender(args) city_name = args["text"].split()[2] import subprocess """ query city4weather.txt for city id""" p = subprocess.Popen("""grep %s /path/to/city4weather.txt | awk '{print $2}' """ %\ city_name , shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) city_id = '101020500' for city_id in p.stdout.readlines(): if city_id[-1] == '\n': city_id = city_id[0:-1] weather_info = "" p = subprocess.Popen('curl http://m.weather.com.cn/data/%s.html' % city_id, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): weather_info = line import json s=json.loads(weather_info) ss = s["weatherinfo"]["city"] +',' + s["weatherinfo"]["date_y"] +',' + s["weatherinfo"]["week"] +',' + s["weatherinfo"]["temp1"] +',' + s["weatherinfo"]["weather1"] +',' + s["weatherinfo"]["wind1"] +',' +s["weatherinfo"]["index_d"] result = ss.encode("UTF-8") from irclib import Event return Event("privmsg", "", target, [result])
def handler(self, **args): from irclib import Event nick = args["text"].split(" ")[2] realnick = who(nick) return Event("privmsg", "", self.return_to_sender(args), [nick + " is " + realnick])
class lunarCal(MooBotModule): """黄历查询 by [email protected] Action: http://www.shpan.com/huangli/MyDetail.asp?currentDate= Method: GET Params: yyyy-mm-dd """ URL = "http://www.shpan.com/huangli/MyDetail.asp?currentDate=" def __init__(self): self.regex = "^hl( +[^ ]*)?" def parse_date(self, strDate): from datetime import date if strDate.isdigit(): d = date(int(strDate[0:-4]), int(strDate[-4:-2]), int(strDate[-2:])) else: tupDate = re.findall('(\d+)-(\d+)-(\d+)', strDate) if len(tupDate) == 1: d = date(int(tupDate[0][0]), int(tupDate[0][1]), int(tupDate[0][2])) else: raise ValueError, "输入格式不正确。"; return d.isoformat() def fetch(self, date): #print date response = urllib.urlopen(lunarCal.URL+date) html = response.read().decode("GBK") response.close() return html def extract(self, text): date = re.compile("中华人民共和国\d{4}年\d+月\d+日黄历".decode("GBK")) hl = re.search(date, text) if hl: msg = ["\002" + hl.group(0) + "\002. "] date = re.compile('<tr>[^<]*<td[^>]*class="TdShow"\s*>([^<]*)</td>\s*<td[^>]*class="TdShow"\s*>([^<]*)</td>\s*</tr>') for item in re.findall(date, text): msg.append("\002" + item[0].strip() + "\002 " + item[1].strip()) return msg else: raise ValueError, "查询结果无效。"; def handler(self, **args): qstr = args["text"].strip().split(" ")[1:] try: if len(qstr) == 1: from datetime import date theDate = date.today().isoformat() elif len(qstr) == 2: theDate = self.parse_date(qstr[1]) else: raise ValueError, "输入格式不正确。"; msg = ["\n".join(self.extract(self.fetch(theDate)))] except ValueError, e: desc = str(e).decode("GBK") msg = [desc] #for m in msg: print m return Event("notice", "", self.return_to_sender(args, select="nick"), msg)
def handler(self, **args): target = self.return_to_sender(args) quoteurl = "http://bash.org/?random1" try: html = urllib2.urlopen(quoteurl).read() except urllib2.URLError: return "error connecting to bash.org" # Grab a one-line quote unless they specify multiline if args["text"].find("multiline") == -1: quote_text=re.search('<p class="qt">(.*?)</p>',html) else: quote_text=re.search('<p class="qt">(.*?)</p>',html,re.DOTALL) try: quote=quote_text.group(1) except AttributeError: return "No quote found" # This replaces various bits of html chars. If someone wants to replace # it with HTMLParser stuff, feel free quote=re.sub('<','<',quote) quote=re.sub('>','>',quote) quote=re.sub(' ',' ',quote) quote=re.sub('"','"',quote) quote=re.sub('<br />','',quote) return Event("privmsg", "", target, [quote])
def test_channel_join(self): event = Event('privnotice', 'dougsmom', 'yourmom', ['*** You are connected using SSL cipher Woooooo']) self.bot._dispatcher(self.cxn, event) action, (channel, ), kw = self.cxn.method_calls.pop() assert action == 'join' assert channel == '#testing'
def handler(self, **args): """Grabs a fortune and spits it out""" import os from irclib import Event fortune_txt = os.popen("fortune -s").read() return Event("privmsg", "", self.return_to_sender(args), [fortune_txt])
class nslookup(MooBotModule): def __init__(self): self.regex="^(?:d?nslookup|dns) .+" def handler(self, **args): """Does domain name lookups or reverse lookups on IPs""" import socket, re query = args["text"].split()[2] if isValidateIp(query): result = socket.getfqdn(query) if result == query: result = "FQDN not found" else: try: result = "" for addressInfo in socket.getaddrinfo(query, 0, 0, 0, socket.SOL_TCP): result = result + " " + addressInfo[4][0] result = result.strip() except Exception, e: result = "Host lookup error: " + str(e) target = self.return_to_sender(args) # target = args["channel"] # if args["type"] == "privmsg": # from irclib import nm_to_n # target = nm_to_n(args["source"]) from irclib import Event result = Event("privmsg", "", target, [ query + ": " + result ]) 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): """Grabs an excuse from the bofh fortune file and spits it out""" import os from irclib import Event fortune_txt = os.popen("fortune bofh-excuses|tail --lines=+2").read() return Event("privmsg", "", self.return_to_sender(args), [fortune_txt])
def handler(self, **args): txts = self.getRawArgs(args) cmd = txts[0] txts = txts[1:] if cmd == "encode" or cmd == "decode": if len(txts) < 2: return self.usage(args) encodings = txts[0] msg = ' '.join(txts[1:]) elif cmd == "codec": if len(txts) < 2: return self.usage(args) encodings = txts[0] msg = ' '.join(txts[1:]) cmd = "encode" else: if len(txts) < 1: return self.usage(args) msg = ' '.join(txts) encodings = cmd if encodings.lower().startswith("un"): encodings = encodings[2:] cmd = "decode" elif encodings.startswith('-'): encodings = encodings[1:] cmd = "decode" else: if encodings.startswith('+'): encodings = encodings[1:] cmd = "encode" return Event("privmsg", "", self.return_to_sender(args), [ self.doEncodeDecode(cmd, encodings, msg) ])