Example #1
0
 def action(self, complete):
     msg=complete.message()
     votes=int(settingsHandler.readSetting(complete.cmd()[0], "votes"))
     plugin=settingsHandler.readSetting(complete.cmd()[0], "plugin")
     user=complete.userMask().split('!')[1]
     if msg.lower() in self.Voted.keys():
         if user in self.Voted[msg.lower()]:
             return ["PRIVMSG $C$ :You have already voted!"]
         else:
             self.Voted[msg.lower()].append(user)
             numRequired=votes-len(self.Voted[msg.lower()])
             if numRequired>0:
                 if msg!="":
                     msg=" "+msg
                 if numRequired!=1:
                     s="s"
                 else:
                     s=""
                 return ["PRIVMSG $C$ :Voted to %s%s. %s more vote%s required."%(plugin,msg,numRequired,s)]
     else:
         self.Voted[msg.lower()]=[user]
         numRequired=votes-len(self.Voted[msg.lower()])
         if msg!="":
             msg=" "+msg
         if numRequired!=1:
             s="s"
         else:
             s=""
         return ["PRIVMSG $C$ :Voted to %s%s. %s more vote%s required."%(plugin,msg,numRequired,s)]
     if len(self.Voted[msg.lower()])>=votes:
         input=":%s!%s PRIVMSG %s :!%s %s"%(globalv.nickname,globalv.miscVars[0][globalv.nickname],complete.channel(),plugin, msg)
         inputObj=formatInput(pluginArguments(input))
         output=globalv.loadedPlugins[plugin.split()[0]].action(inputObj)
         self.Voted[msg.lower()]=[]
         return output
Example #2
0
 def action(self, complete):
     commands = shlex.split(complete.message())
     commands = [c.replace("\x00","") for c in commands] #Working around a unicode bug in shlex
     commandString = commands[0]
     commands = commands[1:15]
     commandString = commandString.split(' ',1)
     outputList=[]
     for command in commands:
         if len(commandString)>1:
             argumentsToRun = self.expand(commandString[1], command)
         else:
             argumentsToRun = command 
         commandToRun = commandString[0]
         print "Running command", commandToRun, "with arguments", argumentsToRun
         print "Constructing plugin object"
         arguments = pluginArguments(complete.complete())
         firstBit=arguments.complete().split(':')[1]
         arguments.setComplete(":"+firstBit+":"+globalv.commandCharacter+commandToRun+" "+argumentsToRun)
         print "Pre-formatting plugin object:", arguments.complete()
         arguments=formatInput(arguments)
         print "Running command"
         pluginOutput=globalv.loadedPlugins[commandToRun].action(arguments)
         print "Formatting output"
         output = formatOutput(pluginOutput, complete)
         print "Decoding output"
         output = [o for o in output]
         print "Success! Adding output to output list",output
         outputList+=output
     return outputList
Example #3
0
def run_command(commandString, arguments):
    pluginIn = ":%s PRIVMSG %s :!%s"%(arguments.userMask(), arguments.channel(), commandString)
    args = pluginArguments(pluginIn)
    formatted = formatInput(args)

    pluginToRun = commandString.split()[0]

    output = globalv.loadedPlugins[pluginToRun].action(formatted)
    return output
Example #4
0
 def action(self, complete):
     msg=complete.message()
     commands=msg.split('|')
     random.shuffle(commands)
     command=commands[0]
     plugin=command.split()[0]
     arguments=' '.join(command.split()[1:])
     arguments=":%s PRIVMSG %s :!%s %s"%(complete.userMask(), complete.channel(),plugin ,arguments)
     arguments=formatInput(pluginArguments(arguments))
     pluginOutput=globalv.loadedPlugins[plugin].action(arguments)
     return pluginOutput 
