def action(self, complete): msg=complete.message() amsg=msg if isAllowed(complete.userMask())<getLevel(complete.cmd()[0]): return ["PRIVMSG $C$ :No."] if msg=="*": #settingsHandler.deleteSetting("coreIgnorance","1","1") settingsHandler.dropTable("coreIgnorance") settingsHandler.newTable("coreIgnorance","ignorance","nickname") return ["PRIVMSG $C$ :Unignored everything, my lord"] if msg in globalv.miscVars[0]: msg=globalv.miscVars[0][msg] try: if amsg in [x[0] for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")]: settingsHandler.deleteSetting("coreIgnorance","ignorance",amsg) return ["PRIVMSG $C$ :"+amsg + " successfully unignored, cap'n!"] msg=".*@"+msg.split('@')[1] if msg.find('@')>0 else msg if msg in [x[0] for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")]: settingsHandler.deleteSetting("coreIgnorance","ignorance",msg) return ["PRIVMSG $C$ :"+amsg + " successfully unignored, cap'n!"] else: matches=difflib.get_close_matches(msg,[x[0] for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")],3,0.4) matches=["None"] if matches==[] else matches globalv.variables['ignored']=matches[0] return ["PRIVMSG $C$ :"+msg+" is not ignored, commander! Near matches: "+', '.join(matches)+". ~ignored~ set to nearest match."] except Exception as detail: return ["PRIVMSG $C$ :"+msg+" not unignored: "+str(detail)] return ["PRIVMSG $C$ :"+amsg + " successfully unignored, cap'n!"]
def action(self, complete): msg = complete.message() returner = "" elevated = getLevel(complete.userMask()) >= isAllowed( complete.cmd()[0]) if msg == "": returner = "This is the %s dictionary. Run !%s -list for a list of known values!" % ( complete.cmd()[0], complete.cmd()[0]) elif msg.split()[0] == "-add" and elevated: settingsHandler.writeSetting( complete.cmd()[0], ["key", "value"], [msg.split()[1], ' '.join(msg.split()[2:])]) returner = "Key:Value pair added!" elif msg.split()[0] == "-delete" and elevated: settingsHandler.deleteSetting(complete.cmd()[0], "key", msg.split()[1]) returner = "Key removed!" elif msg.split()[0] == "-list": keypairs = [ x[0] for x in settingsHandler.readSettingRaw( complete.cmd()[0], "key") ] returner = ', '.join(keypairs) elif msg.split()[0] == "-random": keypairs = settingsHandler.readSettingRaw(complete.cmd()[0], "key, value") pairs = {} for keypair in keypairs: pairs[keypair[0].lower()] = keypair[1] import random keys = pairs.keys() random.shuffle(keys) returner = keys[0] + ": " + pairs[keys[0]] else: keypairs = settingsHandler.readSettingRaw(complete.cmd()[0], "key, value") pairs = {} for keypair in keypairs: pairs[keypair[0].lower()] = keypair[1] if unicode(msg.split()[0]).lower() in pairs.keys(): returner = pairs[unicode(msg.split()[0]).lower()] elif "default" not in pairs.keys(): returner = "No definition." matches = difflib.get_close_matches(msg.split()[0], pairs.keys(), 10, 0.1) if len(matches) > 0: returner += " Perhaps you meant: " + ', '.join( matches[:-1]) if len(matches) > 1: returner += " or " + matches[-1] else: returner += " No similar definitions" else: returner = pairs['default'] if returner == "": return [""] return ["PRIVMSG $C$ :" + returner]
def action(self, complete): msg = complete.message() if isAllowed(complete.userMask()) >= getLevel(complete.cmd()[0]): trigger = msg.split()[0] command = ' '.join(msg.split()[1:]) try: if trigger not in [ x[0] for x in settingsHandler.readSettingRaw( "'core-expansions'", "trigger") ]: settingsHandler.writeSetting("'core-expansions'", ["trigger", "command"], [trigger, command]) else: settingsHandler.updateSetting("'core-expansions'", "command", command, where="trigger='%s'" % trigger) msg = "%s will now substitute to the output of %s" % (trigger, command) except Exception as detail: msg = "Failure: %s" % detail else: msg = "Sorry, you need to be elevated to use this command!" return ["PRIVMSG $C$ :" + msg]
def action(self, complete): user = complete.user() if complete.type() != "JOIN": return [""] returns = [] messages = settingsHandler.readSettingRaw("greetd", "channel,greet") if complete.channel().lower() in [ message[0].lower() for message in messages ]: greetPlugin = settingsHandler.readSetting("greetd", "greet", where="channel='%s'" % complete.channel()) senderMask = complete.userMask() arguments = pluginArguments( str(':' + senderMask + " PRIVMSG " + complete.channel() + " :!" + greetPlugin + " " + complete.user())) arguments = formatInput(arguments) print[arguments.complete()] arguments.argument = str(arguments.argument) message = globalv.loadedPlugins[greetPlugin].action(arguments) print message message = formatOutput(message, arguments) returns += message return returns
def action(self, complete): msg = complete.message() nick = complete.userMask() amsg = msg nickname = "*Unknown*" if securityHandler.isAllowed(nick) >= getLevel(complete.cmd()[0]): if msg[0] == "#": nmsg = msg nickname = "" elif msg in globalv.miscVars[0]: nmsg = ".*@" + globalv.miscVars[0][msg].split('@')[1] nickname = msg else: nmsg = msg nmsg = nmsg.replace('*', '.*').replace('..*', '.*') fullCMD = nmsg if fullCMD not in [ x[0] for x in settingsHandler.readSettingRaw( "coreIgnorance", "ignorance") ]: settingsHandler.writeSetting("coreIgnorance", ["ignorance", "nickname"], [fullCMD, nickname]) return [ "PRIVMSG $C$ :" + amsg + " successfully ignored, cap'n!" ] else: return [ "PRIVMSG $C$ :" + amsg + " is already ignored, m'lord!" ] else: return ["PRIVMSG $C$ :Go away."]
def readAllActions(user): return settingsHandler.readSettingRaw( "laterd", "id,sender,senderMask,timestamp,message,channel,anonymous", where= "('%s' GLOB recipient OR recipient GLOB '*|%s|*' OR recipient GLOB '%s|*' OR recipient GLOB '*|%s') AND sent='0'" % (user.lower(), user.lower(), user.lower(), user.lower()))
def action(self, complete): msg = complete.message() sender = complete.userMask() if len(msg.split()) > 1: mode = msg.split()[1].lower() else: mode = "on" msg = msg.split()[0] print sender print globalv.basePlugin if msg == "list": return [ "PRIVMSG $C$ :" + ', '.join([ x[0] for x in settingsHandler.readSettingRaw( "coreAutoLoad", "loadAs") ]) ] if isAllowed(sender) >= getLevel(complete.cmd()[0]): if mode == "on": settingsHandler.writeSetting("coreAutoLoad", ["plugin", "loadAs"], [globalv.basePlugin[msg], msg]) return ["PRIVMSG $C$ :Plugin set to autoload"] else: settingsHandler.deleteSetting("coreAutoLoad", "loadAs", msg) return ["PRIVMSG $C$ :Plugin no longer autoloading"] return ["PRIVMSG $C$ :You do not have the required access rights!"]
def action(self, complete): msg = complete.message() amsg = msg if isAllowed(complete.userMask()) < getLevel(complete.cmd()[0]): return ["PRIVMSG $C$ :No."] if msg == "*": #settingsHandler.deleteSetting("coreIgnorance","1","1") settingsHandler.dropTable("coreIgnorance") settingsHandler.newTable("coreIgnorance", "ignorance", "nickname") return ["PRIVMSG $C$ :Unignored everything, my lord"] if msg in globalv.miscVars[0]: msg = globalv.miscVars[0][msg] try: if amsg in [ x[0] for x in settingsHandler.readSettingRaw( "coreIgnorance", "ignorance") ]: settingsHandler.deleteSetting("coreIgnorance", "ignorance", amsg) return [ "PRIVMSG $C$ :" + amsg + " successfully unignored, cap'n!" ] msg = ".*@" + msg.split('@')[1] if msg.find('@') > 0 else msg if msg in [ x[0] for x in settingsHandler.readSettingRaw( "coreIgnorance", "ignorance") ]: settingsHandler.deleteSetting("coreIgnorance", "ignorance", msg) return [ "PRIVMSG $C$ :" + amsg + " successfully unignored, cap'n!" ] else: matches = difflib.get_close_matches(msg, [ x[0] for x in settingsHandler.readSettingRaw( "coreIgnorance", "ignorance") ], 3, 0.4) matches = ["None"] if matches == [] else matches globalv.variables['ignored'] = matches[0] return [ "PRIVMSG $C$ :" + msg + " is not ignored, commander! Near matches: " + ', '.join(matches) + ". ~ignored~ set to nearest match." ] except Exception as detail: return ["PRIVMSG $C$ :" + msg + " not unignored: " + str(detail)] return ["PRIVMSG $C$ :" + amsg + " successfully unignored, cap'n!"]
def expandExpansions(toExpand, complete=None): def runPluginReturnOutput(matchObj): command=expanDict[matchObj.group(1)] if matchObj.group(2) is not None: arguments=matchObj.group(2)[1:-1] else: arguments="" appendOnto=True for index, content in enumerate(arguments.split()): if "$%s$"%index in command: command=command.replace("$%s$"%index, content) appendOnto=False if "$*$" in command: command=command.replace("$*$",arguments) appendOnto=False if appendOnto: command="%s %s"%(command, arguments) inputString=":%s PRIVMSG %s :%s"%(toExpand.userMask(), toExpand.channel(), "!%s"%command) input=formatInput(pluginArguments(inputString)) pluginOutput=' | '.join(globalv.loadedPlugins[command.split()[0]].action(input)) output=' :'.join(pluginOutput.split(' :')[1:]) return output if type(toExpand) in [str,unicode]: isObj=False else: isObj=True if settingsHandler.tableExists("'core-expansions'")==False: settingsHandler.newTable("'core-expansions'","trigger","command") allCommands=[[x.replace('(','\(').replace(')', '\)'),x] for x in globalv.loadedPlugins.keys()] expansions=settingsHandler.readSettingRaw("'core-expansions'","trigger,command") + allCommands expanDict={} for trigger, command in expansions: expanDict[trigger]=command if isObj: string=toExpand.fullMessage() #if string.find("$%s$"%trigger)!=-1: if re.findall("(\$%s(\(.*?\))?\$)"%trigger, string)!=[]: string=re.sub("\$(%s)(\(.*?\))?\$"%trigger,runPluginReturnOutput,string) ret=toExpand.complete()[1:].split(' :',1) ret[1]=string toExpand.setComplete(':'+' :'.join(ret)) else: if complete==None: usermask="dummy!dummy@dummy" channel="#dummy" else: usermask=complete.userMask() channel=complete.channel() #if toExpand.find("$%s$"%trigger)!=-1: if re.findall("(\$%s(\(.*?\))?\$)"%trigger, toExpand)!=[]: toExpand=re.sub("\$(%s)(\(.*?\))?\$"%trigger,runPluginReturnOutput,toExpand) for variable in globalv.variables.keys(): if toExpand.fullMessage().find(variable)!=-1: string=re.sub("~%s~"%variable,str(globalv.variables[variable]),string) ret=toExpand.complete()[1:].split(' :',1) ret[1]=string toExpand.setComplete(':'+' :'.join(ret)) return toExpand
def action(self, complete): msg=complete.message() returner="" elevated = getLevel(complete.userMask()) >= isAllowed(complete.cmd()[0]) if msg=="": returner="This is the %s dictionary. Run !%s -list for a list of known values!"%(complete.cmd()[0], complete.cmd()[0]) elif msg.split()[0]=="-add" and elevated: settingsHandler.writeSetting(complete.cmd()[0],["key","value"], [msg.split()[1],' '.join(msg.split()[2:])]) returner="Key:Value pair added!" elif msg.split()[0]=="-delete" and elevated: settingsHandler.deleteSetting(complete.cmd()[0],"key",msg.split()[1]) returner="Key removed!" elif msg.split()[0]=="-list": keypairs=[x[0] for x in settingsHandler.readSettingRaw(complete.cmd()[0],"key")] returner=', '.join(keypairs) elif msg.split()[0]=="-random": keypairs=settingsHandler.readSettingRaw(complete.cmd()[0],"key, value") pairs={} for keypair in keypairs: pairs[keypair[0].lower()]=keypair[1] import random keys=pairs.keys() random.shuffle(keys) returner=keys[0]+": "+pairs[keys[0]] else: keypairs=settingsHandler.readSettingRaw(complete.cmd()[0],"key, value") pairs={} for keypair in keypairs: pairs[keypair[0].lower()]=keypair[1] if unicode(msg.split()[0]).lower() in pairs.keys(): returner=pairs[unicode(msg.split()[0]).lower()] elif "default" not in pairs.keys(): returner="No definition." matches=difflib.get_close_matches(msg.split()[0],pairs.keys(),10,0.1) if len(matches)>0: returner+=" Perhaps you meant: "+', '.join(matches[:-1]) if len(matches)>1: returner+=" or "+matches[-1] else: returner+=" No similar definitions" else: returner=pairs['default'] if returner=="": return [""] return ["PRIVMSG $C$ :"+returner]
def action(self, complete): msg=complete.message() command=msg.split()[0] if command=="list": names=settingsHandler.readSettingRaw("laterd","recipient, sender, timestamp", where="sent='0' AND anonymous='0'") returns=[] for name in names: try: recipient=name[0] sender=name[1] timestamp=name[2] ctime=time.strftime("%H:%M on %d-%m-%Y",time.gmtime(int(timestamp))) message=recipient+" has a message from "+sender+" (Sent on "+ctime+")" returns.append(message) except: pass if returns==[]: returns.append("No messages.") return ["PRIVMSG $C$ :"+', '.join(returns)] elif command=="remove": try: senderString=" and sender=='%s'"%complete.user() if isAllowed(complete.userMask())>=150: senderString="" where = "recipient=%s and sent='0'" % repr(msg.split()[1].lower()) where += senderString print where settingsHandler.updateSetting("laterd","sent", "'2'", where=where) return ["PRIVMSG $C$ :Later successfully removed!"] except Exception as detail: return ["PRIVMSG $C$ :Later not removed"] else: anonymous = "0" secret_pfx = "secret::" if msg.startswith(secret_pfx): anonymous = "1" msg = msg[len(secret_pfx):] channels=[] while msg.split()[0][0]=="#": channels.append(msg.split()[0]) msg=' '.join(msg.split()[1:]) channel='|'.join(channels) recipients=list(set(msg.split()[0].lower().split(','))) recipients = [re.sub('[^0-9a-z-[\]*?]', '?', x) for x in recipients] sender=complete.user() senderMask=complete.userMask() timestamp=str(int(time.time())) message=' '.join(msg.split()[1:]) message = message.replace('$U$','$recipient$') for recipient in recipients: print recipient id=str(int(settingsHandler.readSetting("laterd", "COUNT(id)"))+1) settingsHandler.writeSetting("laterd",["id", "recipient","sender","senderMask","timestamp","message", "channel", "anonymous", "sent"],[id, recipient, sender, senderMask, timestamp, message, channel, anonymous, "0"]) settingsHandler.db.commit() return ["PRIVMSG $C$ :Ok, I'll tell "+', '.join(recipients[:-1])+(" and "+recipients[-1] if len(recipients)>1 else recipients[-1])+" that when they next speak!"] return ["PRIVMSG $C$ :"+msg]
def action(self, complete): msg = complete.message() list = settingsHandler.readSettingRaw("coreIgnorance", "ignorance,nickname") print[ x[0] for x in settingsHandler.readSettingRaw( "coreIgnorance", "ignorance") ] laters = [] print list for line in list: laters.append(line[0] + ( (" (" + line[1] + ")") if line[1] != "*Unknown*" else "")) if len(list) == 0: laters = ["PRIVMSG $C$ :No users ignored, cap'n!"] else: laters = "PRIVMSG $C$ :" + ', '.join(laters) return laters
def action(self, complete): user=complete.user() if complete.type()!="PRIVMSG": return [""] returns=[] messages=settingsHandler.readSettingRaw("laterd","id",where="('"+user.lower()+"' GLOB recipient OR recipient GLOB '*|"+user.lower()+"|*') AND sent='0'") if messages!=[]: for message in messages: wipeMessage=True messageID=str(message[0]) try: sender=getSender(messageID) senderMask=getSenderMask(messageID) timestamp=getTimestamp(messageID) messageText=getMessage(messageID) plugin=messageText.split()[0] if not correctChannel(messageID, complete.channel()): continue if plugin in globalv.loadedPlugins.keys(): arguments=pluginArguments(':'+senderMask+" PRIVMSG "+complete.channel()+" :!"+messageText.replace('$recipient$', user).replace('$*$', complete.fullMessage())) arguments=formatInput(arguments) message=globalv.loadedPlugins[plugin].action(arguments) if message in [[],[""]]: wipeMessage=False #returns+=[m.decode('utf-8') for m in message] returns+=message if message!=[""] and message!=[]: msg=message[0] if msg.split()[0]=="PRIVMSG" or msg.split()[0]=="NOTICE": location=msg.split()[1] else: location="$C$" if not getAnonymous(messageID): returns.append("PRIVMSG "+location+" :From "+sender+" to "+user+" "+GetTimeUntilDatetime(timestamp)) if wipeMessage: setMessageSent(messageID) else: returns.append("PRIVMSG $C$ :"+messageText) if not getAnonymous(messageID): returns.append("PRIVMSG $C$ :From "+sender+" to "+user+" "+GetTimeUntilDatetime(timestamp)) setMessageSent(messageID) if len(returns) >= 13: break except Exception as detail: print "There was an error in one of the later messages:",detail setMessageSent(messageID) return returns
def formatInput(arguments, aliases=globalv.aliasExtensions, preprocess=True): if settingsHandler.tableExists("'core-doNotExpand'")==False: settingsHandler.newTable("'core-doNotExpand'","doNotExpand") doNotExpand=[str(x[0]) for x in settingsHandler.readSettingRaw("'core-doNotExpand'","doNotExpand")] if aliases[arguments.cmd()[0]]!="": toAdd=aliases[arguments.cmd()[0]][1:] result=re.findall("\$([0-9][0-9]?[\+-]?)\$",toAdd) suchAThingExists=re.search('\$..?.?\$',toAdd) if result!=[]: for value in result: if value.find('+')==-1 and value.find('-')==-1: if (len(arguments.cmd()))>int(value): toAdd=toAdd.replace("$"+value+"$",arguments.cmd()[int(value)]) else: if int(value)!=1: toAdd=toAdd.replace("$"+value+"$"," ") else: toAdd=toAdd.replace("$"+value+"$",arguments.user()) elif value.find('+')!=-1: value=value[:-1] if (len(arguments.cmd()))>(int(value)-1): toAdd=toAdd.replace("$"+value+"+$",' '.join(arguments.cmd()[int(value):])) else: toAdd=toAdd.replace("$"+value+"+$"," ") elif value.find('-')!=-1: value=value[:-1] if (len(arguments.cmd()))>int(value): toAdd=toAdd.replace("$"+value+"-$",' '.join(arguments.cmd()[1:][:int(value)])) else: toAdd=toAdd.replace("$"+value+"-$"," ") if toAdd.find('$*$')!=-1: toAdd=toAdd.replace('$*$',' '.join(arguments.cmd()[1:])) if toAdd.find('$URL$')!=-1: toAdd=toAdd.replace('$URL$',' '.join(arguments.cmd()[1:]).replace(' ','%20')) if suchAThingExists!=None: msg=globalv.commandCharacter+arguments.cmd()[0]+" "+toAdd else: msg=arguments.complete()[1:].split(' :',1)[1]+aliases[arguments.cmd()[0]] ret=arguments.complete()[1:].split(' :',1) ret[1]=msg arguments.setComplete(':'+' :'.join(ret)) if arguments.cmd()[0] not in doNotExpand and preprocess: arguments=expand(arguments) return arguments
def action(self, complete): user=complete.user() if complete.type()!="JOIN": return [""] returns=[] messages=settingsHandler.readSettingRaw("greetd","channel,greet") if complete.channel().lower() in [message[0].lower() for message in messages]: greetPlugin=settingsHandler.readSetting("greetd","greet",where="channel='%s'"%complete.channel()) senderMask=complete.userMask() arguments=pluginArguments(str(':'+senderMask+" PRIVMSG "+complete.channel()+" :!"+greetPlugin+" "+complete.user())) arguments=formatInput(arguments) print [arguments.complete()] arguments.argument = str(arguments.argument) message=globalv.loadedPlugins[greetPlugin].action(arguments) print message message = formatOutput(message, arguments) returns+=message return returns
def action(self, complete): msg=complete.message() if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]): trigger=msg.split()[0] command=' '.join(msg.split()[1:]) try: if trigger not in [x[0] for x in settingsHandler.readSettingRaw("'core-expansions'","trigger")]: settingsHandler.writeSetting("'core-expansions'",["trigger","command"],[trigger,command]) else: settingsHandler.updateSetting("'core-expansions'","command",command,where="trigger='%s'"%trigger) msg="%s will now substitute to the output of %s"%(trigger, command) except Exception as detail: msg="Failure: %s"%detail else: msg="Sorry, you need to be elevated to use this command!" return ["PRIVMSG $C$ :"+msg]
def isBanned(complete): toIgnore = [ str(x[0]) for x in settingsHandler.readSettingRaw("coreIgnorance", "ignorance") ] hostmasks = [mask for mask in toIgnore if mask.find("@") != -1] try: channels = [ channel.lower() for channel in toIgnore if channel[0] == "#" ] except IndexError: print "Alert - ignorance failure, one of your ignrance entries is 0-length!" if isAllowed(complete.userMask()) >= 20: return 0 else: return 1 nick = complete.user() if "@whitelist" in toIgnore: if isAllowed(complete.userMask()) < 10: print complete.complete() print isAllowed(complete.userMask()) print "Ignored" return 1 if isAllowed(complete.userMask()) >= 100: return 0 if nick in globalv.miscVars[0]: for line in hostmasks: try: if re.match("^" + line.rstrip() + "$", globalv.miscVars[0][nick], re.I) != None: return 1 except Exception as detail: print "There is an invalid entry in your ignorance list" with open("crashLog.txt", "a") as file: file.write("\nSecurity Handler Failure: " + str(detail)) if complete.channel().lower() in channels: if isAllowed(complete.userMask()) >= 10: return 0 else: return 1 return 0
def action(self, complete): msg=complete.message() sender=complete.userMask() if len(msg.split())>1: mode=msg.split()[1].lower() else: mode="on" msg=msg.split()[0] print sender print globalv.basePlugin if msg=="list": return ["PRIVMSG $C$ :"+', '.join([x[0] for x in settingsHandler.readSettingRaw("coreAutoLoad", "loadAs")])] if isAllowed(sender)>=getLevel(complete.cmd()[0]): if mode=="on": settingsHandler.writeSetting("coreAutoLoad", ["plugin", "loadAs"], [globalv.basePlugin[msg], msg]) return ["PRIVMSG $C$ :Plugin set to autoload"] else: settingsHandler.deleteSetting("coreAutoLoad", "loadAs", msg) return ["PRIVMSG $C$ :Plugin no longer autoloading"] return ["PRIVMSG $C$ :You do not have the required access rights!"]
def action(self, complete): message = str(complete.fullMessage()) triggertexts=settingsHandler.readSettingRaw("words","trigger, text") triggertexts.reverse() text={} for trigger, texts in triggertexts: matchObj = re.search(trigger, message, re.I) if matchObj is not None: for i in xrange(0, 99): if texts.find("$%s$"%i): try: texts = texts.replace("$%s$"%i, matchObj.group(i)) except IndexError: pass print texts return run_command(texts, complete) if complete.fullMessage().lower() in text.keys(): return ["PRIVMSG $C$ :"+text[complete.fullMessage().lower()]] return [""]
def expand(complete): string=complete.fullMessage() while getArguments(string)!=[]: positions=getArguments(string) positions.sort(key=lambda list: list[0]) positions.reverse() topDepth=positions[0][0] positions=filter(lambda position:position[0]==topDepth, positions) for position in positions: command=string[position[1]:position[2]][1:-1] #Extract the command/arguments and then cut off the $ delimiters. if '(' in command: command=command.split('(',1) command[-1]=command[-1][:-1] command=' '.join(command) string=list(string) for i in range(position[1], position[2]): del string[position[1]] expansions=dict(settingsHandler.readSettingRaw("'core-expansions'","trigger,command")) if command.split()[0] in globalv.loadedPlugins.keys() or command.split()[0] in expansions.keys(): if command.split()[0] in expansions.keys(): command=expansions[command.split()[0]] inputString=":%s PRIVMSG %s :%s"%(complete.userMask(), complete.channel(), "!%s"%command) input=formatInput(pluginArguments(inputString)) pluginOutput=globalv.loadedPlugins[command.split()[0]].action(input) pluginOutput = [entry for entry in pluginOutput if entry!=""] pluginOutput=map(lambda output:output.split(' :',1)[1], pluginOutput) commandResult=' | '.join(pluginOutput) else: commandResult=command string.insert(position[1], str(commandResult)) string=''.join(string) complete.setMessage(string) string=complete.fullMessage() for variable in globalv.variables.keys(): if complete.fullMessage().find(variable)!=-1: string=re.sub("~%s~"%variable,str(globalv.variables[variable]),string) ret=complete.complete()[1:].split(' :',1) ret[1]=string complete.setComplete(':'+' :'.join(ret)) return complete
def action(self, complete): msg=complete.message() nick=complete.userMask() amsg=msg nickname="*Unknown*" if securityHandler.isAllowed(nick)>=getLevel(complete.cmd()[0]): if msg[0]=="#": nmsg = msg nickname="" elif msg in globalv.miscVars[0]: nmsg=".*@"+globalv.miscVars[0][msg].split('@')[1] nickname=msg else: nmsg=msg nmsg=nmsg.replace('*','.*').replace('..*','.*') fullCMD=nmsg if fullCMD not in [x[0] for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")]: settingsHandler.writeSetting("coreIgnorance",["ignorance","nickname"],[fullCMD,nickname]) return ["PRIVMSG $C$ :"+amsg+ " successfully ignored, cap'n!"] else: return ["PRIVMSG $C$ :"+amsg+" is already ignored, m'lord!"] else: return ["PRIVMSG $C$ :Go away."]
def action(self, complete): triggertexts=[x[0].lower() for x in settingsHandler.readSettingRaw("noMeme","meme")] returns="" for text in triggertexts: if re.findall(text,complete.fullMessage().lower())!=[]: if complete.user() not in self.strikes.keys(): self.strikes[complete.user()]=1 else: self.strikes[complete.user()]+=1 if self.strikes[complete.user()]==1: returns="PRIVMSG $C$ :That word/phrase is banned, $U$. This is your first warning (%s)"%re.findall(text,complete.fullMessage().lower())[-1] elif self.strikes[complete.user()]==2: returns="PRIVMSG $C$ :$U$, this is your last warning. No saying that. (%s)"%re.findall(text,complete.fullMessage().lower())[-1] elif self.strikes[complete.user()]>=3: self.strikes[complete.user()]==0 returns="KICK $C$ $U$ :Out. Now." if complete.user() not in self.banStrikes.keys(): self.banStrikes[complete.user()]=1 else: self.banStrikes[complete.user()]+=1 if self.banStrikes[complete.user()]>=3: returns=["MODE $C$ +b "+globalv.miscVars[0][complete.user()],returns,"MODE $C$ -b "+globalv.miscVars[0][complete.user()]] return returns
def action(self, complete): triggertexts = [ x[0].lower() for x in settingsHandler.readSettingRaw("noMeme", "meme") ] returns = "" for text in triggertexts: if re.findall(text, complete.fullMessage().lower()) != []: if complete.user() not in self.strikes.keys(): self.strikes[complete.user()] = 1 else: self.strikes[complete.user()] += 1 if self.strikes[complete.user()] == 1: returns = "PRIVMSG $C$ :That word/phrase is banned, $U$. This is your first warning (%s)" % re.findall( text, complete.fullMessage().lower())[-1] elif self.strikes[complete.user()] == 2: returns = "PRIVMSG $C$ :$U$, this is your last warning. No saying that. (%s)" % re.findall( text, complete.fullMessage().lower())[-1] elif self.strikes[complete.user()] >= 3: self.strikes[complete.user()] == 0 returns = "KICK $C$ $U$ :Out. Now." if complete.user() not in self.banStrikes.keys(): self.banStrikes[complete.user()] = 1 else: self.banStrikes[complete.user()] += 1 if self.banStrikes[complete.user()] >= 3: returns = [ "MODE $C$ +b " + globalv.miscVars[0][complete.user()], returns, "MODE $C$ -b " + globalv.miscVars[0][complete.user()] ] return returns
def isBanned(complete): toIgnore=[str(x[0]) for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")] hostmasks=[mask for mask in toIgnore if mask.find("@")!=-1] try: channels=[channel.lower() for channel in toIgnore if channel[0]=="#"] except IndexError: print "Alert - ignorance failure, one of your ignrance entries is 0-length!" if isAllowed(complete.userMask())>=20: return 0 else: return 1 nick=complete.user() if "@whitelist" in toIgnore: if isAllowed(complete.userMask())<10: print complete.complete() print isAllowed(complete.userMask()) print "Ignored" return 1 if isAllowed(complete.userMask())>=100: return 0 if nick in globalv.miscVars[0]: for line in hostmasks: try: if re.match("^"+line.rstrip()+"$", globalv.miscVars[0][nick],re.I)!=None: return 1 except Exception as detail: print "There is an invalid entry in your ignorance list" with open("crashLog.txt","a") as file: file.write("\nSecurity Handler Failure: "+str(detail)) if complete.channel().lower() in channels: if isAllowed(complete.userMask())>=10: return 0 else: return 1 return 0
def getArguments(string, depth=0, startIndex=0): def reset(): argumentStart = -1 lowerDepths = [] argumentEnd = -1 argumentDepth = 0 hasArguments = False start = -1 end = -1 #print "Starting parse on string: %s"%string positions = [] #In format (depth, start, length) lowerDepths = [] beginCharacter = '$' breakCharacters = [' '] argumentCharacter = ['(', ')'] argumentStart = -1 argumentEnd = -1 argumentDepth = 0 hasArguments = False commandName = "" start = -1 end = -1 for index, letter in enumerate(string): if letter == beginCharacter: if start == -1: start = index elif not hasArguments or (hasArguments and string[index - 1] == argumentCharacter[-1] and argumentDepth == 0): end = index capturedString = string[start + 1:end] print capturedString if capturedString.isdigit() or capturedString == "*": argumentStart = -1 lowerDepths = [] argumentEnd = -1 argumentDepth = 0 hasArguments = False start = -1 end = -1 print "Reset, continuing" continue if hasArguments: lowerDepths = getArguments( string[argumentStart + 1:argumentEnd], depth + 1, startIndex + argumentStart + 1) else: commandName = string[start + 1:end] print "commandName is", commandName expansions = dict( settingsHandler.readSettingRaw("'core-expansions'", "trigger,command")) if commandName in (globalv.loadedPlugins.keys() + expansions.keys()): positions += lowerDepths + [ (depth, startIndex + start, startIndex + end + 1) ] argumentStart = -1 lowerDepths = [] argumentEnd = -1 argumentDepth = 0 hasArguments = False start = -1 end = -1 continue if (start == -1): continue if letter == argumentCharacter[0] and not hasArguments: hasArguments = True commandName = string[start + 1:index] argumentStart = index argumentDepth += 1 elif letter == argumentCharacter[0]: argumentDepth += 1 elif letter == argumentCharacter[-1]: argumentDepth -= 1 if argumentDepth == 0: argumentEnd = index elif letter in breakCharacters and not hasArguments: argumentStart = -1 lowerDepths = [] argumentEnd = -1 argumentDepth = 0 hasArguments = False start = -1 end = -1 return positions
returns=["PRIVMSG $C$ :(Command name auto-corrected from %s to %s [Other possibilities were: %s])"%(arguments.cmd()[0], nearestMatch[0], ', '.join(nearMatches[1:]))] else: returns=["PRIVMSG $C$ :(Command name auto-corrected from %s to %s)"%(arguments.cmd()[0], nearestMatch[0])] send(formatOutput(returns, arguments)) if __name__=="__main__": #Load plugins and aliases. print "Loading plugins..." for plugin, loadAs in globalv.pluginList: load_plugin(plugin, loadAs) print "Loading aliases..." for line in settingsHandler.readSettingRaw("alias","aliasName, aliasPlugin, aliasArguments"): print line load_alias(line[0], ' '.join(line[1:])) print "Loading input sources..." if settingsHandler.tableExists("'core-input'"): for input in []: #settingsHandler.readSettingRaw("'core-input'","input, definition"): if input[0] not in globalv.loadedInputs.keys(): x=__import__(str(input[1].split()[0])) reload(x) arguments=str(' '.join(input[1].split()[1:])) arguments=arguments.split() globalv.loadedInputs[input[0]]=globalv.input.addInputSource(x.asyncInput,tuple(arguments)) else: globalv.loadedInputs[input[0]].put(str(input[1])) else: settingsHandler.newTable("'core-input'","input", "definition")
def __init__(self): self.users=settingsHandler.readSettingRaw("autoidentifyd","nickname") self.users=[x[0] for x in self.users] self.giveup={}
def getArguments(string, depth=0, startIndex=0): def reset(): argumentStart=-1 lowerDepths=[] argumentEnd=-1 argumentDepth=0 hasArguments=False start=-1 end=-1 #print "Starting parse on string: %s"%string positions=[] #In format (depth, start, length) lowerDepths=[] beginCharacter='$' breakCharacters=[' '] argumentCharacter=['(',')'] argumentStart=-1 argumentEnd=-1 argumentDepth=0 hasArguments=False commandName="" start=-1 end=-1 for index,letter in enumerate(string): if letter==beginCharacter: if start==-1: start=index elif not hasArguments or (hasArguments and string[index-1]==argumentCharacter[-1] and argumentDepth==0): end=index capturedString=string[start+1:end] print capturedString if capturedString.isdigit() or capturedString=="*": argumentStart=-1 lowerDepths=[] argumentEnd=-1 argumentDepth=0 hasArguments=False start=-1 end=-1 print "Reset, continuing" continue if hasArguments: lowerDepths=getArguments(string[argumentStart+1:argumentEnd], depth+1,startIndex+argumentStart+1) else: commandName=string[start+1:end] print "commandName is",commandName expansions=dict(settingsHandler.readSettingRaw("'core-expansions'","trigger,command")) if commandName in (globalv.loadedPlugins.keys() + expansions.keys()): positions+=lowerDepths+[(depth, startIndex+start, startIndex+end+1)] argumentStart=-1 lowerDepths=[] argumentEnd=-1 argumentDepth=0 hasArguments=False start=-1 end=-1 continue if (start==-1): continue if letter==argumentCharacter[0] and not hasArguments: hasArguments=True commandName=string[start+1:index] argumentStart=index argumentDepth+=1 elif letter==argumentCharacter[0]: argumentDepth+=1 elif letter==argumentCharacter[-1]: argumentDepth-=1 if argumentDepth==0: argumentEnd=index elif letter in breakCharacters and not hasArguments: argumentStart=-1 lowerDepths=[] argumentEnd=-1 argumentDepth=0 hasArguments=False start=-1 end=-1 return positions
def __init__(self): subs = settingsHandler.readSettingRaw("stripMCBotNames", "minecraft, irc") self.substitutions = {} for sub in subs: self.substitutions[str(sub[0].lower())] = str(sub[1])
class pluginClass(plugin): def gettype(self): return "realtime" def __init__(self): self.lastURLs = [] def __init_db_tables__(self, name): settingsHandler.newTable("tumblrdIgnores", "ignore") settingsHandler.newTable("tumblrd", "username", "password") def action(self, completeargs): def makeRequest(reqData, async=True): success = False failed = 0 if async else 14 while not success: try: con = urllib2.urlopen(req, None, 10) success = True except: failed += 1 print "Tumblrd failed", failed, "times." if failed > 15: success = True time.sleep(30) if not settingsHandler.tableExists("tumblrdIgnores"): settingsHandler.newTable("tumblrdIgnores", "ignore") complete = completeargs.complete()[1:].split(' :', 1) imageFileTypes = [".jpg", ".png", ".bmp"] username = settingsHandler.readSetting("tumblrd", "username") password = settingsHandler.readSetting("tumblrd", "password") ignores = [ x[0].lower() for x in settingsHandler.readSettingRaw("tumblrdIgnores", "ignore") ] if completeargs.channel().lower() in ignores or completeargs.user( ).lower() in ignores: return [""] if len(complete[0].split()) > 2: if complete[0].split()[1] == "PRIVMSG": msg = complete[1] sender = complete[0].split(' ') sender = sender[2] if msg.find('http://') != -1 or msg.find('https://') != -1: url = re.search(".*(?P<url>https?://.+?)[\".,?!]?\s", msg + " ").group("url") if url in self.lastURLs: return [""] else: self.lastURLs.append(url) if len(self.lastURLs) > 10: self.lastURLs.pop(0) logindata = { 'email': username, "password": password, "tags": ','.join((completeargs.channel(), completeargs.user())) } if url[-4:].lower() in imageFileTypes: uploaddata = {"type": "photo", "source": url} elif url.lower().find("youtube.com/watch") != -1: request = urllib2.urlopen(url) page = request.read(10000).replace('\n', '') print page title = re.findall("<\s*title\s*>(.*?)</title\s*>", page, re.I) print title title = title[0] uploaddata = { "type": "video", "embed": url, "caption": title } else: uploaddata = {"type": "link", "url": url} logindata.update(uploaddata) print logindata uploadData = urllib.urlencode(logindata) req = urllib2.Request("http://www.tumblr.com/api/write", uploadData) print "Constructing thread..." thread = threading.Thread(target=makeRequest, args=(req, )) print "Launching thread..." try: thread.start() print "Thread launched..." except: print "Thread failed to launch - using synchronous fallback" makeRequest(req, False) print "Sucessfully submitted data" return [""]
returns=["PRIVMSG $C$ :(Command name auto-corrected from %s to %s [Other possibilities were: %s])"%(arguments.cmd()[0], nearestMatch[0], ', '.join(nearMatches[1:]))] else: returns=["PRIVMSG $C$ :(Command name auto-corrected from %s to %s)"%(arguments.cmd()[0], nearestMatch[0])] send(formatOutput(returns, arguments)) if __name__=="__main__": #Load plugins and aliases. print "Loading plugins..." for plugin, loadAs in globalv.pluginList: load_plugin(plugin, loadAs) print "Loading aliases..." for line in settingsHandler.readSettingRaw("alias","aliasName, aliasPlugin, aliasArguments"): load_alias(line[0], ' '.join(line[1:])) print "Loading input sources..." if settingsHandler.tableExists("'core-input'"): for input in settingsHandler.readSettingRaw("'core-input'","input, definition"): if input[0] not in globalv.loadedInputs.keys(): x=__import__(str(input[1].split()[0])) reload(x) arguments=str(' '.join(input[1].split()[1:])) arguments=arguments.split() globalv.loadedInputs[input[0]]=globalv.input.addInputSource(x.asyncInput,tuple(arguments)) else: globalv.loadedInputs[input[0]].put(str(input[1])) else: settingsHandler.newTable("'core-input'","input", "definition") for input in globalv.loadedInputs.keys():
def action(self, complete): msg = complete.message() command = msg.split()[0] if command == "list": names = settingsHandler.readSettingRaw( "laterd", "recipient, sender, timestamp", where="sent='0' AND anonymous='0'") returns = [] for name in names: try: recipient = name[0] sender = name[1] timestamp = name[2] ctime = time.strftime("%H:%M on %d-%m-%Y", time.gmtime(int(timestamp))) message = recipient + " has a message from " + sender + " (Sent on " + ctime + ")" returns.append(message) except: pass if returns == []: returns.append("No messages.") return ["PRIVMSG $C$ :" + ', '.join(returns)] elif command == "remove": try: senderString = " and sender=='%s'" % complete.user() if isAllowed(complete.userMask()) >= 150: senderString = "" where = "recipient=%s and sent='0'" % repr( msg.split()[1].lower()) where += senderString print where settingsHandler.updateSetting("laterd", "sent", "'2'", where=where) return ["PRIVMSG $C$ :Later successfully removed!"] except Exception as detail: return ["PRIVMSG $C$ :Later not removed"] else: anonymous = "0" secret_pfx = "secret::" if msg.startswith(secret_pfx): anonymous = "1" msg = msg[len(secret_pfx):] channels = [] while msg.split()[0][0] == "#": channels.append(msg.split()[0]) msg = ' '.join(msg.split()[1:]) channel = '|'.join(channels) recipients = list(set(msg.split()[0].lower().split(','))) recipients = [ re.sub('[^0-9a-z-[\]*?]', '?', x) for x in recipients ] sender = complete.user() senderMask = complete.userMask() timestamp = str(int(time.time())) message = ' '.join(msg.split()[1:]) message = message.replace('$U$', '$recipient$') for recipient in recipients: print recipient id = str( int(settingsHandler.readSetting("laterd", "COUNT(id)")) + 1) settingsHandler.writeSetting("laterd", [ "id", "recipient", "sender", "senderMask", "timestamp", "message", "channel", "anonymous", "sent" ], [ id, recipient, sender, senderMask, timestamp, message, channel, anonymous, "0" ]) settingsHandler.db.commit() return [ "PRIVMSG $C$ :Ok, I'll tell " + ', '.join(recipients[:-1]) + (" and " + recipients[-1] if len(recipients) > 1 else recipients[-1]) + " that when they next speak!" ] return ["PRIVMSG $C$ :" + msg]
def action(self, complete): user=complete.user() if complete.type()!="PRIVMSG": return [""] returns=[] messages=settingsHandler.readSettingRaw("laterd","id,sender,senderMask,timestamp,message,channel,anonymous",where="('%s' GLOB recipient OR recipient GLOB '*|%s|*' OR recipient GLOB '%s|*' OR recipient GLOB '*|%s') AND sent='0'" % (user.lower(), user.lower(), user.lower(), user.lower())) if messages!=[]: dispatches=[] for message in messages: wipeMessage=True messageID=str(message[0]) sender=message[1] senderMask=message[2] timestamp=datetime.datetime.fromtimestamp(int(message[3])) messageText=message[4] messageChannel=message[5] anonymous=message[6]=="1" if not correctChannel(messageChannel, complete.channel()): continue try: plugin=messageText.split()[0] messageTextNew = messageText messageTextNew = messageTextNew.replace('$recipient$', user) messageTextNew = messageTextNew.replace('$*$', complete.fullMessage().decode('utf-8')) if plugin=="dispatch": senderName="" if not anonymous: senderName=sender dispatches.append("%s: [%s] <%s>: %s" % (user, GetTimeUntilDatetime(timestamp), senderName, ' '.join(messageTextNew.split(' ')[1:]))) setMessageSent(messageID) continue if plugin not in globalv.loadedPlugins.keys(): plugin = 'say' messageTextNew = 'say ' + messageTextNew arguments=pluginArguments(':'+senderMask+" PRIVMSG "+complete.channel()+" :!"+messageTextNew) arguments=formatInput(arguments) try: message=globalv.loadedPlugins[plugin].action(arguments) except: message=["PRIVMSG $C$ :%s" % messageText] if message in [[],[""]]: wipeMessage=False #returns+=[m.decode('utf-8') for m in message] returns+=message if message!=[""] and message!=[]: msg=message[0] if msg.split()[0]=="PRIVMSG" or msg.split()[0]=="NOTICE": location=msg.split()[1] else: location="$C$" if not anonymous: returns.append("PRIVMSG "+location+" :From "+sender+" to "+user+" "+GetTimeUntilDatetime(timestamp)) if wipeMessage: setMessageSent(messageID) if len(returns) >= 13: break except Exception as detail: print "There was an error in one of the later messages:",detail traceback.print_tb(sys.exc_info()[2]) setMessageSent(messageID) target="$C$" if len(dispatches) > 1: target=user returns.append("PRIVMSG $C$ :%s: Messages incoming" % user) returns += ["PRIVMSG %s :%s" % (target, dispatch) for dispatch in dispatches] return returns
def action(self, complete): msg=complete.message() list=settingsHandler.readSettingRaw("coreIgnorance","ignorance,nickname") print [x[0] for x in settingsHandler.readSettingRaw("coreIgnorance","ignorance")]
def action(self, arguments): ignores = [x[0].lower() for x in settingsHandler.readSettingRaw("logd", "ignore")] if arguments.channel().lower() in ignores or arguments.user().lower() in ignores: print "Channel or User Ignored" return [""] complete = arguments.complete()[1:].split(" :", 1) if len(complete) > 1: msg = complete[1] else: msg = "" if len(complete[0].split()) < 2: print "Message Not Long Enough, exiting" return [""] try: sender = complete[0].split(" ") channel = arguments.channel() userMask = arguments.userMask() user = arguments.user() msgType = sender[1] ttime = time.gmtime() message = "" if not os.path.exists("logs"): os.makedirs("logs") if os.path.exists(os.path.join("logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7]))): file = open( os.path.join("logs", "LogFile - " + channel.lower() + "-" + str(ttime[0]) + "-" + str(ttime[7])), "a", ) else: file = open( os.path.join("logs", "LogFile - " + channel.lower() + "-" + str(ttime[0]) + "-" + str(ttime[7])), "w", ) if msgType == "PRIVMSG": if msg.split()[0] == "ACTION": msg = " ".join(msg.split()[1:])[:-1] else: msg = "* " + msg message = "[%(time)s] * %(user)s %(umessage)s" % { "time": time.strftime("%d %b %y %H:%M"), "user": user, "umessage": msg, } if msgType == "JOIN": message = "[%(time)s] > %(user)s has joined" % { "time": time.strftime("%d %b %y %H:%M"), "user": userMask, } if msgType == "PART": message = "[%(time)s] < %(user)s has left" % {"time": time.strftime("%d %b %y %H:%M"), "user": userMask} if msgType == "KICK": message = "[%(time)s] < %(user)s kicked %(kicked)s: %(reason)s" % { "time": time.strftime("%d %b %y %H:%M"), "user": user, "kicked": complete[0].split()[3], "reason": complete[1], } if msgType == "MODE": message = "[%(time)s] = %(user)s set mode %(mode)s on %(person)s" % { "time": time.strftime("%d %b %y %H:%M"), "user": user, "mode": complete[0].split()[3], "person": ", ".join(complete[0].split()[4:]), } if msgType == "TOPIC": message = "[%(time)s] = %(user)s changed the topic to: %(topic)s" % { "time": time.strftime("%d %b %y %H:%M"), "user": user, "topic": complete[1], } if message != "": file.write(message + "\n") file.flush() file.close() if msgType == "QUIT": for channel in set(globalv.channels): if channel in globalv.channelUsers.keys(): if not user in globalv.channelUsers[channel]: continue if os.path.exists( os.path.join("logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])) ): file = open( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7]) ), "a", ) else: file = open( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7]) ), "w", ) message = "[%(time)s] < %(user)s has quit: %(reason)s" % { "time": time.strftime("%d %b %y %H:%M"), "user": userMask, "reason": msg, } file.write(message + "\n") file.close() if msgType == "NICK": for channel in set(globalv.channels): if not user in globalv.channelUsers[channel]: continue if os.path.exists( os.path.join("logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])) ): file = open( os.path.join("logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])), "a", ) else: file = open( os.path.join("logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])), "w", ) user = complete[0].split()[0].split("!")[0] newNick = complete[1] message = "[%(time)s] = %(user)s is now known as %(newnick)s" % { "time": time.strftime("%d %b %y %H:%M"), "user": user, "newnick": newNick, } file.write(message + "\n") file.close() except Exception as detail: print "Log failure: %s" % detail return [""]
timeUsers={} channelUsers={} loadedInputs={} input=inputSystem() outputQueue=[] basePlugin={} communication={} from pickle import load with open(os.path.join("config","variables")) as file: variables=load(file) del load #It's nice to keep these steady nickname="" commandCharacter="!" miscVars=[] masks={} nicks=dict([(nick, mask) for nick, mask in readSettingRaw("'core-nickmasks'","nick,hostmask")]) miscVars.append(nicks) miscVars.append(nickname) #Stores the bot's current nickname [1] miscVars.append([]) #OMGbot Identified Users [2] miscVars.append({}) #Later variables[3] miscVars.append({}) #Topics [4] channels=readSetting("coreAutoJoin","channel") if type(channels[0])==tuple: channels=[x[0] for x in channels] elif type(channels[0])==unicode: channels=[channels] pluginList=[] for line in readSettingRaw("coreAutoLoad", "plugin, loadAs"): pluginList.append(line)
def __init__(self): self.users = settingsHandler.readSettingRaw("autoidentifyd", "nickname") self.users = [x[0] for x in self.users] self.giveup = {}
def action(self, arguments): ignores = [ x[0].lower() for x in settingsHandler.readSettingRaw("logd", "ignore") ] if arguments.channel().lower() in ignores or arguments.user().lower( ) in ignores: print "Channel or User Ignored" return [""] complete = arguments.complete()[1:].split(' :', 1) if len(complete) > 1: msg = complete[1] else: msg = "" if len(complete[0].split()) < 2: print "Message Not Long Enough, exiting" return [""] try: sender = complete[0].split(' ') channel = arguments.channel() userMask = arguments.userMask() user = arguments.user() msgType = sender[1] ttime = time.gmtime() message = "" if not os.path.exists("logs"): os.makedirs("logs") if os.path.exists( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7]))): file = open( os.path.join( "logs", "LogFile - " + channel.lower() + "-" + str(ttime[0]) + "-" + str(ttime[7])), "a") else: file = open( os.path.join( "logs", "LogFile - " + channel.lower() + "-" + str(ttime[0]) + "-" + str(ttime[7])), "w") if msgType == "PRIVMSG": if msg.split()[0] == "ACTION": msg = ' '.join(msg.split()[1:])[:-1] message = "[%(time)d] * %(user)s %(umessage)s" % { "time": time.time(), "user": user, "umessage": msg } else: message = "[%(time)d] <%(user)s> %(umessage)s" % { "time": time.time(), "user": user, "umessage": msg } if msgType == "JOIN": message = "[%(time)d] -->| %(user)s has joined" % { "time": time.time(), "user": userMask } if msgType == "PART": message = "[%(time)d] <--| %(user)s has left" % { "time": time.time(), "user": userMask } if msgType == "KICK": message = "[%(time)d] =-= %(user)s kicked %(kicked)s: %(reason)s" % { "time": time.time(), "user": user, "kicked": complete[0].split()[3], "reason": complete[1] } if msgType == "MODE": message = "[%(time)d] =-= %(user)s set mode %(mode)s on %(person)s" % { "time": time.time(), "user": user, "mode": complete[0].split()[3], "person": ', '.join(complete[0].split()[4:]) } if msgType == "TOPIC": message = "[%(time)d] =-= %(user)s changed the topic to: %(topic)s" % { "time": time.time(), "user": user, "topic": complete[1] } if message != "": file.write(message + "\n") file.flush() file.close() if msgType == "QUIT": for channel in set(globalv.channels): if channel in globalv.channelUsers.keys(): if not user in globalv.channelUsers[channel]: continue if os.path.exists( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7]))): file = open( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])), "a") else: file = open( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])), "w") message = "[%(time)d] |<-- %(user)s has quit: %(reason)s" % { "time": time.time(), "user": userMask, "reason": msg } file.write(message + "\n") file.close() if msgType == "NICK": for channel in set(globalv.channels): if not user in globalv.channelUsers[channel]: continue if os.path.exists( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7]))): file = open( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])), "a") else: file = open( os.path.join( "logs", "LogFile - " + channel + "-" + str(ttime[0]) + "-" + str(ttime[7])), "w") user = complete[0].split()[0].split('!')[0] newNick = complete[1] message = "[%(time)d] =-= %(user)s is now known as %(newnick)s" % { "time": time.time(), "user": user, "newnick": newNick } file.write(message + "\n") file.close() except Exception as detail: print "Log failure: %s" % detail return [""]