Example #5
0
    def action(self, complete):
        msg=complete.message()
        output=msg.split('>')[-1]
        if output==msg or len(output.split())!=1:
            output="$C$"
        else:
            msg=msg.split('>')[0]
        commandlist=msg.split('&&')
        returns=[]
        for msg in commandlist:
            msg=msg.replace('\|','__PIPE__')
            commands=msg.split('|')
            commands=map(lambda x: x.replace('__PIPE__','|'), commands)
            pluginOutput=""
            for command in commands:
                plugin=command.split()[0]
                args=' '.join(command.split()[1:])
                if globalv.loadedPlugins[plugin].__append_seperator__()==True:
                    args+="::"
                args+=pluginOutput
                arguments=pluginArguments(complete.complete())
                # print "======", arguments.complete()
                firstBit=arguments.complete().split(' :')[0]
                if isinstance(args, unicode):
                    args = args.encode('utf-8')
                arguments.setComplete(firstBit+" :"+globalv.commandCharacter+plugin+" "+args)
                arguments=formatInput(arguments)
                pluginOutput=globalv.loadedPlugins[plugin].action(arguments)
                # print pluginOutput
                if pluginOutput!=[""]:
                    starter=pluginOutput[0].split(' :')[0]
                    # print starter
                    if starter.split()[0]=="PRIVMSG":
                        content=""
                        pluginOutput=[x for x in pluginOutput if x!=""]
                        for i,line in enumerate(pluginOutput):
                            content+=' :'.join(line.split(' :')[1:])+(" | " if i!=len(pluginOutput)-1 else "")
                            # print content
                        pluginOutput=starter+(' :'+content if content!="" else "")
                        pluginOutput=' :'.join(pluginOutput.split(' :')[1:]) if command!=commands[-1] else pluginOutput
                        # print pluginOutput
                else:
                    pluginOutput=""

            if type(pluginOutput)!=list:
                pluginOutput=pluginOutput.replace('$C$', output)
            else:
                pluginOutput=[x.replace('$C$', output) for x in pluginOutput]
            outputstr=formatOutput(pluginOutput,complete)
            if outputstr!="":
                #returns.append(outputstr)
                returns+=outputstr
        return returns
Example #6
0
    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
Example #7
0
File: if.py Project: Phoshi/OMGbot
    def action(self, complete):
        reload(braceParser)
        parseBraces=braceParser.parseBraces
        try:
            msg=parseBraces(complete.fullMessage())
        except Exception as detail:
            return ["PRIVMSG $C$ :Parse Failure: "+str(detail)]
        conditionState=True
        toReturn=[]
        for condition in msg[0]:
            try:
                calcInput=":%s PRIVMSG %s :!%s %s"%(complete.userMask(),complete.channel(),"calculate", condition)
                inputObj=formatInput(pluginArguments(calcInput))
                output=':'.join(globalv.loadedPlugins["calculate"].action(inputObj)[0].split(':')[1:])
                if output=="False":
                    conditionState=False
                    break
            except Exception as detail:
                return ["PRIVMSG $C$ :Conditional execution failure in %s"%condition,"PRIVMSG $C$ :Reason:%s"%str(detail)]

        if conditionState==True:
            commandList=msg[1][0].split(';')
        elif len(msg[1])>1:
            commandList=msg[1][1].split(';')
        else:
            commandList=[]
        for command in commandList:
            try:
                plugin=command.split()[0]
                args=' '.join(command.split()[1:])
                input=":%s PRIVMSG %s :!%s %s"%(complete.userMask(),complete.channel(),plugin, args)
                inputObj=formatInput(pluginArguments(input))
                toReturn+=[x.replace('\x00','').encode('utf-8') for x in globalv.loadedPlugins[plugin.split()[0]].action(inputObj)]
            except Exception as detail:
                return ["PRIVMSG $C$ :!if failure in command %s"%command,"PRIVMSG $C$ :Reason:%s"%str(detail)]
        return toReturn 
Example #8
0
	def action(self, args):
		complete=args.complete()[1:].split(':',1)
		if len(complete[0].split())>2:
			msg=args.message()
			laterMessages = self.getLater(args.user())
			msg=[]
			if args.channel!=globalv.nickname:
				if laterMessages!="":
					if laterMessages[1].split()[0] in globalv.loadedPlugins.keys():
						toSend=pluginArguments(":"+laterMessages[0]+" PRIVMSG $C$ :"+globalv.commandCharacter+laterMessages[1])
						output=globalv.loadedPlugins[laterMessages[1].split()[0]].action(toSend)
						print output,'###'
						msg+=(formatOutput(output,args))
					else:
						msg+=(["PRIVMSG $C$ :Hey, "+args.user()+": "+laterMessages[0].split('!')[0]+" said "+laterMessages[1]])
					self.remLater(args.user())
					msg+=["PRIVMSG $C$ :(From "+laterMessages[0].split('!')[0]+" to "+args.user()+")"]
					return msg
		return [""]
Example #9
0
    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
Example #10
0
def load_alias(name, plugin): #Loads an alias
    try:
        if plugin.split()[0] in globalv.loadedPlugins:
            if plugin.split()[0] in globalv.aliasExtensions:
                argumentsObject = pluginArguments(":nothing!nobody@nowhere PRIVMSG #NARChannel :%s%s"%(globalv.commandCharacter, plugin))
                argumentsObject = formatInput(argumentsObject, globalv.aliasExtensions, False)
                plugin = argumentsObject.fullMessage()[len(globalv.commandCharacter):]
                print plugin

            globalv.loadedPlugins.update({name:globalv.loadedPlugins[plugin.split()[0]]})
            if settingsHandler.tableExists(name)==0:
                globalv.loadedPlugins[plugin.split()[0]].__init_db_tables__(name)
            if name not in [x[0] for x in settingsHandler.readSetting("'core-userlevels'", "plugin")]:
                settingsHandler.writeSetting("'core-userlevels'", ["plugin", "level"],[name, str(globalv.loadedPlugins[plugin.split()[0]].__level__())])
        else: #If the aliases dependancy isn't loaded, load it, then get rid of it afterwards.
            load_plugin(plugin.split()[0])
            globalv.loadedPlugins.update({name:globalv.loadedPlugins[plugin.split()[0]]})
            if settingsHandler.tableExists(name)==0:
                globalv.loadedPlugins[plugin.split()[0]].__init_db_tables__(name)
            if name not in [x[0] for x in settingsHandler.readSetting("'core-userlevels'", "plugin")]:
                settingsHandler.writeSetting("'core-userlevels'", ["plugin", "level"],[name, str(globalv.loadedPlugins[plugin.split()[0]].__level__())])
            unload_plugin(plugin.split()[0])
        globalv.loadedAliases.update({name:plugin})
        globalv.basePlugin[name] = plugin.split()[0]
    except Exception as detail:
        print detail
        try:
            message("Function syntax: "+globalv.commandCharacter+"alias [word] [command] [arguments]",info[2])
        except:
            print "Plugin",name,"failed to load"
    try:
        print "Adding Extensions"
        print plugin
        globalv.aliasExtensions.update({name:" "+' '.join(plugin.split()[1:])})
    except:
        globalv.aliasExtensions.update({name:''})
    if globalv.aliasExtensions[plugin.split()[0]]!="":
        try:
            #globalv.aliasExtensions.update({name:globalv.aliasExtensions[plugin.split()[0]]})
            print "Would have broken here"
        except:
            globalv.aliasExtensions.update({name:''})
Example #11
0
File: var.py Project: Phoshi/OMGbot
    def action(self, complete):
        msg=complete.message().split()
        if len(msg)>1:
            if isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]):
                try:
                    calcInput=":%s PRIVMSG %s :!%s %s"%(complete.userMask(),complete.channel(),"calculate", ' '.join(msg[1:]))
                    inputObj=formatInput(pluginArguments(calcInput))
                    output=':'.join(globalv.loadedPlugins["calculate"].action(inputObj)[0].split(':')[1:])
                    globalv.variables[msg[0]]=str(output)
                    with open(os.path.join("config","variables"),'w') as file:
                        pickle.dump(globalv.variables,file,pickle.HIGHEST_PROTOCOL)
                except Exception as detail:
                    return ["PRIVMSG $C$ :Variable setting failure with expression !var %s: %s"%(complete.message(), detail)]

        else:
            if msg[0] in globalv.variables.keys():
                return ["PRIVMSG $C$ :%s"%globalv.variables[msg[0]]]
            else:
                return ["PRIVMSG $C$ :Undefined"]
        return [""]
Example #12
0
 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
Example #13
0
    def action(self, complete):
        command=complete.message()
        print "To repeat:", command
        commands=command.split()

        repeatTimes = int(commands[0])
        plugin = commands[1]

        command = ' '.join(commands[1:])
        arguments=pluginArguments(complete.complete())
        firstBit=arguments.complete().split(' :')[0]
        arguments.setComplete(firstBit+" :"+globalv.commandCharacter+command)
        arguments=formatInput(arguments)

        if plugin in globalv.loadedPlugins:
            result = []
            for i in xrange(repeatTimes):
                result += globalv.loadedPlugins[plugin].action(arguments)
            return result

        return []
Example #14
0
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
Example #15
0
    def action(self, complete):
        argumentString = ":null!nobody@nowhere PRIVMSG nothing :!sr388"
        argumentsObject = formatInput(pluginArguments(argumentString))
        numbers={}
        if complete.message().isdigit()==False:
            totalIterations = 10000
        else:
            totalIterations=int(complete.message())
        for i in xrange(0,totalIterations):
            output = globalv.loadedPlugins['sr388'].action(argumentsObject)[0]
            number = output.split()[3][1:]
            if number in numbers:
                numbers[number]+=1
            else:
                numbers[number]=1
        sortedNumbers = sorted(numbers.iteritems(), key=operator.itemgetter(1))
        sortedNumbers.reverse()
        minHits=(0, totalIterations)
        maxHits=(0,0)
        total=0
        for number in sortedNumbers:
            total+=number[1]
        mean = total/len(sortedNumbers)
        devTotal=0

        for number in sortedNumbers:
            devTotal+= (number[1]-mean)**2
            if number[1]>maxHits[1]:
                maxHits = number
            elif number[1]<minHits[1]:
                minHits = number

        devMean = devTotal/len(sortedNumbers)
        stdDev = devMean**0.5


        return ["PRIVMSG $C$ :Total iterations: %s; Most often picked quote: %s (with %s hits); Least often picked quote: %s (with %s hits); Results have a standard devation of %s"%(totalIterations, maxHits[0], maxHits[1], minHits[0], minHits[1], stdDev)]
Example #16
0
    def action(self, complete):
        msg=complete.message()
        isElevated=(isAllowed(complete.userMask())>=getLevel(complete.cmd()[0]))
        beRandom=True
        if len(self.answers)==0:
            self.__init_answers__(complete,beRandom)
        if len(msg.split())>=1:
            cmd=msg.split()[0]
            msg=' '.join(msg.split()[1:])
        else:
            cmd=""
            msg=""
        if cmd=="-add" and isElevated:
            settingsHandler.writeSetting("'"+complete.cmd()[0]+"'","answer",msg)
            toReturn="Added that answer"
            self.__init_answers__(complete,beRandom)
        elif cmd=="-delete" and isElevated:
            settingsHandler.deleteSetting("'"+complete.cmd()[0]+"'","answer",msg)
            toReturn="Wiped that answer."
            self.__init_answers__(complete,beRandom)
        elif cmd=="-wipe" and isElevated:
            settingsHandler.dropTable("'"+complete.cmd()[0]+"'")
            settingsHandler.newTable("'"+complete.cmd()[0]+"'","answer")
            toReturn="Answer table wiped!"
            self.__init_answers__(complete,beRandom)
        elif cmd=="-reset" and isElevated:
            self.__init_answers__(complete,beRandom)
            toReturn="Re-randomising list..."
        else:
            toReturn=self.answers.pop()
            inputs=":%s PRIVMSG %s :!%s"%(complete.userMask(), complete.channel(), toReturn)
            input=formatInput(pluginArguments(inputs))
            pluginOut=globalv.loadedPlugins[toReturn.split()[0]].action(input)
            return pluginOut

        return ["PRIVMSG $C$ :"+toReturn]
Example #17
0
    def action(self, complete):
        user = complete.user()
        if complete.type() != "PRIVMSG":
            return [""]
        returns = []

        messages = readAllActions(user)
        if (user.lower() == "joshdreamland"):
            messages += readAllActions("josh")
        if (user.lower() == "ismavatar"):
            messages += readAllActions("ism")
        if (user.lower() == "goombert"):
            messages += readAllActions("robert")

        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
Example #18
0
def load_alias(name, plugin):  #Loads an alias
    try:
        if plugin.split()[0] in globalv.loadedPlugins:
            if plugin.split()[0] in globalv.aliasExtensions:
                argumentsObject = pluginArguments(
                    ":nothing!nobody@nowhere PRIVMSG #NARChannel :%s%s" %
                    (globalv.commandCharacter, plugin))
                argumentsObject = formatInput(argumentsObject,
                                              globalv.aliasExtensions, False)
                plugin = argumentsObject.fullMessage()[len(globalv.
                                                           commandCharacter):]
                print plugin

            globalv.loadedPlugins.update(
                {name: globalv.loadedPlugins[plugin.split()[0]]})
            if settingsHandler.tableExists(name) == 0:
                globalv.loadedPlugins[plugin.split()[0]].__init_db_tables__(
                    name)
            if name not in [
                    x[0] for x in settingsHandler.readSetting(
                        "'core-userlevels'", "plugin")
            ]:
                settingsHandler.writeSetting("'core-userlevels'", [
                    "plugin", "level"
                ], [
                    name,
                    str(globalv.loadedPlugins[plugin.split()[0]].__level__())
                ])
        else:  #If the aliases dependancy isn't loaded, load it, then get rid of it afterwards.
            load_plugin(plugin.split()[0])
            globalv.loadedPlugins.update(
                {name: globalv.loadedPlugins[plugin.split()[0]]})
            if settingsHandler.tableExists(name) == 0:
                globalv.loadedPlugins[plugin.split()[0]].__init_db_tables__(
                    name)
            if name not in [
                    x[0] for x in settingsHandler.readSetting(
                        "'core-userlevels'", "plugin")
            ]:
                settingsHandler.writeSetting("'core-userlevels'", [
                    "plugin", "level"
                ], [
                    name,
                    str(globalv.loadedPlugins[plugin.split()[0]].__level__())
                ])
            unload_plugin(plugin.split()[0])
        globalv.loadedAliases.update({name: plugin})
        globalv.basePlugin[name] = plugin.split()[0]
    except Exception as detail:
        print detail
        try:
            message(
                "Function syntax: " + globalv.commandCharacter +
                "alias [word] [command] [arguments]", info[2])
        except:
            print "Plugin", name, "failed to load"
    try:
        print "Adding Extensions"
        print plugin
        globalv.aliasExtensions.update(
            {name: " " + ' '.join(plugin.split()[1:])})
    except:
        globalv.aliasExtensions.update({name: ''})
    if globalv.aliasExtensions[plugin.split()[0]] != "":
        try:
            #globalv.aliasExtensions.update({name:globalv.aliasExtensions[plugin.split()[0]]})
            print "Would have broken here"
        except:
            globalv.aliasExtensions.update({name: ''})
Example #19
0
 def action(self, complete):
     msg=complete.message()
     arguments=pluginArguments("no!body@nowhere PRIVMSG #nothing :!ocr kindred")
     result=globalv.loadedPlugins['ocr'].action(arguments)
     return ["PRIVMSG $C$ :"+result[0]]
Example #20
0
def parse(msg):
    arguments=pluginArguments(msg)
    global load_plugin
    global unload_plugin
    global isAllowed
    global isBanned
    global load_alias
    global save_alias

    if not isBanned(arguments):
        if arguments.cmd()[0]=="reimportGlobalVariables" and arguments.user()==owner:
            reload(globalv)
            reload(pluginHandler)
            reload(aliasHandler)
            reload(securityHandler)
            load_plugin=pluginHandler.load_plugin
            unload_plugin=pluginHandler.unload_plugin
            isAllowed=securityHandler.isAllowed
            isBanned=securityHandler.isBanned
            load_alias=aliasHandler.load_alias
            save_alias=aliasHandler.save_alias
            load_plugin("load")
            message("Reloaded globalv variables. You may encounter some slight turbulence as we update.",arguments.channel())
        elif arguments.cmd()[0] in globalv.loadedPlugins.keys():
            if arguments.cmd()[0] not in globalv.accessRights[arguments.user()]:
                try:
                    arguments=formatInput(arguments)
                    output=globalv.loadedPlugins[arguments.cmd()[0]].action(arguments)
                    output=formatOutput(output,arguments)
                    if type(output)==list:
                        output=[x for x in output if x!=""]
                    send(output)
                except Exception as detail:
                    print arguments.cmd()[0], "failed:",str(detail)
                    traceback.print_tb(sys.exc_info()[2])
            else:
                output=globalv.loadedPlugins[arguments.cmd[0]].disallowed(formatInput(arguments))
                send(formatOutput(lines,arguments))
        else:
            verboseAutoComplete = True if settingsHandler.readSetting("coreSettings", "verboseAutoComplete")=="True" else False
            command=arguments.cmd()[0]
            nearMatches=difflib.get_close_matches(command, globalv.loadedPlugins.keys(), 6, 0.5)
            nearestMatch=difflib.get_close_matches(command, globalv.loadedPlugins.keys(),1,0.6)
            commandExists = os.path.exists(os.path.join("plugins","command",command+".py"))
            returns=[]
            if nearMatches==[]:
                if not commandExists:
                    if not verboseAutoComplete:
                        return
                    returns=["PRIVMSG $C$ :No such command!"]

                else:
                    returns=["PRIVMSG $C$ :Command not loaded!"]
            elif nearestMatch==[]:
                if not commandExists:
                    if not verboseAutoComplete:
                        return
                    returns=["PRIVMSG $C$ :No such command! Did you mean: %s"%', '.join(nearMatches)]
                else:
                    returns=["PRIVMSG $C$ :Command not loaded! Did you mean: %s"%', '.join(nearMatches)]
            else:
                newArguments=arguments.complete()[1:]
                constructArguments=newArguments.split(' :',1)
                commands=constructArguments[1].split()
                commands[0]=globalv.commandCharacter+nearestMatch[0]
                constructArguments[1]=' '.join(commands)
                newArguments=':'+' :'.join(constructArguments)
                parse(newArguments)
                if (arguments.cmd()[0].lower()!=nearestMatch[0].lower()):
                    if len(nearMatches)>1:
                        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))
Example #21
0
 #irc.recv(4096) #Grab the hostname auth message to assure connection was successful.
 print "Connection Succesful!"
 globalv.input.startInputDaemons()
 send ('USER '+nickname+' * * :'+owner) #Tell the IRC server who we are
 send ('NICK '+nickname) #And what we're called.
 while on==1:
     try:
         if globalv.input.getPrimaryProducerStatus()==False:
             sys.exit(0)
         data = globalv.input.getInput()
         print data
         for datum in data.split('\r\n')[0:-1]:
             if datum[:1]!="#":
                 for plugin in globalv.loadedPreprocess.keys():
                     try:
                         datum=globalv.loadedPreprocess[plugin].action(pluginArguments(datum))
                     except Exception as detail:
                         print plugin, "failed:",detail
                         traceback.print_tb(sys.exc_info()[2])
                 if datum=="":
                     break
                 arguments=pluginArguments(datum)
                 for plugin in sorted(globalv.loadedRealtime.keys()):
                     try:
                         output=globalv.loadedRealtime[plugin].action(arguments)
                         send(formatOutput(output,arguments))
                     except Exception as detail:
                         print plugin, "failed:",str(detail)
                         traceback.print_tb(sys.exc_info()[2])
                 if datum.split()[0]=="ERROR":
                         sys.exit(0)
Example #22
0
    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